diff --git a/docs/admin-api.md b/docs/admin-api.md index 4a0e23e..06f5ca1 100644 --- a/docs/admin-api.md +++ b/docs/admin-api.md @@ -326,6 +326,7 @@ interface UserView { ```ts type RepoStatus = 'CREATING' | 'READY' | 'FAILED'; type PublishStatus = 'UNPUBLISHED' | 'PUBLISHED' | 'BLOCKED'; +type AssemblyAnimationStatus = 'UNPROCESSED' | 'IN_PROGRESS' | 'COMPLETED'; interface ProjectInput { name: string; @@ -369,6 +370,7 @@ interface ProjectView { interface ManagedProjectView { project: ProjectView; + assemblyAnimationStatus: AssemblyAnimationStatus; moderationStatus: 'NORMAL' | 'BLOCKED'; moderationReason: string | null; deleted: boolean; @@ -394,6 +396,7 @@ interface TypeView { | publishStatus | `UNPUBLISHED` 未发布;`PUBLISHED` 已发布;`BLOCKED` 管理员下架 | | publishedCommitSha | 社区当前已发布的文件版本,**不是工作区最新版本** | | moderationStatus / moderationReason | 后台治理状态及下架原因;BLOCKED 与 publishStatus=BLOCKED 对应 | +| assemblyAnimationStatus | 拼装动画制作状态:`UNPROCESSED` 未处理(默认)、`IN_PROGRESS` 进行中、`COMPLETED` 已完成;位于 ManagedProjectView 顶层,仅管理端返回 | | sourceProjectCode / sourceCommitSha | 从社区内部 Fork 的来源;没有则为 null | | sourceRepositoryUrl / sourceLicense | 在线迁移项目的外部来源和许可证;没有或未取得则为 null | | urdfMainUrl / urdfBaseUrl | 已绑定的 URDF 主文件和资源基地址;未绑定则为 null | @@ -438,6 +441,7 @@ interface TypeView { | publishStatus | UNPUBLISHED / PUBLISHED / BLOCKED | | repoStatus | CREATING / READY / FAILED | | moderationStatus | NORMAL / BLOCKED | +| assemblyAnimationStatus | UNPROCESSED / IN_PROGRESS / COMPLETED;省略时查询全部,非法值返回 400 | | sort | 可选:`CREATED_AT_DESC`(默认)、`PUBLISHED_AT_DESC`、`RESOURCES_FIRST`;其他值返回 400 | 结果只包含未删除项目。排序模式: @@ -489,11 +493,24 @@ interface TypeView { "updatedAt": "2026-10-20T02:30:00" }, "moderationStatus": "NORMAL", + "assemblyAnimationStatus": "UNPROCESSED", "moderationReason": null, "deleted": false } ``` +#### 拼装动画制作状态 + +`PUT /admin-api/projects/{projectCode}/assembly-animation-status` → `ManagedProjectView`。 + +```json +{ "status": "IN_PROGRESS" } +``` + +`status` 必填且仅接受 `UNPROCESSED`、`IN_PROGRESS`、`COMPLETED`,可以在三种状态之间自由切换。新建及历史项目默认未处理。此接口仅限管理员,按项目编码更新数据库状态及系统更新时间,返回可直接用于回显的完整管理详情;不存在或已删除项目返回 404。仓库未就绪时也可设置状态,不触发资源上传、绑定或发布。重复设置同一状态不更新系统时间;并发操作由项目锁串行处理,以最后一次成功写入为准。 + +前端在「装配与仿真」页的「刷新资源绑定」右侧显示状态下拉框,选择后自动保存,保存期间禁用重复操作,失败时保留原显示值并提示错误。项目列表显示同一字段,筛选携带 `assemblyAnimationStatus`;清空或重置时省略此参数,查询、分页和发布时间倒序沿用原有规则。 + ### 5.4 创建、编辑、删除 `POST /admin-api/projects` → `ProjectView`,body: diff --git a/docs/admin-database.md b/docs/admin-database.md index b6f5611..007e8d2 100644 --- a/docs/admin-database.md +++ b/docs/admin-database.md @@ -8,6 +8,18 @@ 治理相关字段为 moderation_reason(管理员下架原因)和 repo_write_status(跨进程写入状态)。下架直接使用现有 publish_status=BLOCKED,不再增加独立治理状态。GitHub来源标识、地址、默认分支和许可证属于迁移任务,统一放在 project_import_task;第一版只支持GitHub,不存平台类型,也不额外区分用户创建与后台创建。 +## 已有数据库增加拼装动画制作状态 + +升级社区端、管理端和导入工具前,已有数据库先手工执行以下 SQL;新建数据库的 `database.md` 已包含该字段,不要重复执行。已有项目和新建项目均默认为未处理,Fork 的新项目也独立从未处理开始。 + +```sql +ALTER TABLE project + ADD COLUMN assembly_animation_status VARCHAR(16) NOT NULL DEFAULT 'UNPROCESSED' + COMMENT '拼装动画制作状态 UNPROCESSED未处理 IN_PROGRESS进行中 COMPLETED已完成'; +``` + +状态仅供后台制作进度管理,独立于仓库、资源绑定和发布状态;修改时只更新此字段及系统更新时间,不修改文件、资源绑定或发布信息。 + ## 已有数据库增加 STEP 单文件字段 已有数据库手工执行以下 SQL,再升级社区端、管理端和导入工具;新建数据库的 `database.md` 已包含这三个字段,不要重复执行。应用不自动迁库,不新增上传批次表。 diff --git a/docs/cad-ai-deepagents-refactor-plan-20261116.md b/docs/cad-ai-deepagents-refactor-plan-20261116.md new file mode 100644 index 0000000..dec4f7a --- /dev/null +++ b/docs/cad-ai-deepagents-refactor-plan-20261116.md @@ -0,0 +1,382 @@ +# CAD AI 独立 Python 后台重构实施方案 + +日期:2026-11-16。状态:本轮代码与模拟验收已完成,新 Python 后台、Rust/WASM v2 客户端及主站桥接均已创建。Python 280 项(含隔离 PostgreSQL/Redis)、主站 89 项、Rust Web 82 项及 UI 定向 4 项通过;完整 WASM、新网页包和真实浏览器 7 组跨端冒烟通过。未调用真实模型,尚未切换 8091 或部署生产。实际交付及未验收项以新工程 `docs/implementation.md` 为准。下面的任务清单保留为最初设计基准,不代表所有生产验收已经完成。首期不依赖私有 OSS,不支持关闭或刷新 CAD 页面后继续旧任务。 + +## 1. 已确认的决策与范围 + +- 新建独立的 CAD AI Python 后台项目,建议项目名 cad-ai-server,独立依赖、测试、镜像、配置和发布。 +- 使用官方 Deep Agents Python SDK。Deep Agents 底层运行于 LangGraph;一个 Agent 图负责推理和工具循环,不再增加第二套推理循环。 +- 使用 PostgreSQL 保存 Agent 检查点及 CAD AI 业务状态,Redis 用于通知、限流和临时协调。 +- 首期不要求私有 OSS,不建设 AI 文档恢复快照或通用附件上传服务。受限的大型工具文本/JSON 结果保存到 PostgreSQL 专用结果表,按权限、字段或页读取。 +- 复用当前网站账号和 CAD 项目权限,通过现有 Java HTTP 接口校验。新后台不读取或修改原站 MySQL、会话 Redis、登录实现或其他业务。 +- 首期不支持关闭、刷新页面或浏览器崩溃后继续旧任务。正常离开时尽力通知取消;异常离开通过执行端租约过期停止任务。重开后建立新执行端绑定,需要重新发起任务。 +- 保留同一页面、同一内存文档仍有效时的短暂断线重连、事件补发及有限模型重试,不把一次 SSE 断流直接视为用户取消。 +- 首期以单用户稳定性和小范围灰度为验收目标,不预先承诺特定并发量。 +- 保留新增知识库、流式输出、浏览器 CAD 执行器、权限门禁和文档保护;模型厂商及协议不静默改变。 +- 账号、项目、手动保存、社区 AI、CAD 内核均保留现有实现。旧 Java CAD AI 在灰度期保留,作为新会话的回退入口。 +- 不修改当前项目的 .sql 文件。新数据库 DDL 单独交付,字段及表使用中文注释;框架自带检查点表按固定依赖版本的官方迁移机制管理。 + +“独立”指代码、数据及部署独立;网站仍然是账号和项目权限的权威来源。原站鉴权不可用时,新后台应暂停需要授权的操作;页面绑定失效或超过等待期限后明确结束任务,不放行或伪报成功。 + +## 2. 当前代码基线与需要保留的能力 + +CAD 当前本地基线:solidcraft-main 的 ade571ebe,2026-11-16,已合并上游 0.43.0。Java 基线:community 的 6b96ca1,另有用户现存未提交知识生成记录,实施不得覆盖。 + +| 部位 | 当前实现 | 重构方式 | +| --- | --- | --- | +| Java CAD AI | CadAiService 处理一次模型推理,输出 SSE | v2 迁往新 Python 后台;Java v1 保留灰度回退 | +| Rust/WASM | PlatformBackend 维护历史、模型请求重试、工具执行和任务循环 | v2 改成任务客户端;复用工具执行与文档保护 | +| 主站 JavaScript | 账号、项目、agentChat/agentKnowledge 桥接、修订绑定 | 增加独立 AgentClient,连接新后台,复用原业务接口 | +| 流式展示 | TextPreview 为尝试级草稿,完成后确认正式回答 | 保留预览与确认的分离,增加断线后事件补发 | +| 文档保存 | createSnapshot、IndexedDB 草稿、SaveCoordinator | 保留原保存及草稿行为;首期不增加 AI 快照、快照上传或跨页面恢复 | +| 工具 | 白名单、Schema、门禁、顺序执行、撤销分组 | Python 与浏览器双重校验;文档修改保持单写者 | +| Skills | 随 CAD 源码更新,Java 资源包曾落后 | 建立单一来源、版本清单与发布校验 | +| 知识库 | 阅读目录、按 document_id 读取 Markdown、版本和 SHA256 | 原样迁入 Python 资源,保留选择与 not_found 语义 | + +当前 Skills 同步发现:原包 17 个,最新源 19 个,新增 makecad-layers 和 makecad-sheetmetal,14 个既有 SKILL.md 有变化。新方案的资源基线必须采用本次同步后的版本,不能沿用旧包。 + +主要源码位置: + +- Java 推理服务:/Users/lk/Projects/vibemake相关项目/community/vibemake-service/src/main/java/com/linkerbot/vibemake/service/cad/ai/CadAiService.java +- Java 知识读取:/Users/lk/Projects/vibemake相关项目/community/vibemake-service/src/main/java/com/linkerbot/vibemake/service/cad/ai/CadAiKnowledge.java +- Java Skills:/Users/lk/Projects/vibemake相关项目/community/vibemake-service/src/main/resources/cad/ai/skills.json +- 浏览器助手:/Users/lk/Projects/vibemake相关项目/solidcraft-main/apps/solidcraft-web/src/agent.rs +- 助手公共事件:/Users/lk/Projects/vibemake相关项目/solidcraft-main/crates/ui-egui/src/agent_chat/backend.rs +- 文档与快照桥接:/Users/lk/Projects/vibemake相关项目/solidcraft-main/apps/solidcraft-web/src/platform.rs +- CAD 工具门禁:/Users/lk/Projects/vibemake相关项目/solidcraft-main/crates/ui-egui/src/agent_chat/gate.rs +- 主站桥接:/Users/lk/Projects/vibemake相关项目/vibemake/js/cad/app.js +- 主站请求:/Users/lk/Projects/vibemake相关项目/vibemake/js/cad/api.js +- 本地草稿:/Users/lk/Projects/vibemake相关项目/vibemake/js/cad/drafts.js + +## 3. 目标架构与职责 + +浏览器 CAD / Rust-WASM 助手面板 + → 新 Python CAD AI HTTP API / SSE + → Deep Agents + LangGraph + Worker + → 模型厂商、PostgreSQL、Redis + +浏览器继续通过原 Java API 登录、读取项目和手动保存。 +Python 只通过固定的原站接口验证当前用户和项目访问权。 +LangGraph 需要执行 CAD 工具时持久化调用意图,然后等待浏览器领取、执行和回传;Python 不直接执行几何,也不在服务器启动桌面 CAD。 + +建议技术组成:FastAPI、Pydantic、Deep Agents、LangGraph、官方 PostgreSQL checkpointer、psycopg 连接池、Redis 客户端、异步 HTTP 客户端、pytest。首期无需 OSS SDK 或对象存储部署。具体依赖版本在第一阶段联合验证后锁定,提交锁文件,不默认追随最新版本。 + +同一代码库提供 API 与 Worker 两种进程。首期可以单实例部署,但队列、检查点、文档租约和状态都要持久化,不能把生产任务只放在 FastAPI 的内存后台任务中。服务进程重启后,只有原页面和原文档仍有效、执行授权重新确认时才能继续;旧页面已经消失的任务不得自动恢复 CAD 操作。 + +服务端只有一套模型重试预算。浏览器 v2 只负责连接恢复和工具执行,不再自行重跑模型。 + +## 4. 新后台工作清单 + +### 4.1 工程、边界和契约 + +- [ ] 创建独立工程、锁定依赖、格式和类型检查、测试目录、容器及部署示例。 +- [ ] 定义 cad-agent-v2,对旧 cad-agent-v1 不做含义不明的字段复用。 +- [ ] 实现能力接口:支持的协议、工具集、CAD 构建、Skills/知识版本、模型能力、配额。 +- [ ] 复用已有工具 JSON Schema,建立与 CAD 源码可核对的版本清单,避免两份手工维护的 Schema。 +- [ ] 文档写操作单写者;模型即使一次返回多个工具,也按原始顺序逐个授权与执行。 +- [ ] 默认不加载通用 shell、任意真实文件系统、任意网络访问或能修改 CAD 的子 Agent。处理 Deep Agents 默认 execute 与 CAD execute 的命名冲突。 + +### 4.2 身份和项目权限适配 + +当前原站使用服务端保存的随机 Bearer Token,不是可让新后台自行验签的 JWT。 + +新后台通过原有接口校验: + +- GET /api/users/me:取得可信 userCode,只使用所需身份字段,不保存邮箱等无关资料。 +- GET /api/cad/workspace/projects/{cadProjectCode}:校验该 Token 对项目的当前权限及项目是否有效。 + +- [ ] 浏览器从现有登录上下文向新后台发起请求;不额外要求用户登录一次。 +- [ ] 用户与项目只能从校验结果绑定,不能相信请求正文中的 userCode。 +- [ ] 原站 Token 不落数据库、检查点、模型上下文或日志,不传给模型厂商,不通过 URL 传递。 +- [ ] 新建/同页面继续任务、领取工具、提交回执、读取事件及大型工具结果都检查权限。 +- [ ] SSE 长连接期间周期性重新检查授权;心跳与短期执行租约控制离线和权限失效窗口。 +- [ ] 账号退出、封禁或权限丢失时停止新工具授权并结束当前执行绑定;原站校验暂时不可用时在等待期限内暂停,超期结束。已完成修改按现有保存机制处理。 +- [ ] 原站地址由服务端配置固定,禁止模型或客户端指定鉴权回调地址。 + +### 4.3 任务、持久化和调度 + +建议状态:queued、running、waiting_tool、waiting_user、retrying、reconnecting、paused_conflict、paused_budget、reconciling、completed、failed、cancelled。执行端丢失以明确的 executor_lost 原因结束,不能保留为跨页面可续跑状态。 + +- [ ] 区分 conversation/session、run/用户任务、model attempt、tool call 和事件编码。 +- [ ] 同一会话禁止并发提交两个修改任务;同一文档仅有一个有效写入者。 +- [ ] 用户消息通过 clientMessageCode 幂等提交,重复 HTTP 请求返回同一 runCode。 +- [ ] 接收成功前先持久化输入和待办记录,Worker 通过可恢复的工作记录领取任务。 +- [ ] Redis 仅提供唤醒、限流、缓存,不作为唯一队列或唯一任务状态。 +- [ ] Worker 使用租约和 fencing 代次,旧 Worker 不能继续提交;重新领取未完成任务后先确认原执行端仍有效,不能只凭检查点继续分发修改。 +- [ ] Graph thread 与账号、项目、会话及 pageInstanceCode 绑定;执行器、模型配置、Skills、知识和工具版本固定到任务。页面实例标识只保留在本页内存中,不从本地存储恢复旧执行权。 +- [ ] 等待浏览器或用户时使用持久暂停,不占用持续轮询的模型调用;暂停及继续仅在当前页面绑定有效时开放。 +- [ ] 记录待处理问题和用户答复,重复答复不得触发重复恢复。 +- [ ] 检查点推进、工具账本与事件日志之间设计对账流程;不假设框架写检查点会自动与业务表成为一个事务。 + +### 4.4 浏览器工具代理与防重复执行 + +每次工具调用至少绑定:runCode、toolCallCode、dispatchCode、工具顺序、参数哈希、文档绑定、beforeRevision、引擎/工具版本、执行租约代次。 + +安全执行顺序: + +1. 模型本次输出完整结束,工具名及参数通过校验。 +2. 新后台持久化工具意图和顺序,生成可领取记录。 +3. 浏览器获得通知后,调用领取接口确认该操作仍未执行且租约有效。 +4. 浏览器再次检查账号、项目、当前文档、修订、权限门禁和参数 Schema。 +5. 执行前在当前页面内存记录待执行状态;文档修改串行进行。 +6. 执行完成后先在当前页面记录结果、前后修订和创建/修改/移除对象,再进行异步回传。首期不为每一步生成或上传文档快照。 +7. 网络恢复时重发同一工具回执,服务端确认收据。重发回执不得重新执行该工具;未确认收据时不得开始依赖它的下一次修改。 +8. 服务端按 toolCallCode 幂等接收;相同编码不同参数或结果属于冲突,不覆盖既有收据。 +9. Graph 从持久账本获取结果继续推理,已确认的工具不再执行。 + +浏览器内几何修改与服务端提交不是一个跨端事务,不能承诺数学意义的 exactly-once。同一页面仍存活但回执丢失时,先用页面内收据、服务端账本和前后修订对账;无法确认时暂停或结束,禁止盲目重放修改。页面崩溃或刷新后不恢复旧执行权,旧任务最终结束;新任务先读取当前文档再规划,不能自动重放旧待执行操作。 + +LangGraph 的 interrupt 恢复可能重新进入节点;所有外部副作用都要放在可幂等查询的账本边界后,不能只依赖“这个节点应该执行过”。 + +### 4.5 同页面断线、退出与撤销边界 + +- [ ] 为每个页面实例建立短期执行端绑定。页面仍存活且文档绑定不变时,允许在可配置宽限期内自动重连,初始建议 60 秒。 +- [ ] SSE 单次断开只触发传输恢复,不取消任务、不重发用户消息、不重跑已执行工具。事件订阅与执行端心跳分别判断。 +- [ ] 连接或授权过期期间停止签发新 CAD 操作;宽限期内对账通过后继续,超期以 executor_lost 等明确原因结束。 +- [ ] 正常关闭、刷新、退出账号或切换项目时尽力通知取消,同时立即废弃当前执行端的本地授权;不依赖浏览器退出回调保证通知必达。 +- [ ] 页面异常消失由执行端租约过期兜底。新页面生成新 pageInstanceCode,不能接管旧页面的未完成任务。 +- [ ] 不因 visibilitychange/document.hidden 单独判定页面退出;后台标签冻结或浏览器节流导致超时后可以安全结束,但不能让旧租约继续执行。 +- [ ] 正在运行的工具只能在其安全边界停止;取消不声称自动撤销已完成修改。迟到结果可用于记账,但不能把终态任务重新变成运行中。 +- [ ] 手动修改、引擎变化或多标签页冲突时停止新修改并要求校验;只有原页面及原绑定仍有效时才考虑继续。 +- [ ] 已完成的设计修改按现有手动保存和本地草稿机制处理,首期不新增 AI 自动保存承诺,不改变正式项目版本。 +- [ ] 保留当前页面内的撤销分组,不新增 AI 专用 IndexedDB 快照、不做跨页面任务恢复或跨页面撤销。 + +### 4.6 模型、错误分类与恢复预算 + +保留现有协议:OpenAI/豆包使用 Responses;DeepSeek 使用 Chat Completions。模型、endpoint、思考参数和输出上限显式迁移到新后台,禁止静默降级或切换。 + +- [ ] 每个供应商有独立 profile、能力声明、协议适配和模拟契约测试。 +- [ ] 验证自定义 endpoint、工具调用编码、推理状态续接、图片和 usage,不能假设所有 compatible 地址语义相同。 +- [ ] 模型配置由新后台的版本化配置和安全密钥注入管理;前端只提交允许的 profileCode,不接受任意 endpoint 和密钥。 +- [ ] 模型切换在安全轮次边界进行。跨厂商不直接重放不兼容的推理状态;首期默认新建会话或明确转换。 +- [ ] 输出未结束、参数分片不完整、JSON 损坏、重复调用编码时不得下发 CAD 操作。 +- [ ] 区分空输出、截断、拒绝、HTTP 错误、网络断流、参数错误、上下文超限、权限失效和任务预算耗尽。 +- [ ] 短暂网络/429/部分 5xx 做有限退避,遵守 Retry-After;401、权限、余额、配置错误不能反复重试。 +- [ ] 上下文超限先触发受控压缩或减量,再尝试;不重复发送同一超限请求。 +- [ ] 协议/参数错误允许有限纠错。模型正常返回的工具执行错误交回模型,允许调整参数或方案。 +- [ ] 只有 runtime 维护模型重试预算;关闭或计入 SDK、HTTP、Graph 中其他自动重试,避免乘法放大。 +- [ ] 单次模型超时、整个任务预算、同页面重连宽限期分开,不用一个 300 秒请求截止时间杀掉整个持久任务;也不因保留检查点而无限等待已退出的页面。 +- [ ] 推理次数、CAD 修改次数、总 token 和费用受限;可恢复的预算耗尽显示为暂停,继续入口仅对仍有效的原页面开放。 + +## 5. 上下文与 token 控制 + +上下文方案保留摘要、大结果按需读取与 CAD 任务记忆。首期结果外置使用 PostgreSQL 专用结果表,不依赖 OSS;必须配置模型窗口和大小/保留限额,不能只启用默认值。 + +| 层次 | 保存内容 | 用途 | +| --- | --- | --- | +| 完整会话记录 | 用户消息、确认回答、工具原文/结果句柄、事件 | UI、审计、排错、回看 | +| 模型有效上下文 | 当前目标、任务记忆、最近步骤和按需读取的参考 | 控制每次输入大小 | +| 结构化任务状态 | 用户约束、单位、参数、关键对象、未完成项、文档版本、最近验证 | 同页面任务续接与摘要后防止丢失关键事实 | + +- [ ] 每次模型请求前执行 token 预算检查,而不是只在新用户轮次按消息条数裁剪。 +- [ ] 为模型 profile 配置窗口、输出/推理预留和安全余量;未知模型不盲信统一 fallback。 +- [ ] 按预算优先压缩可重读目录、旧 Schema、旧只读结果,再摘要旧对话;保留最近错误、用户约束及工具调用配对。 +- [ ] 参数、对象编码、单位、执行状态及文档版本保存为结构化数据,不能只依赖自然语言摘要。 +- [ ] 受限的工具文本/JSON 原文放 PostgreSQL 的 cad_ai_tool_result 表(TEXT/JSONB),图状态只保存短结果和 resultCode;需要时鉴权后按页、字段读取。限制单条大小、每任务总量和保留期,禁止把数据库当作无上限文件仓库。 +- [ ] 截图与用户图片继续遵守既有数量、大小和模型能力限制;按当前请求/会话受限传递,不新增通用附件上传。若需要随检查点保存小图片,使用有总量及 TTL 限制的 PostgreSQL BYTEA 记录,不放公开 URL。 +- [ ] 不能把大量原文塞进图状态虚拟文件后,误以为它不会再增加检查点体积;模型视图与完整存储分离。 +- [ ] 继续使用已实现的 list_commands 精简目录、分页和 describe_command 精确读取,不丢失命令可发现性。 +- [ ] 静态命令 Schema 按引擎版本缓存;enabled、disabled_reason 等动态结果按当前文档重新检查。 +- [ ] 知识与 Skills 按有效上下文去重;正文已经被摘要/淘汰时允许重新读取。 +- [ ] 图片缩放及保留策略配置化,清理旧图后留下说明,不让长对话不断携带所有截图。 +- [ ] 记录系统说明、工具定义、目录、知识、Skills、历史、图片和推理状态的分类用量;区分估算和上游实际 usage。 +- [ ] 摘要和恢复调用也计入任务费用。缓存命中减少费用不等于缩小上下文。 + +## 6. Skills 与新增知识库 + +### 6.1 Skills 随 CAD 发布同步 + +- 当前 Java 资源先通过 solidcraft-main/scripts/sync-cad-ai-skills.mjs 同步,与最新源逐字节核对。 +- 新 Python 项目引入只读、版本化 Skills 资源。CAD 源码保持权威来源,发布生成清单包含 sourceCommit、engineBuild、skillsRevision、各文件 SHA256。 +- CI 检查漏项、旧版本、引用文件缺失、超限及路径穿越;校验失败不能发布。 +- 运行时只注入技能目录和说明,按任务读取正文及 references,避免每次推理都塞入全部文档。 +- 终端用户建模技能与仓库开发/发布技能分组。首期保留全部源资源,是否暴露某个分组使用明确配置;不要因打包过滤而悄悄删除建模能力。 +- Skills 无权提高工具权限;文档中提到桌面文件或系统能力,不会让网页绕过 gate。 + +### 6.2 新增知识库完整迁移 + +- 阅读目录与其登记的 17 份文档、版本、文件路径映射及 Markdown 原文迁入新服务构建资源。 +- 保留 knowledge_lookup(document_id)、knowledgeMode、cad-knowledge-v1 兼容含义及未知文档 not_found。 +- 保留模型自行选择文档的机制,不增加关键词强制路由或前置分类器。 +- 知识来源仍是受维护目录,不把模型传入的任意路径作为文件路径。 +- 保留正文完整性和有效历史去重;正文超大时可外置并提供完整重读,不直接按普通文本限额剪掉后半部分。 +- 新旧后台资源逐文件哈希对照,回归已知文档、未知编码、关闭模式、裁剪后重读及跨用户隔离。 +- 新 Python 服务直接读取自身打包资源;灰度期 Java 知识接口继续服务 v1,两个发布包都记录知识版本。 + +## 7. 前端改造清单 + +现有前端有两层,不需要改为 Vue/React。 + +| 层与位置 | 必须修改的内容 | 保留能力 | +| --- | --- | --- | +| Rust/WASM agent.rs、agent_tools.rs | 为 v2 增加服务端任务客户端,移除该路径的模型主循环和模型重试;消费状态、工具意图和确认事件 | v1 平台入口及桌面 API/ACP 的独立行为 | +| 公共 backend.rs、mod.rs、panel.rs | 映射任务状态、流式预览、同页面暂停/继续、输入问题、重连状态和可定位错误 | 现有聊天、工具卡片、权限确认和当前页面撤销分组 | +| platform.rs | AI 工具领取、执行、回执与修订校验,绑定页面实例和租约代次;不增加 AI 快照链路 | 现有文档桥接、内核与普通命令 API | +| 主站 app.js | 绑定新 AgentClient;页面离开或账号/项目切换时废弃旧执行权;页面重开使用新绑定 | 登录、打开项目、原本地草稿恢复和手动保存流程 | +| 主站 api.js / 新 agent-client.js | 新服务地址、鉴权、会话/任务 API、fetch SSE 游标续接、传输退避 | 原 CadApi 普通项目接口 | +| 当前页面 AI 状态 | 在本页内存保存页面实例、最后事件游标、工具收据和待确认操作;首期不新增 AI IndexedDB 持久层 | 原本地草稿和普通保存日志保持现有结构 | +| 构建与缓存 | 能力协商、版本化 WASM、资源哈希、灰度开关和旧构建保留 | 不手改生成的 cad/js 产物 | +| 自动化测试 | Node API、Rust 助手、Playwright、同页面断线、页面退出及租约失效场景 | 既有 CAD 手动操作回归 | + +普通文本、工具状态、询问用户和权限审批是不同事件。用户补充尺寸等业务信息时使用问题卡片,原页面有效时答复后继续同一任务,不能把“问用户”做成普通终止。持久化问题记录不赋予新页面继续旧任务的能力。 + +流式展示约束: + +1. 合法正文增量立即展示为当前 attempt 的临时文字。 +2. 未完整结束的正文不进入正式会话记录,也不能触发工具。 +3. 服务端确认一次模型步骤后,发出正文确认事件,前端以消息编码替换草稿。 +4. 当前尝试失败后清除其草稿,显示恢复状态;下一次尝试使用新的 attemptCode。 +5. SSE 重连根据序号去重,只补 UI 事件,不重新提交任务。 +6. 工具通知的事件回放不能作为执行授权;必须重新领取待执行工具。 +7. 取消、退出、换项目后清理未确认预览,已确认回答和设计修改保留。 + +## 8. 新接口与持久化清单 + +建议独立路由前缀 /api/cad-agent/v2;反向代理仅把这一前缀交给 Python,原 /api/cad/ai 与其他 Java 路由保持原行为。 + +| 接口 | 职责 | +| --- | --- | +| GET /capabilities | 能力、模型 profile、协议与资源版本 | +| POST /sessions | 建立账号、项目、页面实例及内存文档绑定的执行会话;刷新后新建绑定 | +| POST /sessions/{sessionCode}/messages | 幂等提交用户任务,返回 runCode | +| GET /runs/{runCode} | 查询任务权威状态 | +| GET /runs/{runCode}/events?afterSequence=... | fetch SSE 订阅和事件补发 | +| POST /runs/{runCode}/heartbeat | 更新执行端在线状态与短期绑定 | +| POST /runs/{runCode}/tools/{toolCallCode}/claim | 领取并校验当前执行授权 | +| POST /runs/{runCode}/tools/{toolCallCode}/result | 幂等提交工具回执 | +| POST /runs/{runCode}/pause、resume、cancel | 显式控制任务;resume 仅用于原页面仍有效的暂停/重连,校验页面与文档,不支持退出后续跑 | +| POST /runs/{runCode}/answers | 回复持久化问题或审批 | +| GET /tool-results/{resultCode} | 鉴权后分页/按字段读取受限的工具结果,无对象存储或上传签名接口 | + +事件至少包含 eventCode、sequence、sessionCode、runCode、attemptCode、事件类型和内容;所有对外身份均使用业务编码,不暴露数据库主键。 + +SSE 只承担传输;业务事件先持久化再发布。事件日志有保留期限与状态基线补齐机制,游标过旧时先返回当前状态及已确认消息;这里的状态基线不包含 CAD 文档快照。断开订阅不等于取消 run,但原执行端离开或租约超期后必须结束旧任务。 + +建议应用表: + +| 表 | 用途 | +| --- | --- | +| cad_ai_session | 用户、项目、资源版本和会话配置 | +| cad_ai_run | 用户任务、状态、预算、页面绑定及执行端丢失原因 | +| cad_ai_message | 确认消息及内容引用 | +| cad_ai_tool_execution | 意图、顺序、参数哈希、执行状态与回执 | +| cad_ai_event | 有序、可补发的业务事件 | +| cad_ai_tool_result | 受限工具文本/JSON,以及按需启用的受限小图片;记录归属、哈希、大小和保留期,不保存 CAD 恢复快照 | +| cad_ai_work_item | 可恢复调度、待发布通知/续接任务 | +| cad_ai_document_lease | 文档写入租约、代次和过期时间 | +| cad_ai_question | 等待用户的问题、审批和幂等答复 | + +Graph 检查点使用官方 PostgreSQL 适配器自身的表,单独记录版本及升级流程,不手写一套检查点序列化。所有用户数据有归属、创建/更新时间、保留策略与删除流程。重要唯一约束包括用户提交编码、run+toolCallCode、会话+事件序号。 + +## 9. 部署、隐私和运维 + +- [ ] 新后台、PostgreSQL 和 Redis 使用独立凭据与数据命名空间,不共享原业务数据库权限。 +- [ ] 首期部署不要求 OSS、对象存储密钥或私有路径。工具结果按账号/项目/任务鉴权读取,禁止为省事改用公开 URL。 +- [ ] 同源代理优先,生产检查 SSE 缓冲、心跳、空闲超时和连接清理;API 与 SSE 禁止 Service Worker 缓存。 +- [ ] 本地继续从 8091 进入;新增后台只通过受控本机/容器网络接入,不随意启动额外前端端口。 +- [ ] health/readiness、优雅停机、Worker 租约回收、连接池和队列背压作为首期交付内容。 +- [ ] 各用户/项目的速率、并发、模型调用、修改次数、token、图片大小及数据库结果存储配额受限。 +- [ ] 建立任务、事件及数据库工具结果的保留和清理策略,活动检查点仍引用的必要结果不得提前删除。 +- [ ] 监控模型失败、恢复次数、暂停原因、首字时间、工具耗时、token 分类、队列和存储用量。 +- [ ] 日志包含 requestId、sessionCode、runCode、toolCallCode、供应商、模型 profile、阶段、错误类别、耗时和资源版本。 +- [ ] 不记录密码、Token、签名 URL、原始推理、完整设计及未处理的上游错误正文。CAD 数据不默认上传外部 tracing 平台。 +- [ ] 发布固定 Graph/状态格式版本。服务更新期间只对仍有效的原页面任务进行校验后续接;不兼容时明确结束,不让旧代码误读检查点后继续修改。 + +## 10. 必须通过的验收清单 + +| 测试组 | 必须验证的行为 | +| --- | --- | +| 模型协议 | 现有三厂商协议不变,工具参数、续接和模型配置正确;不调用真实厂商的模拟测试先通过 | +| SSE | 中文 UTF-8 分片、CRLF、跨包、心跳、断流、缺终态、重复/乱序事件及过旧游标 | +| 尝试级预览 | completed 前可看到文字;失败草稿清除;重连不重复提交回答 | +| 服务端恢复 | 原页面与文档仍有效时,在模型等待、写回执前后或 Graph 续接前后重启 Worker,校验执行端后继续且不重跑确认操作;执行端丢失则结束 | +| 浏览器连接与退出 | 同页面短暂断线后补事件和回执;关闭、刷新、崩溃或重连超时后旧任务结束,新页面不能接管旧任务 | +| 操作不确定窗口 | CAD 成功但回执丢失时先用原页面收据对账;页面已丢失或无法确认时不盲重放、不伪报成功 | +| 文档一致性 | 手动修改、云版本变化、引擎变化、多标签、旧租约和迟到响应都不能修改错误文档 | +| 权限 | 用户/项目/会话/工具结果隔离;登录失效、删除项目、原站权限接口不可用时拒绝新授权 | +| 上下文 | 长对话与单轮多工具都在请求前控预算;摘要后保留约束和对象编码;大结果可完整回读 | +| 目录与知识 | list_commands 不漏可发现命令;Skills 与源一致;知识原文/路由/模式/裁剪后重新读取正确 | +| 预算 | 重试无叠加,单次调用与整个任务预算分离;耗尽后可解释并按规则暂停,继续仅限有效原页面 | +| 取消 | 停止后无新操作,正在执行的步骤真实收尾,已修改内容准确保留 | +| 原业务 | 账号、社区 AI、CAD 打开、手动保存、普通业务接口与原有限额不回归 | +| 升级/回退 | 新旧前端、后端、资源清单及缓存组合正确;会话不在 v1/v2 中途互相接管 | + +真实模型使用固定 profile、参数、CAD 初始文档和任务样例,分别记录建模成功、恢复成功、总输入/输出、费用及耗时。先测当前基线,再确定真实任务成功率门槛;模拟测试全部通过不等于模型任务 100% 成功。 + +旧验收记录中存在一次 CadAiTest 异步 SSE 结果为空、复测通过但根因未明的情况。新实现必须以可控时钟/事件同步与断连故障注入覆盖生命周期,不能把偶然复测通过当作修复。 + +## 11. 实施顺序与阶段验收 + +| 阶段 | 可评审交付与退出条件 | +| --- | --- | +| 基线与技术验证 | 固定 0.43 资源;验证三协议、浏览器工具等待/同页面续接、PG 检查点和版本化工具集,包含退出后旧任务失效 | +| 新后台骨架与持久任务 | 独立服务、原站鉴权适配、会话/任务、PG/Redis、执行端租约和事件日志;服务重启先校验原页面 | +| 工具桥与页面保护 | Rust/JS 执行授权、顺序执行、幂等回执、同页面重连和修订冲突处理;无已确认操作自动重复执行 | +| 模型/上下文/资源迁移 | 三协议适配、预算、摘要、PG 工具结果按需读取、Skills 和知识完整校验 | +| 流式与任务交互 | 实时文字、清理草稿、状态卡、提问、同页面继续/停止及执行端丢失提示 | +| 故障回归与小范围灰度 | 自动化、真实样例基线、小规模压力观察、打包部署、回退演练和已知限制 | + +实施优先顺序:工具与文档安全 → 同页面断线和重试可靠性 → 流式与上下文 → 小范围真实模型质量 → 按数据扩容。跨页面任务恢复、AI 文档快照、对象存储、联网搜索、多子 Agent、语义向量知识库和管理控制台作为后续独立增强,不阻挡首期交付。 + +## 12. 灰度与回退 + +1. 单独部署 Python API/Worker、PostgreSQL 和 Redis,不要求对象存储,不替换原 Java 服务。 +2. 新前端以账号/会话灰度开关选择 v1 或 v2;同一会话固定运行时。 +3. 先用模拟模型完成断线、重启、重复回执和文档冲突测试。 +4. 固定模型与样例小范围验证,核对模型配置、资源版本、token 和恢复效果。 +5. 灰度期保留旧 WASM/manifest,校验实际 HTTP 文件长度及哈希,防止旧缓存混用。 +6. 新任务可关闭 v2 回到 Java v1;已有 v2 任务先停止分发、明确结束并保留记录,不把中途任务直接交给旧循环。设计修改由原有保存/草稿机制处理。 +7. 新后台自身回退需检查 Graph/状态格式兼容,不通过删除新库记录作为“回滚”。 + +## 13. 完成后的效果与边界 + +| 用户能看到的效果 | 形成该效果的机制 | 边界 | +| --- | --- | --- | +| 同页面网络短暂波动后继续 | 有效原页面、持久事件、SSE 续接、回执对账和有限模型重试 | 页面退出、文档绑定失效或超过宽限期后旧任务结束 | +| 不要求私有 OSS 即可部署 | 大型工具文本/JSON 在受限 PG 结果表中保存并鉴权读取 | 首期不提供退出后续跑、AI 文档快照或通用附件服务 | +| 长对话输入受控 | 每步预算、摘要、结构化记忆、数据库大结果按需读取 | 摘要有质量风险,不能承诺无限任务或零信息损失 | +| 失败原因可定位 | 固定错误类别、阶段、关联编码和恢复次数 | 不能让上游永远返回正确响应 | +| 不因重试重复挤出/删除 | 幂等账本、领取授权、页面与文档代次、不确定状态对账 | 无法对账时暂停或结束,不冒险重放或声称 exactly-once | +| 正文持续流式显示 | 尝试级草稿和确认事件 | 模型思考等待期间显示状态,不伪造正文 | +| 多模型选择可控 | 版本化 profile、协议适配与能力协商 | 更换模型会改变质量,不自动切厂商 | +| 知识与技能继续有效 | 原文、哈希、按需读取、有效上下文去重 | Skills 不能代替权限或几何验证 | +| 产品具有多用户隔离基础 | 独立归属、租约、限额、工具结果鉴权和脱敏监控 | 首期不宣称未经压测的并发容量 | +| 原站其他业务保持原行为 | 新服务与新路由隔离,Java 只被调用现有读接口 | 原站授权不可用时需要安全暂停 | + +## 14. 最终交付物 + +- 独立 Python 后台工程、依赖锁文件、CI、镜像及 API 契约。 +- Rust/WASM 与主站 JavaScript 改造、构建包和对应版本清单。 +- CAD AI PostgreSQL 数据设计与单独 DDL、官方检查点迁移及备份说明。 +- Skills/知识完整迁移和资源同步/打包校验。 +- 任务/工具/事件状态机、同页面重连、页面退出及冲突处理说明。 +- 模拟故障回归、真实模型同条件基线、小范围灰度记录。 +- 部署配置、监控、数据保留、清理、升级与回退操作说明。 + +## 15. 框架依据 + +以下为官方资料路径;实施时以锁定版本的公开接口和实际契约测试为准: + +- `https://docs.langchain.com/oss/python/deepagents/overview` +- `https://docs.langchain.com/oss/python/deepagents/context-engineering` +- `https://docs.langchain.com/oss/python/deepagents/backends` +- `https://docs.langchain.com/oss/python/deepagents/skills` +- `https://docs.langchain.com/oss/python/langgraph/persistence` +- `https://docs.langchain.com/oss/python/langgraph/interrupts` +- `https://docs.langchain.com/oss/python/langgraph/durable-execution` + +Deep Agents 提供 Agent 工程基础,LangGraph 提供状态与持久化基础。首期仍须完成浏览器几何副作用、原站权限、页面绑定、业务事件回放和产品级故障验收;跨页面任务恢复及文档快照已明确延后。 + +## 16. 本次 Java Skills 同步结果 + +- 来源提交:ade571ebe95bd3b2dff3fff744ee33f584f76fe0(本地 CAD 0.43.0 基线)。 +- 使用既有 sync-cad-ai-skills.mjs 同步,19 个 Skills、32 个文件,新增 2 项,14 个既有 SKILL.md 正文更新。 +- 资源 revision:b9c715912afefe96fa839a749f804d42d86724b258a7e56c48c32d73c2ccbca1。 +- skills.json 文件 SHA256:9d71ac78011b890c182e4ef28da15a52cc9714cc777f7fef2c806e63489a90a6。 +- 4 个既有测试文件同步更新技能数量及资源哈希断言;Java 生产代码和模型配置未改。 +- JDK 21 下 6 个 CAD AI 测试类共 120 项通过,0 失败、0 错误、0 跳过;覆盖资源、协议、模型适配、知识读取和 API。 +- 首次沙箱测试因本机模拟 HTTP 端口绑定被拒绝;获得执行权限后相同测试全部通过,未调用真实模型。 +- 最终 JAR 内 Skills 与源文件字节完全一致,37 个打包知识资源与当前源哈希一致,40 个受检知识源文件未改。 +- 发现并移除 1 个仅存在于 target/classes 的过时知识文件后重新打包,未修改知识源文件。 +- 验证记录:/Users/lk/Projects/vibemake相关项目/community/target/cad-ai-skills-sync-20261116/verification-summary.json。 +- 构建完成,未重启运行服务,未提交 Git。 diff --git a/docs/cad-ai-modeling-skills-audit-20261117.md b/docs/cad-ai-modeling-skills-audit-20261117.md new file mode 100644 index 0000000..4c883cf --- /dev/null +++ b/docs/cad-ai-modeling-skills-audit-20261117.md @@ -0,0 +1,618 @@ +# CAD Agent 建模能力、Skills 与提示词全量梳理 + +审计日期:2026-11-17。目标:为继续优化 CAD 生成效果建立可核对的能力清单,重点是几何构造、参数化、工具使用、建模规范和验收;不展开摘要、缓存、会话恢复等通用 Agent 工程。 + +本报告基于当前本地工作区源码。核对了 community 的 Java v1、独立 cad-ai-server 的 Python v2,以及 solidcraft-main 的共享技能和原生工具实现。没有调用真实模型,没有改业务代码或运行中的服务。本次同步检查成功,不代表线上部署已核对,也不代表建模效果已重新验证。 + +## 1. 先明确当前到底有多少内容 + +| 层次 | 当前实际内容 | 如何影响生成 | +| --- | --- | --- | +| 共享常驻工作流 | `solidcraft-main/skills/agent-workflow.md` | 每次推理的系统提示包含它,规定先理解、计算、分阶段构建、测量、改参、修复 | +| makeCAD Skill 集合 | **19 个 Skill、32 个文本文件** | 系统提示包含目录和描述,正文通过 `skill_reference` 按需读取,并非 19 份全文常驻 | +| 直接相关 Skill | **5 个核心建模 Skill+1 个故障复现/报告 Skill** | modeling、editing、checking、mechanisms、sheetmetal;辅助 reporting | +| 零件专用运行规程 | **17 份:15 份齿轮/传动+球轴承+XZ 筋板风险提示** | 通过 `knowledge_lookup` 按目录读取,属于实际建模知识,但并不是 17 个 `makecad-*` Skill | +| 工具契约 | 11 个基础浏览器 CAD 工具,另有 Skill/知识读取及 v2 的研究、读图等服务工具 | 限定怎样发现命令、执行、测量、校验和观察 | +| 离线知识 | 203 类分类目录、6 个完整零件族、9 份共享特征、6 份完整示例,以及候选和历史证据 | 不会因为存在于仓库就自动进入生产模型上下文 | + +**最需要避免的误解:**“有文件”“已打包”“模型能读取”“这次确实读了”“依规程执行了”“最终几何正确”“改参仍正确”“统计上提高成功率”,是不同层次。 + +历史资料多处仍写 17 个通用 Skill。当前实际已是 19 个;同步脚本校验结果一致,不能继续用旧数字判断现状。 + +## 2. 真正生效的提示词来自哪里 + +### 2.1 Java v1:community + +入口:[ArkCadAiClient.java](../vibemake-service/src/main/java/com/linkerbot/vibemake/service/cad/ai/ArkCadAiClient.java),主要看 `SYSTEM` 和 `instructions()`。 + +系统提示组合: + +1. [CadAiTools.java](../vibemake-service/src/main/java/com/linkerbot/vibemake/service/cad/ai/CadAiTools.java) 读取打包的 [skills.json](../vibemake-service/src/main/resources/cad/ai/skills.json)。 +2. 拼接共享 `workflow`、19 个 Skill 的名称、描述和文件目录。 +3. 知识功能开启且请求声明 `cad-knowledge-v1` 时,拼接 [CadAiKnowledge.INSTRUCTIONS](../vibemake-service/src/main/java/com/linkerbot/vibemake/service/cad/ai/CadAiKnowledge.java)。 +4. 再拼接浏览器环境规则:仅修改当前设计、精确查询命令、优先参数表达式、按测量证据报告、不能通过工具保存云端文件等;这部分明确优先于 Skill 中的桌面示例。 +5. 协议恢复时再追加纠错提示;不属于新增建模知识。 + +Java 知识提示有一条很具体的质量约束:**除用户明确要求运动学占位,不能把齿轮擅自降级为无齿圆柱。** + +读取目录的 17 项名称和摘要由 `knowledgeDefinition()` 放进 `knowledge_lookup` 工具说明。Java 的新读取请求需要 `document_id`。知识默认配置为 `off`;`pilot` 和 `enabled` 都展示同一个直读工具,当前不再按 experimental/approved 决定哪些正文可读。这里只描述代码默认值,没有读取私有 `.env` 推断现场设置。 + +### 2.2 Python v2:cad-ai-server + +入口:[resources.py](../../cad-ai-server/src/cad_ai/resources.py),主要看 `Resources.prompt`、`skill()`、`knowledge()`;实际模型调用覆盖见 [runtime.py](../../cad-ai-server/src/cad_ai/runtime.py) 的 `CadRuntimeMiddleware.awrap_model_call()`。 + +系统提示组合: + +1. `codex_reference/agent_rules.md`:自主完成、只按证据报告、错误后诊断等通用操作规则。 +2. 同一份共享 `workflow`。 +3. 同一份 19 个 Skill 目录。 +4. 浏览器执行、参考图、公开资料研究等规则。 +5. 当前文档修订等运行数据;与建模知识本身分开。 + +v2 与建模效果直接相关的补充: + +- **参考图先读再建模**:记录看得清的尺寸和未解决细节;历史截图不能当成当前文档;精确几何优先用 CAD 测量。 +- `read_image` 可重新读取会话中的参考图或截图,能力取决于所选模型 profile 是否支持图像。 +- **外部规格有依据**:需要时用 `web_search`、`read_web_page` 查公开事实,优先制造商/一手来源,保留单位并区分事实与假设。 +- [search.py](../../cad-ai-server/src/cad_ai/search.py) 另有研究提示,要求返回来源、精确单位、不猜缺失事实;返回的是有来源的摘要,不等于网页全文。 +- 只为无法推断或检查、且影响正确性的必要问题使用 `ask_user`。 +- 不知道参数时读 Schema,已有准确 Schema 可以复用。 + +**重要差异:**v2 的 `knowledge_lookup({})` 先返回目录,带 `document_id` 才读正文;17 条摘要没有像 v1 那样直接展开在工具说明里。v2 没有自动拼入 Java 的 `CadAiKnowledge.INSTRUCTIONS`,包括其中明确的“齿轮不得降为无齿圆柱”原句。是否影响选文和降级行为,需要正式任务比较,不能仅凭提示差异宣布效果下降。 + +**不要改错提示文件:**`cad-ai-server/src/cad_ai/codex_reference/prompt.md` 是上下文摘要提示,`runtime.py` 将它读为 `COMPACT_PROMPT`;它不是日常建模主提示。通用模型行为在 `agent_rules.md`,建模行为主要在 `Resources.prompt` 与共享工作流/Skills。 + +### 2.3 权威来源和同步关系 + +```text +solidcraft-main/skills/ + ├─ agent-workflow.md + └─ makecad-*/SKILL.md、reference、scripts、templates + │ scripts/sync-cad-ai-skills.mjs + ▼ +community/vibemake-service/src/main/resources/cad/ai/skills.json + │ cad-ai-server/scripts/sync_resources.py + ▼ +cad-ai-server/src/cad_ai/data/skills.json + +community/knowledge/cad-parts/generation/reading-catalog.json + └─ 精确登记的 17 份 Markdown + ├─ Java Maven resources 打包为 classpath 资源 + └─ Python sync_resources.py 复制为 data/knowledge/ 资源 +``` + +修改原生建模 Skill 应改 `solidcraft-main/skills/`,再同步;不要仅手改 Java/Python 的副本。修改零件规程应改 community 中目录实际指向的 canonical Markdown,再同步 Python 资源。发布仍须构建相应 Java/WASM/Python 产物;本报告未执行发布。 + +## 3. 常驻工作流已经规定了哪些建模规范 + +来源:[agent-workflow.md](../../solidcraft-main/skills/agent-workflow.md)。 + +| 阶段 | 当前要求 | 试图避免的问题 | +| --- | --- | --- | +| 理解需求 | 将自然语言转成功能、零件/装配结构、尺寸、参数、特征顺序和验收条件 | 只按外观关键词堆几何,漏结构 | +| 缺省信息 | 关键缺失先澄清,普通选择声明合理假设 | 任意编造安装尺寸或反复问无关问题 | +| 初始检查 | 即使看起来是空白,也先精简 `inspect_design` | 误清已有设计、误判当前状态 | +| 数学规划 | 先算参数、位置、阶段体积、包围盒及拾取世界坐标 | 边建边猜、无法知道结果是否合理 | +| 命令发现 | 筛选 `list_commands`、准确 `describe_command` | 猜工具名、命令 ID 或参数字段 | +| 构建策略 | 分阶段 batch、命名特征;板/块/柱/孔等优先带表达式的原语 | 大量脆弱草图、无可编辑参数链 | +| 特征顺序 | 一般先外圆角再抽壳,再内部结构,最后贯墙孔槽 | 抽壳失败、后加材料堵孔 | +| 孔深度 | 盲孔及只穿空心件一层壁的孔必须明确深度 | 默认 through-all 误穿另一壁 | +| 参数传播 | 相关尺寸/位置必须存为表达式、草图尺寸或阵列间距 | 看似参数化,修改后孔位等不动 | +| 草图 | `sketch.solve` 验证 dof=0 | 改参后漂移、翻边、无报错变形 | +| 拾取 | 使用计算过并验证的世界坐标,不能乱猜 | 圆角/抽壳挑错边面 | +| 阶段验收 | measure 对比独立计算;查实体数、bbox、圆柱轴等 | `ok` 但切空、Join 未接上、孔位错 | +| 改参测试 | `check_parameters` 并确认恢复;或修改、测量、恢复 | 只对默认尺寸有效 | +| 修复 | 优先改原特征/参数,checkpoint 做有限试验 | 整件重建、重复操作、破坏下游 | +| 完成标准 | 报实际结果、测量证据和剩余限制 | 仅凭截图或结束话术宣称完成 | + +这些是模型侧要求,读取或遵循并非全部有程序硬门禁;后面单列硬检查。 + +## 4. 直接相关的 6 个 Skill + +### 4.1 makecad-modeling:新零件如何构造 + +来源:[SKILL.md](../../solidcraft-main/skills/makecad-modeling/SKILL.md)、[reference.md](../../solidcraft-main/skills/makecad-modeling/reference.md)。 + +**适用:**新零件、壳体、支架、安装板、法兰及其他实体。通常与 checking 同用。 + +具体内容: + +- 建模前列参数、原点、全部特征与拾取点、预期体积和包围盒。 +- 常见顺序:参数/草图/首特征 → 圆角与抽壳 → 孔、切除、阵列。风险布尔单独一个 batch。 +- 已有合适原语时直接用 box/cylinder/hole 等;其他轮廓用草图。 +- 位置要通过表达式、相对边引用或草图尺寸跟随参数;普通数字不会自动变成依赖。 +- 草图 ID 按类型计数,但矩形构造对角线、轴约束新增构造线等会改变后续编号,不能忽略。 +- 选边点是普通数值世界坐标;存储的拓扑拾取可随改参跟随,不应把表达式塞进 edge pick。 +- 原生镜像/阵列保留参数依赖;不能把一个 mirror/pattern 特征再次当作同类特征的输入;某些情形可改用 bodies。 +- 多个草图区域的默认拉伸含嵌套孔洞语义;不能把第三个内圆生成的独立圆盘误当孔。 +- 圆角/抽壳有例外:被移除面边缘的圆角应在抽壳后;曲面之间的圆角可能导致抽壳不支持。 +- 曲面相切处 primitive boolean 失败时,用草图轮廓拉伸切除等已有替代策略。 +- 每阶段量体积/bbox/面数;改参后复测;孔柱位置用圆柱轴/原点/半径核对;末尾看 iso,内部特征补 top。 + +**reference 的实际价值:**不是泛泛“画得准确”,而是具体命令形状、单位、坐标、ID、错误修复和一个可运行安装板示例。 + +特别容易影响效果的规则: + +1. 平面映射:XY=(+X,+Y),法向+Z;**XZ=(+X,−Z),法向+Y**;YZ=(+Y,+Z),法向+X。 +2. `rectangle.center` 额外产生两条构造对角线,不能按普通四线矩形推断所有 ID。 +3. 圆心用 `c1.center`,不是猜一个 `p1`;尺寸到圆边与到圆心不同。 +4. 草图距离通常无符号,几何要先画在正确一侧。 +5. 圆角拾取按最近拓扑解析;多个体位置重合时应限定 body。 +6. 空切可能返回成功;显式 `operation` 和 `targets` 很重要。 +7. pattern count 包含原件,重复实体名称可能被自动改名,后续必须用实际创建结果。 +8. `measure` 有数值误差,不能把统一的零误差当所有模型的目标。 + +**贡献的能力:**通用实体生成策略、稳定的命令使用方式、可编辑性、基础尺寸/位置验证。 + +### 4.2 makecad-editing:已有模型如何改和修 + +来源:[SKILL.md](../../solidcraft-main/skills/makecad-editing/SKILL.md)。 + +- 先精简 inspect,再用 `parameters.list {filter:"feature"}` 一次找特征输入 d1/d2 等,并做 measure 基线。 +- 改数值优先 `parameters.change`;固定值参数化:先加用户参数,再替换原输入表达式。 +- 改 profiles、方向、operation、拾取等结构性信息时用 `timeline.inspect`+`timeline.edit`。 +- 中间插入特征用 `timeline.roll_to`,插入后回时间线末尾,核对所有下游特征。 +- 删除前读 `timeline.dependents`。 +- 风险编辑先单独 checkpoint;restore 会消耗该 checkpoint,不能无限复用;只保留最近 16 个。 +- “高 2 mm”优先保留原相对设计意图,例如 wall+6 → wall+8,说明理解。 +- 成组独立修改后对照总预期变化;不匹配再还原、分项定位。 +- 位置变化可不改变体积,必须查世界坐标或质心变化;内部特征补顶视。 +- 改参验证后恢复原值;不通过删除重建掩盖原问题。 + +**贡献的能力:**保留历史、参数依赖与零件身份,局部修复,减少“修改一次整件重画”。 + +**浏览器边界:**文中的 open/save、崩溃恢复 CLI 等桌面能力不等于网页端可调用;受宿主工具限制。 + +### 4.3 makecad-checking:防止无报错但做错 + +来源:[SKILL.md](../../solidcraft-main/skills/makecad-checking/SKILL.md)。 + +核心检查: + +- 参数注释写范围和整数性;当前引擎不会因为写了注释就强制所有用户改参都遵守范围。 +- 共用表达式提升为命名参数,用户关注的结构各自命名;可把驱动参数设 favourite。 +- 每个草图 dof=0;量体积、bbox、质心,关注 warning。 +- 遍历参数允许范围两端,并连续改回默认;有些错误在“到达零尺寸后的下一次修改”才出现。 +- 计数 0 会重建失败,分数可能被圆整,但位置表达式未圆整,导致阵列和居中不一致;应写清整数并统一 `round(n)` 语义。 +- 零距离尺寸可能丢失所在侧;需要通过对齐约束或外部基准避免跨零。 +- 外切正多边形即便有尺寸和一条竖边,也可能剩 1 dof,需 polygon 约束。 +- Boolean retry 的 warning 可能伴随真实几何错误,也可能是体积吻合的小扰动,不能一律当成功或失败。 +- 表达式支持的函数和单位有边界:无 if/比较运算;asin/acos/atan/atan2 有角度单位;计数必须无量纲。 +- 重名 body 会静默重命名,targets 可能只指向第一件。 + +附属文件与可用边界: + +| 文件 | 做什么 | 当前网页 Agent 能直接执行吗 | +| --- | --- | --- | +| `scripts/run.py` | 调 CLI 执行脚本,输出 FAIL/WARN/SKETCH/BODY;可检查中间状态 | 不能;读取源码不等于具备 shell/CLI | +| `scripts/scb.py` | 生成 fully constrained 的圆、六角形、圆角矩形与定位尺寸;拒绝重名 | 不能;可作为离线构造辅助 | +| `scripts/compare_step.py` | 独立 STEP 形体对称差/xor,默认阈值 1e-3 mm³,并定位差异块 | 不能;需要外部运行环境与 STEP 文件 | +| `reference/porting.md` | 迁移模型的坐标对齐、显式近似、逐参数 STEP 对比 | 只能理解流程,执行取决于外部能力 | +| `templates/test_design.py` | 同一会话连续参数变化,对比冻结的体积/面积/COM/bbox | 不能;供仓库中的设计回归 | +| `scripts/tests/test_*.py` | 校验上述助手、行为陷阱和约定本身 | 离线维护测试,不是模型自动验收 | + +**贡献的能力:**参数稳健性、错误识别、独立几何比较。最重要的是补上“工具没有报错”与“满足设计”之间的差距。 + +### 4.4 makecad-mechanisms:装配与运动 + +来源:[SKILL.md](../../solidcraft-main/skills/makecad-mechanisms/SKILL.md)、[reference.md](../../solidcraft-main/skills/makecad-mechanisms/reference.md)。 + +- 先计算组件、固定件、关节、世界点/轴、限位、传动比、闭环关系与最终回到的姿态。 +- 运动上是两件的东西必须拆组件,例如执行器筒体与活塞杆。 +- 每条运动链最终连到固定件;浮动链 dof=6,驱动可能 `moved:false`。 +- 已经摆好位置的件优先 as-built joint;两端同世界轴时 `flip:true` 避免装配后翻转 180°。 +- 使用明确 occurrence;多次实例化的子装配还要对应 path,防止关节连到另一份实例。 +- 开链可批量加,闭环关节分开加并检查 conflicts;加入关节前后比较 occurrence.properties,防止零件跳位。 +- 角度用度,位移 mm;关节超限可能被钳制,并不一定报错。 +- motion_link:b=ratio*a+offset;ratio 要按两侧单位计算,不能把 mm/rad 直接当 mm/deg。 +- gear/rack_pinion/screw 由半径、齿距等参数派生;cam 有轮廓、刀尖/滚轮/平底从动件等定义。 +- 闭环检查行程与铰角的独立几何关系;只驱动主动关节,从动件由约束求解。 +- contact、interference、clearance、joint.sweep/find_limits、motion.study/play/export/trace/plot 分别解决碰撞、范围、轨迹和速度等检查。 +- `truncated` 或 `unchecked` 不能被理解成全程无干涉;静态姿态正确不能代表动态正确。 +- 最后恢复约定姿态;URDF 是树,不能保留所有闭环关节。 + +**贡献的能力:**正确的组件/关节建模、传动单位、闭环、限位与运动验收。它不负责把光滑圆柱变成真实轮齿,也不等于接触仿真。 + +### 4.5 makecad-sheetmetal:钣金与自然语言折弯 + +来源:[SKILL.md](../../solidcraft-main/skills/makecad-sheetmetal/SKILL.md)、[reference.md](../../solidcraft-main/skills/makecad-sheetmetal/reference.md)。 + +- 按 sheet metal 特征建,不用普通块体拼出来后就声称可展开。 +- 先查 `sheet.rules`,厚度、K-factor、半径、避让和 gap 来自规则;K-factor 不能凭空编造。 +- base flange 先于 edge flange;支持 path_flange、hem、fold、convert、unfold/refold 等。 +- `segments` 是对一条边的连续分区,from/to 为 0..1 纯数字,不接受表达式;从 0 铺到 1,不能留洞、重叠或误当 set-back。 +- 不对称分区必须核对方向;段上的 angle/height/flip 覆盖边级/特征级值;flip 不是相对翻转。 +- segments 与 then 不兼容;弯曲窄于 relief 可能产生 warning;普通实体特征改变钣金体后可能不能再生成 flat pattern。 +- 折弯算术:BA=θ(R+kT),θ 为弧度;回退量、腿长、展开尺寸由 angle/position/height_from 共同决定。 +- `sheet.flat_pattern` 与 JSON bend table 复核展开外形、折线、角度、方向、长度、allowance;还要做配合干涉/间隙检查。 +- 自然语言推断要说明分区/角度的假设、置信度与备选;几何与描述矛盾则先解决。 +- 优化最多 8 组分区/角度/高度/侧向候选,以干涉为零、间隙够、板材放得下、半径满足规则为目标,并记录数值。 + +**贡献的能力:**制造语义较强的钣金构造、折弯参数解释、展开检查与有限搜索。 + +**版本边界:**文内仍有 feature branch / PR #9911 等说明,不能用文件存在推断当前部署全部支持;要查询实际命令 Schema。网页导出文件也受宿主权限约束。 + +### 4.6 makecad-reporting:把建模失败转成可定位问题 + +来源:[SKILL.md](../../solidcraft-main/skills/makecad-reporting/SKILL.md)、[report-template.md](../../solidcraft-main/skills/makecad-reporting/reference/report-template.md)。 + +- 记录版本、确切命令和错误、预期与实际数值。 +- 在独立设计中复现,删到不能再删的最小脚本;找边界如圆角 5 失败而 4.9 成功。 +- 空切、选错边等不能只信 ok,必须实际测量。 +- 对慢操作记录每步耗时及规模变化;不能无限盲等或原样重试崩溃命令。 +- 报告模板整理复现、预期、实际、截图与限制,用户文件不能擅自上传。 + +**贡献的能力:**更快定位“提示错误、参数错误、几何方法错误、内核问题”。主要为失败排查服务,不直接增加某类零件构造能力。 + +## 5. 当前可读的 17 份零件规程:逐份做了什么 + +真源:[reading-catalog.json](../knowledge/cad-parts/generation/reading-catalog.json)。下述“检查”是正文要求,不代表本次或每次都会自动执行。 + +### K01 外渐开线直齿轮 + +- ID:`involute-spur-gear`;版本 0.2.0;[原文](../knowledge/cad-parts/generation/candidates/involute-spur-gear-equation-v2.md)。 +- **构造:**根圆柱 → 两条方程渐开线+径向根线+齿顶弧闭合单齿 → 单齿 Join → 特征圆周阵列 → 按需轮毂/孔/键槽。 +- **解决:**手工展开采样点出错、漏掉 `sqrt(1+t^2)` 导致一圈圆包、角度/弧度错、未 Join 就阵列成多体、键槽不与轴孔贯通。 +- **检查/边界:**20°、零变位/侧隙、18–40 齿,基圆以下径向简化;检查实际曲线、齿厚/齿数、单体和孔槽。`atan(t)/(1 rad)` 必须保留;键槽从孔腔切到用户给定槽底,不能留月牙。 + +### K02 内直齿轮 + +- ID:`internal-spur-gear`;版本 0.1.0;[原文](../knowledge/cad-parts/generation/candidates/internal-spur-gear-v1.md)。 +- **构造:**环坯 → 从内孔跨入材料的闭合渐开线齿槽 → Cut → 阵列齿槽特征。 +- **解决:**内/外齿公式混用、把外齿缩小放到环里、齿槽不连通、切穿外缘。 +- **检查/边界:**36–100 齿,`outerRadius>rootRadius>tipRadius>baseRadius>0` 等条件;内齿顶朝内、齿根朝外;区分 +X 齿中心和槽中心,检查实际齿廓与最薄轮缘。 + +### K03 外斜齿圆柱齿轮 + +- ID:`helical-cylindrical-gear`;版本 0.1.2;[原文](../knowledge/cad-parts/generation/candidates/helical-cylindrical-gear-v1-2.md)。 +- **构造:**开口扇区链在草图圆周阵列成完整闭合齿圈 → 轴线路径上 parallel sweep+twist → 再孔槽。 +- **解决:**单齿扭转后逐齿 Join 布尔缝失败、法向模数直接当端面模数、β 被直接当总 twist、根圆/基圆分支画错。 +- **检查/边界:**`mt=mn/cosβ`,总扭转 `b*tanβ/rp`;根圆小于/大于基圆有不同扇区;沿 Z 检查真实曲线相位、齿向和旋向,不能只看体积。 + +### K04 直齿齿条 + +- ID:`straight-rack`;版本 0.1.0;[原文](../knowledge/cad-parts/generation/candidates/straight-rack-v1.md)。 +- **构造:**基座+伸入基座的梯形单齿 Join+线性特征阵列。 +- **解决:**误用圆齿轮渐开线、三角齿、齿底只相贴、阵列连基座一起复制、齿数多算一个。 +- **检查/边界:**p=πm、节线齿厚=p/2、压力角直线斜率、完整 N 齿/内部 N−1 槽、解析体积;用户指定总长时不能静默替换成 Np。 + +### K05 斜齿齿条 + +- ID:`helical-rack`;版本 0.1.1;[原文](../knowledge/cad-parts/generation/candidates/helical-rack-v1-1.md)。 +- **构造:**法向转端面参数 → 梯形齿 → 有横向位移的直线路径 parallel sweep → Join+直线阵列,不加 twist。 +- **解决:**把直齿条整体旋转当斜齿条、用扭转代替平移、XZ 符号错、端部齿被裁掉。 +- **检查/边界:**1–96 齿,0<|β|≤35°;ΔX=b*tanβ,样板长度 Npt+|ΔX| 不是用户总长的默认替代;检查实际斜齿线、工作面共面性和两端完整齿数。 + +### K06 ZA 圆柱蜗杆 + +- ID:`worm`;版本 0.1.1;[原文](../knowledge/cad-parts/generation/candidates/worm-za-v1-1.md)。 +- **构造:**延长芯轴+YZ 轴向梯形草图的 solid.coil Join → 多头特征圆周阵列 → 两端裁切。 +- **解决:**多头时仍用 πm 当导程、默认圆截面 coil 变弹簧、把梯形旋转成圆环、混用法向/轴向模数。 +- **检查/边界:**ZA、轴向压力角20°、1–4头;lead=sπm;核对实际轴向齿形、头数、端面、导程和旋向;不覆盖 ZI/ZN/ZK 或制造级包络蜗杆。 + +### K07 直齿锥齿轮 + +- ID:`straight-bevel-gear`;版本 0.1.1;[原文](../knowledge/cad-parts/generation/candidates/straight-bevel-gear-scaled-section-v1-1.md)。 +- **构造:**完整大端渐开线齿圈 → 沿轴线整体缩放扫掠 → 后切圆柱孔。 +- **解决:**母线齿宽直接当轴向高度、每齿独立布尔、大小端不共顶点、孔随齿圈缩放成锥孔。 +- **检查/边界:**18–40齿、锥半角20–65°、缩比0.45–0.9;H=b*cosδ;检查同源点共顶点、缩比及截面积积分体积;明确为缩放近似,不是制造级共轭齿面。 + +### K08 螺旋锥齿轮 + +- ID:`spiral-bevel-gear`;版本 0.1.0;[原文](../knowledge/cad-parts/generation/candidates/spiral-bevel-gear-axial-twist-v1.md)。 +- **构造:**完整大端齿圈整体缩放+线性轴向 twist,轴线路径过齿圈中心。 +- **解决:**等径斜齿冒充锥齿、扫掠绕单齿中心自转、误称恒螺旋角、圆孔变锥孔。 +- **检查/边界:**中高齿线角5–35°,其余有锥齿域约束;检查 r(z) 与 phase(z),中高相位为总 twist 一半;不声称 Gleason/Klingelnberg 加工齿面或共轭制造模型。 + +### K09 示意蜗轮 + +- ID:`worm-wheel`;版本 0.1.2;[原文](../knowledge/cad-parts/generation/candidates/worm-wheel-toroidal-throat-illustration-v1-2.md)。 +- **构造:**有 1.5m 齿顶毛坯余量的完整齿圈整体扭转 → 独立 torus Cut 出环面凹喉部 → 再孔槽。 +- **解决:**普通斜齿改名蜗轮、只切中部不切两端、根部圆弧端点误抄导致草图断开、把 torus 半径当直径。 +- **检查/边界:**18–40齿,参考头数1–4;严格检查喉部定义域和全宽余量;采样环面方程及齿相位,体积按切喉后的截面积积分;仍是示意,不是配对蜗杆滚切包络。 + +### K10 平行轴外齿轮副 + +- ID:`gear-pair`;版本 0.2.0;[原文](../knowledge/cad-parts/generation/candidates/gear-pair-fixed-axis-v2.md)。 +- **补接口:**各轮另读单轮规程;a=r1+r2,斜齿两轮旋向相反,在同一轴向截面计算实际相位。 +- **解决:**相加齿顶半径算轴距、两轮默认零角度齿对齿、定位后绕世界原点旋转使轴心绕走。 +- **检查/边界:**相位满足 `z1(λ1−φ1)+z2(λ2−φ2)=180° mod 360°`;侧隙必须显式选择和报告,不能缩轮/改齿数躲穿透;静态无穿透不等于全程接触验证。 + +### K11 齿轮齿条机构 + +- ID:`rack-and-pinion`;版本 0.1.0;[原文](../knowledge/cad-parts/generation/candidates/rack-and-pinion-straight-v1.md)。 +- **补接口:**轮心距节线 rp、两个独立实体、共模数/压力角/齿宽;齿条齿数奇偶决定中心接触初相位。 +- **解决:**轮心按齿顶半径定位、齿对齿、移动轮但孔留原点、两体误 Join。 +- **检查/边界:**运动按需再建 revolute/slider 和 rack_pinion;s=rp*θrad,明确 mm/deg 换算、实际方向和有限有效齿段。 + +### K12 蜗轮蜗杆机构 + +- ID:`worm-drive`;版本 0.1.0;[原文](../knowledge/cad-parts/generation/candidates/worm-drive-illustrative-v1.md)。 +- **补接口:**蜗轮轴 Z,蜗杆轴 X,轴线正交但不相交,中心距 r1+r2;两件独立定位,Cut/Join 限定部件。 +- **解决:**“正交”误成轴线穿过同一中心、按 πm 而非头数导程算相位、把运动比正确当齿面正确。 +- **检查/边界:**参考单体是 ZA 蜗杆+示意蜗轮,局部干涉仍可能存在;运动比绝对值 n/z2,方向取决于轴向/旋向/安装侧,不以挪远零件宣称标准啮合。 + +### K13 行星齿轮机构 + +- ID:`planetary-gear-mechanism`;版本 0.1.0;[原文](../knowledge/cad-parts/generation/candidates/planetary-gear-mechanism-straight-v1.md)。 +- **补接口:**太阳轮、行星轮、内齿圈、架分别建;`zr=zs+2zp`,等分装配 `(zs+zr)/n` 为整数,核对相邻行星和销轴间隙。 +- **解决:**只等分中心不计算每轮相位、销轴把行星轮一起 Join、把固定轴齿轮联动直接套给公转行星。 +- **检查/边界:**每轮本地建后按独立相位定位;Willis 关系 `zs(ωs−ωc)+zr(ωr−ωc)=0`;静态、运动比、干涉、接触各自验证。 + +### K14 球轴承 + +- ID:`ball-bearing`;版本 0.1.0;[原文](../knowledge/cad-parts/generation/candidates/ball-bearing-open-deep-groove-v1.md)。 +- **构造:**独立内/外圈 → 两圈 torus 滚道 → 独立球体阵列 → 带球窝薄环保持架。 +- **解决:**标准件 bearing 实际只是包络圆环,没有滚珠;用名称或遮盖解释缺球;把球和圈 Join;只搬套圈留下球。 +- **检查/边界:**N 球+两圈+保持架预期 N+3 个体;球数参数 unit="";检查球心节圆、轴向中面、间距、滚道/球窝/壁厚与改参。6202 的外形尺寸不证明球径/球数/内部结构为原厂值,默认结构是示意。 + +### K15 XZ 三角筋方向 + +- ID:`ribbed-bearing-housing`;版本 0.2.0;[原文](../knowledge/cad-parts/generation/candidates/xz-rib-orientation-risk-v2.md)。 +- **仅风险提示:**XZ 局部第二坐标对应世界 −Z;世界 (X,Z) 写成 [X,−Z];筋沿 Y 居中,offset=−t/2,挤出 t 并 Join 实际座体。 +- **解决:**把筋画到板下,出现不连接的多个 shell;后加筋堵座孔。 +- **边界:**不是完整轴承座教程;先筋再切座孔,检查筋与底板/支承均实际连通。 + +### K16 无槽连续人字齿 + +- ID:`herringbone-gear`;版本 0.1.1;[原文](../knowledge/cad-parts/generation/candidates/herringbone-continuous-v1-1.md)。 +- **构造:**完整下半截面扭转成 new 实体 → 关于中面镜像整个半体并 combine,不先造重合芯轴。 +- **解决:**两半同旋向、中面错半齿/有槽、预建根圆芯与扫掠体布尔失败、展开 φ±A(t) 符号写错。 +- **检查/边界:**18–30齿、|β|5–25°、G=0;两端同相、中面连续、相位导数反号、一个连通体;显式提供两侧 equation_curve 短 JSON 保留括号,不声称制造级中面过渡。 + +### K17 带中央槽双斜齿 + +- ID:`double-helical-gear`;版本 0.1.1;[原文](../knowledge/cad-parts/generation/candidates/double-helical-central-gap-v1-1.md)。 +- **构造:**下齿带整体扭转 new → 只从下带端面向中面接半槽根圆芯 → 整半体镜像合并。 +- **解决:**两件悬空斜齿冒充一件、槽中残齿、两边相位不对、整段重合芯布尔失败,以及方程曲线符号抄错。 +- **检查/边界:**0`reference/porting.md`
`scripts/compare_step.py`
`scripts/run.py`
`scripts/scb.py`
`scripts/tests/test_compare_step.py`
`scripts/tests/test_facts.py`
`scripts/tests/test_run.py`
`scripts/tests/test_scb.py`
`templates/test_design.py` | +| [makecad-commands](../../solidcraft-main/skills/makecad-commands/SKILL.md) | 命令开发 | CommandSpec、Schema、命令入口和开发分层 | `SKILL.md` | +| [makecad-contributing](../../solidcraft-main/skills/makecad-contributing/SKILL.md) | 贡献开发 | 选题、PR、验证、审查及协作流程 | `SKILL.md` | +| [makecad-crash-safety](../../solidcraft-main/skills/makecad-crash-safety/SKILL.md) | 稳定性开发 | Rust错误处理、输入上限、崩溃与恢复;不是零件设计规范 | `SKILL.md` | +| [makecad-editing](../../solidcraft-main/skills/makecad-editing/SKILL.md) | 核心建模 | 已有设计的参数修改、局部结构编辑与下游修复 | `SKILL.md` | +| [makecad-file-formats](../../solidcraft-main/skills/makecad-file-formats/SKILL.md) | 格式开发 | 设计格式兼容、导入/导出与文件安全 | `SKILL.md` | +| [makecad-ground-rules](../../solidcraft-main/skills/makecad-ground-rules/SKILL.md) | 工程规范 | 独立实现、许可、资源归属和产品命名 | `SKILL.md` | +| [makecad-layers](../../solidcraft-main/skills/makecad-layers/SKILL.md) | 架构开发 | makeCAD与solidcore、内核与ops的职责边界 | `SKILL.md` | +| [makecad-mechanisms](../../solidcraft-main/skills/makecad-mechanisms/SKILL.md) | 核心建模 | 组件、关节、固定、传动、闭环、碰撞和运动检查 | `SKILL.md`
`reference.md` | +| [makecad-modeling](../../solidcraft-main/skills/makecad-modeling/SKILL.md) | 核心建模 | 新零件的几何规划、命令与参数化构建、阶段验收 | `SKILL.md`
`reference.md` | +| [makecad-packaging](../../solidcraft-main/skills/makecad-packaging/SKILL.md) | 发布开发 | 构建、打包、版本、签名和发布产物 | `SKILL.md` | +| [makecad-performance](../../solidcraft-main/skills/makecad-performance/SKILL.md) | 性能开发 | 不阻塞窗口、实际性能测量、WASM限制 | `SKILL.md` | +| [makecad-preferences](../../solidcraft-main/skills/makecad-preferences/SKILL.md) | 产品开发 | 默认行为兼容和设置项 | `SKILL.md` | +| [makecad-reporting](../../solidcraft-main/skills/makecad-reporting/SKILL.md) | 故障辅助 | 最小复现、期望/实际对照和错误报告 | `SKILL.md`
`reference/report-template.md` | +| [makecad-sheetmetal](../../solidcraft-main/skills/makecad-sheetmetal/SKILL.md) | 核心建模 | 钣金规则、分段折弯、展开、自然语言推断和有限优化 | `SKILL.md`
`reference.md` | +| [makecad-tests](../../solidcraft-main/skills/makecad-tests/SKILL.md) | 测试开发 | 测试放置、参考值来源、几何oracle、回归和CI | `SKILL.md` | +| [makecad-ui](../../solidcraft-main/skills/makecad-ui/SKILL.md) | 界面开发 | 容器、控件、主题、相机和UI验证 | `SKILL.md` | +| [makecad-ui-text](../../solidcraft-main/skills/makecad-ui-text/SKILL.md) | 文案开发 | 本地化目录、术语、消息与排序 | `SKILL.md` | + +## 附录 B:不在当前阅读目录中的 18 个 candidates 文件 + +这些文件的存在不意味着当前模型能通过 knowledge_lookup 读取。分类为历史/未登记是基于当前目录,不重新判断其内容是否有用。 + +- [covered-enclosure-shared-interface-v1.md](../knowledge/cad-parts/generation/candidates/covered-enclosure-shared-interface-v1.md) +- [double-helical-central-gap-v1.md](../knowledge/cad-parts/generation/candidates/double-helical-central-gap-v1.md) +- [double-helical-gap-risk-v2.md](../knowledge/cad-parts/generation/candidates/double-helical-gap-risk-v2.md) +- [gear-pair-fixed-axis-v1.md](../knowledge/cad-parts/generation/candidates/gear-pair-fixed-axis-v1.md) +- [helical-cylindrical-gear-v1-1.md](../knowledge/cad-parts/generation/candidates/helical-cylindrical-gear-v1-1.md) +- [helical-cylindrical-gear-v1.md](../knowledge/cad-parts/generation/candidates/helical-cylindrical-gear-v1.md) +- [helical-rack-v1.md](../knowledge/cad-parts/generation/candidates/helical-rack-v1.md) +- [herringbone-continuous-risk-v2.md](../knowledge/cad-parts/generation/candidates/herringbone-continuous-risk-v2.md) +- [herringbone-continuous-v1.md](../knowledge/cad-parts/generation/candidates/herringbone-continuous-v1.md) +- [hex-head-bolt-simplified-v1.md](../knowledge/cad-parts/generation/candidates/hex-head-bolt-simplified-v1.md) +- [mounting-plate-through-holes-v1.md](../knowledge/cad-parts/generation/candidates/mounting-plate-through-holes-v1.md) +- [ribbed-bearing-housing-y-bore-v1.md](../knowledge/cad-parts/generation/candidates/ribbed-bearing-housing-y-bore-v1.md) +- [stepped-shaft-cumulative-v1.md](../knowledge/cad-parts/generation/candidates/stepped-shaft-cumulative-v1.md) +- [straight-bevel-gear-scaled-section-v1.md](../knowledge/cad-parts/generation/candidates/straight-bevel-gear-scaled-section-v1.md) +- [worm-wheel-risk-notes-v2.md](../knowledge/cad-parts/generation/candidates/worm-wheel-risk-notes-v2.md) +- [worm-wheel-toroidal-throat-illustration-v1-1.md](../knowledge/cad-parts/generation/candidates/worm-wheel-toroidal-throat-illustration-v1-1.md) +- [worm-wheel-toroidal-throat-illustration-v1.md](../knowledge/cad-parts/generation/candidates/worm-wheel-toroidal-throat-illustration-v1.md) +- [worm-za-v1.md](../knowledge/cad-parts/generation/candidates/worm-za-v1.md) + +## 附录 C:后续修改时的最短入口 + +| 要优化什么 | 优先修改位置 | +| --- | --- | +| 通用建模、坐标、阶段检查 | [agent-workflow.md](../../solidcraft-main/skills/agent-workflow.md)、[makecad-modeling/](../../solidcraft-main/skills/makecad-modeling/) | +| 修改模型和局部修复 | [makecad-editing/](../../solidcraft-main/skills/makecad-editing/) | +| 参数稳健性和验收 | [makecad-checking/](../../solidcraft-main/skills/makecad-checking/),以及实际引擎检查接口 | +| 机构与运动 | [makecad-mechanisms/](../../solidcraft-main/skills/makecad-mechanisms/) | +| 钣金 | [makecad-sheetmetal/](../../solidcraft-main/skills/makecad-sheetmetal/) | +| 某类零件的具体错误 | [reading-catalog.json](../knowledge/cad-parts/generation/reading-catalog.json) 指向的正文 | +| Java v1 常驻规则/工具描述 | [ArkCadAiClient.java](../vibemake-service/src/main/java/com/linkerbot/vibemake/service/cad/ai/ArkCadAiClient.java)、[CadAiTools.java](../vibemake-service/src/main/java/com/linkerbot/vibemake/service/cad/ai/CadAiTools.java)、[CadAiKnowledge.java](../vibemake-service/src/main/java/com/linkerbot/vibemake/service/cad/ai/CadAiKnowledge.java) | +| Python v2 常驻规则/知识发现/读图研究 | [resources.py](../../cad-ai-server/src/cad_ai/resources.py)、[search.py](../../cad-ai-server/src/cad_ai/search.py) | +| 易错几何算法确定性实现 | 先按 solidcraft-main 的 AGENTS.md 和 layers 规范定位引擎/solidcore-ops/内核职责 | diff --git a/docs/database.md b/docs/database.md index 50fe6ad..2a0c840 100644 --- a/docs/database.md +++ b/docs/database.md @@ -41,6 +41,7 @@ CREATE TABLE project ( model_parts_files JSON NOT NULL DEFAULT (JSON_ARRAY()) COMMENT '零件GLB文件清单,包含relativePath和sizeBytes', assembly_json_object_key VARCHAR(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '拼装步骤JSON环境相对路径,不含域名和环境根目录', assembly_json_size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '拼装步骤JSON文件大小,单位字节', + assembly_animation_status VARCHAR(16) NOT NULL DEFAULT 'UNPROCESSED' COMMENT '拼装动画制作状态 UNPROCESSED未处理 IN_PROGRESS进行中 COMPLETED已完成', walking_resources_prefix VARCHAR(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '行走资源环境相对目录,以斜杠开头和结尾', walking_resources_files JSON NOT NULL DEFAULT (JSON_ARRAY()) COMMENT '行走资源文件清单,包含relativePath和sizeBytes', project_type VARCHAR(64) NOT NULL COMMENT '配置中的项目类型编码', diff --git a/docs/deployment-dev-20261119.md b/docs/deployment-dev-20261119.md new file mode 100644 index 0000000..4b57c66 --- /dev/null +++ b/docs/deployment-dev-20261119.md @@ -0,0 +1,83 @@ +# 开发环境更新记录(2026-11-19) + +## 范围与版本 + +- 仅更新开发服务器 `39.105.93.138`,SSH 别名 `cad_ai_dev`,主机名 `lingmiaodongli`。 +- 发布编号:`20261119T085751Z`。已恢复对外访问。 +- 社区 API:`vibemake-api`,继续使用端口 `8993`。 +- 管理 API:`vibemake-adminapi`,继续使用端口 `8994`。 +- 管理前端:`https://dev-vibemake-admin.robotquan.com/`。 +- 接口入口:`https://dev-vibemake-api.robotquan.com`,分别使用 `/api` 和 `/admin-api`。 +- 本次未操作正式服务器 `101.200.225.61`,未更新 CAD 前端或 Python CAD 服务。 + +构建来自当前两个工作区的独立源码快照,包含当时未提交的修改,未使用旧的 `dist.zip`。社区仓库基准提交为 `6b96ca1eb042bad58521543dc6f1f5c0681cd6d9`,管理前端仓库基准提交为 `25acae2c8b32ebd3eb0b62fe4b1713dcdb7a1052`。发布目录中的两个 `*-source-manifest.json` 记录完整快照文件摘要;构建后已核对源文件未漂移。 + +## 本次变化 + +- 管理端增加拼装动画制作状态的展示、切换和筛选,状态为 `UNPROCESSED`、`IN_PROGRESS`、`COMPLETED`。 +- 管理 API 增加 `PUT /admin-api/projects/{projectCode}/assembly-animation-status`,项目列表接受 `assemblyAnimationStatus` 参数。 +- 两个 Java 应用一起更新,使用相同的新项目实体。其余当前工作区的已构建修改同时纳入此次发布。 +- 保留现有容器环境变量、端口、日志挂载、网络、重启策略及其他 HostConfig;凭据未输出到部署记录。 +- 基于原服务器镜像,仅替换应用 JAR;未在线升级 JDK、Docker、MySQL 或其他服务。 +- 静态资源先上传,入口 `index.html` 最后原子替换,旧的带摘要资源文件保留。 +- 切换期间对两个开发 API 路径临时返回 503,恢复后代理文件与备份逐字节一致;未永久变更反向代理或 CORS。 + +## 数据库变更 + +开发库 `community` 的实体字段已逐一核对,只有下列字段缺失。在备份数据库并停止两个旧 Java 服务后执行;未修改仓库内的 `.sql` 文件: + +```sql +ALTER TABLE project + ADD COLUMN assembly_animation_status VARCHAR(16) NOT NULL DEFAULT 'UNPROCESSED' + COMMENT '拼装动画制作状态 UNPROCESSED未处理 IN_PROGRESS进行中 COMPLETED已完成'; +``` + +更新后原有 111 个项目均为 `UNPROCESSED`。切换前后仓库状态均为 `IDLE=108`、`REVIEW=3`;迁移任务仍为 `SUCCEEDED/LINKED=4`、`FAILED/MIGRATING=3`,未重试或清理既有失败、待核对记录。没有执行全量历史迁移。 + +## 验证结果 + +- 使用 Homebrew JDK 21 完成 `mvn -B -ntp verify`,全部模块构建成功。764 项测试,750 项通过、14 项真实外部环境测试按配置跳过,无失败或错误。 +- 本地测试显式禁用真实 AI、OSS、Git 外部集成;测试类内的模拟功能测试按各自配置运行。这些参数没有覆盖服务器现有应用配置。 +- 首轮测试曾遇到一次 AI 搜索 SSE 用例事件为空;未修改代码,随后完整测试通过,最终发布基于成功的整轮构建。 +- 管理前端 `npm run build:dev` 成功,状态功能、环境地址、日期相关的 22 项 Playwright 测试全部通过。 +- 服务器两个新容器均正常运行、重启次数为 0,启动及验收时的应用标准输出日志未发现 ERROR。运行中 JAR 与本地产物 SHA-256 一致。 +- 公网管理首页 HTTP 200,HTML 摘要与本地新构建一致,部署的 22 个前端文件摘要全部一致。 +- 实际 Chromium 打开开发管理站,登录界面正常、新入口脚本已加载,无页面异常或本站静态资源错误。 +- 公网项目类型和项目列表均为 HTTP 200 / `OK`,验证了新实体在现有 MySQL 库上的读取。 +- 管理端匿名访问返回 HTTP 401 / `UNAUTHORIZED`。 +- 开发管理 Origin 的登录 POST、状态更新 PUT 预检均 HTTP 200,允许来源正确。 +- 运行中管理 API 的 OpenAPI 确认新状态 PUT 接口及列表筛选参数均已注册。 +- Python CAD API、worker 保持原启动时间,未重启。 + +未使用真实管理员密码登录,也未在现有业务项目上执行状态写入;状态保存、筛选、权限和旧元数据覆盖保护由隔离的后端及前端测试验证。 + +## 产物摘要 + +| 产物 | SHA-256 | +| --- | --- | +| `vibemake-api.jar` | `309565f62970082e27c585f40609a796dd14f13bede689b10ed02f0dbba84940` | +| `vibemake-adminapi.jar` | `5e758ea3d1b711804e8971730798ca899a1e7d3613100cf6f65a8cc9e62f2b1d` | +| 管理前端 `index.html` | `d32969a62483eb3ee371ed6f08abe2c07ceefae415699c0452f253b49e62d943` | + +## 备份与回退 + +服务器发布目录:`/opt/vibemake-deploy/releases/20261119T085751Z`。 + +服务器备份目录:`/opt/vibemake-deploy/backups/20261119T085751Z`,根目录权限为 700,包含: + +- 两次数据库备份:`community-before.mysql.gz`、`community-stopped.mysql.gz`,备份退出状态、压缩文件可读性、大小及摘要已验证。内容仅保存在服务器受保护目录。 +- 原容器完整配置 `containers.json`,包含敏感环境变量,禁止复制到 Git 或公开输出。 +- 原管理前端 `admin-dist.tar.gz` 及文件摘要。 +- 原开发域名配置及两个 API 代理文件。 + +旧容器保留为 `vibemake-api-backup-20261119T085751Z` 和 `vibemake-adminapi-backup-20261119T085751Z`。旧容器已停止,自动重启已关闭,避免主机重启时与当前版本争抢端口;当前新容器保持原来的 `always` 重启策略。 + +如确认需要回退应用,在核对没有新导入或写入任务后,执行以下命令。该命令是实际回退操作,未在本次验收中运行: + +```bash +ssh cad_ai_dev 'cd /opt/vibemake-deploy/releases/20261119T085751Z && python3 rollback_release.py' +``` + +回退脚本会临时开启维护、恢复旧容器及其重启策略、恢复旧前端入口,再恢复代理。**保留新增字段及其数据,不自动回滚数据库或删除对象。** 如有正在运行的任务或未排空写入,先处理任务,不能强制回退。数据库备份只供必要时人工恢复,不应覆盖更新后产生的新业务数据。 + +服务器剩余磁盘约 6.3 GiB(使用率 91%),已保留此次回退所需镜像和容器,未执行全局清理。后续发布前需继续检查磁盘与内存余量。 diff --git a/docs/deployment-prod-20261119.md b/docs/deployment-prod-20261119.md new file mode 100644 index 0000000..24e2297 --- /dev/null +++ b/docs/deployment-prod-20261119.md @@ -0,0 +1,85 @@ +# 正式环境发布记录(2026-11-19) + +## 发布范围 + +- 服务器:`101.200.225.61`,SSH 别名 `lk_a`,主机名 `iZ2zeaflbjvw94civ7z5yhZ`。 +- 发布编号:`20261119T094355Z`;晋级自已验收的开发版本 `20261119T085751Z`。 +- 社区 API:`vibemake-api`,端口 `8993`。 +- 管理 API:`vibemake-adminapi`,端口 `8994`。 +- 管理前端:`https://vibemake-admin.robotquan.com/`。 +- 接口域名:`https://vibemake-api.robotquan.com`。 +- 静态目录:`/opt/1panel/www/sites/vibemake-admin.robotquan.com/index/dist`。 + +两个后端 JAR 直接复用开发环境通过全量构建和验收的产物,SHA-256 完全一致。管理前端使用同一份冻结源码执行 `npm run build:prod`,浏览器已确认请求正式 API。此次没有更新 CAD 前端、Python CAD API/worker 或开发服务器。 + +本次主要新增拼装动画制作状态的展示、切换和筛选,同时晋级开发环境已验收的其他当前源码改动。源码摘要位于发布目录的 `community-source-manifest.json`、`vibemake-admin-source-manifest.json`;版本来源见 `release.json`。 + +## 数据库与切换 + +正式业务库是 RDS 上的 `vibemake`。发布前已对照实体核对全部列,只有 `project.assembly_animation_status` 缺失。完成表结构和数据备份、暂停入口流量、确认无活跃任务并停止两个旧服务后,执行以下增量变更;未修改仓库 `.sql` 文件,也未执行全量历史 SQL: + +```sql +ALTER TABLE project + ADD COLUMN assembly_animation_status VARCHAR(16) NOT NULL DEFAULT 'UNPROCESSED' + COMMENT '拼装动画制作状态 UNPROCESSED未处理 IN_PROGRESS进行中 COMPLETED已完成'; +``` + +发布后已有 408 个项目的新增状态均为 `UNPROCESSED`。以下原有任务状态在切换前后相同,没有重试、删除或清空历史记录: + +| 项目或任务 | 原状态及数量 | +| --- | --- | +| 项目仓库写入状态 | `IDLE=337`,`REVIEW=71` | +| 导入任务 | `SUCCEEDED/LINKED=144`,`FAILED/MIGRATING=50`,`REVIEW/MIGRATING=7`,`REVIEW/VERIFYING=1`,`REVIEW/CLEANING=1`,`REVIEW/NORMALIZING=1` | +| 普通仓库写入凭据 | `SUCCEEDED=335`,`NEEDS_REVIEW=7` | + +两个新镜像分别基于正式服务器原有镜像,仅替换 JAR。保留正式环境的 `prod` profile、全部 Env、端口、日志挂载、实际 `1panel-network` 连接和重启策略。旧社区容器的 HostConfig.NetworkMode 为 bridge、实际网络为 1panel-network,已按实际配置完整保留。Docker 将旧配置中未设定的 `OomKillDisable=null` 规范化为默认的 `false`,验证时仅将这一等价表示视为一致。 + +切换期间只在正式 API 的两个现有代理块中临时返回 503,两个应用就绪并验收后恢复。恢复后的 `root.conf`、`admin.conf` 与发布前备份逐字节相同。原跨域配置已允许正式管理 Origin 的 POST 和 PUT,无永久代理或跨域改动。 + +前端资源先部署,`index.html` 最后原子替换,旧带摘要资源继续保留。Python CAD API/worker 的启动时间保持不变。 + +## 验证结果 + +- 继承开发环境的后端验证:764 项测试中 750 项通过、14 项外部环境测试跳过,失败和错误为 0;正式运行中 JAR 与这些已验证产物摘要一致。 +- 前端来自开发环境已通过 22 项浏览器测试的同一冻结源码,正式模式构建成功。 +- 两个正式新容器正常运行,重启次数均为 0,启动及验收时的应用日志未发现 ERROR。 +- 正式项目类型、项目列表请求均 HTTP 200 / `OK`,已验证新实体在正式 MySQL 库上的读取。 +- 管理端匿名请求及状态资源匿名请求均返回 HTTP 401。 +- 正式管理站 HTTP 200,入口 HTML 摘要与新构建一致,部署的 22 个前端文件摘要全部通过校验。 +- 真实 Chromium 加载正式管理站和新的 `index-DJBL3-Ou.js`,登录界面正常,无页面异常或本站静态资源错误。 +- 浏览器登录请求通过本地拦截验证,目标为 `https://vibemake-api.robotquan.com/admin-api/auth/login`;该检查没有向真实登录接口提交账号密码。 +- 真实公网登录 POST、状态更新 PUT 的 OPTIONS 预检均 HTTP 200,允许的 Origin 正确。 +- `prod` 配置及产物中关闭 OpenAPI/Swagger 的设置保持不变。 + +没有使用真实管理员凭据登录,也没有对现有项目执行状态保存。功能保存、筛选、权限及防旧元数据覆盖由开发版本的隔离测试覆盖。 + +## 产物摘要 + +| 产物 | SHA-256 | +| --- | --- | +| `vibemake-api.jar` | `309565f62970082e27c585f40609a796dd14f13bede689b10ed02f0dbba84940` | +| `vibemake-adminapi.jar` | `5e758ea3d1b711804e8971730798ca899a1e7d3613100cf6f65a8cc9e62f2b1d` | +| 正式管理前端 `index.html` | `52617e0a2153f4d872bf14c69b7e1e31a9f634bbccceafbc840a2ac315f6f646` | + +## 备份与回退 + +服务器发布目录:`/opt/vibemake-deploy/releases/20261119T094355Z`。 + +服务器备份目录:`/opt/vibemake-deploy/backups/20261119T094355Z`,目录权限 700。保存发布前及停机后的两次 MySQL 表结构与数据备份、旧前端及其摘要、旧代理和站点配置、原容器完整配置。MySQL 备份命令成功退出,压缩文件完整可读并记录摘要,文件权限为 600。凭据只在服务器内存中读取,未写入部署命令参数或本文档;包含敏感 Env 的 `containers.json` 仅留在受保护的服务器目录,不得提交 Git。 + +本次保留的旧容器: + +- `vibemake-api-backup-20261119T094355Z` +- `vibemake-adminapi-backup-20261119T094355Z` + +旧容器已停止并关闭自动重启,避免服务器重启时与当前版本争抢端口。当前新容器保留原有 `always` 重启策略。未执行 Docker 全局清理,也未删除其他历史容器。 + +如需要回退,先确认没有新导入、仓库写入等活跃任务,再执行以下实际回退命令;该命令未在发布验收中执行: + +```bash +ssh lk_a 'cd /opt/vibemake-deploy/releases/20261119T094355Z && python3 deploy_prod.py rollback' +``` + +脚本先核对任务、开启维护并再次核对任务,然后恢复旧容器及其原重启策略、旧前端入口和代理。新增字段及其状态数据保留,不自动恢复数据库,不删除对象。数据库备份仅供必要时人工恢复,不得覆盖发布后产生的新业务数据。 + +服务器发布目录同时保留 `artifact-manifest.json`、`java-test-summary.json`、`verification.json`、`public-verification.json` 和 `browser-verification.json`,供后续追溯。 diff --git a/knowledge/cad-parts/generation/HANDOFF.md b/knowledge/cad-parts/generation/HANDOFF.md index c08cff8..c60afa1 100644 --- a/knowledge/cad-parts/generation/HANDOFF.md +++ b/knowledge/cad-parts/generation/HANDOFF.md @@ -1,6 +1,10 @@ # CAD 零件知识库:当前交接 -更新:2026-11-12。先读本文及[维护规范](MAINTENANCE.md),再核对实际文件、进程和队列。本文不注入生成模型。[精简前交接快照](../reports/utility-pruning-20261112/handoff-before-utility-v1.txt)保存此前发布和试验细节。 +更新:2026-11-13。先读本文及[维护规范](MAINTENANCE.md),再核对实际文件、进程和队列。本文不注入生成模型。[精简前交接快照](../reports/utility-pruning-20261112/handoff-before-utility-v1.txt)保存此前发布和试验细节。 + +## CAD助手模型配置(2026-11-13) + +用户要求改为`gpt-6.1-sol`、极高`xhigh`。本机`.env`已切为`CAD_AI_PROVIDER=openai`、`CAD_AI_OPENAI_MODEL=gpt-6.1-sol`、`CAD_AI_OPENAI_REASONING_EFFORT=xhigh`,保留既有上游、密钥和其他配置。先确认生成全部结束,再于11:35(Asia/Shanghai)沿用下述球轴承冻结JAR重启共享8993,PID观察80050;JAR SHA仍为`80c647921b6c7a6298eb2d914bedffdc1b8c58b4fc1b997d57e6d267f56439b8`。上游最小流式ping工具调用通过;正式登录编辑器能力接口确认`openai/gpt-6.1-sol/xhigh`,65536输出、pilot知识模式、13工具及524288字节文本限制保持。前端、引擎、知识正文与原Skill/工具循环未改,独立8994未操作。本次CAD生成请求0,不重跑旧题,不声称新模型效果已验收。原页面有未保存设计,应先保存再刷新并新建对话。详见[切换核验](../reports/cad-model-switch-20261113/README.md)。 ## 球轴承增量(2026-11-12,当前优先读) diff --git a/knowledge/cad-parts/reports/cad-model-switch-20261113/README.md b/knowledge/cad-parts/reports/cad-model-switch-20261113/README.md new file mode 100644 index 0000000..a615f09 --- /dev/null +++ b/knowledge/cad-parts/reports/cad-model-switch-20261113/README.md @@ -0,0 +1,19 @@ +# CAD 助手模型切换(2026-11-13) + +用户要求将 CAD 编辑器 AI 助手后端改为 `gpt-6.1-sol`,推理强度“极高”(`xhigh`)。本次仅修改本机 `.env` 的三项 CAD 配置:`CAD_AI_PROVIDER=doubao → openai`、`CAD_AI_OPENAI_MODEL=gpt-6.1-terra → gpt-6.1-sol`、`CAD_AI_OPENAI_REASONING_EFFORT=high → xhigh`。沿用既有上游地址和凭据,不改社区助手及其他服务配置。 + +## 实际发布 + +2026-11-13 11:35(Asia/Shanghai),先确认正式编辑器已完成当前轮生成,并逐请求核对当前进程日志(69次开始均已结束,包含连接关闭终态),再将8993从PID30800重启为PID80050。沿用球轴承发布的冻结JAR,SHA256为`80c647921b6c7a6298eb2d914bedffdc1b8c58b4fc1b997d57e6d267f56439b8`;没有重新打包,没有修改前端、引擎、知识正文、原17个通用Skill或工具循环。8091前端PID2522与独立8994后端PID65032未操作。PID只是本次观察值,后续操作前重核。 + +## 已证实的结果 + +- 现有上游一次最小流式Responses工具调用返回HTTP200和completed,返回模型`gpt-6.1-sol`、`reasoning.effort=xhigh`,ping函数名及空参数正确。本次连通性检查不传CAD设计或历史,不导出凭据。 +- 8993成功启动;正式8091编辑器复用正常登录会话,通过原`CadApi.aiCapabilities()`读取实际能力:`enabled=true`、`provider=openai`、`model=gpt-6.1-sol`、`reasoningEffort=xhigh`。输出上限65536、知识模式pilot、13个工具及524288字节文本上限保留。 +- 本次CAD生成请求0,未重跑历史模型试验,不据此声称几何质量或速度提高。公开官方模型文档本次未能取得有效内容;这里只确认当前已配置上游实际接受的模型名、强度和流式工具协议,不扩展推断其他接口能力。 + +非敏感核验字段见[verification.json](verification.json)。运行日志在本机`target/cad-model-switch-20261113/backend.log`,没有保存整份.env或登录状态。 + +## 使用与后续 + +原编辑器仍有尚未保存的设计,本次未刷新或改动设计。先保存,再刷新并开始新对话,避免携带豆包会话的旧推理历史。后续生成使用新配置;如另行开展效果对比,需独立版本并保留原失败。 diff --git a/knowledge/cad-parts/reports/cad-model-switch-20261113/verification.json b/knowledge/cad-parts/reports/cad-model-switch-20261113/verification.json new file mode 100644 index 0000000..2380f8b --- /dev/null +++ b/knowledge/cad-parts/reports/cad-model-switch-20261113/verification.json @@ -0,0 +1,83 @@ +{ + "changed_at": "2026-11-13T11:35:33.521400+08:00", + "old_pid": 30800, + "new_pid": 80050, + "port": 8993, + "jar": "/Users/lk/Projects/cad-generation-benchmark/experiments/ball-bearing-knowledge-20261112/backend-bearing-v1/vibemake-api-0.0.1-SNAPSHOT.jar", + "jar_sha256": "80c647921b6c7a6298eb2d914bedffdc1b8c58b4fc1b997d57e6d267f56439b8", + "provider": "openai", + "model": "gpt-6.1-sol", + "reasoning_effort": "xhigh", + "idle_requests_verified": 69, + "changes": [ + "CAD_AI_PROVIDER", + "CAD_AI_OPENAI_MODEL", + "CAD_AI_OPENAI_REASONING_EFFORT" + ], + "frontend_rebuilt": false, + "backend_rebuilt": false, + "engine_rebuilt": false, + "upstream_probe": { + "checked_at": "2026-11-13T11:34:35.099994+08:00", + "requested_model": "gpt-6.1-sol", + "requested_reasoning_effort": "xhigh", + "stream": true, + "store": false, + "cad_generation_requests": 0, + "connectivity_requests": 1, + "http_status": 200, + "content_type": "text/event-stream", + "event_counts": { + "response.created": 1, + "response.in_progress": 1, + "response.output_item.added": 1, + "response.function_call_arguments.delta": 1, + "response.function_call_arguments.done": 1, + "response.output_item.done": 1, + "response.completed": 1 + }, + "response_status": "completed", + "response_model": "gpt-6.1-sol", + "response_reasoning": { + "context": "all_turns", + "effort": "xhigh", + "mode": "standard", + "summary": "detailed" + }, + "usage": { + "input_tokens": 18488, + "input_tokens_details": { + "cached_tokens": 0 + }, + "output_tokens": 14, + "output_tokens_details": { + "reasoning_tokens": 0 + }, + "total_tokens": 18502 + }, + "output_types": [ + "function_call" + ], + "ping_call_valid": true, + "encrypted_reasoning_present": false, + "success": true, + "duration_seconds": 4.22 + }, + "authenticated_capabilities": { + "verified_at": "2026-11-13T11:38:56.866552+08:00", + "source": "正式8091编辑器的既有登录会话,通过原CadApi.aiCapabilities读取;不导出登录状态或Token", + "enabled": true, + "provider": "openai", + "model": "gpt-6.1-sol", + "reasoningEffort": "xhigh", + "maxOutputTokens": 65536, + "knowledgeMode": "pilot", + "toolCount": 13, + "textBytes": 524288 + }, + "cad_generation_requests": 0, + "endpoint_changed": false, + "frontend_pid_unchanged": 2522, + "independent_8994_pid_unchanged": 65032, + "historical_results_modified": false +} diff --git a/vibemake-adminapi/src/main/java/com/linkerbot/vibemake/adminapi/controller/AdminProjectController.java b/vibemake-adminapi/src/main/java/com/linkerbot/vibemake/adminapi/controller/AdminProjectController.java index 2615d25..c2d266e 100644 --- a/vibemake-adminapi/src/main/java/com/linkerbot/vibemake/adminapi/controller/AdminProjectController.java +++ b/vibemake-adminapi/src/main/java/com/linkerbot/vibemake/adminapi/controller/AdminProjectController.java @@ -39,6 +39,7 @@ public class AdminProjectController { @RequestParam(required = false) String publishStatus, @RequestParam(required = false) String repoStatus, @RequestParam(required = false) String moderationStatus, + @RequestParam(required = false) String assemblyAnimationStatus, @RequestParam(defaultValue = "CREATED_AT_DESC") String sort) { return ApiResponse.success( management.projects( @@ -50,6 +51,7 @@ public class AdminProjectController { publishStatus, repoStatus, moderationStatus, + assemblyAnimationStatus, sort)); } @@ -80,6 +82,13 @@ public class AdminProjectController { return ApiResponse.success(null); } + @PutMapping("/{projectCode}/assembly-animation-status") + public ApiResponse assemblyAnimationStatus( + @PathVariable String projectCode, + @Valid @RequestBody AssemblyAnimationStatusInput input) { + return ApiResponse.success(management.assemblyAnimationStatus(projectCode, input.status())); + } + @GetMapping("/{projectCode}/tree") public ApiResponse tree( @PathVariable String projectCode, diff --git a/vibemake-adminapi/src/main/java/com/linkerbot/vibemake/adminapi/controller/AdminUserController.java b/vibemake-adminapi/src/main/java/com/linkerbot/vibemake/adminapi/controller/AdminUserController.java index 42ad415..ad49df2 100644 --- a/vibemake-adminapi/src/main/java/com/linkerbot/vibemake/adminapi/controller/AdminUserController.java +++ b/vibemake-adminapi/src/main/java/com/linkerbot/vibemake/adminapi/controller/AdminUserController.java @@ -53,6 +53,6 @@ public class AdminUserController { @RequestParam(defaultValue = "1") long page, @RequestParam(defaultValue = "20") long size) { return ApiResponse.success( - service.projects(page, size, userCode, null, null, null, null, null, null)); + service.projects(page, size, userCode, null, null, null, null, null, null, null)); } } diff --git a/vibemake-adminapi/src/test/java/com/linkerbot/vibemake/adminapi/AdminWorkflowTest.java b/vibemake-adminapi/src/test/java/com/linkerbot/vibemake/adminapi/AdminWorkflowTest.java index 59ecd39..9bac5fa 100644 --- a/vibemake-adminapi/src/test/java/com/linkerbot/vibemake/adminapi/AdminWorkflowTest.java +++ b/vibemake-adminapi/src/test/java/com/linkerbot/vibemake/adminapi/AdminWorkflowTest.java @@ -365,6 +365,107 @@ class AdminWorkflowTest { request(signed(get("/admin-api/projects").param("sort", invalid)), 400); } + @Test + void assemblyAnimationStatusDefaultsAndPersistsIndependentlyOfOtherMetadata() throws Exception { + String code = createProject(); + String endpoint = "/admin-api/projects/" + code; + JsonNode initial = request(signed(get(endpoint)), 200).path("data"); + assertThat(initial.path("assemblyAnimationStatus").asText()).isEqualTo("UNPROCESSED"); + com.fasterxml.jackson.databind.node.ObjectNode expectedProject = initial.path("project").deepCopy(); + expectedProject.remove("updatedAt"); + for (String status : List.of("IN_PROGRESS", "COMPLETED", "UNPROCESSED")) { + JsonNode saved = request(signed(body(put(endpoint + "/assembly-animation-status"), + Map.of("status", status))), 200).path("data"); + assertThat(saved.path("assemblyAnimationStatus").asText()).isEqualTo(status); + com.fasterxml.jackson.databind.node.ObjectNode actualProject = saved.path("project").deepCopy(); + actualProject.remove("updatedAt"); + assertThat(actualProject).isEqualTo(expectedProject); + assertThat(request(signed(get(endpoint)), 200).path("data") + .path("assemblyAnimationStatus").asText()).isEqualTo(status); + assertThat(jdbc.queryForObject("SELECT assembly_animation_status FROM project WHERE project_code=?", + String.class, code)).isEqualTo(status); + } + jdbc.update("UPDATE project SET repo_status='CREATING' WHERE project_code=?", code); + assertThat(request(signed(body(put(endpoint + "/assembly-animation-status"), + Map.of("status", "IN_PROGRESS"))), 200).path("data") + .path("assemblyAnimationStatus").asText()).isEqualTo("IN_PROGRESS"); + } + + @Test + void assemblyAnimationStatusSurvivesStaleMetadataUpdatesAndRepeatedRequests() throws Exception { + String code = createProject(); + String endpoint = "/admin-api/projects/" + code; + Project stale = projects.selectOne(new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper() + .eq(Project::getProjectCode, code)); + JsonNode saved = request(signed(body(put(endpoint + "/assembly-animation-status"), + Map.of("status", "COMPLETED"))), 200).path("data"); + JsonNode repeated = request(signed(body(put(endpoint + "/assembly-animation-status"), + Map.of("status", "COMPLETED"))), 200).path("data"); + assertThat(repeated.path("project").path("updatedAt")).isEqualTo(saved.path("project").path("updatedAt")); + stale.setName("其他业务更新的名称"); + assertThat(projects.updateById(stale)).isEqualTo(1); + JsonNode current = request(signed(get(endpoint)), 200).path("data"); + assertThat(current.path("assemblyAnimationStatus").asText()).isEqualTo("COMPLETED"); + assertThat(current.path("project").path("name").asText()).isEqualTo("其他业务更新的名称"); + } + + @Test + void assemblyAnimationStatusFiltersBeforePaginationAndCombinesWithExistingFilters() throws Exception { + String first = createProject(); + String second = createProject(); + String untouched = createProject(); + for (String code : List.of(first, second)) + request(signed(body(put("/admin-api/projects/" + code + "/assembly-animation-status"), + Map.of("status", "COMPLETED"))), 200); + Set found = new HashSet<>(); + for (int page = 1; page <= 2; page++) { + JsonNode data = request(signed(get("/admin-api/projects") + .param("assemblyAnimationStatus", "COMPLETED").param("page", Integer.toString(page)) + .param("size", "1").param("sort", "PUBLISHED_AT_DESC") + .param("type", "WHEELED").param("keyword", "测试") + .param("repoStatus", "READY").param("publishStatus", "UNPUBLISHED") + .param("moderationStatus", "NORMAL")), 200).path("data"); + assertThat(data.path("total").asLong()).isEqualTo(2); + assertThat(data.path("items")).hasSize(1); + JsonNode item = data.path("items").get(0); + assertThat(item.path("assemblyAnimationStatus").asText()).isEqualTo("COMPLETED"); + found.add(item.path("project").path("projectCode").asText()); + } + assertThat(found).containsExactlyInAnyOrder(first, second); + JsonNode unprocessed = request(signed(get("/admin-api/projects") + .param("assemblyAnimationStatus", "UNPROCESSED")), 200).path("data"); + assertThat(unprocessed.path("total").asLong()).isEqualTo(1); + assertThat(unprocessed.path("items").get(0).path("project").path("projectCode").asText()) + .isEqualTo(untouched); + assertThat(request(signed(get("/admin-api/projects").param("assemblyAnimationStatus", "IN_PROGRESS")), 200) + .path("data").path("total").asLong()).isZero(); + assertThat(request(signed(get("/admin-api/projects")), 200).path("data").path("total").asLong()) + .isEqualTo(3); + } + + @Test + void assemblyAnimationStatusRejectsInvalidValuesAndProtectsMissingOrDeletedProjects() throws Exception { + String code = createProject(); + String endpoint = "/admin-api/projects/" + code + "/assembly-animation-status"; + for (String invalid : List.of("", " ", "unknown", "in_progress", "已完成")) { + request(signed(body(put(endpoint), Map.of("status", invalid))), 400); + request(signed(get("/admin-api/projects").param("assemblyAnimationStatus", invalid)), 400); + } + request(signed(body(put(endpoint), Map.of())), 400); + request(signed(put(endpoint).contentType(MediaType.APPLICATION_JSON).content("{\"status\":null}")), 400); + Map input = Map.of("status", "COMPLETED"); + request(body(put(endpoint), input), 401); + String ordinaryToken = tokens.issue(ordinary.getId(), ordinary.getSessionVersion()); + request(body(put(endpoint), input).header("Authorization", "Bearer " + ordinaryToken), 403); + assertThat(request(signed(get("/admin-api/projects/" + code)), 200).path("data") + .path("assemblyAnimationStatus").asText()).isEqualTo("UNPROCESSED"); + request(signed(body(put("/admin-api/projects/missing/assembly-animation-status"), input)), 404); + request(signed(delete("/admin-api/projects/" + code)), 200); + request(signed(body(put(endpoint), input)), 404); + assertThat(request(signed(get("/admin-api/projects").param("assemblyAnimationStatus", "UNPROCESSED")), 200) + .path("data").path("total").asLong()).isZero(); + } + private MockHttpServletRequestBuilder uploadRequest(String code, String sha) { return signed(multipart("/admin-api/projects/" + code + "/uploads/commit") .file(new MockMultipartFile("files", "sample.txt", "text/plain", "hello".getBytes())) diff --git a/vibemake-api/src/test/java/com/linkerbot/vibemake/api/CadAiTest.java b/vibemake-api/src/test/java/com/linkerbot/vibemake/api/CadAiTest.java index de362d2..9e5493f 100644 --- a/vibemake-api/src/test/java/com/linkerbot/vibemake/api/CadAiTest.java +++ b/vibemake-api/src/test/java/com/linkerbot/vibemake/api/CadAiTest.java @@ -189,7 +189,7 @@ class CadAiTest { assertThat(body).doesNotContain("cad-test-placeholder", "apiKey", "endpoint", "SolidCraft"); assertThat(json.readTree(body).path("data").path("tools")).anySatisfy(tool -> { assertThat(tool.path("name").asText()).isEqualTo("skill_reference"); - assertThat(tool.path("parameters").path("properties").path("skill").path("enum")).hasSize(17); + assertThat(tool.path("parameters").path("properties").path("skill").path("enum")).hasSize(19); assertThat(tool.path("parameters").path("properties").path("file").path("default").asText()).isEqualTo("SKILL.md"); }); assertThat(json.readTree(body).path("data").has("id")).isFalse(); diff --git a/vibemake-bean/src/main/java/com/linkerbot/vibemake/bean/AdminContracts.java b/vibemake-bean/src/main/java/com/linkerbot/vibemake/bean/AdminContracts.java index 52059a2..20fb48f 100644 --- a/vibemake-bean/src/main/java/com/linkerbot/vibemake/bean/AdminContracts.java +++ b/vibemake-bean/src/main/java/com/linkerbot/vibemake/bean/AdminContracts.java @@ -45,6 +45,9 @@ public final class AdminContracts { public record ReasonInput(@NotBlank @Size(max = 500) String reason) {} + public record AssemblyAnimationStatusInput( + @NotBlank @Pattern(regexp = "UNPROCESSED|IN_PROGRESS|COMPLETED") String status) {} + public record UserView( String userCode, String nickname, @@ -105,6 +108,7 @@ public final class AdminContracts { public record ManagedProjectView( ProjectView project, + String assemblyAnimationStatus, String moderationStatus, String moderationReason, boolean deleted) {} diff --git a/vibemake-bean/src/main/java/com/linkerbot/vibemake/bean/entity/Project.java b/vibemake-bean/src/main/java/com/linkerbot/vibemake/bean/entity/Project.java index a66ad5d..437a2ef 100644 --- a/vibemake-bean/src/main/java/com/linkerbot/vibemake/bean/entity/Project.java +++ b/vibemake-bean/src/main/java/com/linkerbot/vibemake/bean/entity/Project.java @@ -28,6 +28,10 @@ public class Project extends BaseEntity { private String modelPartsFiles = "[]"; private String assemblyJsonObjectKey = ""; private Long assemblyJsonSizeBytes = 0L; + // 仅由制作状态接口局部更新,避免其他业务持有的旧项目快照覆盖进度。 + @com.baomidou.mybatisplus.annotation.TableField( + updateStrategy = com.baomidou.mybatisplus.annotation.FieldStrategy.NEVER) + private String assemblyAnimationStatus = "UNPROCESSED"; private String walkingResourcesPrefix = ""; private String walkingResourcesFiles = "[]"; private String projectType; diff --git a/vibemake-service/src/main/java/com/linkerbot/vibemake/service/admin/AdminManagementService.java b/vibemake-service/src/main/java/com/linkerbot/vibemake/service/admin/AdminManagementService.java index a1b624c..676a679 100644 --- a/vibemake-service/src/main/java/com/linkerbot/vibemake/service/admin/AdminManagementService.java +++ b/vibemake-service/src/main/java/com/linkerbot/vibemake/service/admin/AdminManagementService.java @@ -27,6 +27,8 @@ import java.util.Set; @RequiredArgsConstructor public class AdminManagementService { private static final Logger log = LoggerFactory.getLogger(AdminManagementService.class); + private static final Set ASSEMBLY_ANIMATION_STATUSES = + Set.of("UNPROCESSED", "IN_PROGRESS", "COMPLETED"); private final UserMapper users; private final ProjectMapper mapper; private final ProjectService projects; @@ -190,10 +192,13 @@ public class AdminManagementService { String publishStatus, String repoStatus, String moderationStatus, + String assemblyAnimationStatus, String sort) { requireAdmin(); ProjectSupport.pageCheck(page, size); checkKeyword(keyword); + if (assemblyAnimationStatus != null && !ASSEMBLY_ANIMATION_STATUSES.contains(assemblyAnimationStatus)) + throw BusinessException.badRequest("拼装动画制作状态不合法"); LambdaQueryWrapper query = ProjectSort.fromParameter(sort).query().eq(Project::getDeleted, false); query.select(Project.class, field -> !Set.of("urdfFiles", "modelPartsFiles", "walkingResourcesFiles") @@ -201,7 +206,8 @@ public class AdminManagementService { if (ownerCode != null) query.eq(Project::getOwnerUserId, user(ownerCode).getId()); query.eq(type != null, Project::getProjectType, type) .eq(publishStatus != null, Project::getPublishStatus, publishStatus) - .eq(repoStatus != null, Project::getRepoStatus, repoStatus); + .eq(repoStatus != null, Project::getRepoStatus, repoStatus) + .eq(assemblyAnimationStatus != null, Project::getAssemblyAnimationStatus, assemblyAnimationStatus); if (moderationStatus != null) { if (!Set.of("NORMAL", "BLOCKED").contains(moderationStatus)) throw BusinessException.badRequest("治理状态不合法"); @@ -222,6 +228,7 @@ public class AdminManagementService { managed.add( new AdminContracts.ManagedProjectView( views.get(index), + project.getAssemblyAnimationStatus(), "BLOCKED".equals(project.getPublishStatus()) ? "BLOCKED" : "NORMAL", project.getModerationReason(), Boolean.TRUE.equals(project.getDeleted()))); @@ -233,6 +240,7 @@ public class AdminManagementService { requireAdmin(); return new AdminContracts.ManagedProjectView( projects.view(project, null), + project.getAssemblyAnimationStatus(), "BLOCKED".equals(project.getPublishStatus()) ? "BLOCKED" : "NORMAL", project.getModerationReason(), Boolean.TRUE.equals(project.getDeleted())); @@ -248,6 +256,30 @@ public class AdminManagementService { return projects.create(owner.getId(), input.project()); } + public AdminContracts.ManagedProjectView assemblyAnimationStatus(String code, String status) { + requireAdmin(); + if (status == null || !ASSEMBLY_ANIMATION_STATUSES.contains(status)) + throw BusinessException.badRequest("拼装动画制作状态不合法"); + return locks.serial( + code, + () -> { + Project project = projects.owner(0, code); + if (status.equals(project.getAssemblyAnimationStatus())) return projectView(project); + int updated = mapper.update( + null, + new LambdaUpdateWrapper() + .eq(Project::getId, project.getId()) + .eq(Project::getDeleted, false) + .set(Project::getAssemblyAnimationStatus, status) + .set(Project::getUpdatedAt, ProjectSupport.now())); + if (updated != 1) throw BusinessException.conflict("项目已变化,请刷新重试"); + log.info( + "拼装动画制作状态修改 operatorUserCode={} projectCode={} previousStatus={} status={}", + ProjectActors.admin().userCode(), code, project.getAssemblyAnimationStatus(), status); + return projectView(projects.owner(0, code)); + }); + } + public void moderate(String code, boolean blocked, String reason) { requireAdmin(); locks.serial( diff --git a/vibemake-service/src/main/resources/cad/ai/skills.json b/vibemake-service/src/main/resources/cad/ai/skills.json index c101db6..5a7f033 100644 --- a/vibemake-service/src/main/resources/cad/ai/skills.json +++ b/vibemake-service/src/main/resources/cad/ai/skills.json @@ -6,7 +6,7 @@ "name": "makecad-agent-tools", "description": "Use when running makeCAD to see a change working, driving it through the control channel or CLI, or adding or changing an MCP tool, control method or bundled agent skill.", "files": { - "SKILL.md": "---\nname: makecad-agent-tools\ndescription: \"Use when running makeCAD to see a change working, driving it through the control channel or CLI, or adding or changing an MCP tool, control method or bundled agent skill.\"\n---\n\n# Running the app, the control channel and MCP tools\n\n## Run it and look at it\n- `cargo run --release -p solidcraft -- --sample --control PORT` starts the sample design with the control channel. Pick a free port. With no display, run it under `Xvfb :99` with `DISPLAY=:99`.\n- Talk JSON lines to `127.0.0.1:PORT` (`docs/control-protocol.md`). The first request on a connection carries the launch token as `\"token\"`: read it from `~/.local/share/solidcraft/control/PORT.token`, or start the app with `SOLIDCRAFT_CONTROL_TOKEN=$(openssl rand -hex 32)` and send that. Never paste the token into a PR or issue.\n - `{\"id\":1,\"method\":\"engine.execute\",\"params\":{\"command\":\"solid.extrude\",\"params\":{\"distance\":20}}}`\n - `{\"id\":2,\"method\":\"ui.start\",\"params\":{\"command\":\"sketch.create\"}}`, then `ui.click {x, y}`\n - `{\"id\":3,\"method\":\"ui.screenshot\",\"params\":{\"path\":\"/tmp/shot.png\"}}`, then read the PNG\n- For UI work, look at the result. Without a window use `ui.render` or `solidcraft-cli snapshot`.\n- Headless: `solidcraft-cli run script.json --out part.step`, `solidcraft-cli eval design.sc`, `solidcraft-cli snapshot script.json --out shot.png`, `solidcraft-cli commands`.\n- Build with `CARGO_TARGET_DIR=/target`.\n\n## MCP tools\nThe server is `solidcraft-cli mcp` (`crates/mcp/src/`, `docs/mcp.md`). Tools are defined in `crates/mcp/src/tools.rs`; keep `docs/mcp.md` in step, and keep tool annotations (read-only, destructive) honest.\n- Anything the user can do is a command; add a command, not a new tool, unless the tool is about the session itself (open, save, screenshot, batch).\n- Files: tools reach only the allowed folders (the design's folder, the recovery folder, the scratch folder, `--allow-path`). Do not widen this casually; paths are resolved before comparing, so `..` and links leaving the allowed set are refused, and on Windows UNC and device paths are refused.\n- Replies stay small: `verbose: false`, no unfiltered command catalogue or topology dumps.\n- The control channel is a local-only interface with a token. A new method needs an entry in `docs/control-protocol.md`; long work follows `skills/makecad-performance/SKILL.md`.\n\n## Bundled agent skills\nAll 17 skills and their text resources are embedded at build time by `crates/mcp/build.rs` for the read-only `skill_reference` tool. `skills/agent-workflow.md` is the shared generation workflow for MCP, the desktop assistant and the hosted Java gateway. Repository-only instructions do not grant the browser filesystem or shell capabilities.\n- When a command, parameter name or behaviour those skills describe changes, update them in the same PR. `skills_name_only_real_tools_and_commands` in `crates/mcp/src/tests.rs` fails when a skill names a tool or command that is gone.\n- Adding a skill or text resource embeds it automatically. Run `node scripts/sync-cad-ai-skills.mjs ` to update the Java package and rerun with `--check` to detect drift; rebuild WASM and Java together.\n- `skills/README.md` explains the layout and the other tests; `cargo xtask skills` checks that AGENTS.md and every SKILL.md cite real paths, commands and skills.\n" + "SKILL.md": "---\nname: makecad-agent-tools\ndescription: \"Use when running makeCAD to see a change working, driving it through the control channel or CLI, or adding or changing an MCP tool, control method or bundled agent skill.\"\n---\n\n# Running the app, the control channel and MCP tools\n\n## Run it and look at it\n- `cargo run --release -p solidcraft -- --sample --control PORT` starts the sample design with the control channel. Pick a free port. With no display, run it under `Xvfb :99` with `DISPLAY=:99`.\n- Talk JSON lines to `127.0.0.1:PORT` (`docs/control-protocol.md`). The first request on a connection carries the launch token as `\"token\"`: read it from `~/.local/share/solidcraft/control/PORT.token`, or start the app with `SOLIDCRAFT_CONTROL_TOKEN=$(openssl rand -hex 32)` and send that. Never paste the token into a PR or issue.\n - `{\"id\":1,\"method\":\"engine.execute\",\"params\":{\"command\":\"solid.extrude\",\"params\":{\"distance\":20}}}`\n - `{\"id\":2,\"method\":\"ui.start\",\"params\":{\"command\":\"sketch.create\"}}`, then `ui.click {x, y}`\n - `{\"id\":3,\"method\":\"ui.screenshot\",\"params\":{\"path\":\"/tmp/shot.png\"}}`, then read the PNG\n- For UI work, look at the result. Without a window use `ui.render` or `solidcraft-cli snapshot`.\n- Headless: `solidcraft-cli run script.json --out part.step`, `solidcraft-cli eval design.sc`, `solidcraft-cli snapshot script.json --out shot.png`, `solidcraft-cli commands`.\n- Build with `CARGO_TARGET_DIR=/target`.\n\n## MCP tools\nThe server is `solidcraft-cli mcp` (`crates/mcp/src/`, `docs/mcp.md`). Tools are defined in `crates/mcp/src/tools.rs`; keep `docs/mcp.md` in step, and keep tool annotations (read-only, destructive) honest.\n- Anything the user can do is a command; add a command, not a new tool, unless the tool is about the session itself (open, save, screenshot, batch).\n- Files: tools reach only the allowed folders (the design's folder, the recovery folder, the scratch folder, `--allow-path`). Do not widen this casually; paths are resolved before comparing, so `..` and links leaving the allowed set are refused, and on Windows UNC and device paths are refused.\n- Replies stay small: `verbose: false`, no unfiltered command catalogue or topology dumps.\n- The control channel is a local-only interface with a token. A new method needs an entry in `docs/control-protocol.md`; long work follows `skills/makecad-performance/SKILL.md`.\n\n## Bundled agent skills\nAll 19 skills and their text resources are embedded at build time by `crates/mcp/build.rs` for the read-only `skill_reference` tool. `skills/agent-workflow.md` is the shared generation workflow for MCP, the desktop assistant and the hosted Java gateway. Repository-only instructions do not grant the browser filesystem or shell capabilities.\n- When a command, parameter name or behaviour those skills describe changes, update them in the same PR. `skills_name_only_real_tools_and_commands` in `crates/mcp/src/tests.rs` fails when a skill names a tool or command that is gone.\n- Adding a skill or text resource embeds it automatically. Run `node scripts/sync-cad-ai-skills.mjs ` to update the Java package and rerun with `--check` to detect drift; rebuild WASM and Java together.\n- `skills/README.md` explains the layout and the other tests; `cargo xtask skills` checks that AGENTS.md and every SKILL.md cite real paths, commands and skills.\n" } }, { @@ -29,21 +29,21 @@ "name": "makecad-commands", "description": "Use when adding or changing a makeCAD command or any user-visible behaviour, or when deciding which crate code belongs in. Covers CommandSpec, command ids, programmatic calls vs dialogs, crate layering and the generated feature list.", "files": { - "SKILL.md": "---\nname: makecad-commands\ndescription: \"Use when adding or changing a makeCAD command or any user-visible behaviour, or when deciding which crate code belongs in. Covers CommandSpec, command ids, programmatic calls vs dialogs, crate layering and the generated feature list.\"\n---\n\n# Adding a command\n\nUser-visible behaviour is a command. The toolbar, dialogs, sketch tools, palette, scripts, CLI, control channel and MCP all reach the same commands through `Session::execute(id, params)`. The long form is `docs/book/src/dev/commands.md`.\n\n## Steps\n1. Add a `CommandSpec` to the right file in `crates/engine/src/cmd/` and implement `run` (`fn(&mut Session, &Value) -> Result`). Fields: id, label, toolbar tab and panel (`.at`), icon (`.icon`), shortcut (`.key`), params doc (`.params`), `enabled` (its error string is the disabled-button tooltip).\n2. The id is our own: dotted, lower-case `.[.]`, such as `solid.extrude` or `sketch.rectangle.two_point`. Never another product's id.\n3. Validate inputs first (units, ranges, references) and return `BadParams` rather than building a broken feature. Parameters are hostile: see `skills/makecad-crash-safety/SKILL.md`.\n4. Give it input and output schemas: a contract and a reply type in `crates/engine/src/schema/`, registered with `checked!`, `.contract` and `.output`. A command should have them and a test warns without them; this will become required. `schema/unconverted.txt` only shrinks. How: `docs/book/src/dev/schemas.md`.\n5. Engine tests measure the result: volume, area, face/edge/vertex counts against values you can derive by hand. Where they go: `skills/makecad-tests/SKILL.md`.\n6. Add the label as `cmd.` in a pending locale file (`cargo xtask i18n --add-missing` lists what is missing); a test fails without it. See `skills/makecad-ui-text/SKILL.md`.\n7. A command the ribbon shows also needs help: `help.` (what it does, then when to use it) in the pending file, and its id in `DOCUMENTED` in `crates/ui-egui/src/command_help.rs`. A test fails without them.\n8. Run `cargo xtask features` to see the generated `docs/features.md` change, but do not commit it: `main` regenerates it after each merge.\n9. If the command saves something new in a design, add a format file: `skills/makecad-file-formats/SKILL.md`.\n10. If it needs a dialog or panel: `skills/makecad-ui/SKILL.md`.\n\n## Programmatic calls never open dialogs\n`engine.execute` runs the JSON form. Only toolbar clicks (`ui.start`) start interactive tools and dialogs, which then run commands. A dialog is a front-end form that builds the parameters.\n\nA command that changes the design is undoable by default (the session snapshots the document first), and a failing command leaves the document unchanged.\n\n## Layering\n`cargo xtask layers` fails the build when a lower layer depends on a higher one:\n\nL0 `geom` -> L1 `sketch`, `kernel`, `render` -> L2 `doc` -> L3 `io` -> L4 `engine` -> L5 `ui-egui` -> apps.\n\n- Nothing below L5 depends on egui, eframe, winit, wgpu or rfd. The UI crate is swappable.\n- Only `crates/kernel` may use `truck`.\n- The UI is thin: panels read engine state and act through `app.run(id, params)` or `app.start(id)`.\n- A new module's `mod` line goes into the existing sorted group, not a new group at the end (`cargo fmt` keeps each group sorted).\n\n## Roadmap\n`ROADMAP.md` tracks milestones; update it when a milestone task lands.\n" + "SKILL.md": "---\nname: makecad-commands\ndescription: \"Use when adding or changing a makeCAD command or any user-visible behaviour, or when deciding which crate code belongs in. Covers CommandSpec, command ids, programmatic calls vs dialogs, crate layering and the generated feature list.\"\n---\n\n# Adding a command\n\nUser-visible behaviour is a command. The toolbar, dialogs, sketch tools, palette, scripts, CLI, control channel and MCP all reach the same commands through `Session::execute(id, params)`. The long form is `docs/book/src/dev/commands.md`.\n\n## Steps\n1. Add a `CommandSpec` to the right file in `crates/engine/src/cmd/` and implement `run` (`fn(&mut Session, &Value) -> Result`). Fields: id, label, toolbar tab and panel (`.at`), icon (`.icon`), shortcut (`.key`), params doc (`.params`), `enabled` (its error string is the disabled-button tooltip).\n2. The id is our own: dotted, lower-case `.[.]`, such as `solid.extrude` or `sketch.rectangle.two_point`. Never another product's id.\n3. Validate inputs first (units, ranges, references) and return `BadParams` rather than building a broken feature. Parameters are hostile: see `skills/makecad-crash-safety/SKILL.md`.\n4. Give it input and output schemas: a contract and a reply type in `crates/engine/src/schema/`, registered with `checked!`, `.contract` and `.output`. A command should have them and a test warns without them; this will become required. `schema/unconverted.txt` only shrinks. How: `docs/book/src/dev/schemas.md`.\n5. Engine tests measure the result: volume, area, face/edge/vertex counts against values you can derive by hand. Where they go: `skills/makecad-tests/SKILL.md`.\n6. Add the label as `cmd.` in a pending locale file (`cargo xtask i18n --add-missing` lists what is missing); a test fails without it. See `skills/makecad-ui-text/SKILL.md`.\n7. A command the ribbon shows also needs help: `help.` (what it does, then when to use it) in the pending file, and its id in `DOCUMENTED` in `crates/ui-egui/src/command_help.rs`. A test fails without them.\n8. Run `cargo xtask features` to see the generated `docs/features.md` change, but do not commit it: `main` regenerates it after each merge.\n9. If the command saves something new in a design, add a format file: `skills/makecad-file-formats/SKILL.md`.\n10. If it needs a dialog or panel: `skills/makecad-ui/SKILL.md`.\n\n## Programmatic calls never open dialogs\n`engine.execute` runs the JSON form. Only toolbar clicks (`ui.start`) start interactive tools and dialogs, which then run commands. A dialog is a front-end form that builds the parameters.\n\nA command that changes the design is undoable by default (the session snapshots the document first), and a failing command leaves the document unchanged.\n\n## Layering\n`cargo xtask layers` fails the build when a lower layer depends on a higher one:\n\nL0 `geom` -> L1 `sketch`, `kernel`, `render` -> L2 `doc` -> L3 `io` -> L4 `engine` -> L5 `ui-egui` -> apps.\n\n- Nothing below L5 depends on egui, eframe, winit, wgpu or rfd. The UI crate is swappable.\n- Only `crates/kernel` may use `truck`.\n- Solidcore only through `solidcore-ops` (STEP too; `solidcore_ops::Order`), `-tess`, `-record`; exceptions: `xtask/solidcore-seam.txt`, shrink only.\n- The UI is thin: panels read engine state and act through `app.run(id, params)` or `app.start(id)`.\n- A new module's `mod` line goes into the existing sorted group, not a new group at the end (`cargo fmt` keeps each group sorted).\n\n## Roadmap\n`ROADMAP.md` tracks milestones; update it when a milestone task lands.\n" } }, { "name": "makecad-contributing", "description": "Use when someone wants to contribute code or documentation to makeCAD, from setting up a fork and choosing an issue through submitting a pull request and responding to review.", "files": { - "SKILL.md": "---\nname: makecad-contributing\ndescription: Use when someone wants to contribute code or documentation to makeCAD, from setting up a fork and choosing an issue through submitting a pull request and responding to review.\n---\n\n# Contribute to makeCAD\n\nRead [CONTRIBUTING.md](../../CONTRIBUTING.md), [AGENTS.md](../../AGENTS.md) (the router\nto the other skills), the [contributor book page](../../docs/book/src/dev/contributing.md),\nand the [skills index](../README.md) first. Follow their current rules; use this skill to\nhelp a first-time contributor apply them. This skill concerns the repository,\nnot modelling a part through MCP.\n\n## Rules for every PR\n\n- **Look at what is open first.** Pull the whole list, drafts included:\n `gh pr list -R tangency-labs/solidcraft --state open --limit 500` and\n `gh issue list -R tangency-labs/solidcraft --state open --limit 500`. Look for the same issue, the same\n feature under another number, and PRs that change the files you will change\n (`gh pr list ... --json number,title,files`). If someone has it, comment on their PR or issue\n instead of opening a second one: two PRs for one change cannot both land.\n- **Claim with a draft PR.** `gh pr list -R tangency-labs/solidcraft --state open --search \"#N\"`; if none,\n branch from the latest `origin/main`, `git commit --allow-empty -m \"claim: #N\"`, push, and open a\n draft PR titled ` (#N)`. The lowest-numbered open PR for an issue wins; close yours if it\n lost. The bot assigns you and labels the issue `in progress`. Do not claim by editing files; comment\n `/claim` only to stake a claim before you have a branch.\n- **Write the title and first sentence for a reader who has seen nothing else.** Not your chat, not the\n issue, not the code. Maintainers pick what to review from the title, and it becomes the commit on\n `main`. Say which part of the app changes and what a user now sees or can do, in everyday words. Don't\n paste the issue's title unless it passes this too. Before opening the PR, and again before marking it\n ready, read both with everything else closed: if \"there\", \"it\", \"this\" or \"that\" has nothing to point\n at, or a term only makes sense after reading the diff, rewrite it. Keep the terms a user sees in the\n app and explain the others.\n - Unclear: `Send to Slicer: pick one print face per body there, and show print faces only while it is open`\n - Clear: `3D printing: choose the face each body rests on in the Send to Slicer window, not the face menu`\n- **Write PR text in plain, literal English.** This follows the spirit of Simplified Technical English,\n not its approved-word list. Keep the names a user sees in the app, even if they aren't everyday words.\n - One idea per sentence, and about 20 words at most.\n - Use active voice: \"The view tints the face\", not \"The face is tinted\".\n - Use one word for one thing, and don't switch to a synonym partway through.\n - Repeat the noun when \"it\" or \"this\" could be unclear.\n - Don't stack nouns: \"the option for picking in the face menu\", not \"face menu picking option\".\n- **Push daily.** A draft with no pushes for 72 hours may be taken over: comment first, then open your\n own claim (you may start from its branch). The bot's automatic cleanup deadlines in CONTRIBUTING.md\n are separate.\n- **One topic and one issue per PR.** Never commit `plan/`, build directories (`target*/`) or generated\n reference data; check `git ls-files` before pushing. Run `cargo xtask ci` before every commit.\n Commit after every feature arc that builds.\n- **Merge flow.** The heavy CI jobs start when a maintainer adds `approved-for-ci`; approved PRs go\n through the merge queue (`gh pr merge N -R tangency-labs/solidcraft --squash --auto`), which runs the\n full suite on each group before it lands on `main`. Never force-push `main`.\n- **Do not push only to catch up with `main`** (no merge of `main`, no Update branch, no rebase for\n that alone): every push restarts the whole CI run, and `main`'s own run catches what lands in between.\n When you push anyway, or GitHub reports a conflict, rebase onto the latest `main` and push your own\n branch with `--force-with-lease`; never merge `main` into a PR. Resolve conflicts without discarding\n others' work. Do not re-run CI on an unchanged commit: re-run only a job that runner trouble\n cancelled, with \"Re-run failed jobs\".\n- **Evidence.** For observable CAD, UI or model behaviour (kernel, geometry, assembly and backend\n changes included), the issue or PR carries real screenshots or a short recording from a small\n reproduction, preferably before and after, with steps and expected/actual behaviour. Capture it\n yourself; do not ask a human for evidence you can produce. Diagrams do not replace it. Changes with\n nothing observable need none. Use a public-safe example, check for private designs, paths and account\n details, attach the media rather than committing it.\n- **Follow through.** Check the PR's merge status throughout and before handoff. Report the state you\n checked and any conflicts resolved. While the PR is open, keep monitoring it and say clearly that it\n is pending; do not claim it merged without checking.\n- **Shared build machine.** Check the load before a big build (`cut -d' ' -f1 /proc/loadavg`), wait\n while it is over 24, and build with `nice`.\n- **Maintainers' machines** keep a local, gitignored `plan/` folder: read `plan/STATUS.md` (current\n milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md`\n section. Kernel and library decisions are in `plan/adr/0001-geometry-kernel.md`. Follow the autonomous\n operation protocol in `plan/execution-plan.md` section 6; do not stop to ask unless it lists the decision\n as the owner's. Contributors without `plan/` can ignore this.\n- **Update the roadmap** when a milestone task lands: `docs/roadmap-detail.md` tracks status, milestones and estimates; `ROADMAP.md` is the short user-facing roadmap.\n- **Start here.** What to work on: `ROADMAP.md`, \"Where help is wanted most\" in CONTRIBUTING.md and the open issues labelled `help wanted`, `good first issue`, `needs-triage`; check what is already open first. Architecture: `docs/architecture.md` and \"How the code is laid out\" in CONTRIBUTING.md; kernel work is paused (\"Kernel work is paused\" in CONTRIBUTING.md). Licence rules: `deny.toml` and `cargo xtask licences --check`; only `crates/kernel` may use `truck`. When the code, docs and rules settle a question, act; ask on the issue or PR only when the answer changes what users see or what the change covers.\n- **Do not open a second PR** for an issue a lower-numbered open PR already closes, and keep the `Changes a default:` line filled in: `pr-checks.yml` fails both.\n- **The gate reads the working tree.** Do not switch branches while `cargo xtask ci` runs: it compiles the other branch's code and fails on a change not in the PR. Run it in the background and wait for its log.\n\n## Working as an agent\n\n- **The code is English. The comments are English. Always.** Identifiers, doc comments,\n inline comments, commit messages, branch names, test names, error messages and\n documentation are all in English. This is not a preference: a comment in another\n language is a defect, it is not reviewable by the people who maintain this code, and a\n reviewer rejects it. If something is not obvious, write it in English and keep it\n short. A user-visible string is not inline in the code: it goes to the message\n catalogs in `assets/locales/` (a new one to `assets/locales/pending/.json`),\n and `skills/makecad-ui-text/SKILL.md` says how to name and translate it.\n- **Parallel work runs in parallel.** When a task splits into independent parts (several\n files, several areas, several checks that do not depend on each other), dispatch one\n subagent per part and let them run concurrently instead of walking the list one item at\n a time. Give every subagent a self-contained brief: what to change, what not to touch,\n and what to report back. Read the answers before you continue; a subagent's report is\n not a result you can assume.\n- **Do not parallelize what depends on itself.** A fix and the test that proves it, a\n refactor and the callers it breaks, two edits to the same file: those stay sequential.\n One subagent per independent unit of work, and no two units may write the same file.\n\n## 1. Check the environment\n\nExplain what you are checking and why, in everyday language. Run:\n\n```sh\ngh --version\ngh auth status\ngit --version\nrustup show\nrustc --version\ncargo --version\ndf -h .\n```\n\nCheck available memory, CPU and whether a display is available. Establish whether\nthis is the person's computer or a cloud sandbox; do not assume desktop access,\npersistent files or enough space for a full build. Compare Rust with the current\nminimum in CONTRIBUTING.md. If tools or sign-in are missing, explain the next\nstep and help the person set them up; never ask them to paste credentials.\n\nBefore every public action, show the exact proposed content and destination and\nask the person to approve it. This includes creating a public fork, pushing,\nopening or updating a PR, uploading evidence, marking it ready and commenting.\nExplain a PR as a request for maintainers to review a change. Keep check-ins short\nat each step: what you found, what comes next, and what needs their decision.\n\n## 2. Fork and clone\n\nExplain that changes go to their own copy on GitHub. After approval, run:\n\n```sh\ngh repo fork tangency-labs/solidcraft --clone --remote\ncd solidcraft\ngit remote -v\n```\n\nEnsure `origin` points to the person's fork. If `upstream` is absent, add it:\n\n```sh\ngit remote add upstream https://github.com/tangency-labs/solidcraft.git\n```\n\nNever push to upstream. If cloning an existing fork instead, check the same remote\nlayout. With a clean working tree, sync local `main` before starting work:\n\n```sh\ngit fetch upstream\ngit switch main\ngit merge --ff-only upstream/main\n```\n\nAfter approval, sync the fork with `git push origin main`. If fast-forwarding\nfails, inspect the divergence and preserve existing work; do not reset it away.\n\n## 3. Choose an unclaimed task together\n\nAsk about their interests and show a few issues that fit the available resources.\nRead the current kernel-pause notice in CONTRIBUTING.md and skip kernel work\nwhile paused, including tasks outside `crates/kernel/` that change kernel behaviour.\nFetch the whole open list, including drafts, before narrowing it:\n\n```sh\ngh issue list -R tangency-labs/solidcraft --state open --limit 500\ngh pr list -R tangency-labs/solidcraft --state open --limit 500 --json number,title,files\ngh issue list -R tangency-labs/solidcraft --state open --label 'good first issue' --search '-label:kernel-paused -label:\"in progress\"' --limit 100\ngh issue list -R tangency-labs/solidcraft --state open --label 'help wanted' --search '-label:kernel-paused -label:\"in progress\"' --limit 100\n```\n\nLet the person choose. Set `N` to that issue's number, then inspect its discussion,\nassignee and linked PRs; check similar work under other numbers and overlapping files:\n\n```sh\ngh issue view \"$N\" -R tangency-labs/solidcraft --comments\ngh pr list -R tangency-labs/solidcraft --state open --search \"#$N\"\n```\n\nIf it is already claimed, choose another task with the person. Do not open a\ncompeting PR or post a comment without their approval.\n\n## 4. Claim with a draft PR\n\nExplain the proposed change and show the draft title and body for approval before\npublishing. Recheck availability immediately before claiming. Follow the claim\nrules in CONTRIBUTING.md; substitute the chosen summary and fork owner below:\n\n```sh\ngit fetch upstream\ngit switch -c \"fix-$N\" upstream/main\ngit commit --allow-empty -m \"claim: #$N\"\ngit push -u origin \"fix-$N\"\ngh pr create --repo tangency-labs/solidcraft --head \"FORK_OWNER:fix-$N\" --base main --draft --title \"SUMMARY (#$N)\" --body-file /tmp/solidcraft-pr-body.md\n```\n\nWrite the body file first, describing the intended fix and referencing `Fixes #N`.\nThe draft PR is the claim; check the bot's response and the lowest-numbered open\nPR rule before editing. If another claim won, explain it and ask before closing\nthe duplicate. Do not try to claim by editing files.\n\n## 5. Make and check one focused change\n\nExplain the intended behaviour, then pick the skill for the area from AGENTS.md's table and\nfollow it (never crash, commands, layering, clean-room rules and tests all live there).\nPut synthetic regression tests in the existing test module for the affected area;\nprove a bug test fails before the fix and passes after it.\n\nUse the affected crate and test module in commands such as:\n\n```sh\ncargo test --profile ci -p solidcraft-engine --lib -- tests::feature_inputs_are_parameters\ncargo clippy -p solidcraft-engine --all-targets -- -D warnings\ncargo fmt --all -- --check\ncargo xtask ci\n```\n\nRun `cargo xtask ci` before each implementation commit on a capable environment.\nOn small environments, use targeted tests and report exactly what passed and what\ncould not run; leave the full suite to CI rather than claiming it passed. Follow\n[testing guidance](../../docs/book/src/dev/testing.md) for applicable checks.\nReview the diff, keep one topic, and commit the finished change. Before an approved\npush, follow \"Rules for every PR\" above; do not push solely to catch up\nwith `main`. Explain progress and ask before publishing each update.\n\n## 6. Show the result\n\nFor visible changes, reproduce the result with a small public-safe example and\ncapture actual screenshots or a short recording, preferably before and after.\nFor model output without a display, run:\n\n```sh\nsolidcraft-cli snapshot script.json --out /tmp/solidcraft-result.png\n```\n\nFor UI behaviour, launch the desktop app with a free control port:\n\n```sh\ncargo run --release -p solidcraft -- --sample --control 7878\n```\n\nFollow [the control protocol](../../docs/control-protocol.md): connect to\n`127.0.0.1:7878`, read the launch token from its documented location, and send JSON\nlines. Put the real token in the first request's top-level `token` field:\n\n```json\n{\"id\":1,\"token\":\"TOKEN\",\"method\":\"ui.inspect\",\"params\":{}}\n{\"id\":2,\"method\":\"ui.screenshot\",\"params\":{\"path\":\"/tmp/solidcraft-result.png\"}}\n```\n\nUse `engine.execute` for commands and `ui.start` plus `ui.click` for interactive\nreproductions. Open and inspect the image. Check for private designs, paths and\ncredentials before sharing; never expose the token. Show the person the media\nand ask before attaching it to the PR or linking an accessible recording. Include\nbrief reproduction steps and expected/actual behaviour; do not commit generated\nreview media. Documentation-only changes need no screenshot.\n\n## 7. Finish and respond to review\n\nPrepare the final title and body: `Fixes #N`, the problem, resulting behaviour,\nvalidation and any evidence or limitations. Show them to the person before\nupdating the PR. After their approval, mark the draft ready:\n\n```sh\ngh pr ready PR_NUMBER -R tangency-labs/solidcraft\n```\n\nExplain that a maintainer reviews the change and adds `approved-for-ci` to start\nheavy checks; do not add that label yourself. Monitor checks and merge status,\naddress review comments, rerun affected checks for fixes, and ask before public\nreplies or pushes. Report whether it merged or remains pending; do not promise a\nmerge or rerun an unchanged failing check without evidence of infrastructure trouble.\n\n## Cloud sandbox\n\nWithout a display, use `solidcraft-cli snapshot` for model evidence or launch the\napp under `Xvfb :99` with `DISPLAY=:99` for UI evidence. With limited disk or CPU,\nprefer a documentation or small isolated task, targeted tests and existing build\nartifacts; explain any missing checks. Preserve work before temporary storage\nexpires and ask before publishing it. Always push only to the person's fork,\nnever to upstream.\n" + "SKILL.md": "---\nname: makecad-contributing\ndescription: Use when someone wants to contribute code or documentation to makeCAD, from setting up a fork and choosing an issue through submitting a pull request and responding to review.\n---\n\n# Contribute to makeCAD\n\nRead [CONTRIBUTING.md](../../CONTRIBUTING.md), [AGENTS.md](../../AGENTS.md) (the router\nto the other skills), the [contributor book page](../../docs/book/src/dev/contributing.md),\nand the [skills index](../README.md) first. Follow their current rules; use this skill to\nhelp a first-time contributor apply them. This skill concerns the repository,\nnot modelling a part through MCP.\n\n## Rules for every PR\n\n- **Look at what is open first.** Pull the whole list, drafts included:\n `gh pr list -R tangency-labs/solidcraft --state open --limit 500` and\n `gh issue list -R tangency-labs/solidcraft --state open --limit 500`. Look for the same issue, the same\n feature under another number, and PRs that change the files you will change\n (`gh pr list ... --json number,title,files`). If someone has it, comment on their PR or issue\n instead of opening a second one: two PRs for one change cannot both land.\n- **Claim with a draft PR.** `gh pr list -R tangency-labs/solidcraft --state open --search \"#N\"`; if none,\n branch from the latest `origin/main`, `git commit --allow-empty -m \"claim: #N\"`, push, and open a\n draft PR titled ` (#N)`. The lowest-numbered open PR for an issue wins; close yours if it\n lost. The bot assigns you and labels the issue `in progress`. Do not claim by editing files; comment\n `/claim` only to stake a claim before you have a branch.\n- **Write the title and first sentence for a reader who has seen nothing else.** Not your chat, not the\n issue, not the code. Maintainers pick what to review from the title, and it becomes the commit on\n `main`. Say which part of the app changes and what a user now sees or can do, in everyday words. Don't\n paste the issue's title unless it passes this too. Before opening the PR, and again before marking it\n ready, read both with everything else closed: if \"there\", \"it\", \"this\" or \"that\" has nothing to point\n at, or a term only makes sense after reading the diff, rewrite it. Keep the terms a user sees in the\n app and explain the others.\n - Unclear: `Send to Slicer: pick one print face per body there, and show print faces only while it is open`\n - Clear: `3D printing: choose the face each body rests on in the Send to Slicer window, not the face menu`\n- **Write PR text in plain, literal English.** This follows the spirit of Simplified Technical English,\n not its approved-word list. Keep the names a user sees in the app, even if they aren't everyday words.\n - One idea per sentence, and about 20 words at most.\n - Use active voice: \"The view tints the face\", not \"The face is tinted\".\n - Use one word for one thing, and don't switch to a synonym partway through.\n - Repeat the noun when \"it\" or \"this\" could be unclear.\n - Don't stack nouns: \"the option for picking in the face menu\", not \"face menu picking option\".\n- **Push daily.** A draft with no pushes for 72 hours may be taken over: comment first, then open your\n own claim (you may start from its branch). The bot's automatic cleanup deadlines in CONTRIBUTING.md\n are separate.\n- **One topic and one issue per PR.** Never commit `plan/`, build directories (`target*/`) or generated\n reference data; check `git ls-files` before pushing. Run `cargo xtask ci` before every commit.\n Commit after every feature arc that builds.\n- **Merge flow.** The heavy CI jobs start when a maintainer adds `approved-for-ci`. Contributors don't\n queue or merge their own PRs: a maintainer or steward adds `ready to merge` (and `approved-for-ci` for\n a fork), and the merge shepherd enqueues the PR once it is green and passes the review gates\n (CodeRabbit threads resolved; CI or workflow changes need the owner's approval). The queue runs the\n full suite on each group before it lands on `main`. Never force-push `main`.\n- **Do not push only to catch up with `main`:** every push restarts the whole CI run, and `main`'s own\n run catches what lands in between. When you push anyway, or GitHub reports a conflict, rebase onto\n the latest `main` (preferred for your own branch; push it with `--force-with-lease`) or merge `main`\n in; both are fine. Never force-push a branch someone else works on. Automation that updates your PR\n merges `main` into your branch and never force-pushes over your history. Resolve conflicts without\n discarding others' work. Do not re-run CI on an unchanged commit: re-run only a job that runner\n trouble cancelled, with \"Re-run failed jobs\".\n- **Kernel, series and drawings.** Kernel work goes in `solidcore/` on `main` (there is no kernel\n branch) and follows `solidcore/docs/layers.md` and §7 of\n `solidcore/docs/definitions-and-certificates.md`. The first PR of a series that sets a shape (a type,\n error shape, API, format or schema) gets a design review before later parts are accepted. Drawings\n work targets the `drawings` branch. A UI addition needs full-flow 1280×720 screenshots and a\n small-window check.\n- **Evidence.** For observable CAD, UI or model behaviour (kernel, geometry, assembly and backend\n changes included), the issue or PR carries real screenshots or a short recording from a small\n reproduction, preferably before and after, with steps and expected/actual behaviour. Capture it\n yourself; do not ask a human for evidence you can produce. Diagrams do not replace it. Changes with\n nothing observable need none. Use a public-safe example, check for private designs, paths and account\n details, attach the media rather than committing it.\n- **Follow through.** Check the PR's merge status throughout and before handoff. Report the state you\n checked and any conflicts resolved. While the PR is open, keep monitoring it and say clearly that it\n is pending; do not claim it merged without checking.\n- **Shared build machine.** Check the load before a big build (`cut -d' ' -f1 /proc/loadavg`), wait\n while it is over 24, and build with `nice`.\n- **Maintainers' machines** keep a local, gitignored `plan/` folder: read `plan/STATUS.md` (current\n milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md`\n section. Kernel and library decisions are in `plan/adr/0001-geometry-kernel.md`. Follow the autonomous\n operation protocol in `plan/execution-plan.md` section 6; do not stop to ask unless it lists the decision\n as the owner's. Contributors without `plan/` can ignore this.\n- **Update the roadmap** when a milestone task lands: `docs/roadmap-detail.md` tracks status, milestones and estimates; `ROADMAP.md` is the short user-facing roadmap.\n- **Start here.** What to work on: `ROADMAP.md`, \"Where help is wanted most\" in CONTRIBUTING.md and the open issues labelled `help wanted`, `good first issue`, `needs-triage`; check what is already open first. Architecture: `docs/architecture.md` and \"How the code is laid out\" in CONTRIBUTING.md; kernel work goes in `solidcore/` (\"Kernel work goes in solidcore/\" in CONTRIBUTING.md). Licence rules: `deny.toml` and `cargo xtask licences --check`; only `crates/smlib` may use `solidcore`. When the code, docs and rules settle a question, act; ask on the issue or PR only when the answer changes what users see or what the change covers.\n- **Do not open a second PR** for an issue a lower-numbered open PR already closes, and keep the `Changes a default:` line filled in: `pr-checks.yml` fails both.\n- **The gate reads the working tree.** Do not switch branches while `cargo xtask ci` runs: it compiles the other branch's code and fails on a change not in the PR. Run it in the background and wait for its log.\n\n## Working as an agent\n\n- **The code is English. The comments are English. Always.** Identifiers, doc comments,\n inline comments, commit messages, branch names, test names, error messages and\n documentation are all in English. This is not a preference: a comment in another\n language is a defect, it is not reviewable by the people who maintain this code, and a\n reviewer rejects it. If something is not obvious, write it in English and keep it\n short. A user-visible string is not inline in the code: it goes to the message\n catalogs in `assets/locales/` (a new one to `assets/locales/pending/.json`),\n and `skills/makecad-ui-text/SKILL.md` says how to name and translate it.\n- **Parallel work runs in parallel.** When a task splits into independent parts (several\n files, several areas, several checks that do not depend on each other), dispatch one\n subagent per part and let them run concurrently instead of walking the list one item at\n a time. Give every subagent a self-contained brief: what to change, what not to touch,\n and what to report back. Read the answers before you continue; a subagent's report is\n not a result you can assume.\n- **Do not parallelize what depends on itself.** A fix and the test that proves it, a\n refactor and the callers it breaks, two edits to the same file: those stay sequential.\n One subagent per independent unit of work, and no two units may write the same file.\n- **Keep the cost down.** Keep one long-running agent session instead of restarting it.\n Don't `--resume` a session after its prompt cache has gone cold: a cold resume re-reads the\n whole history at full price. Act on CodeRabbit comments only when they're about crashes,\n wrong results, data loss or security, and ignore style nitpicks. Don't push just to\n re-trigger a review.\n\n## 1. Check the environment\n\nExplain what you are checking and why, in everyday language. Run:\n\n```sh\ngh --version\ngh auth status\ngit --version\nrustup show\nrustc --version\ncargo --version\ndf -h .\n```\n\nCheck available memory, CPU and whether a display is available. Establish whether\nthis is the person's computer or a cloud sandbox; do not assume desktop access,\npersistent files or enough space for a full build. Compare Rust with the current\nminimum in CONTRIBUTING.md. If tools or sign-in are missing, explain the next\nstep and help the person set them up; never ask them to paste credentials.\n\nBefore every public action, show the exact proposed content and destination and\nask the person to approve it. This includes creating a public fork, pushing,\nopening or updating a PR, uploading evidence, marking it ready and commenting.\nExplain a PR as a request for maintainers to review a change. Keep check-ins short\nat each step: what you found, what comes next, and what needs their decision.\n\n## 2. Fork and clone\n\nExplain that changes go to their own copy on GitHub. After approval, run:\n\n```sh\ngh repo fork tangency-labs/solidcraft --clone --remote\ncd solidcraft\ngit remote -v\n```\n\nEnsure `origin` points to the person's fork. If `upstream` is absent, add it:\n\n```sh\ngit remote add upstream https://github.com/tangency-labs/solidcraft.git\n```\n\nNever push to upstream. If cloning an existing fork instead, check the same remote\nlayout. With a clean working tree, sync local `main` before starting work:\n\n```sh\ngit fetch upstream\ngit switch main\ngit merge --ff-only upstream/main\n```\n\nAfter approval, sync the fork with `git push origin main`. If fast-forwarding\nfails, inspect the divergence and preserve existing work; do not reset it away.\n\n## 3. Choose an unclaimed task together\n\nAsk about their interests and show a few issues that fit the available resources.\nKernel and geometry tasks are fine: they go in `solidcore/` (CONTRIBUTING.md, \"Kernel work goes in solidcore/\").\nFetch the whole open list, including drafts, before narrowing it:\n\n```sh\ngh issue list -R tangency-labs/solidcraft --state open --limit 500\ngh pr list -R tangency-labs/solidcraft --state open --limit 500 --json number,title,files\ngh issue list -R tangency-labs/solidcraft --state open --label 'good first issue' --search '-label:\"in progress\"' --limit 100\ngh issue list -R tangency-labs/solidcraft --state open --label 'help wanted' --search '-label:\"in progress\"' --limit 100\n```\n\nLet the person choose. Set `N` to that issue's number, then inspect its discussion,\nassignee and linked PRs; check similar work under other numbers and overlapping files:\n\n```sh\ngh issue view \"$N\" -R tangency-labs/solidcraft --comments\ngh pr list -R tangency-labs/solidcraft --state open --search \"#$N\"\n```\n\nIf it is already claimed, choose another task with the person. Do not open a\ncompeting PR or post a comment without their approval.\n\n## 4. Claim with a draft PR\n\nExplain the proposed change and show the draft title and body for approval before\npublishing. Recheck availability immediately before claiming. Follow the claim\nrules in CONTRIBUTING.md; substitute the chosen summary and fork owner below:\n\n```sh\ngit fetch upstream\ngit switch -c \"fix-$N\" upstream/main\ngit commit --allow-empty -m \"claim: #$N\"\ngit push -u origin \"fix-$N\"\ngh pr create --repo tangency-labs/solidcraft --head \"FORK_OWNER:fix-$N\" --base main --draft --title \"SUMMARY (#$N)\" --body-file /tmp/solidcraft-pr-body.md\n```\n\nWrite the body file first, describing the intended fix and referencing `Fixes #N`.\nThe draft PR is the claim; check the bot's response and the lowest-numbered open\nPR rule before editing. If another claim won, explain it and ask before closing\nthe duplicate. Do not try to claim by editing files.\n\n## 5. Make and check one focused change\n\nExplain the intended behaviour, then pick the skill for the area from AGENTS.md's table and\nfollow it (never crash, commands, layering, clean-room rules and tests all live there).\nPut synthetic regression tests in the existing test module for the affected area;\nprove a bug test fails before the fix and passes after it.\n\nUse the affected crate and test module in commands such as:\n\n```sh\ncargo test --profile ci -p solidcraft-engine --lib -- tests::feature_inputs_are_parameters\ncargo clippy -p solidcraft-engine --all-targets -- -D warnings\ncargo xtask fmt --check\ncargo xtask ci\n```\n\nRun `cargo xtask ci` before each implementation commit on a capable environment.\nOn small environments, use targeted tests and report exactly what passed and what\ncould not run; leave the full suite to CI rather than claiming it passed. Follow\n[testing guidance](../../docs/book/src/dev/testing.md) for applicable checks.\nReview the diff, keep one topic, and commit the finished change. Before an approved\npush, follow \"Rules for every PR\" above; do not push solely to catch up\nwith `main`. Explain progress and ask before publishing each update.\n\n## 6. Show the result\n\nFor visible changes, reproduce the result with a small public-safe example and\ncapture actual screenshots or a short recording, preferably before and after.\nFor model output without a display, run:\n\n```sh\nsolidcraft-cli snapshot script.json --out /tmp/solidcraft-result.png\n```\n\nFor UI behaviour, launch the desktop app with a free control port:\n\n```sh\ncargo run --release -p solidcraft -- --sample --control 7878\n```\n\nFollow [the control protocol](../../docs/control-protocol.md): connect to\n`127.0.0.1:7878`, read the launch token from its documented location, and send JSON\nlines. Put the real token in the first request's top-level `token` field:\n\n```json\n{\"id\":1,\"token\":\"TOKEN\",\"method\":\"ui.inspect\",\"params\":{}}\n{\"id\":2,\"method\":\"ui.screenshot\",\"params\":{\"path\":\"/tmp/solidcraft-result.png\"}}\n```\n\nUse `engine.execute` for commands and `ui.start` plus `ui.click` for interactive\nreproductions. Open and inspect the image. Check for private designs, paths and\ncredentials before sharing; never expose the token. Show the person the media\nand ask before attaching it to the PR or linking an accessible recording. Include\nbrief reproduction steps and expected/actual behaviour; do not commit generated\nreview media. Documentation-only changes need no screenshot.\n\n## 7. Finish and respond to review\n\nPrepare the final title and body: `Fixes #N`, the problem, resulting behaviour,\nvalidation and any evidence or limitations. Show them to the person before\nupdating the PR. After their approval, mark the draft ready:\n\n```sh\ngh pr ready PR_NUMBER -R tangency-labs/solidcraft\n```\n\nExplain that a maintainer reviews the change and adds `approved-for-ci` to start\nheavy checks; do not add that label yourself. Monitor checks and merge status,\naddress review comments, rerun affected checks for fixes, and ask before public\nreplies or pushes. Report whether it merged or remains pending; do not promise a\nmerge or rerun an unchanged failing check without evidence of infrastructure trouble.\n\n## Cloud sandbox\n\nWithout a display, use `solidcraft-cli snapshot` for model evidence or launch the\napp under `Xvfb :99` with `DISPLAY=:99` for UI evidence. With limited disk or CPU,\nprefer a documentation or small isolated task, targeted tests and existing build\nartifacts; explain any missing checks. Preserve work before temporary storage\nexpires and ask before publishing it. Always push only to the person's fork,\nnever to upstream.\n" } }, { "name": "makecad-crash-safety", "description": "Use when writing or reviewing non-test Rust in makeCAD, handling design files, command parameters or control-channel input, calling the kernel, or investigating a crash report. A crash loses someone's work, so this outranks feature work.", "files": { - "SKILL.md": "---\nname: makecad-crash-safety\ndescription: \"Use when writing or reviewing non-test Rust in makeCAD, handling design files, command parameters or control-channel input, calling the kernel, or investigating a crash report. A crash loses someone's work, so this outranks feature work.\"\n---\n\n# Never crash\n\nPeople trust makeCAD with their designs. This outranks feature work.\n\n## In non-test code\n- No `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or `unimplemented!`. Every production crate root carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; `cargo xtask ci` runs clippy with `-D warnings`.\n- No `unsafe` (`unsafe_code = \"forbid\"`). The exceptions, in the app crate and in `crates/threedx-client` (which deny it instead), have no safe API:\n - macOS only: `crates/threedx-client/src/macos.rs` (loads the 3Dconnexion driver's client framework at run time and calls through its function pointers), two functions in `apps/solidcraft/src/open_documents.rs` (macOS hands Finder files only to an Objective-C method), and `apps/solidcraft/src/native_crash_macos.rs` (the signal handler that records crashes inside native code, as `native_crash.rs` does on Windows)\n - Windows only: `apps/solidcraft/src/native_crash.rs` (the exception filter that records crashes inside native code such as graphics drivers), `apps/solidcraft/src/native_frame.rs` (the window procedure that answers the resize-border hit test of the window without OS decorations, and gives its class the icon the taskbar falls back on) and `apps/solidcraft/src/space_mouse/windows_hid.rs` (asks Plug and Play which HID interfaces are 3D mice, so no other device is sent anything)\n- Errors are `Result` through the crate's error type and `?`. An unfinished feature returns an error (\"not supported yet: ...\"); it never panics.\n- Input-derived numbers are hostile (command parameters, design files, control-channel input): `get()` not `[i]`, finite checks, caps on sizes and loop counts.\n- Everything that calls `truck` goes through `solidcraft_kernel::guard`, which turns a panic into `KernelError::Internal`. Only `crates/kernel` may use `truck`.\n- Last resort: `Session::execute` runs every command under `catch_unwind`; an escaped panic restores the design and reports `EngineError::Internal`. Do not rely on it.\n- Files are written with `crates/io/src/safe_write.rs` (temporary file, flush, one rename), so a crash leaves the old file or the new one.\n\n## Proving a crash fix\n- Every crash fix lands with a regression test. `hostile_params_never_panic` in `crates/engine/src/tests.rs` runs every command with junk parameters; a new command gets this for free.\n- A crash report's `design.sc` and `replay.json` are the test's starting point. Put the test in the area's existing test file (see `skills/makecad-tests/SKILL.md`).\n\n## When someone says the app crashed\nThe desktop app writes every panic and every unclean exit to a local crash folder, with the design and the commands that reproduce it (`solidcraft_engine::crash`, `docs/crash-reports.md`). Look there first:\n- `solidcraft-cli crashes`, `solidcraft-cli crashes show `, `solidcraft-cli crashes replay `\n- the `diagnostics.crash_reports` command, or the MCP `crash_reports` tool\n\nCrashes and data loss are taken as issues even while kernel work is paused (CONTRIBUTING.md, \"Kernel work is paused\").\n" + "SKILL.md": "---\nname: makecad-crash-safety\ndescription: \"Use when writing or reviewing non-test Rust in makeCAD, handling design files, command parameters or control-channel input, calling the kernel, or investigating a crash report. A crash loses someone's work, so this outranks feature work.\"\n---\n\n# Never crash\n\nPeople trust makeCAD with their designs. This outranks feature work.\n\n## In non-test code\n- No `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or `unimplemented!`. Every production crate root carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; `cargo xtask ci` runs clippy with `-D warnings`.\n- No `unsafe` (`unsafe_code = \"forbid\"`). The exceptions, in the app crate and in `crates/threedx-client` (which deny it instead), have no safe API:\n - macOS only: `crates/threedx-client/src/macos.rs` (loads the 3Dconnexion driver's client framework at run time and calls through its function pointers), two functions in `apps/solidcraft/src/open_documents.rs` (macOS hands Finder files only to an Objective-C method), and `apps/solidcraft/src/native_crash_macos.rs` (the signal handler that records crashes inside native code, as `native_crash.rs` does on Windows)\n - Windows only: `apps/solidcraft/src/native_crash.rs` (the exception filter that records crashes inside native code such as graphics drivers), `apps/solidcraft/src/native_frame.rs` (the window procedure that answers the resize-border hit test of the window without OS decorations, and gives its class the icon the taskbar falls back on) and `apps/solidcraft/src/space_mouse/windows_hid.rs` (asks Plug and Play which HID interfaces are 3D mice, so no other device is sent anything)\n- Errors are `Result` through the crate's error type and `?`. An unfinished feature returns an error (\"not supported yet: ...\"); it never panics.\n- Input-derived numbers are hostile (command parameters, design files, control-channel input): `get()` not `[i]`, finite checks, caps on sizes and loop counts.\n- Everything that calls `solidcore` is caught in `crates/smlib` and becomes `Error::Internal`. Only `crates/smlib` may use `solidcore`.\n- Last resort: `Session::execute` runs every command under `catch_unwind`; an escaped panic restores the design and reports `EngineError::Internal`. Do not rely on it.\n- Files are written with `crates/io/src/safe_write.rs` (temporary file, flush, one rename), so a crash leaves the old file or the new one.\n\n## Proving a crash fix\n- Every crash fix lands with a regression test. `hostile_params_never_panic` in `crates/engine/src/tests.rs` runs every command with junk parameters; a new command gets this for free.\n- A crash report's `design.sc` and `replay.json` are the test's starting point. Put the test in the area's existing test file (see `skills/makecad-tests/SKILL.md`).\n\n## When someone says the app crashed\nThe desktop app writes every panic and every unclean exit to a local crash folder, with the design and the commands that reproduce it (`solidcraft_engine::crash`, `docs/crash-reports.md`). Look there first:\n- `solidcraft-cli crashes`, `solidcraft-cli crashes show `, `solidcraft-cli crashes replay `\n- the `diagnostics.crash_reports` command, or the MCP `crash_reports` tool\n\nCrashes and data loss are taken first, including in kernel code, which lives in `solidcore/` (CONTRIBUTING.md, \"Kernel work goes in solidcore/\").\n" } }, { @@ -57,51 +57,58 @@ "name": "makecad-file-formats", "description": "Use when a makeCAD change saves something new in a design (a field, a feature type, a kind of name) or changes what older designs mean, and when touching STEP, IGES, 3MF, STL, OBJ, DXF or URDF import and export.", "files": { - "SKILL.md": "---\nname: makecad-file-formats\ndescription: \"Use when a makeCAD change saves something new in a design (a field, a feature type, a kind of name) or changes what older designs mean, and when touching STEP, IGES, 3MF, STL, OBJ, DXF or URDF import and export.\"\n---\n\n# Design file format, import and export\n\n## Design file format changes\nA design says which format it is in (`\"format\": \"solidcraft/N\"`). A change that saves something new, or makes older designs mean something else, adds ONE file and edits nothing shared:\n\n1. Create `crates/doc/src/format/pending/.rs` (lowercase, dashes). Start it with a `//!` note: what is saved, what older designs get without it, and that the last release asks for an update instead of meeting it.\n2. If older designs must be rewritten as they open, put `pub fn step(v: &mut Value) -> crate::Result<()>` in the same file. Pending steps run in file-name order, after the older formats' steps.\n3. Never touch `FORMAT`, `JSON_STEPS`, the history in `crates/doc/src/format.rs`, another change's file, or any `v/` folder. The build counts the pending files and writes the next number, so a release refuses a design that carries your change instead of losing it.\n\nTwo PRs that each add a change merge without a conflict. `crates/doc/src/format/pending/README.md` has an example. At release time the maintainer runs `scripts/fold-format-pending.sh`, which moves pending files into `v/` for good; `scripts/test-format-pending.sh` runs in CI. Never add a file to a `v/` folder afterwards. See `docs/releasing.md`.\n\nDrawings follow the same rules with their own numbers, from 1: a drawing-format change is ONE new file in `crates/doc/src/drawing/format/pending/` (see its `README.md`), and the same fold script moves them into `crates/doc/src/drawing/format/v/`.\n\n## Import\n- Every import (STEP, IGES, 3MF, STL, OBJ; inserted, dropped, opened, or run as `file.insert_step`, `file.insert_mesh` or `doc.open`) becomes a new component named after the file, with the Import feature inside it. Bodies never land loose.\n- Imported files are untrusted: sizes, entity counts and nesting are capped, and every kernel call is guarded (`skills/makecad-crash-safety/SKILL.md`). What cannot be read becomes a warning on the feature.\n- STEP is read by our own reader in `crates/kernel/src/step_in`, written from the public standards, with no third-party STEP code. The reader and what it supports: `docs/step-import.md`.\n- Imported assemblies are rigid by default; Unlock Contents releases them.\n- Kernel work (booleans, STEP/IGES import and export, tessellation) is paused except crashes and data loss: CONTRIBUTING.md, \"Kernel work is paused\".\n\n## Export\n- STEP, 3MF, STL, OBJ and URDF go through `file.export` and `file.save_mesh`; the MCP `export` tool calls them. URDF: `docs/urdf.md`. 3MF face tags: `docs/formats/3mf-face-tags.md`.\n- Mesh and design readers and writers live in `crates/io/src/`. Write files through `crates/io/src/safe_write.rs`.\n- Reference tests for exports never take their expected values from makeCAD's own output (`skills/makecad-tests/SKILL.md`).\n" + "SKILL.md": "---\nname: makecad-file-formats\ndescription: \"Use when a makeCAD change saves something new in a design (a field, a feature type, a kind of name) or changes what older designs mean, and when touching STEP, IGES, 3MF, STL, OBJ, DXF or URDF import and export.\"\n---\n\n# Design file format, import and export\n\n## Design file format changes\nA design says which format it is in (`\"format\": \"solidcraft/N\"`). A change that saves something new, or makes older designs mean something else, adds ONE file and edits nothing shared:\n\n1. Create `crates/doc/src/format/pending/.rs` (lowercase, dashes). Start it with a `//!` note: what is saved, what older designs get without it, and that the last release opens such a design with a warning and keeps what it can't read (`crates/doc/src/newer_file.rs`).\n2. If older designs must be rewritten as they open, put `pub fn step(v: &mut Value) -> crate::Result<()>` in the same file. Pending steps run in file-name order, after the older formats' steps.\n3. Never touch `FORMAT`, `JSON_STEPS`, the history in `crates/doc/src/format.rs`, another change's file, or any `v/` folder. The build counts the pending files and writes the next number, so a release knows a design carries a change it doesn't have: it warns, and saving keeps the file's number and what it couldn't read.\n\nTwo PRs that each add a change merge without a conflict. `crates/doc/src/format/pending/README.md` has an example. At release time the maintainer runs `scripts/fold-format-pending.sh`, which moves pending files into `v/` for good; `scripts/test-format-pending.sh` runs in CI. Never add a file to a `v/` folder afterwards. See `docs/releasing.md`.\n\nDrawings follow the same rules with their own numbers, from 1: a drawing-format change is ONE new file in `crates/doc/src/drawing/format/pending/` (see its `README.md`), and the same fold script moves them into `crates/doc/src/drawing/format/v/`.\n\n## Import\n- Every import (STEP, IGES, 3MF, STL, OBJ; inserted, dropped, opened, or run as `file.insert_step`, `file.insert_mesh` or `doc.open`) becomes a new component named after the file, with the Import feature inside it. Bodies never land loose.\n- Imported files are untrusted: sizes, entity counts and nesting are capped, and every kernel call is guarded (`skills/makecad-crash-safety/SKILL.md`). What cannot be read becomes a warning on the feature.\n- STEP is read by our own reader in `crates/kernel/src/step_in`, written from the public standards, with no third-party STEP code. The reader and what it supports: `docs/step-import.md`.\n- Imported assemblies are rigid by default; Unlock Contents releases them.\n- Kernel work (booleans, STEP/IGES import and export, tessellation) goes in `solidcore/`: CONTRIBUTING.md, \"Kernel work goes in solidcore/\".\n\n## Export\n- STEP, 3MF, STL, OBJ and URDF go through `file.export` and `file.save_mesh`; the MCP `export` tool calls them. URDF: `docs/urdf.md`. 3MF face tags: `docs/formats/3mf-face-tags.md`.\n- Mesh and design readers and writers live in `crates/io/src/`. Write files through `crates/io/src/safe_write.rs`.\n- Reference tests for exports never take their expected values from makeCAD's own output (`skills/makecad-tests/SKILL.md`).\n" } }, { "name": "makecad-ground-rules", "description": "Use before adding any dependency, icon, image, font, test reference data or product wording to makeCAD, or when unsure whether something may be copied, read or named. Covers independence from other CAD products, GPL code, asset attribution and the product name.", "files": { - "SKILL.md": "---\nname: makecad-ground-rules\ndescription: \"Use before adding any dependency, icon, image, font, test reference data or product wording to makeCAD, or when unsure whether something may be copied, read or named. Covers independence from other CAD products, GPL code, asset attribution and the product name.\"\n---\n\n# Independence, licences, assets and the name\n\nThe rules that cannot be broken in a PR. `AGENTS.md` lists them in one line each; the reasons are in CONTRIBUTING.md, \"Rules that aren't negotiable\".\n\n## Independent\n- Behaviour comes from public documentation, general CAD conventions and user feedback. File formats come from public specifications.\n- Never copy another product's code, icons, artwork, help text, tooltips, templates or materials.\n- Reference tests use analytic values (`tools/oracle-analytic/`) or open-source tools. Expected values never come from a commercial CAD product.\n- Do not drive, script, automate or extract data from commercial CAD products (Fusion, SolidWorks, Onshape, ...) for this project: no test data, measurements, command lists, ids or files produced with them.\n- Command ids are our own: dotted, lower-case `.[.]`, never another product's id.\n\n## No GPL, LGPL or AGPL code\n- Do not read, copy or link OpenCASCADE, FreeCAD (including planegcs), SolveSpace, CadQuery/OCP, LibreCAD or QCAD. Do not even read their sources.\n- `tools/freecad-oracle/` runs FreeCAD as a separate program through its public scripting API to compute reference values. Nothing from FreeCAD is linked, vendored or shipped. The sketch solver and the blend operations are our own.\n- Permissive dependencies are fine: say which one you add and why in the PR. `THIRD-PARTY-LICENSES.txt` is regenerated on `main`; never edit it in a PR (`cargo xtask licences --check` only reports).\n- Code adapted from other permissive projects (MIT OR Apache-2.0) is noted in ATTRIBUTION.md. Projects published by [storytold](https://github.com/storytold) can serve as references for implementation conventions.\n\n## Assets: the most serious rule\n- makeCAD contains no iconography, images, fonts or artwork from commercial CAD products, ever. Screenshots of commercial CAD software are never committed.\n- Every file asset is original or openly licensed and has a row in ATTRIBUTION.md. `cargo xtask assets` enforces it.\n- Command icons are the original SVG masters in `assets/icons/ui/design/svg/`, compiled through `crates/ui-egui/src/icon_svg.rs`.\n- Before any icon, icon assignment or media edit, read `assets/AGENTS.md`, `assets/icons/ui/AGENTS.md` and `assets/icons/ui/STYLE_GUIDE.md`. Use the canonical bases and named finished references there; never invent a parallel icon style. `cargo xtask icons` validates them.\n\n## The name\n- Product-facing prose, assistant replies and skill names use makeCAD (`makecad-*`). Do not introduce the previous display name.\n- Existing crate and binary names (`solidcraft-*`, `solidcraft`, `solidcraft-cli`), `.sc`/`.solidcraft` designs, the `solidcraft/N` format tag, `SOLIDCRAFT_*` environment variables, settings paths and MCP bridge ids remain technical compatibility identifiers. Do not rename them as a wording change or break existing designs and integrations.\n- Upstream repository URLs and licence attribution remain accurate. Deployment paths follow the host configuration.\n- Labels, parameter docs, messages and docs use the terms in the glossary (`docs/book/src/reference/glossary.md`): one term for each idea. A change that adds a new idea adds its term there.\n- Units are millimetres and radians internally; Z is up.\n" + "SKILL.md": "---\nname: makecad-ground-rules\ndescription: \"Use before adding any dependency, icon, image, font, test reference data or product wording to makeCAD, or when unsure whether something may be copied, read or named. Covers independence from other CAD products, GPL code, asset attribution and the product name.\"\n---\n\n# Independence, licences, assets and the name\n\nHard PR rules. `AGENTS.md` lists them; reasons are in CONTRIBUTING.md, \"Rules that aren't negotiable\".\n\n## Independent\n- Behaviour comes from public documentation, general CAD conventions and user feedback. File formats come from public specifications.\n- Never copy another product's code, icons, artwork, help text, tooltips, templates or materials.\n- Reference tests use analytic values (`tools/oracle-analytic/`) or open-source tools. Expected values never come from a commercial CAD product.\n- Do not drive, script, automate or extract data from commercial CAD products (Fusion, SolidWorks, Onshape, ...) for this project: no test data, measurements, command lists, ids or files produced with them.\n- Command ids are our own: dotted, lower-case `.[.]`, never another product's id.\n\n## No GPL, LGPL or AGPL code\n- Do not read, copy or link OpenCASCADE, FreeCAD (including planegcs), SolveSpace, CadQuery/OCP, LibreCAD or QCAD. Do not even read their sources.\n- `tools/freecad-oracle/` runs FreeCAD as a separate program through its public scripting API to compute reference values. Nothing from FreeCAD is linked, vendored or shipped. The sketch solver and the blend operations are our own.\n- Permissive dependencies are fine: say which one you add and why in the PR. `THIRD-PARTY-LICENSES.txt` is regenerated on `main`; never edit it in a PR (`cargo xtask licences --check` only reports).\n- Code adapted from other permissive projects (MIT OR Apache-2.0) is noted in ATTRIBUTION.md. Projects published by [storytold](https://github.com/storytold) can serve as references for implementation conventions.\n\n## Assets: the most serious rule\n- makeCAD contains no iconography, images, fonts or artwork from commercial CAD products, ever. Screenshots of commercial CAD software are never committed.\n- Every file asset is original or openly licensed and has a row in ATTRIBUTION.md. `cargo xtask assets` enforces it.\n- Command icons are the original SVG masters in `crates/look/icons/design/svg/`, compiled by the look crate (`crates/look/build.rs`, `crates/look/src/icons.rs`).\n- Before any icon, icon assignment or media edit, read `assets/AGENTS.md`, `crates/look/icons/AGENTS.md` and `crates/look/icons/STYLE_GUIDE.md`. Use the canonical bases and named finished references there; never invent a parallel icon style. `cargo xtask icons` validates them.\n\n## The name\n- Product-facing prose, assistant replies and skill names use makeCAD (`makecad-*`). Do not introduce the previous display name.\n- Existing crate and binary names (`solidcraft-*`, `solidcraft`, `solidcraft-cli`), `.sc`/`.solidcraft` designs, the `solidcraft/N` format tag, `SOLIDCRAFT_*` environment variables, settings paths and MCP bridge ids remain technical compatibility identifiers. Do not rename them as a wording change or break existing designs and integrations.\n- Upstream repository URLs and licence attribution remain accurate. Deployment paths follow the host configuration.\n- Labels, parameter docs, messages and docs use the terms in the glossary (`docs/book/src/reference/glossary.md`): one term for each idea. A change that adds a new idea adds its term there.\n- Units are millimetres and radians internally; Z is up.\n" + } + }, + { + "name": "makecad-layers", + "description": "Use when deciding whether code goes in makeCAD or in solidcore (the vendored kernel in solidcore/), and in which solidcore crate: geometry, a modelling workflow, kernel work, or a review comment about the layer split.", + "files": { + "SKILL.md": "---\nname: makecad-layers\ndescription: \"Use when deciding whether code goes in makeCAD or in solidcore (the vendored kernel in solidcore/), and in which solidcore crate: geometry, a modelling workflow, kernel work, or a review comment about the layer split.\"\n---\n\n# Where code goes: makeCAD or solidcore\n\nThe authority is `solidcore/docs/layers.md`; this is its short form. Every job lives in exactly one layer, and two implementations of one job are a bug.\n\n## Decide\n1. **Does it compute geometry?** Anything computed from coordinates: a point, vector, length, angle, curvature, curve or surface, a solve, an intersection, a fit, a mesh, a STEP parse. Then it is a kernel primitive in `solidcore/crates/solidcore`, with its own tests. Dot and cross products, normalising, square roots or trigonometry on coordinates count, however small.\n2. **Is it a workflow recipe of kernel calls?** It picks entities, parameters and defaults, sequences kernel calls, compares what they return with tolerances and reports. Then it is `solidcore/crates/solidcore-ops`. Ops computes no geometric quantity of its own: when it needs one the kernel lacks, add a kernel primitive and call it.\n3. **Is it state, selection, commands, settings, history or UI?** Then it is makeCAD (`crates/`, `apps/`), which computes no geometry.\n\n## What makeCAD may use\n- `solidcore-ops` (modelling), `solidcore-tess` (display meshes, polylines) and `solidcore-record` (geometry as data). CI enforces this seam through `cargo xtask layers` (#13498): solidcore's public API is listed in xtask/solidcore-public.txt, and the remaining direct uses in xtask/solidcore-seam.txt, a list that only shrinks. Within those crates, xtask/solidcore-paths.txt holds each crate's count of paths into solidcore internals (#15031): a count may not go up, and a PR that removes paths lowers its line (`cargo xtask layers --paths ` lists them). The same command keeps solidcore/ self-contained: no manifest under it may use a `path` that leaves solidcore/ or depend on a `solidcraft-*` crate, and CI's \"SolidCore builds on its own\" job runs `cargo check --workspace --all-targets --locked` on an export of solidcore/ alone.\n- Before writing STEP, meshing, surface intersection, tangent chains or frames, look for solidcore's: a second implementation is flagged.\n\n## Lists that only shrink\n- `xtask/mesh-decisions.txt`: model decisions made from a mesh (`cargo xtask mesh-decisions`).\n- `solidcore/plan/panic-sites.tsv`: panic-prone calls in solidcore (SolidCore checks in CI).\n\n## Working in solidcore/\n- Follow `solidcore/AGENTS.md` and the reference doc for the area (`solidcore/docs/`). A change there needs a code owner's review (`.github/CODEOWNERS`) and runs SolidCore checks (its tests, goldens, kernel rig, clippy, fmt, panic sites) in `.github/workflows/ci.yml`.\n- New kernel cases go in `solidcore/crates/solidcore/tests/kernel_cases/`, never in makeCAD (`cargo xtask lists`).\n- Kernel work goes here: CONTRIBUTING.md, \"Kernel work goes in solidcore/\". Kernel PRs target `main`; big multi-step work goes as stacked PRs into `main`.\n- Issues and claims for solidcore are in this repository, like any other change (`skills/makecad-contributing/SKILL.md`): the vendored tree is mirrored to tangency-labs/solidcore by `.github/workflows/solidcore-mirror.yml`, so pull requests are not opened there.\n" } }, { "name": "makecad-mechanisms", "description": "Use when building, driving or animating an assembly or mechanism in makeCAD through its MCP server - components, grounding, joints and joint origins, rigid groups, motion links, closed loops such as an actuator on a hinged panel or a linkage, contact sets, motion studies, degrees of freedom - or when a drive moves nothing, stops early or a part jumps when it is joined. To model the parts themselves, use makecad-modeling.", "files": { - "SKILL.md": "---\nname: makecad-mechanisms\ndescription: Use when building, driving or animating an assembly or mechanism in makeCAD through its MCP server - components, grounding, joints and joint origins, rigid groups, motion links, closed loops such as an actuator on a hinged panel or a linkage, contact sets, motion studies, degrees of freedom - or when a drive moves nothing, stops early or a part jumps when it is joined. To model the parts themselves, use makecad-modeling.\n---\n\n# makeCAD mechanisms\n\n## Overview\nAn assembly is components placed by joints. Work the mechanism out as world points and axes first: every pin, slide and hinge, which part each one joins, and the value you expect at each pose. Then give every joint origin by those coordinates, and check each step against a number you computed yourself. A drive that reports success can still have moved nothing. Command shapes, a worked example, the traps and reply sizes are in `reference.md` next to this file. To build the parts themselves, use `makecad-modeling`.\n\nWritten against makeCAD `main` after 0.11.1, which counts the degrees of freedom of closed loops, carries motion links through chains made in any order, and answers drives in degrees with `moved` (and a `reason` when nothing could move).\n\n## Before the first call\n1. In makeCAD's own chat or any MCP client, call `skill_reference {\"skill\":\"makecad-mechanisms\",\"file\":\"reference.md\"}`. Elsewhere, read `reference.md`.\n2. **Open:** if the design is not open yet, run `open {path}`. When the server is bridged to the app and the current design is `dirty`, ask before opening anything.\n3. **Map it:** run `inspect_design {\"measure\":false,\"sketches\":false}`, then `execute joint.list`. `joint.list` shows `fixed` (the grounded occurrences, always with the root, 0), `dof` per occurrence, `conflicts`, the joints, links and named origins, at about 0.5 KB per joint. `execute motion.list` lists the motion studies.\n4. **Existing design:** take `edit.checkpoint` in its own call before you move bodies into components. `edit.restore_checkpoint {checkpoint}` goes back exactly, once: restoring uses the checkpoint up, so take a new one to go back again.\n5. **Write the plan:**\n - the components, and which one is grounded\n - each joint: type, the two occurrences, its world point and axis, limits\n - each motion link and its ratio\n - for each loop, the relation you will check, such as actuator stroke against hinge angle, and where it should stop\n - the pose to return to before saving\n\n## Build, in stages\n1. **Components and grounding.**\n - Bodies made in the root go into components with `component.create {\"name\":..., \"parent\":\"root\", \"activate\":false}`, then `component.move_bodies {\"bodies\":[...], \"component\":...}`.\n - A part that moves in two pieces, such as an actuator's barrel and rod, becomes two components.\n - Ground the base: `occurrence.ground {\"occurrence\":\"Frame:1\", \"grounded\":true}`. The design's first top-level part is grounded when it is made; check `joint.list` `fixed`, and unground it (`\"grounded\":false`) if it is not the base. A grounded part refuses `occurrence.move`. Occurrences are named `:`. Joint commands also take a component name (its first occurrence); `occurrence.ground` does not.\n2. **Open-chain joints in one batch.** Read `occurrence.properties` of each moving occurrence before the batch and after it. If something moved, split the batch to find the joint.\n3. **Each joint that closes a loop, in a call of its own.** Then check `conflicts` in its reply.\n4. **Motion links.**\n5. **Contact sets and the motion study.**\n\n## Joints\n- **Origins by world coordinates:** `{\"occurrence\":..., \"point\":[x,y,z], \"z\":[ax,ay,az]}`. Always give `occurrence`; without it the nearest body is used. Use the same form on both sides; `frame`, `face`, `circle` and named origins are in `reference.md`.\n- **Pass `flip: true`** when both origins are the same world point and axis, which is the case when you join parts where they sit. Without it, b's z mates against a's and part b turns 180 degrees.\n- **Parts already in place:** `joint.as_built {\"type\":..., \"a\":..., \"b\":..., \"at\":{origin}, \"name\":..., \"limits\":[[min,max]]}` keeps them where they are.\n- **Values and limits** are degrees for angles and mm for distances. An angle turns right-handed about the joint's z. A drive past a joint's own limits is clamped to them, which is not a failure. A new joint starts at its `values` (default 0); one outside the limits starts at the nearer limit, so the part turns there as it is joined, and the reply's `warnings` say so. `value` drives a joint's first value and `values` the ones it lists; the others keep theirs.\n- **Every chain must reach something grounded.** A part that is neither grounded nor joined to a grounded part is never placed. A drive on a joint in that chain moves nothing and answers `moved: false`, with a `reason` and the part joined to nothing as `unconnected`. `joint.list` lists such chains under `floating`, and their occurrences have `dof: 6`. Fix it with `joint.rigid_group {\"occurrences\":[\"Frame:1\", ...]}`, or with a joint to the grounded structure.\n\n## Linked and closed motion\n- **Motion links:** `joint.motion_link {\"a\":..., \"b\":..., \"ratio\":r, \"offset\":o}` sets b = r·a + o, clamped to b's own limits. `ratio` is b's units per a's: a pinion that moves its rack 0.5 mm per degree takes `ratio: 0.5`. `offset` is in b's units: degrees for an angle, mm for a distance, or an expression. A mirrored part takes `ratio: -1`, and limits mirrored too. Chains (a drives b, b drives c) work in any order of creation. Drive only the head of a chain.\n- **Gears, racks and screws:** links whose ratio comes from radii or a pitch, kept up to date when they change. `joint.gear {\"a\":..., \"b\":..., \"ra\":r1, \"rb\":r2}` turns b r1/r2 as far as a, the other way (`internal: true`: the same way). `joint.rack_pinion {\"a\":pinion, \"b\":rack, \"radius\":r}` moves the rack r·θ. `joint.screw {\"joint\":cylindrical, \"pitch\":p}` (or `a`, `b` for a revolute and a slider) advances p per turn. A size is mm, an expression (`\"m*z1/2\"`), or a round face `{\"occurrence\":..., \"circle\":[x,y,z]}` whose radius is read again after every edit. `reverse: true` turns b the other way (a left-hand thread). The driven joint keeps where it is. Drive a, never b.\n- **Cams:** `joint.cam {\"a\":camJoint, \"b\":follower, \"profile\":{\"sketch\":\"CamSketch\"}}` (or `{\"edges\":[[x,y,z]]}` on the cam's body) makes a slider or revolute follower ride the cam's outline. `follower`: `knife` (default), `roller` with `radius` (mm, an expression or the roller's round face), `flat`. A revolute follower needs `tip` (its knife's point or roller's centre). The table is worked out again after every edit; the follower keeps where it is, so model it touching. Drive the cam, never the follower.\n- **Closed loops:** an actuator between a frame and a hinged panel takes three joints besides the hinge:\n - a revolute root pin (frame and barrel)\n - a slider (barrel and rod), with z along the actuator from root to tip on both origins, both at the root pin, and the stroke as its limits\n - a revolute tip pin (rod and panel), which closes the loop\n\n A four-bar or a slider-crank follows the same pattern. Drive the hinge; the pins and the slider follow.\n- **Stops:** at the end of the stroke the drive stops, with `stopped_by_loop: {joint, fraction}` naming the joint that could not follow. A loop that cannot close at all is listed under `conflicts`, and nothing in it moves.\n- **dof** counts the loop: here the panel, barrel and rod report 1 each, also at a pose where the actuator lies along its tip pin's path.\n\n## Contact and motion studies\n- **Contact:** `contact.create {\"occurrences\":[...], \"name\":...}` and `contact.enable_sets {}`. A drive then stops where two bodies of one set would pass through each other, with `stopped_by_contact: {a, b, fraction}`. `contact.check {}` lists the pairs that overlap now.\n- **Motion study:** `motion.study {\"name\":..., \"steps\":N, \"keys\":[{\"joint\":..., \"points\":[[step, value], ...]}]}`. Values are degrees or mm, linear between points. Key only the driving joints; linked joints and loops follow.\n- **Play:** `motion.play {\"study\":..., \"step\":s}` sets the joints there, which changes the design, and answers every occurrence's pose (about 0.2 KB per occurrence). `motion.export {\"study\":..., \"samples\":n}` gives the poses at every step without changing the design.\n- **Trace:** `motion.trace {\"occurrence\":..., \"point\":[x,y,z], \"joint\":..., \"from\":0, \"to\":360}` (or `\"study\":...` instead of joint, from and to) answers the world path of a point of a part, such as a coupler curve, without changing the design. It ends at `stopped_at` where a loop or contact stops the motion. `motion.trace.keep` with the same params keeps it as a 3D sketch spline.\n- **Plot:** `motion.plot {\"study\":..., \"joints\":[...], \"duration\":seconds}` answers each joint value's `value`, `velocity` and `acceleration` per sample (finite differences; per step, or per second with a duration), and with `\"occurrence\"` and `\"point\"` a point's `position`, `velocity`, `acceleration`, `speed`. Check a follower's rate against the analytic one this way, without changing the design.\n- **Collisions:** `motion.interference {\"study\":..., \"occurrences\":[...], \"against\":[...]}` plays the study (contact sets don't stop it) and lists each colliding pair with `first_step` and `steps` ranges; `clear: true` when none and every step was checked (never while `truncated`: then it stopped at `checked_to`; give a gear train or other detailed parts more time with `budget_s`). It takes at most 256 bodies: on a big design list the moving part as `occurrences` and what it must miss as `against`. Parts joined at a knuckle often overlap by design and show up at every step.\n- **Sweep until contact:** `joint.sweep {\"joint\":..., \"from\":0, \"to\":120, \"occurrences\":[...], \"against\":[...], \"report_gaps\":true}` answers how far a hinge, door or linkage opens: `stopped_at` (last clear value, bisected to `refine` mm, default 0.01), `stopped_by` `{a, b, at}` (or `\"loop\"`, `\"limit\"`), per-sample `min_gap_mm` and the nearest each part came (`min_gap`). It runs on a copy; `\"apply\":true` leaves the design at the stop. Pairs touching at `from` (`touching_at_start`) stop it only once they pass into each other.\n- **Find limits:** `joint.find_limits {\"joint\":...}` sweeps each value both ways from where it is (its own limits ignored, on a copy) and answers per value `min`, `max`, `min_by`/`max_by` (`{a, b, at}`, `\"loop\"`, `\"limit\"`, `\"turn\"`: nothing met within a turn, `\"range\"`: a distance meets nothing, `null` value). Set the joint's limits from it with `joint.limits`. A full turn of curved parts resting in each other can take a few seconds.\n\n## Verify\n- **Each joint:** `execute occurrence.properties {\"occurrence\":\"Wing:1\"}` (about 2 KB) gives the world bbox, centre of mass and inertia of one occurrence. Joining must not move them.\n- **Each drive:** compute the expected value of every follower, and read it back from `joint.list` (degrees and mm, with `unit`). For an actuator from root R to tip T on a panel hinged at H: `L(θ) = |T(θ) - R|`, where `T(θ)` is T turned by θ about the hinge axis through H, and the stroke is `L(θ) - L(0)`. A closed loop matches to 1e-6 mm.\n- **Each stop:** solve for where the limit is reached, and compare with the value the drive stopped at. Stops are found by bisection, so they land within about 0.01 degrees.\n- **Links:** b must equal r·a + o exactly, unless that is outside b's limits; then b sits at the limit and the mirror stops following.\n- **The whole motion:** `motion.play` at a few steps, or one `motion.export`, and compare the poses with the values you planned.\n- **Look:** when the server is bridged, `screenshot` after `motion.play` shows the app window at that step. `motion.export_animation {\"study\":..., \"path\":\"tour.gif\"}` (or `joint`, `from`, `to`) writes the whole motion as an animated GIF without changing the design.\n\n## Save\n- Drive the joints back to the pose you planned to keep (`motion.play` at step 0, or `joint.drive`), then `save {path}`.\n- An `.urdf` export leaves out each joint that closes a loop, because URDF is a tree.\n\n## Red flags\n\n| Thought | Do instead |\n|---|---|\n| \"The origins are at the same point, so `flip` doesn't matter\" | Pass `flip: true`, or the part turns 180 degrees. |\n| \"The drive answered values, so it moved\" | Read `moved`; a chain joined to nothing grounded answers `moved: false` and a `reason`. |\n| \"Drive the arm joint by joint until the gripper gets there\" | `joint.reach {\"occurrence\":..., \"at\":..., \"point\":...}` solves every joint on its chain at once; read `reached` and `error_mm`. |\n| \"Key every joint of the loop in the study\" | Key the driving joint only; the loop follows. |\n| \"Check the pose with `component.list`\" | `occurrence.properties` on the one occurrence. `component.list` is 140 KB on a 36-part assembly. |\n| \"Open the design with `file.open`\" | The `open` tool, or `doc.open`; there is no `file.open`. |\n", - "reference.md": "# makeCAD mechanism reference for agents\n\nThese are the shapes of the commands an assembly needs, so an agent rarely has to call `list_commands`. All of them run through the `execute` tool or a `batch`. The worked example below runs in CI (`mechanisms_skill_example_moves_as_documented` in `crates/mcp/src/tests.rs`).\n\n- Joint values, limits and study keys are in degrees for angles and mm for distances. Expressions work too: `\"30 deg\"`, `\"stroke/2\"`.\n- Points and axes are world coordinates, as the model sits when you make the joint.\n\n## Joint origins\n\nEach of `a` and `b` in `joint.create` is one of these:\n\n| Form | Shape | Notes |\n|---|---|---|\n| Point | `{\"occurrence\":\"Wing\",\"point\":[0,30,0],\"z\":[1,0,0]}` | The usual form. `z` is the joint axis (default +Z). |\n| Frame | `{\"occurrence\":\"Wing\",\"frame\":{\"origin\":[0,30,0],\"z\":[1,0,0],\"x\":[0,1,0]}}` | `x` fixes where angle 0 is. |\n| Face | `{\"occurrence\":\"Wing\",\"face\":[0,20,3]}` | The centre of the planar face through that point, axis along its normal. It follows the face when the part changes. |\n| Circle | `{\"occurrence\":\"Actuator rod\",\"circle\":[0,32,0]}` | The centre of the round edge through that point, axis along the cylinder. Pick a point on the rim. |\n| Named | `\"Hinge on frame\"` | Made first with `joint.origin {\"name\":..., \"occurrence\":..., \"point\":[...], \"z\":[...]}`. |\n\n- `occurrence` is an occurrence name (`Wing:1`), an id, or a component name (its first occurrence). Without it, the body nearest the point is used, which can be the wrong part where two touch.\n- **Use the same form on both sides.** `point` picks its x axis from z. A `frame` with an `x` on one side and a `point` on the other turned a test panel 90 degrees when it was joined.\n- **`flip`:** `false` (the default) mates the origins as two faces meet: b's z points against a's. Two origins at one point with the same `z` then turn part b 180 degrees about the axis, and a joint that closes a loop reports a conflict (\"off by 71 mm and 180 degrees\" on SELENE). `true` lines b's z up with a's, so parts stay where they are. `joint.edit {\"joint\":..., \"flip\":true}` changes it afterwards.\n- **Moving a side:** `joint.edit` takes `a` or `b` in joint.create's form (a joint origin, or a name), so a joint moves its attachment without being deleted and recreated; its limits, values and expressions stay.\n\n## Joint types\n\n| `type` | Values, in order | Units |\n|---|---|---|\n| `rigid` | none | |\n| `revolute` | angle | deg |\n| `slider` | distance along z | mm |\n| `cylindrical` | angle, distance | deg, mm |\n| `pin_slot` | angle, slide | deg, mm |\n| `planar` | x, y, angle | mm, mm, deg |\n| `ball` | yaw, pitch, roll | deg |\n\nA slider's value grows as b moves along +z of its origin. Give its two origins the same point, so 0 is the position as modelled.\n\n## Commands\n\n```json\n{\"command\":\"component.create\",\"params\":{\"name\":\"Actuator rod\",\"parent\":\"root\",\"activate\":false}}\n{\"command\":\"component.move_bodies\",\"params\":{\"bodies\":[\"Rod\"],\"component\":\"Actuator rod\"}}\n{\"command\":\"occurrence.ground\",\"params\":{\"occurrence\":\"Frame:1\",\"grounded\":true}}\n{\"command\":\"joint.create\",\"params\":{\"type\":\"slider\",\"name\":\"Stroke\",\"flip\":true,\"limits\":[[-5,10]],\"a\":{\"occurrence\":\"Actuator barrel\",\"point\":[0,0,-40],\"z\":[0,0.6,0.8]},\"b\":{\"occurrence\":\"Actuator rod\",\"point\":[0,0,-40],\"z\":[0,0.6,0.8]}}}\n{\"command\":\"joint.as_built\",\"params\":{\"type\":\"revolute\",\"a\":\"Frame\",\"b\":\"Wing 2\",\"at\":{\"occurrence\":\"Frame\",\"point\":[0,0,0],\"z\":[1,0,0]},\"name\":\"Hinge 2\",\"limits\":[[-60,0]]}}\n{\"command\":\"joint.rigid_group\",\"params\":{\"occurrences\":[\"Frame:1\",\"Lamp:1\"]}}\n{\"command\":\"joint.motion_link\",\"params\":{\"a\":\"Hinge\",\"b\":\"Hinge 2\",\"ratio\":-1}}\n{\"command\":\"joint.drive\",\"params\":{\"joint\":\"Hinge\",\"value\":20}}\n{\"command\":\"joint.drive\",\"params\":{\"joint\":\"Spindle\",\"values\":[30,5]}}\n{\"command\":\"joint.reach\",\"params\":{\"occurrence\":\"Gripper\",\"at\":[120,0,40],\"point\":[60,80,40],\"z\":[0,0,-1],\"axis\":[1,0,0],\"quiet\":true}}\n{\"command\":\"joint.limits\",\"params\":{\"joint\":\"Hinge\",\"min\":0,\"max\":60}}\n{\"command\":\"joint.edit\",\"params\":{\"joint\":\"Hinge\",\"flip\":true}}\n{\"command\":\"joint.delete\",\"params\":{\"link\":0}}\n{\"command\":\"contact.create\",\"params\":{\"occurrences\":[\"Frame:1\",\"Wing 2:1\"],\"name\":\"Wing 2 stop\"}}\n{\"command\":\"contact.enable_sets\",\"params\":{}}\n{\"command\":\"motion.study\",\"params\":{\"name\":\"Open\",\"steps\":10,\"keys\":[{\"joint\":\"Hinge\",\"points\":[[0,0],[10,25]]}]}}\n{\"command\":\"motion.play\",\"params\":{\"study\":\"Open\",\"step\":5}}\n{\"command\":\"motion.export\",\"params\":{\"study\":\"Open\",\"samples\":3}}\n{\"command\":\"occurrence.properties\",\"params\":{\"occurrence\":\"Wing:1\"}}\n```\n\n- `joint.create` and `joint.as_built` start the joint at its `values` (default 0). A value outside the limits starts at the nearer limit, and the reply's `warnings` say so: the part turned as it was joined.\n- `joint.as_built` takes occurrences, not origins. `at` is the joint's frame (default: b's component origin).\n- `joint.rigid_group` joins every occurrence to the first one with a rigid as-built joint.\n- `joint.motion_link`: b = ratio·a + offset, clamped to b's limits. `ratio` is in b's units per a's: mm per degree when an angle drives a distance (a pinion of pitch radius r moves its rack r·π/180 mm per degree), degrees per mm the other way, and a plain factor between two angles or two distances. `offset` is in b's units: degrees for an angle, mm for a distance, or an expression such as `\"10 deg\"`. `joint.list` gives each link's `ratio` the same way and its `offset` with its `unit`. `ia`/`ib` pick a value of a multi-value joint (default 0). `joint.delete {\"link\": n}` removes link n (its index in `joint.list` `links`).\n- `joint.gear {a, b, ra, rb, internal?, reverse?}`, `joint.rack_pinion {a, b, radius, reverse?}` and `joint.screw {joint | a, b; pitch, reverse?}` make a motion link whose ratio comes from its sizes: gears -ra/rb (+ra/rb internal), a rack r mm per radian of its pinion (either joint may be `a`), a screw pitch per turn. Each size is mm, an expression, or `{occurrence, circle: [x,y,z]}`: the radius of the round face there, read again whenever the design changes. The reply gives `link` (its index) and `ratio` as `joint.list` does; `link: n` in the params replaces link n and keeps its offset. A new coupling's offset keeps b where it is. `joint.list` `links` carry the `coupling` and an `error` when it can't be worked out (a picked face gone: the last ratio stays). A value two links would set, or a coupling that would drive its own driver, is refused.\n- `joint.cam {a, b, profile, follower?, radius?, tip?, flip?, link?}`: a is the cam's revolute joint, b a slider or revolute follower. `profile` is `{sketch, index?}` (a closed profile of a sketch in the cam's component) or `{edges: [[x,y,z]...], occurrence?}` (edges of the cam's body; one edge continues around its closed loop in the plane). The reply gives `link`, `lift: {min, max, rise, unit}` (b's travel over a turn), `reverse` (the side it rides from; `flip: true` takes the other) and, for a slider, `follower_offset`. `joint.list` `links` show `lift` instead of `ratio` for a cam.\n- `joint.drive`: `values` drives the values it lists, in order (`Spindle` above is cylindrical: 30 degrees, then 5 mm), and `value` the first; values left out keep theirs, or follow in a closed loop. Values are clamped to the limits. The reply gives `values` as `joint.list` does (`{name, value, unit, limits}`), and `moved`; when the joint can move nothing, a `reason`.\n- `joint.reach` (inverse kinematics): moves the joints on the occurrence's chain so its point `at` (world, where it is now; default: the centre of its bodies) gets to `point`, from the pose it is in to the nearest one, within limits, through motion links, and with closed loops kept closed. `z` with `axis` (world, now; default its own z) also turns that axis. `joints: [...]` moves only those (loop followers still follow). The reply: `reached`, `error_mm` (and `error_deg`), `point` where it ended, `values` of the joints that moved, `moved`, and when short, `stopped_by_limit: [{joint, value, limit}]` or `stopped_by_loop: {joint}`. A part that nothing moves answers `moved: false` with a `reason`. Contact sets are not checked; check with `contact.check` afterwards.\n- `motion.study {\"study\":..., ...}` edits a study; `keys` given replace all keys.\n- `motion.play` sets the joints to the study's values at a step (fractions work) and changes the design. `motion.export` does not change it.\n\n## Worked example: a panel on an actuator\n\nA frame holds a panel on a hinge along X at the origin. An actuator runs from a root pin on the frame, R = (0, 0, -40), to a tip pin on the panel, T = (0, 30, 0), 30 mm from the hinge: 50 mm long, along (0, 0.6, 0.8). Its rod slides -5 to +10 mm. A second panel on the other side mirrors the first through a motion link.\n\n```json\n{\"commands\":[\n {\"command\":\"solid.box\",\"params\":{\"length\":40,\"width\":10,\"height\":50,\"corner\":[-20,-10,-50],\"operation\":\"new\",\"body_name\":\"Post\"}},\n {\"command\":\"solid.box\",\"params\":{\"length\":40,\"width\":40,\"height\":10,\"corner\":[-20,0,-50],\"operation\":\"new\",\"body_name\":\"Base\"}},\n {\"command\":\"solid.box\",\"params\":{\"length\":40,\"width\":40,\"height\":3,\"corner\":[-20,0,0],\"operation\":\"new\",\"body_name\":\"Panel\"}},\n {\"command\":\"solid.box\",\"params\":{\"length\":40,\"width\":40,\"height\":3,\"corner\":[-20,-40,0],\"operation\":\"new\",\"body_name\":\"Panel 2\"}},\n {\"command\":\"solid.cylinder\",\"params\":{\"radius\":5,\"height\":20,\"base\":[0,0,-40],\"axis\":[0,0.6,0.8],\"operation\":\"new\",\"body_name\":\"Barrel\"}},\n {\"command\":\"solid.cylinder\",\"params\":{\"radius\":2,\"height\":35,\"base\":[0,9,-28],\"axis\":[0,0.6,0.8],\"operation\":\"new\",\"body_name\":\"Rod\"}},\n {\"command\":\"component.create\",\"params\":{\"name\":\"Frame\",\"parent\":\"root\",\"activate\":false}},\n {\"command\":\"component.move_bodies\",\"params\":{\"bodies\":[\"Post\",\"Base\"],\"component\":\"Frame\"}},\n {\"command\":\"component.create\",\"params\":{\"name\":\"Wing\",\"parent\":\"root\",\"activate\":false}},\n {\"command\":\"component.move_bodies\",\"params\":{\"bodies\":[\"Panel\"],\"component\":\"Wing\"}},\n {\"command\":\"component.create\",\"params\":{\"name\":\"Wing 2\",\"parent\":\"root\",\"activate\":false}},\n {\"command\":\"component.move_bodies\",\"params\":{\"bodies\":[\"Panel 2\"],\"component\":\"Wing 2\"}},\n {\"command\":\"component.create\",\"params\":{\"name\":\"Actuator barrel\",\"parent\":\"root\",\"activate\":false}},\n {\"command\":\"component.move_bodies\",\"params\":{\"bodies\":[\"Barrel\"],\"component\":\"Actuator barrel\"}},\n {\"command\":\"component.create\",\"params\":{\"name\":\"Actuator rod\",\"parent\":\"root\",\"activate\":false}},\n {\"command\":\"component.move_bodies\",\"params\":{\"bodies\":[\"Rod\"],\"component\":\"Actuator rod\"}},\n {\"command\":\"occurrence.ground\",\"params\":{\"occurrence\":\"Frame:1\",\"grounded\":true}},\n {\"command\":\"joint.create\",\"params\":{\"type\":\"revolute\",\"name\":\"Hinge\",\"flip\":true,\"a\":{\"occurrence\":\"Frame\",\"point\":[0,0,0],\"z\":[1,0,0]},\"b\":{\"occurrence\":\"Wing\",\"point\":[0,0,0],\"z\":[1,0,0]}}},\n {\"command\":\"joint.create\",\"params\":{\"type\":\"revolute\",\"name\":\"Root pin\",\"flip\":true,\"a\":{\"occurrence\":\"Frame\",\"point\":[0,0,-40],\"z\":[1,0,0]},\"b\":{\"occurrence\":\"Actuator barrel\",\"point\":[0,0,-40],\"z\":[1,0,0]}}},\n {\"command\":\"joint.create\",\"params\":{\"type\":\"slider\",\"name\":\"Stroke\",\"flip\":true,\"limits\":[[-5,10]],\"a\":{\"occurrence\":\"Actuator barrel\",\"point\":[0,0,-40],\"z\":[0,0.6,0.8]},\"b\":{\"occurrence\":\"Actuator rod\",\"point\":[0,0,-40],\"z\":[0,0.6,0.8]}}},\n {\"command\":\"joint.create\",\"params\":{\"type\":\"revolute\",\"name\":\"Tip pin\",\"flip\":true,\"a\":{\"occurrence\":\"Actuator rod\",\"point\":[0,30,0],\"z\":[1,0,0]},\"b\":{\"occurrence\":\"Wing\",\"point\":[0,30,0],\"z\":[1,0,0]}}},\n {\"command\":\"joint.as_built\",\"params\":{\"type\":\"revolute\",\"a\":\"Frame\",\"b\":\"Wing 2\",\"at\":{\"occurrence\":\"Frame\",\"point\":[0,0,0],\"z\":[1,0,0]},\"name\":\"Hinge 2\",\"limits\":[[-60,0]]}},\n {\"command\":\"joint.motion_link\",\"params\":{\"a\":\"Hinge\",\"b\":\"Hinge 2\",\"ratio\":-1}}\n]}\n```\n\n**Expected:**\n- After the batch, `joint.list` reports `dof` 1 for Wing, Wing 2, the barrel and the rod (the loop and the link leave one motion), 0 for Frame, and no `conflicts`.\n- **Actuator length:** the tip pin turns to `(0, 30 cos θ, 30 sin θ)`, so `L(θ)² = 2500 + 2400 sin θ` and `L(0) = 50`. The stroke is `L(θ) - 50`.\n- `joint.drive {\"joint\":\"Hinge\",\"value\":20}`: the stroke is `L(20°) - 50 = 7.6268` mm, and Hinge 2 is -20. `occurrence.properties {\"occurrence\":\"Wing:1\"}` puts the panel's centre of mass at (0, 18.281, 8.250), and Wing 2's at (0, -18.281, 8.250).\n- `joint.drive {\"joint\":\"Hinge\",\"value\":45}` stops at 27.28 degrees with `stopped_by_loop: {\"joint\":\"Stroke\", ...}`: the rod reaches +10 mm where `L(θ) = 60`, at `sin θ = 11/24`, θ = 27.280 degrees.\n\n## At scale: SELENE\n\nThe same pattern moved the solar wings of the SELENE rover (`Rover-v7.solidcraft` by 0xlillith, 36 occurrences, 1353 features):\n- **Actuators split:** each of the four actuators was one component. Its barrel and its rod (with the eyes and pins that move with them) went into components of their own with `component.create` and `component.move_bodies`.\n- **Loops:** per actuator, a revolute root pin (structure and barrel), a slider with the stroke as its limits, `[[-6, 0.4]]` mm, and a revolute wing pin (rod and wing). All `flip: true`, origins by world point, with z along X for the pins and along the actuator (root to tip) for the slider.\n- **Links:** the six wheels follow the first (`ratio: 1`); the starboard tilt mirrors the port one (`ratio: -1`).\n- **Floating modules:** in v7, 18 components (pedestals, avionics, the lid and others) were neither grounded nor joined, so driving the turret or the dish moved nothing. One `joint.rigid_group` with the structure fixed it.\n- **Hidden:** the arm's flexible hoses are rigid bodies on one link, and their sweep sketches stay in place, so both drift off as the arm moves. `browser.visibility {\"items\":[...], \"visible\":false}` hid them, and `{\"folder\":\"joints\",\"visible\":false}` the joint glyphs for the recording.\n- **Numbers:** the port tilt hinge is at (0, -140, 158) along X, the actuator root at (x, -91, 134) and its wing pin at (x, -180.41, 169.71). From these, the stroke at 20 degrees is -2.87 mm, and the rod reaches -6 mm at 32.230 degrees. The app agrees: a drive to 20 degrees gives -2.87 mm, and a drive towards 45 degrees stops at 32.23 degrees with `stopped_by_loop`.\n\n## Traps\n\n| Symptom | Cause and fix |\n|---|---|\n| A part turns 180 degrees when joined; a loop reports \"off by ... and 180 degrees\" | `flip` left out. Pass `flip: true`, or `joint.edit {\"joint\":..., \"flip\":true}`. |\n| A part turns to a limit as soon as it is joined, and the reply has `warnings` | A new joint starts at 0, or its `values`, inside its limits: `[[10, 60]]` on a hinge turns it 10 degrees. Make the limits include 0, or join the parts where the limits allow. |\n| A part turns by some other angle when joined | The two origins have different forms or x axes. Use `point` + `z` on both sides, or `joint.as_built`. |\n| `joint.drive` answers `moved: false`, or `motion.play` lists the joint under `unmoved` | Read `reason`. Most often the chain is joined to nothing grounded: `unconnected` names the part, and `joint.list` lists the chain under `floating`, its occurrences with `dof: 6`. Ground it, join it, or `joint.rigid_group` it with the structure. |\n| A drive stops short, `stopped_by_loop` | A loop reached a limit or can't close further; `joint` names the joint that stopped it. Check the limits against your stroke numbers. |\n| A gear, rack or screw turns its partner the wrong way | The joints' axes point opposite ways (or the rack lies on the other side of the pinion). Run the command again with `reverse: true` and `link: n`. |\n| `joint.cam` says the follower's line misses the cam | The slider's line (through `tip` when given) passes beside the cam at some angle. Pick the follower's tip, or move its slider's axis over the cam. |\n| A cam's follower rides the wrong flank or sinks into the cam | It took the other side of the cam's axis (`reverse` in the reply): run `joint.cam` again with `flip: true` and `link: n`. |\n| `already follows a motion link` from `joint.gear` | A joint follows one link at most. Make the joint that already follows the driving one (`a`), as in a gear train G1 → G2 → G3. |\n| A linked joint stops following | Its value is clamped to its own limits. Hinge 2 in the example has `[[-60, 0]]`, so a drive of Hinge below 0 leaves it at 0. Give a mirrored joint the mirrored limits. |\n| `joint.reach` answers `reached: false` | The point is out of reach: `point` and `error_mm` give the nearest pose. `stopped_by_limit` names the limits it rests on, `stopped_by_loop` the loop that can't follow further; with neither, the chain can't get there at all (too far, or out of its plane). |\n| A drive stops short, `stopped_by_contact` | Two bodies of a contact set touch. `fraction` is how far the move got. |\n| `occurrence.ground` says there is no occurrence `Frame` | It takes occurrence names only: `Frame:1`. |\n| `a joint needs two different occurrences` | Both origins found the same part. Give `occurrence` on both. If the parts are bodies of one component (an imported STEP file often brings them so), run `component.from_bodies {\"bodies\": [...]}` first. |\n| \"unknown command\" for `file.open` | Open a design with the `open` tool or `doc.open {path}`. |\n| Rigid hoses, cables or springs drift as the mechanism moves | Bodies don't bend. Hide them with `browser.visibility`, or model them per link. |\n| `solidcraft-cli snapshot SCRIPT --in design` runs on an empty design | `snapshot` ignores `--in`. Run `solidcraft-cli run SCRIPT --in design --save out.sc` first. |\n| A URDF export lacks a joint | `export` to `.urdf` leaves out each joint that closes a loop, with a warning, because URDF is a tree. |\n\n## Reply cost\n\n| Call | Size |\n|---|---|\n| `component.list` | **140 KB** on SELENE (a 4x4 transform per occurrence). Avoid it; use `occurrence.properties`. |\n| `joint.list` | about 0.5 KB per joint: 16 KB for 29 joints |\n| `motion.play` | about 0.2 KB per occurrence, per step: 9 KB on SELENE |\n| `motion.export` | the same per sample; pass `samples`, or `path` to write it to a file |\n| `joint.create`, `joint.drive`, `joint.motion_link`, `joint.gear`, `joint.rack_pinion`, `joint.screw` | the `dof` list of every occurrence again, 40 B each; `quiet: true` leaves it out |\n| `occurrence.properties` | under 1 KB per occurrence |\n\n## Showing it moving\n\n`motion.export_animation {\"study\":..., \"path\":\"tour.gif\"}` draws the whole motion as an animated GIF in one call, headless or bridged, and changes nothing: `{\"joint\":..., \"from\":0, \"to\":90, \"path\":...}` animates a drive instead, and `{\"view\":..., \"back\":true, \"path\":...}` an exploded view coming apart and back together (the placements stay as they are). A path that does not end in `.gif` is a folder for PNG frames (`frame-0001.png`, ...). Pass `camera` (the reply of `ui.camera`, or any of its fields), `width`/`height` (default 800 x 500), `samples` (frames; default the study's steps + 1, 100 for a joint, 41 for a view or 81 with `back`), `fps` (default 20), and `grid: false` / `axes: false` for a clean background. The reply is small: `frames`, `bytes`, and `stopped_at` with `stopped_by_loop`/`stopped_by_contact` where the motion first stopped short.\n\nBridged to the app, `motion.play {\"study\":..., \"step\":s}` moves the user's viewport, and `screenshot` captures the window at that step.\n" + "SKILL.md": "---\nname: makecad-mechanisms\ndescription: Use when building, driving or animating an assembly or mechanism in makeCAD through its MCP server - components, grounding, joints and joint origins, rigid groups, motion links, closed loops such as an actuator on a hinged panel or a linkage, contact sets, motion studies, degrees of freedom - or when a drive moves nothing, stops early or a part jumps when it is joined. To model the parts themselves, use makecad-modeling.\n---\n\n# makeCAD mechanisms\n\n## Overview\nAn assembly is components placed by joints. Work the mechanism out as world points and axes first: every pin, slide and hinge, which part each one joins, and the value you expect at each pose. Then give every joint origin by those coordinates, and check each step against a number you computed yourself. A drive that reports success can still have moved nothing. Command shapes, a worked example, the traps and reply sizes are in `reference.md` next to this file. To build the parts themselves, use `makecad-modeling`.\n\nWritten against makeCAD `main` after 0.11.1, which counts the degrees of freedom of closed loops, carries motion links through chains made in any order, and answers drives in degrees with `moved` (and a `reason` when nothing could move).\n\n## Before the first call\n1. In makeCAD's own chat or any MCP client, call `skill_reference {\"skill\":\"makecad-mechanisms\",\"file\":\"reference.md\"}`. Elsewhere, read `reference.md`.\n2. **Open:** if the design is not open yet, run `open {path}`. When the server is bridged to the app and the current design is `dirty`, ask before opening anything.\n3. **Map it:** run `inspect_design {\"measure\":false,\"sketches\":false}`, then `execute joint.list`. `joint.list` shows `fixed` (the grounded occurrences, always with the root, 0), `dof` per occurrence, `conflicts`, the joints, links and named origins, at about 0.5 KB per joint. `execute motion.list` lists the motion studies.\n4. **Existing design:** take `edit.checkpoint` in its own call before you move bodies into components. `edit.restore_checkpoint {checkpoint}` goes back exactly, once: restoring uses the checkpoint up, so take a new one to go back again.\n5. **Write the plan:**\n - the components, and which one is grounded\n - each joint: type, the two occurrences, its world point and axis, limits\n - each motion link and its ratio\n - for each loop, the relation you will check, such as actuator stroke against hinge angle, and where it should stop\n - the pose to return to before saving\n\n## Build, in stages\n1. **Components and grounding.**\n - Bodies made in the root go into components with `component.create {\"name\":..., \"parent\":\"root\", \"activate\":false}`, then `component.move_bodies {\"bodies\":[...], \"component\":...}`.\n - A part that moves in two pieces, such as an actuator's barrel and rod, becomes two components.\n - Ground the base: `occurrence.ground {\"occurrence\":\"Frame:1\", \"grounded\":true}`. The design's first top-level part is grounded when it is made; check `joint.list` `fixed`, and unground it (`\"grounded\":false`) if it is not the base. A grounded part refuses `occurrence.move`. Occurrences are named `:`. Joint commands also take a component name (its first occurrence); `occurrence.ground` does not.\n2. **Open-chain joints in one batch.** Read `occurrence.properties` of each moving occurrence before the batch and after it. If something moved, split the batch to find the joint.\n3. **Each joint that closes a loop, in a call of its own.** Then check `conflicts` in its reply.\n4. **Motion links.**\n5. **Contact sets and the motion study.**\n\n## Joints\n- **Origins by world coordinates:** `{\"occurrence\":..., \"point\":[x,y,z], \"z\":[ax,ay,az]}`. Always give `occurrence`; without it the nearest body is used. Use the same form on both sides; `frame`, `face`, `circle` and named origins are in `reference.md`.\n- **Pass `flip: true`** when both origins are the same world point and axis, which is the case when you join parts where they sit. Without it, b's z mates against a's and part b turns 180 degrees.\n- **Parts already in place:** `joint.as_built {\"type\":..., \"a\":..., \"b\":..., \"at\":{origin}, \"name\":..., \"limits\":[[min,max]]}` keeps them where they are.\n- **Values and limits** are degrees for angles and mm for distances. An angle turns right-handed about the joint's z. A drive past a joint's own limits is clamped to them, which is not a failure. A new joint starts at its `values` (default 0); one outside the limits starts at the nearer limit, so the part turns there as it is joined, and the reply's `warnings` say so. `value` drives a joint's first value and `values` the ones it lists; the others keep theirs.\n- **Every chain must reach something grounded.** A part that is neither grounded nor joined to a grounded part is never placed. A drive on a joint in that chain moves nothing and answers `moved: false`, with a `reason` and the part joined to nothing as `unconnected`. `joint.list` lists such chains under `floating`, and their occurrences have `dof: 6`. Fix it with `joint.rigid_group {\"occurrences\":[\"Frame:1\", ...]}`, or with a joint to the grounded structure.\n\n## Linked and closed motion\n- **Motion links:** `joint.motion_link {\"a\":..., \"b\":..., \"ratio\":r, \"offset\":o}` sets b = r·a + o, clamped to b's own limits. `ratio` is b's units per a's: a pinion that moves its rack 0.5 mm per degree takes `ratio: 0.5`. `offset` is in b's units: degrees for an angle, mm for a distance, or an expression. A mirrored part takes `ratio: -1`, and limits mirrored too. Chains (a drives b, b drives c) work in any order of creation. Drive only the head of a chain.\n- **Gears, racks and screws:** links whose ratio comes from radii or a pitch, kept up to date when they change. `joint.gear {\"a\":..., \"b\":..., \"ra\":r1, \"rb\":r2}` turns b r1/r2 as far as a, the other way (`internal: true`: the same way). `joint.rack_pinion {\"a\":pinion, \"b\":rack, \"radius\":r}` moves the rack r·θ. `joint.screw {\"joint\":cylindrical, \"pitch\":p}` (or `a`, `b` for a revolute and a slider) advances p per turn. A size is mm, an expression (`\"m*z1/2\"`), or a round face `{\"occurrence\":..., \"circle\":[x,y,z]}` whose radius is read again after every edit. `reverse: true` turns b the other way (a left-hand thread). The driven joint keeps where it is. Drive a, never b.\n- **Cams:** `joint.cam {\"a\":camJoint, \"b\":follower, \"profile\":{\"sketch\":\"CamSketch\"}}` (or `{\"edges\":[[x,y,z]]}` on the cam's body) makes a slider or revolute follower ride the cam's outline. `follower`: `knife` (default), `roller` with `radius` (mm, an expression or the roller's round face), `flat`. A revolute follower needs `tip` (its knife's point or roller's centre). The table is worked out again after every edit; the follower keeps where it is, so model it touching. Drive the cam, never the follower.\n- **Closed loops:** an actuator between a frame and a hinged panel takes three joints besides the hinge:\n - a revolute root pin (frame and barrel)\n - a slider (barrel and rod), with z along the actuator from root to tip on both origins, both at the root pin, and the stroke as its limits\n - a revolute tip pin (rod and panel), which closes the loop\n\n A four-bar or a slider-crank follows the same pattern. Drive the hinge; the pins and the slider follow.\n- **Stops:** at the end of the stroke the drive stops, with `stopped_by_loop: {joint, fraction}` naming the joint that could not follow. A loop that cannot close at all is listed under `conflicts`, and nothing in it moves.\n- **dof** counts the loop: here the panel, barrel and rod report 1 each, also at a pose where the actuator lies along its tip pin's path.\n\n## Contact and motion studies\n- **Contact:** `contact.create {\"occurrences\":[...], \"name\":...}` and `contact.enable_sets {}`. A drive, and a drag (`joint.reach`), then stops where two bodies of one set would pass through each other, with `stopped_by_contact: {a, b, fraction}`. `contact.check {}` lists the pairs that overlap now.\n- **Motion study:** `motion.study {\"name\":..., \"steps\":N, \"keys\":[{\"joint\":..., \"points\":[[step, value], ...]}]}`. Values are degrees or mm, linear between points. Key only the driving joints; linked joints and loops follow.\n- **Play:** `motion.play {\"study\":..., \"step\":s}` sets the joints there, which changes the design, and answers every occurrence's pose (about 0.2 KB per occurrence). `motion.export {\"study\":..., \"samples\":n}` gives the poses at every step without changing the design.\n- **Trace:** `motion.trace {\"occurrence\":..., \"point\":[x,y,z], \"joint\":..., \"from\":0, \"to\":360}` (or `\"study\":...` instead of joint, from and to) answers the world path of a point of a part, such as a coupler curve, without changing the design. It ends at `stopped_at` where a loop or contact stops the motion. `motion.trace.keep` with the same params keeps it as a 3D sketch spline.\n- **Plot:** `motion.plot {\"study\":..., \"joints\":[...], \"duration\":seconds}` answers each joint value's `value`, `velocity` and `acceleration` per sample (finite differences; per step, or per second with a duration), and with `\"occurrence\"` and `\"point\"` a point's `position`, `velocity`, `acceleration`, `speed`. Check a follower's rate against the analytic one this way, without changing the design.\n- **Collisions:** `motion.interference {\"study\":..., \"occurrences\":[...], \"against\":[...]}` plays the study (contact sets don't stop it) and lists each colliding pair with `first_step` and `steps` ranges; `clear: true` when none and every step was checked (never while `truncated`: then it stopped at `checked_to`; give a gear train or other detailed parts more time with `budget_s`). It takes at most 256 bodies: on a big design list the moving part as `occurrences` and what it must miss as `against`. Parts joined at a knuckle often overlap by design and show up at every step.\n- **Sweep until contact:** `joint.sweep {\"joint\":..., \"from\":0, \"to\":120, \"occurrences\":[...], \"against\":[...], \"report_gaps\":true}` answers how far a hinge, door or linkage opens: `stopped_at` (last clear value, bisected to `refine` mm, default 0.01), `stopped_by` `{a, b, at}` (or `\"loop\"`, `\"limit\"`), per-sample `min_gap_mm` and the nearest each part came (`min_gap`). It runs on a copy; `\"apply\":true` leaves the design at the stop. Pairs touching at `from` (`touching_at_start`) stop it only once they pass into each other.\n- **Find limits:** `joint.find_limits {\"joint\":...}` sweeps each value both ways from where it is (its own limits ignored, on a copy) and answers per value `min`, `max`, `min_by`/`max_by` (`{a, b, at}`, `\"loop\"`, `\"limit\"`, `\"turn\"`: nothing met within a turn, `\"range\"`: a distance meets nothing, `null` value). Set the joint's limits from it with `joint.limits`. A full turn of curved parts resting in each other can take a few seconds.\n\n## Verify\n- **Each joint:** `execute occurrence.properties {\"occurrence\":\"Wing:1\"}` (about 2 KB) gives the world bbox, centre of mass and inertia of one occurrence. Joining must not move them.\n- **Each drive:** compute the expected value of every follower, and read it back from `joint.list` (degrees and mm, with `unit`). For an actuator from root R to tip T on a panel hinged at H: `L(θ) = |T(θ) - R|`, where `T(θ)` is T turned by θ about the hinge axis through H, and the stroke is `L(θ) - L(0)`. A closed loop matches to 1e-6 mm.\n- **Each stop:** solve for where the limit is reached, and compare with the value the drive stopped at. Stops are found by bisection, so they land within about 0.01 degrees.\n- **Links:** b must equal r·a + o exactly, unless that is outside b's limits; then b sits at the limit and the mirror stops following.\n- **The whole motion:** `motion.play` at a few steps, or one `motion.export`, and compare the poses with the values you planned.\n- **Look:** when the server is bridged, `screenshot` after `motion.play` shows the app window at that step. `motion.export_animation {\"study\":..., \"path\":\"tour.gif\"}` (or `joint`, `from`, `to`) writes the whole motion as an animated GIF without changing the design.\n\n## Save\n- Drive the joints back to the pose you planned to keep (`motion.play` at step 0, or `joint.drive`), then `save {path}`.\n- An `.urdf` export leaves out each joint that closes a loop, because URDF is a tree.\n\n## Red flags\n\n| Thought | Do instead |\n|---|---|\n| \"The origins are at the same point, so `flip` doesn't matter\" | Pass `flip: true`, or the part turns 180 degrees. |\n| \"The drive answered values, so it moved\" | Read `moved`; a chain joined to nothing grounded answers `moved: false` and a `reason`. |\n| \"Drive the arm joint by joint until the gripper gets there\" | `joint.reach {\"occurrence\":..., \"at\":..., \"point\":...}` solves every joint on its chain at once; read `reached` and `error_mm`. |\n| \"Key every joint of the loop in the study\" | Key the driving joint only; the loop follows. |\n| \"Check the pose with `component.list`\" | `occurrence.properties` on the one occurrence. `component.list` is 140 KB on a 36-part assembly. |\n| \"Open the design with `file.open`\" | The `open` tool, or `doc.open`; there is no `file.open`. |\n", + "reference.md": "# makeCAD mechanism reference for agents\n\nThese are the shapes of the commands an assembly needs, so an agent rarely has to call `list_commands`. All of them run through the `execute` tool or a `batch`. The worked example below runs in CI (`mechanisms_skill_example_moves_as_documented` in `crates/mcp/src/tests.rs`).\n\n- Joint values, limits and study keys are in degrees for angles and mm for distances. Expressions work too: `\"30 deg\"`, `\"stroke/2\"`.\n- Points and axes are world coordinates, as the model sits when you make the joint.\n\n## Joint origins\n\nEach of `a` and `b` in `joint.create` is one of these:\n\n| Form | Shape | Notes |\n|---|---|---|\n| Point | `{\"occurrence\":\"Wing\",\"point\":[0,30,0],\"z\":[1,0,0]}` | The usual form. `z` is the joint axis (default +Z). |\n| Frame | `{\"occurrence\":\"Wing\",\"frame\":{\"origin\":[0,30,0],\"z\":[1,0,0],\"x\":[0,1,0]}}` | `x` fixes where angle 0 is. |\n| Face | `{\"occurrence\":\"Wing\",\"face\":[0,20,3]}` | The centre of the planar face through that point, axis along its normal. It follows the face when the part changes. |\n| Circle | `{\"occurrence\":\"Actuator rod\",\"circle\":[0,32,0]}` | The centre of the round edge through that point, axis along the cylinder. Pick a point on the rim. |\n| Named | `\"Hinge on frame\"` | Made first with `joint.origin {\"name\":..., \"occurrence\":..., \"point\":[...], \"z\":[...]}`. |\n\n- `occurrence` is an occurrence name (`Wing:1`), an id, or a component name (its first occurrence). Without it, the body nearest the point is used, which can be the wrong part where two touch.\n- **A part in a sub-assembly placed more than once:** add `\"path\"`, the occurrence ids from the root down to `occurrence` (`occurrence.properties` reports a placement's `path`). Without it, `occurrence` alone means the part in the first copy. The origin is then on that copy: `joint.list` names the copy as its occurrence, and a joint there holds or moves the whole copy.\n- **Use the same form on both sides.** `point` picks its x axis from z. A `frame` with an `x` on one side and a `point` on the other turned a test panel 90 degrees when it was joined.\n- **`flip`:** `false` (the default) mates the origins as two faces meet: b's z points against a's. Two origins at one point with the same `z` then turn part b 180 degrees about the axis, and a joint that closes a loop reports a conflict (\"off by 71 mm and 180 degrees\" on SELENE). `true` lines b's z up with a's, so parts stay where they are. `joint.edit {\"joint\":..., \"flip\":true}` changes it afterwards.\n- **Moving a side:** `joint.edit` takes `a` or `b` in joint.create's form (a joint origin, or a name), so a joint moves its attachment without being deleted and recreated; its limits, values and expressions stay.\n\n## Joint types\n\n| `type` | Values, in order | Units |\n|---|---|---|\n| `rigid` | none | |\n| `revolute` | angle | deg |\n| `slider` | distance along z | mm |\n| `cylindrical` | angle, distance | deg, mm |\n| `pin_slot` | angle, slide | deg, mm |\n| `planar` | x, y, angle | mm, mm, deg |\n| `ball` | yaw, pitch, roll | deg |\n\nA slider's value grows as b moves along +z of its origin. Give its two origins the same point, so 0 is the position as modelled.\n\n## Commands\n\n```json\n{\"command\":\"component.create\",\"params\":{\"name\":\"Actuator rod\",\"parent\":\"root\",\"activate\":false}}\n{\"command\":\"component.move_bodies\",\"params\":{\"bodies\":[\"Rod\"],\"component\":\"Actuator rod\"}}\n{\"command\":\"occurrence.ground\",\"params\":{\"occurrence\":\"Frame:1\",\"grounded\":true}}\n{\"command\":\"joint.create\",\"params\":{\"type\":\"slider\",\"name\":\"Stroke\",\"flip\":true,\"limits\":[[-5,10]],\"a\":{\"occurrence\":\"Actuator barrel\",\"point\":[0,0,-40],\"z\":[0,0.6,0.8]},\"b\":{\"occurrence\":\"Actuator rod\",\"point\":[0,0,-40],\"z\":[0,0.6,0.8]}}}\n{\"command\":\"joint.as_built\",\"params\":{\"type\":\"revolute\",\"a\":\"Frame\",\"b\":\"Wing 2\",\"at\":{\"occurrence\":\"Frame\",\"point\":[0,0,0],\"z\":[1,0,0]},\"name\":\"Hinge 2\",\"limits\":[[-60,0]]}}\n{\"command\":\"joint.rigid_group\",\"params\":{\"occurrences\":[\"Frame:1\",\"Lamp:1\"]}}\n{\"command\":\"joint.motion_link\",\"params\":{\"a\":\"Hinge\",\"b\":\"Hinge 2\",\"ratio\":-1}}\n{\"command\":\"joint.drive\",\"params\":{\"joint\":\"Hinge\",\"value\":20}}\n{\"command\":\"joint.drive\",\"params\":{\"joint\":\"Spindle\",\"values\":[30,5]}}\n{\"command\":\"joint.reach\",\"params\":{\"occurrence\":\"Gripper\",\"at\":[120,0,40],\"point\":[60,80,40],\"z\":[0,0,-1],\"axis\":[1,0,0],\"quiet\":true}}\n{\"command\":\"joint.limits\",\"params\":{\"joint\":\"Hinge\",\"min\":0,\"max\":60}}\n{\"command\":\"joint.edit\",\"params\":{\"joint\":\"Hinge\",\"flip\":true}}\n{\"command\":\"joint.delete\",\"params\":{\"link\":0}}\n{\"command\":\"contact.create\",\"params\":{\"occurrences\":[\"Frame:1\",\"Wing 2:1\"],\"name\":\"Wing 2 stop\"}}\n{\"command\":\"contact.enable_sets\",\"params\":{}}\n{\"command\":\"motion.study\",\"params\":{\"name\":\"Open\",\"steps\":10,\"keys\":[{\"joint\":\"Hinge\",\"points\":[[0,0],[10,25]]}]}}\n{\"command\":\"motion.play\",\"params\":{\"study\":\"Open\",\"step\":5}}\n{\"command\":\"motion.export\",\"params\":{\"study\":\"Open\",\"samples\":3}}\n{\"command\":\"occurrence.properties\",\"params\":{\"occurrence\":\"Wing:1\"}}\n```\n\n- `joint.create` and `joint.as_built` start the joint at its `values` (default 0). A value outside the limits starts at the nearer limit, and the reply's `warnings` say so: the part turned as it was joined.\n- `joint.as_built` takes occurrences, not origins. `at` is the joint's frame (default: b's component origin).\n- `joint.rigid_group` joins every occurrence to the first one with a rigid as-built joint.\n- `joint.motion_link`: b = ratio·a + offset, clamped to b's limits. `ratio` is in b's units per a's: mm per degree when an angle drives a distance (a pinion of pitch radius r moves its rack r·π/180 mm per degree), degrees per mm the other way, and a plain factor between two angles or two distances. `offset` is in b's units: degrees for an angle, mm for a distance, or an expression such as `\"10 deg\"`. `joint.list` gives each link's `ratio` the same way and its `offset` with its `unit`. `ia`/`ib` pick a value of a multi-value joint (default 0). `joint.delete {\"link\": n}` removes link n (its index in `joint.list` `links`).\n- `joint.gear {a, b, ra, rb, internal?, reverse?}`, `joint.rack_pinion {a, b, radius, reverse?}` and `joint.screw {joint | a, b; pitch, reverse?}` make a motion link whose ratio comes from its sizes: gears -ra/rb (+ra/rb internal), a rack r mm per radian of its pinion (either joint may be `a`), a screw pitch per turn. Each size is mm, an expression, or `{occurrence, circle: [x,y,z]}`: the radius of the round face there, read again whenever the design changes. The reply gives `link` (its index) and `ratio` as `joint.list` does; `link: n` in the params replaces link n and keeps its offset. A new coupling's offset keeps b where it is. `joint.list` `links` carry the `coupling` and an `error` when it can't be worked out (a picked face gone: the last ratio stays). A value two links would set, or a coupling that would drive its own driver, is refused.\n- `joint.cam {a, b, profile, follower?, radius?, tip?, flip?, link?}`: a is the cam's revolute joint, b a slider or revolute follower. `profile` is `{sketch, index?}` (a closed profile of a sketch in the cam's component) or `{edges: [[x,y,z]...], occurrence?}` (edges of the cam's body; one edge continues around its closed loop in the plane). The reply gives `link`, `lift: {min, max, rise, unit}` (b's travel over a turn), `reverse` (the side it rides from; `flip: true` takes the other) and, for a slider, `follower_offset`. `joint.list` `links` show `lift` instead of `ratio` for a cam.\n- `joint.drive`: `values` drives the values it lists, in order (`Spindle` above is cylindrical: 30 degrees, then 5 mm), and `value` the first; values left out keep theirs, or follow in a closed loop. Values are clamped to the limits. The reply gives `values` as `joint.list` does (`{name, value, unit, limits}`), and `moved`; when the joint can move nothing, a `reason`.\n- `joint.reach` (inverse kinematics): moves the joints on the occurrence's chain so its point `at` (world, where it is now; default: the centre of its bodies) gets to `point`, from the pose it is in to the nearest one, within limits, through motion links, and with closed loops kept closed. `z` with `axis` (world, now; default its own z) also turns that axis. `joints: [...]` moves only those (loop followers still follow). The reply: `reached`, `error_mm` (and `error_deg`), `point` where it ended, `values` of the joints that moved, `moved`, and when short, `stopped_by_limit: [{joint, value, limit}]` or `stopped_by_loop: {joint}`. A part that nothing moves answers `moved: false` with a `reason`. Contact sets are not checked; check with `contact.check` afterwards.\n- `motion.study {\"study\":..., ...}` edits a study; `keys` given replace all keys.\n- `motion.play` sets the joints to the study's values at a step (fractions work) and changes the design. `motion.export` does not change it.\n\n## Worked example: a panel on an actuator\n\nA frame holds a panel on a hinge along X at the origin. An actuator runs from a root pin on the frame, R = (0, 0, -40), to a tip pin on the panel, T = (0, 30, 0), 30 mm from the hinge: 50 mm long, along (0, 0.6, 0.8). Its rod slides -5 to +10 mm. A second panel on the other side mirrors the first through a motion link.\n\n```json\n{\"commands\":[\n {\"command\":\"solid.box\",\"params\":{\"length\":40,\"width\":10,\"height\":50,\"corner\":[-20,-10,-50],\"operation\":\"new\",\"body_name\":\"Post\"}},\n {\"command\":\"solid.box\",\"params\":{\"length\":40,\"width\":40,\"height\":10,\"corner\":[-20,0,-50],\"operation\":\"new\",\"body_name\":\"Base\"}},\n {\"command\":\"solid.box\",\"params\":{\"length\":40,\"width\":40,\"height\":3,\"corner\":[-20,0,0],\"operation\":\"new\",\"body_name\":\"Panel\"}},\n {\"command\":\"solid.box\",\"params\":{\"length\":40,\"width\":40,\"height\":3,\"corner\":[-20,-40,0],\"operation\":\"new\",\"body_name\":\"Panel 2\"}},\n {\"command\":\"solid.cylinder\",\"params\":{\"radius\":5,\"height\":20,\"base\":[0,0,-40],\"axis\":[0,0.6,0.8],\"operation\":\"new\",\"body_name\":\"Barrel\"}},\n {\"command\":\"solid.cylinder\",\"params\":{\"radius\":2,\"height\":35,\"base\":[0,9,-28],\"axis\":[0,0.6,0.8],\"operation\":\"new\",\"body_name\":\"Rod\"}},\n {\"command\":\"component.create\",\"params\":{\"name\":\"Frame\",\"parent\":\"root\",\"activate\":false}},\n {\"command\":\"component.move_bodies\",\"params\":{\"bodies\":[\"Post\",\"Base\"],\"component\":\"Frame\"}},\n {\"command\":\"component.create\",\"params\":{\"name\":\"Wing\",\"parent\":\"root\",\"activate\":false}},\n {\"command\":\"component.move_bodies\",\"params\":{\"bodies\":[\"Panel\"],\"component\":\"Wing\"}},\n {\"command\":\"component.create\",\"params\":{\"name\":\"Wing 2\",\"parent\":\"root\",\"activate\":false}},\n {\"command\":\"component.move_bodies\",\"params\":{\"bodies\":[\"Panel 2\"],\"component\":\"Wing 2\"}},\n {\"command\":\"component.create\",\"params\":{\"name\":\"Actuator barrel\",\"parent\":\"root\",\"activate\":false}},\n {\"command\":\"component.move_bodies\",\"params\":{\"bodies\":[\"Barrel\"],\"component\":\"Actuator barrel\"}},\n {\"command\":\"component.create\",\"params\":{\"name\":\"Actuator rod\",\"parent\":\"root\",\"activate\":false}},\n {\"command\":\"component.move_bodies\",\"params\":{\"bodies\":[\"Rod\"],\"component\":\"Actuator rod\"}},\n {\"command\":\"occurrence.ground\",\"params\":{\"occurrence\":\"Frame:1\",\"grounded\":true}},\n {\"command\":\"joint.create\",\"params\":{\"type\":\"revolute\",\"name\":\"Hinge\",\"flip\":true,\"a\":{\"occurrence\":\"Frame\",\"point\":[0,0,0],\"z\":[1,0,0]},\"b\":{\"occurrence\":\"Wing\",\"point\":[0,0,0],\"z\":[1,0,0]}}},\n {\"command\":\"joint.create\",\"params\":{\"type\":\"revolute\",\"name\":\"Root pin\",\"flip\":true,\"a\":{\"occurrence\":\"Frame\",\"point\":[0,0,-40],\"z\":[1,0,0]},\"b\":{\"occurrence\":\"Actuator barrel\",\"point\":[0,0,-40],\"z\":[1,0,0]}}},\n {\"command\":\"joint.create\",\"params\":{\"type\":\"slider\",\"name\":\"Stroke\",\"flip\":true,\"limits\":[[-5,10]],\"a\":{\"occurrence\":\"Actuator barrel\",\"point\":[0,0,-40],\"z\":[0,0.6,0.8]},\"b\":{\"occurrence\":\"Actuator rod\",\"point\":[0,0,-40],\"z\":[0,0.6,0.8]}}},\n {\"command\":\"joint.create\",\"params\":{\"type\":\"revolute\",\"name\":\"Tip pin\",\"flip\":true,\"a\":{\"occurrence\":\"Actuator rod\",\"point\":[0,30,0],\"z\":[1,0,0]},\"b\":{\"occurrence\":\"Wing\",\"point\":[0,30,0],\"z\":[1,0,0]}}},\n {\"command\":\"joint.as_built\",\"params\":{\"type\":\"revolute\",\"a\":\"Frame\",\"b\":\"Wing 2\",\"at\":{\"occurrence\":\"Frame\",\"point\":[0,0,0],\"z\":[1,0,0]},\"name\":\"Hinge 2\",\"limits\":[[-60,0]]}},\n {\"command\":\"joint.motion_link\",\"params\":{\"a\":\"Hinge\",\"b\":\"Hinge 2\",\"ratio\":-1}}\n]}\n```\n\n**Expected:**\n- After the batch, `joint.list` reports `dof` 1 for Wing, Wing 2, the barrel and the rod (the loop and the link leave one motion), 0 for Frame, and no `conflicts`.\n- **Actuator length:** the tip pin turns to `(0, 30 cos θ, 30 sin θ)`, so `L(θ)² = 2500 + 2400 sin θ` and `L(0) = 50`. The stroke is `L(θ) - 50`.\n- `joint.drive {\"joint\":\"Hinge\",\"value\":20}`: the stroke is `L(20°) - 50 = 7.6268` mm, and Hinge 2 is -20. `occurrence.properties {\"occurrence\":\"Wing:1\"}` puts the panel's centre of mass at (0, 18.281, 8.250), and Wing 2's at (0, -18.281, 8.250).\n- `joint.drive {\"joint\":\"Hinge\",\"value\":45}` stops at 27.28 degrees with `stopped_by_loop: {\"joint\":\"Stroke\", ...}`: the rod reaches +10 mm where `L(θ) = 60`, at `sin θ = 11/24`, θ = 27.280 degrees.\n\n## At scale: SELENE\n\nThe same pattern moved the solar wings of the SELENE rover (`Rover-v7.solidcraft` by 0xlillith, 36 occurrences, 1353 features):\n- **Actuators split:** each of the four actuators was one component. Its barrel and its rod (with the eyes and pins that move with them) went into components of their own with `component.create` and `component.move_bodies`.\n- **Loops:** per actuator, a revolute root pin (structure and barrel), a slider with the stroke as its limits, `[[-6, 0.4]]` mm, and a revolute wing pin (rod and wing). All `flip: true`, origins by world point, with z along X for the pins and along the actuator (root to tip) for the slider.\n- **Links:** the six wheels follow the first (`ratio: 1`); the starboard tilt mirrors the port one (`ratio: -1`).\n- **Floating modules:** in v7, 18 components (pedestals, avionics, the lid and others) were neither grounded nor joined, so driving the turret or the dish moved nothing. One `joint.rigid_group` with the structure fixed it.\n- **Hidden:** the arm's flexible hoses are rigid bodies on one link, and their sweep sketches stay in place, so both drift off as the arm moves. `browser.visibility {\"items\":[...], \"visible\":false}` hid them, and `{\"folder\":\"joints\",\"visible\":false}` the joint glyphs for the recording.\n- **Numbers:** the port tilt hinge is at (0, -140, 158) along X, the actuator root at (x, -91, 134) and its wing pin at (x, -180.41, 169.71). From these, the stroke at 20 degrees is -2.87 mm, and the rod reaches -6 mm at 32.230 degrees. The app agrees: a drive to 20 degrees gives -2.87 mm, and a drive towards 45 degrees stops at 32.23 degrees with `stopped_by_loop`.\n\n## Traps\n\n| Symptom | Cause and fix |\n|---|---|\n| A part turns 180 degrees when joined; a loop reports \"off by ... and 180 degrees\" | `flip` left out. Pass `flip: true`, or `joint.edit {\"joint\":..., \"flip\":true}`. |\n| A part turns to a limit as soon as it is joined, and the reply has `warnings` | A new joint starts at 0, or its `values`, inside its limits: `[[10, 60]]` on a hinge turns it 10 degrees. Make the limits include 0, or join the parts where the limits allow. |\n| A part turns by some other angle when joined | The two origins have different forms or x axes. Use `point` + `z` on both sides, or `joint.as_built`. |\n| `joint.drive` answers `moved: false`, or `motion.play` lists the joint under `unmoved` | Read `reason`. Most often the chain is joined to nothing grounded: `unconnected` names the part, and `joint.list` lists the chain under `floating`, its occurrences with `dof: 6`. Ground it, join it, or `joint.rigid_group` it with the structure. |\n| A drive stops short, `stopped_by_loop` | A loop reached a limit or can't close further; `joint` names the joint that stopped it. Check the limits against your stroke numbers. |\n| A gear, rack or screw turns its partner the wrong way | The joints' axes point opposite ways (or the rack lies on the other side of the pinion). Run the command again with `reverse: true` and `link: n`. |\n| `joint.cam` says the follower's line misses the cam | The slider's line (through `tip` when given) passes beside the cam at some angle. Pick the follower's tip, or move its slider's axis over the cam. |\n| A cam's follower rides the wrong flank or sinks into the cam | It took the other side of the cam's axis (`reverse` in the reply): run `joint.cam` again with `flip: true` and `link: n`. |\n| `already follows a motion link` from `joint.gear` | A joint follows one link at most. Make the joint that already follows the driving one (`a`), as in a gear train G1 → G2 → G3. |\n| A linked joint stops following | Its value is clamped to its own limits. Hinge 2 in the example has `[[-60, 0]]`, so a drive of Hinge below 0 leaves it at 0. Give a mirrored joint the mirrored limits. |\n| `joint.reach` answers `reached: false` | The point is out of reach: `point` and `error_mm` give the nearest pose. `stopped_by_limit` names the limits it rests on, `stopped_by_loop` the loop that can't follow further; with neither, the chain can't get there at all (too far, or out of its plane). |\n| A drive stops short, `stopped_by_contact` | Two bodies of a contact set touch. `fraction` is how far the move got. |\n| `occurrence.ground` says there is no occurrence `Frame` | It takes occurrence names only: `Frame:1`. |\n| `a joint needs two different occurrences` | Both origins found the same part. Give `occurrence` on both. If the parts are bodies of one component (an imported STEP file often brings them so), run `component.from_bodies {\"bodies\": [...]}` first. |\n| \"unknown command\" for `file.open` | Open a design with the `open` tool or `doc.open {path}`. |\n| Rigid hoses, cables or springs drift as the mechanism moves | Bodies don't bend. Hide them with `browser.visibility`, or model them per link. |\n| `solidcraft-cli snapshot SCRIPT --in design` runs on an empty design | `snapshot` ignores `--in`. Run `solidcraft-cli run SCRIPT --in design --save out.sc` first. |\n| A URDF export lacks a joint | `export` to `.urdf` leaves out each joint that closes a loop, with a warning, because URDF is a tree. |\n\n## Reply cost\n\n| Call | Size |\n|---|---|\n| `component.list` | **140 KB** on SELENE (a 4x4 transform per occurrence). Avoid it; use `occurrence.properties`. |\n| `joint.list` | about 0.5 KB per joint: 16 KB for 29 joints |\n| `motion.play` | about 0.2 KB per occurrence, per step: 9 KB on SELENE |\n| `motion.export` | the same per sample; pass `samples`, or `path` to write it to a file |\n| `joint.create`, `joint.drive`, `joint.motion_link`, `joint.gear`, `joint.rack_pinion`, `joint.screw` | the `dof` list of every occurrence again, 40 B each; `quiet: true` leaves it out |\n| `occurrence.properties` | under 1 KB per occurrence |\n\n## Showing it moving\n\n`motion.export_animation {\"study\":..., \"path\":\"tour.gif\"}` draws the whole motion as an animated GIF in one call, headless or bridged, and changes nothing: `{\"joint\":..., \"from\":0, \"to\":90, \"path\":...}` animates a drive instead, and `{\"view\":..., \"back\":true, \"path\":...}` an exploded view coming apart and back together (the placements stay as they are). A path that does not end in `.gif` is a folder for PNG frames (`frame-0001.png`, ...). Pass `camera` (the reply of `ui.camera`, or any of its fields), `width`/`height` (default 800 x 500), `samples` (frames; default the study's steps + 1, 100 for a joint, 41 for a view or 81 with `back`), `fps` (default 20), and `grid: false` / `axes: false` for a clean background. The reply is small: `frames`, `bytes`, and `stopped_at` with `stopped_by_loop`/`stopped_by_contact` where the motion first stopped short.\n\nBridged to the app, `motion.play {\"study\":..., \"step\":s}` moves the user's viewport, and `screenshot` captures the window at that step.\n" } }, { "name": "makecad-modeling", "description": "Use when building a new part, enclosure, bracket, plate, flange or any other 3D solid in makeCAD through its MCP server (tools such as batch, execute, measure, screenshot), or when a makeCAD session is using many tool calls or tokens.", "files": { - "SKILL.md": "---\nname: makecad-modeling\ndescription: Use when building a new part, enclosure, bracket, plate, flange or any other 3D solid in makeCAD through its MCP server (tools such as batch, execute, measure, screenshot), or when a makeCAD session is using many tool calls or tokens.\n---\n\n# makeCAD modeling\n\n## Overview\nWork the part out as numbers first. Then build it in a few large `batch` calls, and check each stage with `measure` against values you computed yourself. A clean build takes 3-4 build batches, about 10-13 calls with the checks. Command shapes, plane axes, ids, reply sizes and known traps are in `reference.md` next to this file, so you do not need to explore the command catalog.\n\n## Before the first call\n1. In makeCAD's own chat or any MCP client, call `skill_reference {\"skill\":\"makecad-modeling\",\"file\":\"reference.md\"}`. Elsewhere, read `reference.md`.\n2. Run `inspect_design {\"measure\":false,\"sketches\":false}`, even when you think the session is empty.\n - The makeCAD server's instructions end with `Backend: connected to the makeCAD app` when it drives the user's open app, and with `Backend: headless` otherwise.\n - If the design has timeline features, ask before calling `new_design` or `open`, because both discard unsaved work. You can also build into the open design.\n3. Write a plan:\n - the parameters\n - the placement: centre the part on the origin so patterns and mirrors can work from the planes\n - every feature, with the world point you will use for each edge or face pick\n - the expected volume and bounding box\n\n## Build\n- **Stages:** use one batch per stage:\n 1. parameters, sketch, dimensions, finish and the first feature\n 2. fillets and shell\n 3. holes, cuts and patterns\n- **Failures:** a batch is all-or-nothing. On failure, read `failed.index` and `failed.error`, fix that step only, and send the batch again.\n- **Risky steps:** put a risky step in a batch of its own, so a failure does not roll back the work around it. This covers booleans between curved faces that touch, and anything you have not done before.\n- **Reply size:** in large designs, pass `\"verbose\": false` to `batch` and `execute`.\n- **Sketch ids are predictable,** so later steps in the same batch can use them:\n - Each sketch counts each kind from 1 (`l1`, `c1`, `a1`, `p1`).\n - Count what the earlier steps of that sketch created. For example, `rectangle.center` makes `l1`-`l6` and `p1`-`p5`.\n - Do not split a batch just to read ids back.\n- **Positions that must follow a parameter** come from:\n - sketch dimensions to `\"origin\"` with expression values (`\"w/2 - wall - 6\"`)\n - expression fields such as `solid.cylinder base:[\"w/2-6\",\"d/2-6\",\"wall\"]`\n\n A plain number never follows a parameter.\n- **Repeats:** `solid.pattern.rectangular` takes expression spacing; `solid.mirror` takes `XY`/`XZ`/`YZ`, a construction plane or `{origin, normal}` (origin coordinates may be length expressions such as `[\"half\", 0, 0]`). A mirror or pattern feature cannot be mirrored or patterned again.\n- **Edge and face picks** snap to the nearest edge or face. An edge pick farther than 5% of the body's size from every edge is refused (`the nearest edge is 15.000 mm away`). On a large body that limit is wide (about 48 mm on a 949 mm board), so compute the exact midpoint from your geometry (the vertical corner edge of a centred box is `[w/2, d/2, h/2]`).\n - Picks must be plain numbers.\n - A pick is resolved once and then follows its edge when parameters change.\n - A face can be given by name instead of a point (`faces:[\"F1:+z\"]`, the `face` of `sheet.convert`). `body_topology` lists each face's `name`, a `point` that lies on it (the centroid of a face with a hole is in the hole) and, for a cylinder, `{origin, axis, radius}`.\n- **Profiles:** extrude takes every region by default, and a region inside another is a hole in it: two concentric circles give a ring. A third circle inside the ring gives a separate disc body. Pass `profiles` to choose regions.\n- **Order:** fillet the outside edges before you shell, so the shell follows the fillets. There are two exceptions:\n - An edge of the face the shell removes, such as the rim of an open box: round it after the shell, because the shell can fail on it.\n - A fillet between two curved faces, such as a sphere joined to a cylinder: the shell then fails with `offset: only bodies with planes, cylinders, cones, spheres and tori`. Shell first. The inside corner then stays sharp, so the wall there is thinner than `thickness`.\n\n## Verify\n- **Each stage:** run `measure {}` (about 0.9 KB per body; `{\"summary\":true}` keeps only name, volume, bbox, face count and `closed` per body) and compare the volume, bbox and face count with your numbers. A cut or hole that leaves the volume unchanged has missed, even though it reported success.\n- **Timeline health:** `inspect_design {\"measure\":false,\"sketches\":false}` shows each feature's `error` and `warning`.\n- **Parameter test:** run `set_parameter`. Expect `errors: []`, then `measure` again; the COM and bbox should move by the amounts you computed. To try values without keeping them, `check_parameters {\"set\": {\"L\": \"140 mm\"}}` reports the volume, errors and cylinder axes and puts the design back.\n- **Positions:** `measure` does not say where a feature sits.\n - On an asymmetric part, check the COM shift you computed.\n - On a symmetric part (a mirrored or patterned layout) the COM does not move, so take a top-view screenshot and compare distances in pixels against a known size.\n - For holes and bosses, `body_topology {\"body\":\"Body1\",\"faces\":\"cylinders\"}`: one entry per cylinder (`radius`, `origin`, `axis`, `extent` along the axis, the merged faces' `names`), a few lines.\n - The full `body_topology` is a last resort: it costs 25-45 KB and splits cylinders into half faces.\n- **Final look:** one `screenshot {\"source\":\"model\",\"view\":\"iso\",\"width\":480,\"height\":320}`. Use `\"view\":\"top\"` for features inside walls, which the iso view hides.\n - `width` and `height` apply only to model renders.\n - When the server is bridged, `source` defaults to the whole app window and `view` also turns the user's camera, so pass `\"source\":\"model\"` and leave out `view` unless the user wants the camera moved.\n\n## Finish\n`export {path}` writes `.step` for CAD, `.3mf`/`.stl` for printing, or `.urdf` (an assembly with joints, for robot simulators). `save {path}` writes `.sc` (`.solidcraft` files from earlier releases still open).\n\n## Red flags\n\n| Thought | Do instead |\n|---|---|\n| \"List all commands first\" | `reference.md`, or `list_commands {\"filter\":\"\"}`. The unfiltered list is over 100 KB. |\n| \"Check positions with body_topology\" | `measure` COM and bbox against your numbers. |\n| \"Inspect the sketch\" | `sketch.solve` returns dof and the profile count in under 100 bytes. Run `sketch.inspect` on its own, never inside a big batch. |\n| \"new_design for a clean start\" | When the server is bridged, ask first. |\n| \"It reported ok, so it worked\" | Only a `measure` that matches the computed values counts. |\n", - "reference.md": "# makeCAD command reference for agents\n\nThese are the shapes of the commands a part build needs, so an agent rarely has to call `list_commands`. The worked example at the end runs in CI (`skill_reference_example_builds_as_documented` in `crates/mcp/src/tests.rs`).\n\n- Lengths are in mm.\n- Lengths take a unit suffix, in parameters and in feature fields: `\"16 in\"` is 406.4 mm, and `length:\"1 in\"` works in `solid.box`. `measure` still reports mm.\n- Angles inside expressions take units: `\"30 deg\"`.\n- Any numeric field can be an expression that names parameters: `\"w/2 - wall - 6\"`.\n\n## Sketch planes: where sketch (x, y) lands in the world\n\n| `plane` | sketch x | sketch y | normal (+distance) |\n|---|---|---|---|\n| `\"XY\"` | +X | +Y | +Z |\n| `\"XZ\"` | +X | **-Z** | +Y |\n| `\"YZ\"` | +Y | +Z | +X |\n| `{origin, x_dir, y_dir}` | x_dir | y_dir | x_dir x y_dir |\n\n- `offset: \"expr\"` on `sketch.create` moves the plane along its normal and follows parameters.\n- **Front wall (-Y) of a part centred on the origin:**\n - Sketch on `{\"plane\":\"XZ\",\"offset\":\"-d/2\"}`.\n - Draw a feature at height z at sketch y = **-z**.\n - A cut with a positive distance goes into the wall.\n- **Top face:** sketch on `{\"plane\":\"XY\",\"offset\":\"h\"}`.\n- **Hole direction:** `solid.hole {sketch}` drills into the part from the face nearest the sketch. A hole sketch at z=0, or below the part, drills up into the bottom face. Put the sketch on the face the hole starts from.\n\n## Ids\n\n- **Numbering:** every creator returns `created: {points, curves, constraints, dimensions}`. Ids are stable and numbered per sketch.\n- **Curves:** `l1`, `c1`, `a1`.\n- **Points:** `p1`, `l1.start`, `l1.end`, `c1.center`, `a1.center`, and the sketch origin `\"origin\"`.\n- **Rectangles:** `sketch.rectangle.*` also returns `sides {bottom,right,top,left}` and `corners {bottom_left,...}`.\n - `rectangle.center` adds 2 construction diagonals, so each corner joins 3 lines. Its centre point is `p5`.\n - `sketch.fillet {point}` therefore fails on its corners. Use `{a:\"l1\", b:\"l4\", radius}` or the 3D `solid.fillet`.\n- **Slots:** `sketch.slot.overall` and `sketch.slot.center_to_center` create 2 lines, 2 arcs and 4 points, plus `a1.center` and `a2.center`. The ids count on from what the sketch already has: in an empty sketch `l1, a1, l2, a2` and `p1`-`p4`, after a `rectangle.two_point` `l5, a1, l6, a2` and `p5`-`p8`.\n - The `length` role of `slot.overall` is the overall length. The arc centres are at ±(length/2 - width/2).\n - After `length` and `width`, 3 dof remain. To remove them, dimension `origin` to `a1.center` horizontally and vertically, and `origin` to `a2.center` vertically. For a slot along Y the solver refuses that last dimension as over-constraining; dimension `a2.center` horizontally instead.\n - `sketch.slot.center_point` creates no centre point. Dimension an arc centre instead.\n- **Circles:** `sketch.circle.center` creates `c1` and `c1.center`, and no `p` point.\n- **Dimensions** share the `k` counter with constraints.\n- **Constraints can add curves:** a constraint about an axis, such as `sketch.constraint.symmetry` with `line:\"y\"`, adds a construction line and so takes the next `l` id. Read `created` before you count further.\n- **Over-constraining** is refused with `that conflicts with the sketch: neither entity can move to satisfy it`. For example, symmetry already makes two circles equal.\n\n## Dimensions\n\n```json\n{\"command\":\"sketch.dimension\",\"params\":{\"entities\":[\"origin\",\"c1.center\"],\"type\":\"horizontal\",\"value\":\"w/2 - wall - 6\"}}\n{\"command\":\"sketch.dimension\",\"params\":{\"entities\":[\"c1\"],\"type\":\"diameter\",\"value\":\"6\"}}\n{\"command\":\"sketch.dimension\",\"params\":{\"entities\":[\"l1\"],\"value\":\"w\"}}\n{\"command\":\"sketch.dimension\",\"params\":{\"entities\":[\"l1\",\"c1\"],\"value\":\"2\"}}\n{\"command\":\"sketch.dimension\",\"params\":{\"entities\":[\"c1\",\"c2\"],\"value\":\"3\"}}\n```\n\nA line, a point or another circle with a circle or arc measures to its edge (0 is tangent, or the point on the circle); two circles measure between their edges (the overlap when they cross, the thinnest wall when one is inside the other). Give the centre point (`c1.center`) for the distance to the centre.\n\nDistances are unsigned. Draw the geometry on the correct side first, and the dimension keeps it there.\n\n`sketch.draw.dimensioned` creates a shape and its dimensions in one undo step. The dimension roles depend on the creator:\n\n| Creator | Roles |\n|---|---|\n| `line` (exactly 2 points) | `length`, `angle` |\n| `rectangle.*` | `width`, `height` |\n| `circle.*` | `radius` or `diameter` |\n| `arc.center_point` | `radius`, `sweep` |\n| `slot.center_to_center`, `slot.overall` | `length`, `width` |\n| `polygon.*` | `radius` |\n\n```json\n{\"command\":\"sketch.draw.dimensioned\",\"params\":{\"command\":\"sketch.rectangle.center\",\"params\":{\"center\":[0,0],\"corner\":[35,25]},\"dimensions\":{\"width\":\"w\",\"height\":\"d\"}}}\n```\n\n## Features\n\n| Command | Minimal params | Traps |\n|---|---|---|\n| `solid.extrude` | `distance` | `profiles` defaults to **every region**, with a region inside another as a hole in it: two concentric circles give a ring. Pick regions with `[{\"point\":[x,y]}]` or `[index]`. Other options: `operation` (new/join/cut/intersect/auto), `direction` (positive/negative/symmetric), `through_all: true`, `start_offset`. A cut that misses reports success. |\n| `solid.box` | `length`, `width`, `height` | `center:[x,y,z]` or `corner`. The quickest way to block out a part. `body_name` names the body it makes. With `operation:\"cut\"`, `targets:[\"Top\"]` cuts only the bodies listed, so the cutter can pass through other bodies. |\n| `solid.cylinder` | `radius` or `diameter`, `height` | `base` is the centre of the bottom (default origin), `axis` defaults to `Z`. Expressions work in `base`. To tie a cylinder standing on a flat face to the part, give `base` as numbers on that face and add `references: [{edge:[x,y,z], distance}]` (up to two straight edges of the face, as for `solid.hole`): the base centre then sits at those distances from the edges and follows them. Always pass `operation`. `body_name` and `targets` work as for `solid.box`. |\n| `sketch.slot.overall` / `sketch.slot.center_to_center` | `p0`, `p1` (overall ends / arc centres), `width` | Ids and dof are in the \"Ids\" section above. |\n| `solid.fillet` / `solid.chamfer` | `edges:[[x,y,z]]`, `radius` / `distance` | The pick snaps to the **nearest** edge. A pick farther than 5% of the body's size from every edge is refused, so check that the face count changed. One pick takes the whole tangent chain: a rounded rim needs 1 point, not 8. |\n| `solid.shell` | `faces:[[x,y,z]]`, `thickness` | A point on each face to remove, or its name from `body_topology`. Fillet first, except an edge of a removed face or a fillet between curved faces (see Order in `SKILL.md`). Bodies with lofted or swept faces are refused (`offset: only bodies with planes, cylinders, cones, spheres and tori`): hollow a loft with a smaller loft and `operation: cut`. |\n| `solid.hole` | `position:[x,y,z]` on a face (numbers or length expressions such as `[\"40\", \"width/2\", \"t\"]`, which the hole then follows) + `diameter`, or `sketch` (+ `points`) | `clearance:\"M3\"`. `depth` defaults to through all. `type` is one of simple/drilled/counterbore/countersink. A `countersink` needs `cs_diameter` and `cs_angle`; a `counterbore` needs `cb_diameter` and `cb_depth`. `position` is a fixed point; to tie it to the part, add `references: [{edge:[x,y,z], distance}]` (up to two straight edges of the face): the centre then sits at those distances from the edges and follows them. |\n| `solid.pattern.rectangular` | `features`, `dir1`, `count1`, `spacing1` (+ `dir2`, `count2`, `spacing2`) | Spacing takes expressions and follows parameters. |\n| `solid.pattern.circular` | `features`, `axis` (`\"Z\"`, `{origin, dir}` whose origin may be length expressions the pattern follows, or `{face: [x,y,z]}` / `{edge: [x,y,z]}` on a cylinder wall or circular edge, which the pattern follows), `count` | `angle` defaults to 360 deg. A full pattern keeps the COM on the axis, so check its radius with a top-view screenshot. |\n| `solid.mirror` | `features:[names]` or `bodies:[names]`, `plane` (`XY`/`XZ`/`YZ`, a construction plane, or `{origin, normal}` whose origin may use length expressions) | Follows parameters. A mirror or pattern feature cannot be listed in `features` of another mirror or pattern, but `bodies` can mirror the body it made. The mirror is a new body with the first free default name: `Body1`, `Body2` from `features`, and `Side (2)`, `Side (3)` from `bodies:[\"Side\"]`. Read the name from `created_bodies`. With `combine:true`, a mirror that overlaps the original joins it and makes no new body. `features` copies only the features listed, so a later cut is left out unless you list it too. `bodies` copies the finished body. To name the mirror, use `body.rename {\"body\":\"Side (2)\",\"name\":\"Side_L\"}`. The new name stays when parameters change. |\n\n- **Names:** name every feature (`\"name\":\"Standoff\"`) and keep names unique across sketches and features. `timeline.roll_to {\"feature\":\"Plate\"}` picks the first match, which can be the sketch.\n- **Counts as parameters:** `parameters.add {\"name\":\"n\",\"expression\":\"6\",\"unit\":\"\"}` creates a unitless parameter, and `\"count\":\"n\"` uses it in a pattern.\n- **Names of pattern and mirror copies:** `solid.pattern.rectangular` and `solid.pattern.circular` take `bodies` as well as `features`, and name copies like `solid.mirror` does. `solid.pattern.circular {\"bodies\":[\"Groove end\"],\"axis\":\"Z\",\"count\":3}` keeps the original and makes the copies `Groove end (2)` and `Groove end (3)`. A name already taken is skipped: with `Groove end (2)` present, the copies are `Groove end (3)` and `Groove end (4)`. With `features`, the pattern makes a new `BodyN`, as in the `solid.mirror` row. Read the names from `created_bodies`. Mirroring a copy adds a suffix: `Groove end (2)` mirrored is `Groove end (2) (2)`. The pattern commands list no body-name parameter, so use `body.rename` for stable names. There is no way yet to refer to every copy at once, for example in `solid.combine` (#8194).\n- **Holes on a parametric bolt circle:**\n 1. Cut one hole with `solid.cylinder {\"diameter\":6.6,\"height\":\"T + 2\",\"base\":[\"bcd/2\",0,-1],\"operation\":\"cut\",\"name\":\"BoltHole\"}`.\n 2. Repeat it with `solid.pattern.circular {\"features\":[\"BoltHole\"],\"axis\":\"Z\",\"count\":\"n\"}`.\n\n Both the radius and the count follow their parameters.\n- **Parameter changes:** for one change, call `set_parameter {\"name\":\"L\",\"value\":\"120 mm\"}`. For several, use one `batch` of `parameters.change` steps instead of one `set_parameter` call each.\n- **Primitive booleans:** a `solid.box` or `solid.cylinder` cut that touches curved faces of the target can fail with `the exact fallback ... takes planar faces only`. Use a sketch profile and an extrude cut instead, for example a slot sketch rather than a box plus 2 cylinders.\n\n## Worked example: parametric plate with 4 counterbored holes (1 batch)\n\n```json\n{\"commands\":[\n {\"command\":\"parameters.add\",\"params\":{\"name\":\"L\",\"expression\":\"80 mm\"}},\n {\"command\":\"parameters.add\",\"params\":{\"name\":\"W\",\"expression\":\"50 mm\"}},\n {\"command\":\"parameters.add\",\"params\":{\"name\":\"T\",\"expression\":\"6 mm\"}},\n {\"command\":\"parameters.add\",\"params\":{\"name\":\"inset\",\"expression\":\"8 mm\"}},\n {\"command\":\"sketch.create\",\"params\":{\"plane\":\"XY\",\"name\":\"PlateSketch\"}},\n {\"command\":\"sketch.draw.dimensioned\",\"params\":{\"command\":\"sketch.rectangle.center\",\"params\":{\"center\":[0,0],\"corner\":[40,25]},\"dimensions\":{\"width\":\"L\",\"height\":\"W\"}}},\n {\"command\":\"sketch.finish\",\"params\":{}},\n {\"command\":\"solid.extrude\",\"params\":{\"distance\":\"T\",\"name\":\"Plate\"}},\n {\"command\":\"solid.fillet\",\"params\":{\"edges\":[[40,25,3],[-40,25,3],[40,-25,3],[-40,-25,3]],\"radius\":5,\"name\":\"Corners\"}},\n {\"command\":\"sketch.create\",\"params\":{\"plane\":\"XY\",\"name\":\"HolePts\",\"offset\":\"T\"}},\n {\"command\":\"sketch.point\",\"params\":{\"point\":[32,17]}},\n {\"command\":\"sketch.dimension\",\"params\":{\"entities\":[\"origin\",\"p1\"],\"type\":\"horizontal\",\"value\":\"L/2 - inset\"}},\n {\"command\":\"sketch.dimension\",\"params\":{\"entities\":[\"origin\",\"p1\"],\"type\":\"vertical\",\"value\":\"W/2 - inset\"}},\n {\"command\":\"sketch.finish\",\"params\":{}},\n {\"command\":\"solid.hole\",\"params\":{\"sketch\":\"HolePts\",\"diameter\":3.4,\"type\":\"counterbore\",\"cb_diameter\":6.5,\"cb_depth\":3.3,\"name\":\"Hole\"}},\n {\"command\":\"solid.pattern.rectangular\",\"params\":{\"features\":[\"Hole\"],\"dir1\":[-1,0,0],\"count1\":2,\"spacing1\":\"L - 2*inset\",\"dir2\":[0,-1,0],\"count2\":2,\"spacing2\":\"W - 2*inset\",\"name\":\"Holes\"}}\n]}\n```\n\n**Expected volume:**\n- Plate: `L*W*T - 4*r²(1-π/4)*T`\n- Each hole: `π*1.7²*(T-3.3) + π*3.25²*3.3`\n- Total: 23335.2 mm³, with 22 faces.\n\nAfter `set_parameter L=120` the volume is 35335.2 mm³, and the holes stay in the corners.\n\n## Reading `measure`\n\n- **Tolerance:** analytic and measured volumes agree to about 0.001-0.01%, so treat a gap that small as a match. Long shallow arcs measure worse, about 0.1% (R 1000 mm over 20 degrees).\n- **Face counts:** compare the logical `faces`, not the larger `kernel.faces`.\n- **Reply types:** `set_parameter` returns `recomputed` as a number. A batch reply echoes every step.\n- **Boolean warning:** a feature `warning` such as `Boolean retry: temporary coincident-face separation up to 2.050000e0 mm per face` means the kernel nudged faces that coincide. A join flush on a face, such as a cylinder joined onto the floor of a shelled box, or a tapered cut that starts on a face, does not log it. When the volume still matches your number the warning is harmless. When it does not, the retry may have left the geometry wrong, with no error. A standoff built as a joined cylinder with a cut pilot hole, patterned together, reports `tool displacement` (moving a tool by about 2e-4 mm) but its volume agrees with the analytic growth; a boss with its hole as one ring profile (two concentric circles, extrude the ring) builds without a warning at every height tried (3 to 20 mm).\n\n## Reply cost (0.8, plate example)\n\n| Call | Size |\n|---|---|\n| `list_commands {}` | **Over 100 KB.** Never call it unfiltered; filter on a distinctive word such as `\"hole\"` or `\"slot\"`. |\n| `body_topology` | 25-45 KB |\n| `inspect_design {}` | 12 KB, and it grows with the sketches |\n| `inspect_design {\"measure\":false,\"sketches\":false}` | 4 KB for one part: parameters, timeline errors, bodies. About 65 B more per body (14 KB at 210 bodies) |\n| `sketch.inspect` | 5 KB per small sketch |\n| `parameters.list {\"filter\":\"feature\"}` | 3 KB |\n| `measure {}` | about 0.9 KB per body: volume, bbox, COM, face/edge/vertex counts. On a large design, `execute inspect.measure {\"bodies\":[...]}` measures only the listed bodies |\n| `sketch.solve` | under 100 B: dof, status, profile count |\n| `screenshot {\"source\":\"model\",\"width\":480,\"height\":320}` | one small image. Without `source`, a bridged server returns the whole app window and ignores the size. |\n\n## Errors\n\n| Error text | Fix |\n|---|---|\n| `... is not available right now: no sketch is being edited` | Run `sketch.create` or `sketch.edit {sketch}` first. |\n| `unknown sketch entity 'p1'` | Use the ids from `created`. A circle's centre is `c1.center`. |\n| `the corner must join exactly two lines` | It is a `rectangle.center` corner. Use the `{a, b}` form. |\n| `` `cs_diameter` must be a number or an expression `` | Countersinks need `cs_diameter` and `cs_angle`, even with `clearance`. |\n| `unsupported dimension role for this creator` | Check the roles table above. |\n| ` cannot be patterned or mirrored yet` | Pattern the original feature, for example one 2x2 rectangular pattern. |\n| `an edge is a point [x,y,z], {point} or {body, index}` | An edge pick contained an expression. Use plain numbers. |\n| `boolean Cut: the operation failed ... planar faces only` | See \"Primitive booleans\" above. |\n" + "SKILL.md": "---\nname: makecad-modeling\ndescription: Use when building a new part, enclosure, bracket, plate, flange or any other 3D solid in makeCAD through its MCP server (tools such as batch, execute, measure, screenshot), or when a makeCAD session is using many tool calls or tokens.\n---\n\n# makeCAD modeling\n\n## Overview\nWork the part out as numbers first. Then build it in a few large `batch` calls, and check each stage with `measure` against values you computed yourself. A clean build takes 3-4 build batches, about 10-13 calls with the checks. Command shapes, plane axes, ids, reply sizes and known traps are in `reference.md` next to this file, so you do not need to explore the command catalog.\n\n## Before the first call\n1. In makeCAD's own chat or any MCP client, call `skill_reference {\"skill\":\"makecad-modeling\",\"file\":\"reference.md\"}`. Elsewhere, read `reference.md`.\n2. Run `inspect_design {\"measure\":false,\"sketches\":false}`, even when you think the session is empty.\n - The makeCAD server's instructions end with `Backend: connected to the makeCAD app` when it drives the user's open app, and with `Backend: headless` otherwise.\n - If the design has timeline features, ask before calling `new_design` or `open`, because both discard unsaved work. You can also build into the open design.\n3. Write a plan:\n - the parameters\n - the placement: centre the part on the origin so patterns and mirrors can work from the planes\n - every feature, with the world point you will use for each edge or face pick\n - the expected volume and bounding box\n\n## Build\n- **Stages:** use one batch per stage:\n 1. parameters, sketch, dimensions, finish and the first feature\n 2. fillets and shell\n 3. holes, cuts and patterns\n- **Failures:** a batch is all-or-nothing. On failure, read `failed.index` and `failed.error`, fix that step only, and send the batch again.\n- **Risky steps:** put a risky step in a batch of its own, so a failure does not roll back the work around it. This covers booleans between curved faces that touch, and anything you have not done before.\n- **Reply size:** in large designs, pass `\"verbose\": false` to `batch` and `execute`.\n- **Sketch ids are predictable,** so later steps in the same batch can use them:\n - Each sketch counts each kind from 1 (`l1`, `c1`, `a1`, `p1`).\n - Count what the earlier steps of that sketch created. For example, `rectangle.center` makes `l1`-`l6` and `p1`-`p5`.\n - Do not split a batch just to read ids back.\n- **Positions that must follow a parameter** come from:\n - sketch dimensions to `\"origin\"` with expression values (`\"w/2 - wall - 6\"`)\n - expression fields such as `solid.cylinder base:[\"w/2-6\",\"d/2-6\",\"wall\"]`\n\n A plain number never follows a parameter.\n- **Repeats:** `solid.pattern.rectangular` takes expression spacing; `solid.mirror` takes `XY`/`XZ`/`YZ`, a construction plane or `{origin, normal}` (origin coordinates may be length expressions such as `[\"half\", 0, 0]`). A mirror or pattern feature cannot be mirrored or patterned again.\n- **Edge and face picks** snap to the nearest edge or face. An edge pick farther than 5% of the body's size from every edge is refused (`the nearest edge is 15.000 mm away`). On a large body that limit is wide (about 48 mm on a 949 mm board), so compute the exact midpoint from your geometry (the vertical corner edge of a centred box is `[w/2, d/2, h/2]`).\n - Picks must be plain numbers.\n - A pick is resolved once and then follows its edge when parameters change.\n - A face can be given by name instead of a point (`faces:[\"F1:+z\"]`, the `face` of `sheet.convert`). `body_topology` lists each face's `name`, a `point` that lies on it (the centroid of a face with a hole is in the hole) and, for a cylinder, `{origin, axis, radius}`.\n- **Profiles:** extrude takes every region by default, and a region inside another is a hole in it: two concentric circles give a ring. A third circle inside the ring gives a separate disc body. Pass `profiles` to choose regions.\n- **Order:** fillet the outside edges before you shell, so the shell follows the fillets. There are two exceptions:\n - An edge of the face the shell removes, such as the rim of an open box: round it after the shell, because the shell can fail on it.\n - A fillet between two curved faces, such as a sphere joined to a cylinder: the shell then fails with `offset: only bodies with planes, cylinders, cones, spheres and tori`. Shell first. The inside corner then stays sharp, so the wall there is thinner than `thickness`.\n\n## Verify\n- **Each stage:** run `measure {}` (about 0.9 KB per body; `{\"summary\":true}` keeps only name, volume, bbox, face count and `closed` per body) and compare the volume, bbox and face count with your numbers. A cut or hole that leaves the volume unchanged has missed, even though it reported success.\n- **Timeline health:** `inspect_design {\"measure\":false,\"sketches\":false}` shows each feature's `error` and `warning`.\n- **Parameter test:** run `set_parameter`. Expect `errors: []`, then `measure` again; the COM and bbox should move by the amounts you computed. To try values without keeping them, `check_parameters {\"set\": {\"L\": \"140 mm\"}}` reports the volume, errors and cylinder axes and puts the design back.\n- **Compare proposals:** call `inspect.parameter_variants` through `execute` with named sets of values when several parameters change together. Compare the baseline and each result's volume, mass and regressions before applying a choice. Every variant starts from the open design and leaves it unchanged.\n- **Positions:** `measure` does not say where a feature sits.\n - On an asymmetric part, check the COM shift you computed.\n - On a symmetric part (a mirrored or patterned layout) the COM does not move, so take a top-view screenshot and compare distances in pixels against a known size.\n - For holes and bosses, `body_topology {\"body\":\"Body1\",\"faces\":\"cylinders\"}`: one entry per cylinder (`radius`, `origin`, `axis`, `extent` along the axis, the merged faces' `names`), a few lines.\n - The full `body_topology` is a last resort: it costs 25-45 KB and splits cylinders into half faces.\n- **Final look:** one `screenshot {\"source\":\"model\",\"view\":\"iso\",\"width\":480,\"height\":320}`. Use `\"view\":\"top\"` for features inside walls, which the iso view hides.\n - `width` and `height` apply only to model renders.\n - When the server is bridged, `source` defaults to the whole app window and `view` also turns the user's camera, so pass `\"source\":\"model\"` and leave out `view` unless the user wants the camera moved.\n\n## Finish\n`export {path}` writes `.step` for CAD, `.3mf`/`.stl` for printing, or `.urdf` (an assembly with joints, for robot simulators). `save {path}` writes `.sc` (`.solidcraft` files from earlier releases still open).\n\n## Red flags\n\n| Thought | Do instead |\n|---|---|\n| \"List all commands first\" | `reference.md`, or `list_commands {\"filter\":\"\"}`. The unfiltered list is over 100 KB. |\n| \"Check positions with body_topology\" | `measure` COM and bbox against your numbers. |\n| \"Inspect the sketch\" | `sketch.solve` returns dof and the profile count in under 100 bytes. Run `sketch.inspect` on its own, never inside a big batch. |\n| \"new_design for a clean start\" | When the server is bridged, ask first. |\n| \"It reported ok, so it worked\" | Only a `measure` that matches the computed values counts. |\n", + "reference.md": "# makeCAD command reference for agents\n\nThese are the shapes of the commands a part build needs, so an agent rarely has to call `list_commands`. The worked example at the end runs in CI (`skill_reference_example_builds_as_documented` in `crates/mcp/src/tests.rs`).\n\n- Lengths are in mm.\n- Lengths take a unit suffix, in parameters and in feature fields: `\"16 in\"` is 406.4 mm, and `length:\"1 in\"` works in `solid.box`. `measure` still reports mm.\n- Angles inside expressions take units: `\"30 deg\"`.\n- Any numeric field can be an expression that names parameters: `\"w/2 - wall - 6\"`.\n\n## Sketch planes: where sketch (x, y) lands in the world\n\n| `plane` | sketch x | sketch y | normal (+distance) |\n|---|---|---|---|\n| `\"XY\"` | +X | +Y | +Z |\n| `\"XZ\"` | +X | **-Z** | +Y |\n| `\"YZ\"` | +Y | +Z | +X |\n| `{origin, x_dir, y_dir}` | x_dir | y_dir | x_dir x y_dir |\n\n- `offset: \"expr\"` on `sketch.create` moves the plane along its normal and follows parameters.\n- **Front wall (-Y) of a part centred on the origin:**\n - Sketch on `{\"plane\":\"XZ\",\"offset\":\"-d/2\"}`.\n - Draw a feature at height z at sketch y = **-z**.\n - A cut with a positive distance goes into the wall.\n- **Top face:** sketch on `{\"plane\":\"XY\",\"offset\":\"h\"}`.\n- **Hole direction:** `solid.hole {sketch}` drills into the part from the face nearest the sketch. A hole sketch at z=0, or below the part, drills up into the bottom face. Put the sketch on the face the hole starts from.\n\n## Ids\n\n- **Numbering:** every creator returns `created: {points, curves, constraints, dimensions}`. Ids are stable and numbered per sketch.\n- **Curves:** `l1`, `c1`, `a1`.\n- **Points:** `p1`, `l1.start`, `l1.end`, `c1.center`, `a1.center`, and the sketch origin `\"origin\"`.\n- **Rectangles:** `sketch.rectangle.*` also returns `sides {bottom,right,top,left}` and `corners {bottom_left,...}`.\n - `rectangle.center` adds 2 construction diagonals, so each corner joins 3 lines. Its centre point is `p5`.\n - `sketch.fillet {point}` therefore fails on its corners. Use `{a:\"l1\", b:\"l4\", radius}` or the 3D `solid.fillet`.\n- **Slots:** `sketch.slot.overall` and `sketch.slot.center_to_center` create 2 lines, 2 arcs and 4 points, plus `a1.center` and `a2.center`. The ids count on from what the sketch already has: in an empty sketch `l1, a1, l2, a2` and `p1`-`p4`, after a `rectangle.two_point` `l5, a1, l6, a2` and `p5`-`p8`.\n - The `length` role of `slot.overall` is the overall length. The arc centres are at ±(length/2 - width/2).\n - After `length` and `width`, 3 dof remain. To remove them, dimension `origin` to `a1.center` horizontally and vertically, and `origin` to `a2.center` vertically. For a slot along Y the solver refuses that last dimension as over-constraining; dimension `a2.center` horizontally instead.\n - `sketch.slot.center_point` creates no centre point. Dimension an arc centre instead.\n- **Circles:** `sketch.circle.center` creates `c1` and `c1.center`, and no `p` point.\n- **Dimensions** share the `k` counter with constraints.\n- **Constraints can add curves:** a constraint about an axis, such as `sketch.constraint.symmetry` with `line:\"y\"`, adds a construction line and so takes the next `l` id. Read `created` before you count further.\n- **Over-constraining** is refused with `that conflicts with the sketch: neither entity can move to satisfy it`. For example, symmetry already makes two circles equal.\n\n## Dimensions\n\n```json\n{\"command\":\"sketch.dimension\",\"params\":{\"entities\":[\"origin\",\"c1.center\"],\"type\":\"horizontal\",\"value\":\"w/2 - wall - 6\"}}\n{\"command\":\"sketch.dimension\",\"params\":{\"entities\":[\"c1\"],\"type\":\"diameter\",\"value\":\"6\"}}\n{\"command\":\"sketch.dimension\",\"params\":{\"entities\":[\"l1\"],\"value\":\"w\"}}\n{\"command\":\"sketch.dimension\",\"params\":{\"entities\":[\"l1\",\"c1\"],\"value\":\"2\"}}\n{\"command\":\"sketch.dimension\",\"params\":{\"entities\":[\"c1\",\"c2\"],\"value\":\"3\"}}\n```\n\nA line, a point or another circle with a circle or arc measures to its edge (0 is tangent, or the point on the circle); two circles measure between their edges (the overlap when they cross, the thinnest wall when one is inside the other). Give the centre point (`c1.center`) for the distance to the centre.\n\nDistances are unsigned. Draw the geometry on the correct side first, and the dimension keeps it there.\n\n`sketch.draw.dimensioned` creates a shape and its dimensions in one undo step. The dimension roles depend on the creator:\n\n| Creator | Roles |\n|---|---|\n| `line` (exactly 2 points) | `length`, `angle` |\n| `rectangle.*` | `width`, `height` |\n| `circle.*` | `radius` or `diameter` |\n| `arc.center_point` | `radius`, `sweep` |\n| `slot.center_to_center`, `slot.overall` | `length`, `width` |\n| `polygon.*` | `radius` |\n\n```json\n{\"command\":\"sketch.draw.dimensioned\",\"params\":{\"command\":\"sketch.rectangle.center\",\"params\":{\"center\":[0,0],\"corner\":[35,25]},\"dimensions\":{\"width\":\"w\",\"height\":\"d\"}}}\n```\n\n## Features\n\n| Command | Minimal params | Traps |\n|---|---|---|\n| `solid.extrude` | `distance` | `profiles` defaults to **every region**, with a region inside another as a hole in it: two concentric circles give a ring. Pick regions with `[{\"point\":[x,y]}]` or `[index]`. Other options: `operation` (new/join/cut/intersect/auto), `direction` (positive/negative/symmetric), `through_all: true`, `start_offset`. A cut that misses reports success. |\n| `solid.box` | `length`, `width`, `height` | `center:[x,y,z]` or `corner`. The quickest way to block out a part. `body_name` names the body it makes. With `operation:\"cut\"`, `targets:[\"Top\"]` cuts only the bodies listed, so the cutter can pass through other bodies. |\n| `solid.cylinder` | `radius` or `diameter`, `height` | `base` is the centre of the bottom (default origin), `axis` defaults to `Z`. Expressions work in `base`. To tie a cylinder standing on a flat face to the part, give `base` as numbers on that face and add `references: [{edge:[x,y,z], distance}]` (up to two straight edges of the face, as for `solid.hole`): the base centre then sits at those distances from the edges and follows them. Always pass `operation`. `body_name` and `targets` work as for `solid.box`. |\n| `sketch.slot.overall` / `sketch.slot.center_to_center` | `p0`, `p1` (overall ends / arc centres), `width` | Ids and dof are in the \"Ids\" section above. |\n| `solid.fillet` / `solid.chamfer` | `edges:[[x,y,z]]`, `radius` / `distance` | The pick snaps to the **nearest** edge. A pick farther than 5% of the body's size from every edge is refused, so check that the face count changed. A pick where two bodies have an edge, shown or hidden (parts touching, the halves of a split), is refused naming both: give `body`. One pick takes the whole tangent chain: a rounded rim needs 1 point, not 8. |\n| `solid.shell` | `faces:[[x,y,z]]`, `thickness` | A point on each face to remove, or its name from `body_topology`. Fillet first, except an edge of a removed face or a fillet between curved faces (see Order in `SKILL.md`). Bodies with lofted or swept faces are refused (`offset: only bodies with planes, cylinders, cones, spheres and tori`): hollow a loft with a smaller loft and `operation: cut`. |\n| `solid.hole` | `position:[x,y,z]` on a face (numbers or length expressions such as `[\"40\", \"width/2\", \"t\"]`, which the hole then follows) + `diameter`, or `sketch` (+ `points`) | `clearance:\"M3\"`. `depth` defaults to through all. `type` is one of simple/drilled/counterbore/countersink. A `countersink` needs `cs_diameter` and `cs_angle`; a `counterbore` needs `cb_diameter` and `cb_depth`, or `head:\"ISO 4762\"` (socket head) / `\"ISO 7380-1\"` (button head) with `clearance`: the recess is then the head's diameter plus `head_gap` (default 0.5 mm) each side, and the head's height plus `head_gap` deep. `position` is a fixed point; to tie it to the part, add `references: [{edge:[x,y,z], distance}]` (up to two straight edges of the face): the centre then sits at those distances from the edges and follows them. |\n| `solid.pattern.rectangular` | `features`, `dir1`, `count1`, `spacing1` (+ `dir2`, `count2`, `spacing2`) | Spacing takes expressions and follows parameters. |\n| `solid.pattern.circular` | `features`, `axis` (`\"Z\"`, `{origin, dir}` whose origin may be length expressions the pattern follows, or `{face: [x,y,z]}` / `{edge: [x,y,z]}` on a cylinder wall or circular edge, which the pattern follows), `count` | `angle` defaults to 360 deg. A full pattern keeps the COM on the axis, so check its radius with a top-view screenshot. |\n| `solid.mirror` | `features:[names]` or `bodies:[names]`, `plane` (`XY`/`XZ`/`YZ`, a construction plane, or `{origin, normal}` whose origin may use length expressions) | Follows parameters. A mirror or pattern feature cannot be listed in `features` of another mirror or pattern, but `bodies` can mirror the body it made. The mirror is a new body with the first free default name: `Body1`, `Body2` from `features`, and `Side (2)`, `Side (3)` from `bodies:[\"Side\"]`. Read the name from `created_bodies`. With `combine:true`, a mirror that overlaps the original joins it and makes no new body. `features` copies only the features listed, so a later cut is left out unless you list it too. `bodies` copies the finished body. To name the mirror, use `body.rename {\"body\":\"Side (2)\",\"name\":\"Side_L\"}`. The new name stays when parameters change. |\n\n- **Names:** name every feature (`\"name\":\"Standoff\"`) and keep names unique across sketches and features. `timeline.roll_to {\"feature\":\"Plate\"}` picks the first match, which can be the sketch.\n- **Counts as parameters:** `parameters.add {\"name\":\"n\",\"expression\":\"6\",\"unit\":\"\"}` creates a unitless parameter, and `\"count\":\"n\"` uses it in a pattern.\n- **Names of pattern and mirror copies:** `solid.pattern.rectangular` and `solid.pattern.circular` take `bodies` as well as `features`, and name copies like `solid.mirror` does. `solid.pattern.circular {\"bodies\":[\"Groove end\"],\"axis\":\"Z\",\"count\":3}` keeps the original and makes the copies `Groove end (2)` and `Groove end (3)`. A name already taken is skipped: with `Groove end (2)` present, the copies are `Groove end (3)` and `Groove end (4)`. With `features`, the pattern makes a new `BodyN`, as in the `solid.mirror` row. Read the names from `created_bodies`. Mirroring a copy adds a suffix: `Groove end (2)` mirrored is `Groove end (2) (2)`. The pattern commands list no body-name parameter, so use `body.rename` for stable names. `body.rename {\"bodies\":[\"A\",\"B\",\"C\"],\"name\":\"Peg\"}` renames several bodies in one step, numbered the same way: `Peg`, `Peg (2)`, `Peg (3)`, skipping a name already taken. There is no way yet to refer to every copy at once, for example in `solid.combine` (#8194).\n- **Holes on a parametric bolt circle:**\n 1. Cut one hole with `solid.cylinder {\"diameter\":6.6,\"height\":\"T + 2\",\"base\":[\"bcd/2\",0,-1],\"operation\":\"cut\",\"name\":\"BoltHole\"}`.\n 2. Repeat it with `solid.pattern.circular {\"features\":[\"BoltHole\"],\"axis\":\"Z\",\"count\":\"n\"}`.\n\n Both the radius and the count follow their parameters.\n- **Parameter changes:** for one change, call `set_parameter {\"name\":\"L\",\"value\":\"120 mm\"}`. For several, use one `batch` of `parameters.change` steps instead of one `set_parameter` call each.\n- **Primitive booleans:** a `solid.box` or `solid.cylinder` cut that touches curved faces of the target can fail with `the exact fallback ... takes planar faces only`. Use a sketch profile and an extrude cut instead, for example a slot sketch rather than a box plus 2 cylinders.\n\n## Worked example: parametric plate with 4 counterbored holes (1 batch)\n\n```json\n{\"commands\":[\n {\"command\":\"parameters.add\",\"params\":{\"name\":\"L\",\"expression\":\"80 mm\"}},\n {\"command\":\"parameters.add\",\"params\":{\"name\":\"W\",\"expression\":\"50 mm\"}},\n {\"command\":\"parameters.add\",\"params\":{\"name\":\"T\",\"expression\":\"6 mm\"}},\n {\"command\":\"parameters.add\",\"params\":{\"name\":\"inset\",\"expression\":\"8 mm\"}},\n {\"command\":\"sketch.create\",\"params\":{\"plane\":\"XY\",\"name\":\"PlateSketch\"}},\n {\"command\":\"sketch.draw.dimensioned\",\"params\":{\"command\":\"sketch.rectangle.center\",\"params\":{\"center\":[0,0],\"corner\":[40,25]},\"dimensions\":{\"width\":\"L\",\"height\":\"W\"}}},\n {\"command\":\"sketch.finish\",\"params\":{}},\n {\"command\":\"solid.extrude\",\"params\":{\"distance\":\"T\",\"name\":\"Plate\"}},\n {\"command\":\"solid.fillet\",\"params\":{\"edges\":[[40,25,3],[-40,25,3],[40,-25,3],[-40,-25,3]],\"radius\":5,\"name\":\"Corners\"}},\n {\"command\":\"sketch.create\",\"params\":{\"plane\":\"XY\",\"name\":\"HolePts\",\"offset\":\"T\"}},\n {\"command\":\"sketch.point\",\"params\":{\"point\":[32,17]}},\n {\"command\":\"sketch.dimension\",\"params\":{\"entities\":[\"origin\",\"p1\"],\"type\":\"horizontal\",\"value\":\"L/2 - inset\"}},\n {\"command\":\"sketch.dimension\",\"params\":{\"entities\":[\"origin\",\"p1\"],\"type\":\"vertical\",\"value\":\"W/2 - inset\"}},\n {\"command\":\"sketch.finish\",\"params\":{}},\n {\"command\":\"solid.hole\",\"params\":{\"sketch\":\"HolePts\",\"diameter\":3.4,\"type\":\"counterbore\",\"cb_diameter\":6.5,\"cb_depth\":3.3,\"name\":\"Hole\"}},\n {\"command\":\"solid.pattern.rectangular\",\"params\":{\"features\":[\"Hole\"],\"dir1\":[-1,0,0],\"count1\":2,\"spacing1\":\"L - 2*inset\",\"dir2\":[0,-1,0],\"count2\":2,\"spacing2\":\"W - 2*inset\",\"name\":\"Holes\"}}\n]}\n```\n\n**Expected volume:**\n- Plate: `L*W*T - 4*r²(1-π/4)*T`\n- Each hole: `π*1.7²*(T-3.3) + π*3.25²*3.3`\n- Total: 23335.2 mm³, with 22 faces.\n\nAfter `set_parameter L=120` the volume is 35335.2 mm³, and the holes stay in the corners.\n\n## Reading `measure`\n\n- **Tolerance:** analytic and measured volumes agree to about 0.001-0.01%, so treat a gap that small as a match. Long shallow arcs measure worse, about 0.1% (R 1000 mm over 20 degrees).\n- **Face counts:** compare the logical `faces`, not the larger `kernel.faces`.\n- **Reply types:** `set_parameter` returns `recomputed` as a number. A batch reply echoes every step.\n- **Boolean warning:** a feature `warning` such as `Boolean retry: temporary coincident-face separation up to 2.050000e0 mm per face` means the kernel nudged faces that coincide. A join flush on a face, such as a cylinder joined onto the floor of a shelled box, or a tapered cut that starts on a face, does not log it. When the volume still matches your number the warning is harmless. When it does not, the retry may have left the geometry wrong, with no error. A standoff built as a joined cylinder with a cut pilot hole, patterned together, reports `tool displacement` (moving a tool by about 2e-4 mm) but its volume agrees with the analytic growth; a boss with its hole as one ring profile (two concentric circles, extrude the ring) builds without a warning at every height tried (3 to 20 mm).\n\n## Reply cost (0.8, plate example)\n\n| Call | Size |\n|---|---|\n| `list_commands {}` | **Over 100 KB.** Never call it unfiltered; filter on a distinctive word such as `\"hole\"` or `\"slot\"`. |\n| `body_topology` | 25-45 KB |\n| `inspect_design {}` | 12 KB, and it grows with the sketches |\n| `inspect_design {\"measure\":false,\"sketches\":false}` | 4 KB for one part: parameters, timeline errors, bodies. About 65 B more per body (14 KB at 210 bodies) |\n| `sketch.inspect` | 5 KB per small sketch |\n| `parameters.list {\"filter\":\"feature\"}` | 3 KB |\n| `measure {}` | about 0.9 KB per body: volume, bbox, COM, face/edge/vertex counts. On a large design, `execute inspect.measure {\"bodies\":[...]}` measures only the listed bodies |\n| `sketch.solve` | under 100 B: dof, status, profile count |\n| `screenshot {\"source\":\"model\",\"width\":480,\"height\":320}` | one small image. Without `source`, a bridged server returns the whole app window and ignores the size. |\n\n## Errors\n\n| Error text | Fix |\n|---|---|\n| `... is not available right now: no sketch is being edited` | Run `sketch.create` or `sketch.edit {sketch}` first. |\n| `unknown sketch entity 'p1'` | Use the ids from `created`. A circle's centre is `c1.center`. |\n| `the corner must join exactly two lines` | It is a `rectangle.center` corner. Use the `{a, b}` form. |\n| `` `cs_diameter` must be a number or an expression `` | Countersinks need `cs_diameter` and `cs_angle`, even with `clearance`. |\n| `unsupported dimension role for this creator` | Check the roles table above. |\n| ` cannot be patterned or mirrored yet` | Pattern the original feature, for example one 2x2 rectangular pattern. |\n| `an edge is a point [x,y,z], {point} or {body, index}` | An edge pick contained an expression. Use plain numbers. |\n| `boolean Cut: the operation failed ... planar faces only` | See \"Primitive booleans\" above. |\n" } }, { "name": "makecad-packaging", "description": "Use when preparing or shipping a makeCAD release, changing installers or packages (AppImage, MSI, dmg, Flatpak, Snap, WinGet, Nix, FreeBSD, web), release asset names, signing or the Pages deployment.", "files": { - "SKILL.md": "---\nname: makecad-packaging\ndescription: \"Use when preparing or shipping a makeCAD release, changing installers or packages (AppImage, MSI, dmg, Flatpak, Snap, WinGet, Nix, FreeBSD, web), release asset names, signing or the Pages deployment.\"\n---\n\n# Packaging and releases\n\nDevelopment pushes are not application releases. Pushing to `main` or pushing a tag does not start a release. The full procedure is `docs/releasing.md`; follow it when asked to prepare or ship a release.\n\n## Preparing\n1. Choose one version for the whole batch from the actual changes (patch, minor, major, `-rc.N`). Do not infer it from commit prefixes. Moving to `1.0` is the owner's decision.\n2. Update `[workspace.package] version` in `Cargo.toml`, then `cargo update --workspace --offline`; only our own crates' `version =` lines in `Cargo.lock` change.\n3. Fold the pending design-format changes with `scripts/fold-format-pending.sh` (`skills/makecad-file-formats/SKILL.md`).\n4. Run `cargo xtask ci` and the packaging checks in `.github/workflows/packaging-lint.yml`. Land the version commit on `main` through the normal review flow; never use `[skip ci]`.\n\n## Building and publishing\n- Advance the `release` branch with fast-forwards only (`git merge --ff-only`); never force-push. `.github/workflows/release.yml` builds every package and creates a draft GitHub Release.\n- Verify the draft before publishing: the run succeeded for the intended SHA, every platform and architecture is present, `sha256sum --check SHA256SUMS.txt` passes, and the built CLI runs (`--version`, an example model).\n- Only when shipping is authorised, publish the verified draft with `gh release edit`, then confirm its tag resolves to the recorded SHA and the downstream deployment ran. A request to prepare a release is not a request to publish.\n- Never overwrite a published version, tag or asset; use a new version. Do not push the version tag yourself. Packages are unsigned unless `docs/releasing.md` says otherwise; do not claim they are signed.\n- Nightlies are prereleases built by the same workflow; they never become latest or advance `release`.\n\n## Names that must stay stable\n- Assets are `solidcraft--...` and are also attached without the version (`solidcraft-windows-x64.msi`). The README links and the in-app update check (`crates/ui-egui/src/update.rs`) pick them by name; renaming one breaks both.\n- The old product name survives only in the shims in `docs/compatibility.md`. Do not rewrite published assets, checksums, tags or historical notes.\n- Documentation, the browser app and the Flatpak repository publish under project Pages `/solidcraft/`. Add no old-name Pages aliases.\n\n## Where things live\n- `packaging/` holds the per-platform scripts (`packaging/linux`, `packaging/windows`, `packaging/macos`, `packaging/freebsd`, `packaging/web`); `packaging/tests` checks them.\n- Nix: `flake.nix` and `docs/nix.md`. Building: `docs/building.md`. Downloads: `docs/downloads.md`.\n- Build with `CARGO_TARGET_DIR=/target`. Windows from Linux: `cargo xwin build --release --target x86_64-pc-windows-msvc -p solidcraft`.\n" + "SKILL.md": "---\nname: makecad-packaging\ndescription: \"Use when preparing or shipping a makeCAD release, changing installers or packages (AppImage, MSI, dmg, Flatpak, Snap, WinGet, Nix, FreeBSD, web), release asset names, signing or the Pages deployment.\"\n---\n\n# Packaging and releases\n\nDevelopment pushes are not application releases. Pushing to `main` or pushing a tag does not start a release. The full procedure is `docs/releasing.md`; follow it when asked to prepare or ship a release.\n\n## Preparing\n1. Choose one version for the whole batch from the actual changes (patch, minor, major, `-rc.N`). Do not infer it from commit prefixes. Moving to `1.0` is the owner's decision.\n2. Update `[workspace.package] version` in `Cargo.toml`, then `cargo update --workspace --offline`; only our own crates' `version =` lines in `Cargo.lock` change.\n3. Fold the pending design-format changes with `scripts/fold-format-pending.sh` (`skills/makecad-file-formats/SKILL.md`).\n4. Run `cargo xtask ci` and the packaging checks in `.github/workflows/packaging-lint.yml`. Land the version commit on `main` through the normal review flow; never use `[skip ci]`.\n\n## Building and publishing\n- Advance the `release` branch with fast-forwards only (`git merge --ff-only`); never force-push. `.github/workflows/release.yml` builds every package and creates a draft GitHub Release.\n- Verify the draft before publishing: the run succeeded for the intended SHA, every platform and architecture is present, `sha256sum --check SHA256SUMS.txt` passes, and the built CLI runs (`--version`, an example model).\n- Only when shipping is authorised, publish the verified draft with `gh release edit`, then confirm its tag resolves to the recorded SHA and the downstream deployment ran. A request to prepare a release is not a request to publish.\n- Never overwrite a published version, tag or asset; use a new version. Do not push the version tag yourself. Packages are unsigned unless `docs/releasing.md` says otherwise; do not claim they are signed.\n- Nightlies are prereleases built by the same workflow; they never become latest or advance `release`.\n\n## Names that must stay stable\n- Assets are `solidcraft--...` and are also attached without the version (`solidcraft-windows-x64.msi`). The README links and the in-app update check (`crates/ui-egui/src/update.rs`) pick them by name; renaming one breaks both.\n- The old product name survives only in the shims in `docs/compatibility.md`. Do not rewrite published assets, checksums, tags or historical notes.\n- Documentation, the browser app and the Flatpak repository publish under project Pages `/solidcraft/`. Add no old-name Pages aliases.\n\n## Where things live\n- `packaging/` holds the per-platform scripts (`packaging/linux`, `packaging/windows`, `packaging/macos`, `packaging/freebsd`, `packaging/web`); `packaging/tests` checks them.\n- Nix: `flake.nix` and `docs/nix.md`. Building: `docs/building.md`. Downloads: `docs/downloads.md`.\n- Build with `CARGO_TARGET_DIR=/target`. Windows from Linux: `cargo xwin build --release --target x86_64-pc-windows-msvc -p solidcraft`.\n\n## No integrations with other platforms\n\nDon't build someone's platform or service into makeCAD (their cloud, sync, hosting, WebDAV, accounts, embedding the app elsewhere, host-page file bridges) without the maintainer's yes first; unasked PRs are closed. Flatpak, Snap, winget, Homebrew, AUR, OS keyrings and file dialogs are fine. The only official external host is the ArtCraft launcher, which downloads our release binaries.\n" } }, { "name": "makecad-performance", "description": "Use when a makeCAD change is slow, blocks the window, runs long work, or must build for the browser. Covers keeping the window thread free, measuring a speed-up, the wasm build and what may be JavaScript or Python.", "files": { - "SKILL.md": "---\nname: makecad-performance\ndescription: \"Use when a makeCAD change is slow, blocks the window, runs long work, or must build for the browser. Covers keeping the window thread free, measuring a speed-up, the wasm build and what may be JavaScript or Python.\"\n---\n\n# Performance, threads and wasm\n\n## Do not block the window\n- Work that can take long (a feature computation, a save, a file load, reading a picture) runs beside the window and is applied when done. Existing examples: `crates/ui-egui/src/save_job.rs`, `crates/ui-egui/src/file_load.rs`, and the agent path in `docs/control-protocol.md` (\"Slow commands and the window\").\n- With the preference \"Keep the window responsive while agents run commands\" (`agent_off_thread`) on, a design change that takes longer than about 150 ms is evaluated ahead on a copy of the design, then run for real reusing that result. A person's edit made meanwhile goes first; Stop drops the computation and nothing is applied. Keep that contract when you add a long-running command.\n- `file.export` and `file.save_mesh` change nothing in the design: they run on a copy and nothing waits behind them.\n- Test it: `crates/ui-egui/src/apply_off_thread_tests.rs` drives a long feature through the harness; never depend on wall-clock timing in a test.\n\n## Measure before you claim a speed-up\n- Profile first. Time with `solidcraft-cli` from `main` and from your branch, alternating runs, after the load is low. On a shared machine check `cut -d' ' -f1 /proc/loadavg` and wait while it is over 24; build with `nice`.\n- Report medians with the range, the machine, and the cases. The pattern to follow is `docs/perf.md`: what was slow, why, the result, and proof that nothing changed (same bodies, volumes, areas and triangle counts).\n- A speed-up never skips work on a mesh's box: decide with the exact bounds (`Body::exact_bounds`, grown by the record's tolerance as `apart` in `crates/kernel/src/ops.rs` does). A mesh is for display, export, previews and mesh bodies.\n- Do not rewrite kernel code for speed: the kernel is being replaced, and kernel work is paused. Report a slow case with its file under the `kernel-perf` label (CONTRIBUTING.md, \"Where help is wanted most\").\n- Pull requests run only the tests for what they touch; geometry-heavy tests run in the merge queue. Use `cargo xtask test` with the `ci` profile locally (`skills/makecad-tests/SKILL.md`).\n\n## The browser build\n- Everything below the apps must build for `wasm32-unknown-unknown`: `cargo xtask wasm` checks every library crate and the web app, and is part of `cargo xtask ci`. Do not add a dependency that cannot.\n- Application code is Rust only. The browser requires two pieces of JavaScript: the service worker `apps/solidcraft-web/sw.js` and the small inline scripts in `apps/solidcraft-web/index.html`. Keep them minimal; `cargo xtask web-offline-test` covers the service worker.\n- Python 3.11+ is allowed only for asset authoring, lint and review tools (`assets/AGENTS.md`), never as an application dependency.\n- Design notes for the browser runtime: `docs/web-runtime.md`, `docs/browser-api.md`.\n" + "SKILL.md": "---\nname: makecad-performance\ndescription: \"Use when a makeCAD change is slow, blocks the window, runs long work, or must build for the browser. Covers keeping the window thread free, measuring a speed-up, the wasm build and what may be JavaScript or Python.\"\n---\n\n# Performance, threads and wasm\n\n## Do not block the window\n- Work that can take long (a feature computation, a save, a file load, reading a picture) runs beside the window and is applied when done. Existing examples: `crates/ui-egui/src/save_job.rs`, `crates/ui-egui/src/file_load.rs`, and the agent path in `docs/control-protocol.md` (\"Slow commands and the window\").\n- With the preference \"Keep the window responsive while agents run commands\" (`agent_off_thread`) on, a design change that takes longer than about 150 ms is evaluated ahead on a copy of the design, then run for real reusing that result. A person's edit made meanwhile goes first; Stop drops the computation and nothing is applied. Keep that contract when you add a long-running command.\n- `file.export` and `file.save_mesh` change nothing in the design: they run on a copy and nothing waits behind them.\n- Test it: `crates/ui-egui/src/apply_off_thread_tests.rs` drives a long feature through the harness; never depend on wall-clock timing in a test.\n\n## Measure before you claim a speed-up\n- Profile first. Time with `solidcraft-cli` from `main` and from your branch, alternating runs, after the load is low. On a shared machine check `cut -d' ' -f1 /proc/loadavg` and wait while it is over 24; build with `nice`.\n- Report medians with the range, the machine, and the cases. The pattern to follow is `docs/perf.md`: what was slow, why, the result, and proof that nothing changed (same bodies, volumes, areas and triangle counts).\n- A speed-up never skips work on a mesh's box: decide with the exact bounds (`Body::exact_bounds`, grown by the record's tolerance as `apart` in `crates/kernel/src/ops.rs` does). A mesh is for display, export, previews and mesh bodies.\n- A speed-up of kernel code goes in `solidcore/` with its root cause, per `solidcore/AGENTS.md`; do not grow `crates/kernel`. Report a slow case with its file under the `kernel-perf` label (CONTRIBUTING.md, \"Where help is wanted most\").\n- Pull requests run only the tests for what they touch; geometry-heavy tests run in the merge queue. Use `cargo xtask test` with the `ci` profile locally (`skills/makecad-tests/SKILL.md`).\n\n## The browser build\n- Everything below the apps must build for `wasm32-unknown-unknown`: `cargo xtask wasm` checks every library crate and the web app, and is part of `cargo xtask ci`. Do not add a dependency that cannot.\n- Application code is Rust only. The browser requires two pieces of JavaScript: the service worker `apps/solidcraft-web/sw.js` and the small inline scripts in `apps/solidcraft-web/index.html`. Keep them minimal; `cargo xtask web-offline-test` covers the service worker.\n- Python 3.11+ is allowed only for asset authoring, lint and review tools (`assets/AGENTS.md`), never as an application dependency.\n- Design notes for the browser runtime: `docs/browser-api.md`.\n" } }, { "name": "makecad-preferences", "description": "Use when a makeCAD change alters a default behaviour, an existing shortcut or the look users already have, or adds a setting in Preferences. Covers keeping the old behaviour behind a preference and the PR's 'Changes a default' line.", "files": { - "SKILL.md": "---\nname: makecad-preferences\ndescription: \"Use when a makeCAD change alters a default behaviour, an existing shortcut or the look users already have, or adds a setting in Preferences. Covers keeping the old behaviour behind a preference and the PR's 'Changes a default' line.\"\n---\n\n# Preferences and defaults\n\nPeople rely on how makeCAD behaves today. A change that makes users see or do something different out of the box is a change of a default.\n\n## The rule\n- Keep the old behaviour reachable. Add a preference whose old value gives the old behaviour, and test that it still does.\n- Fill in the PR template's `Changes a default:` line (`pr-checks.yml` fails a PR description without it, #6442; CONTRIBUTING.md, \"Sending a change\"):\n - `Changes a default: no`\n - `Changes a default: yes - , old behaviour kept behind preference `\n\n## Adding a preference\nSettings live in the `preference_settings!` table in `crates/ui-egui/src/prefs.rs`: the field, its default, the page whose reset restores it, an optional accepted range for the control channel, and the form control. Add one row there.\n- A new setting that changes nothing by default needs no `yes` on the line; one that changes what users see by default does.\n- Give it a label and help text through the catalogs (`skills/makecad-ui-text/SKILL.md`).\n- A reset on its page restores the default; fields left out of every page keep their values when defaults are restored.\n- Control channel: `ui.prefs {...}` reads and sets preferences by name (`docs/control-protocol.md`).\n- Test it in a UI scenario or a `*_tests.rs` file next to the setting (`skills/makecad-tests/SKILL.md`).\n\n## What counts as a default\nAnything a user sees or does differently on first launch after the update: a changed shortcut, camera or navigation behaviour, unit, naming, theme or autosave behaviour, or a tool that appears unasked. A fix that makes the app do what it already claimed is not a default change; say so on the line.\n" + "SKILL.md": "---\nname: makecad-preferences\ndescription: \"Use when a makeCAD change alters a default behaviour, an existing shortcut or the look users already have, or adds a setting in Preferences. Covers keeping the old behaviour behind a preference and the PR's 'Changes a default' line.\"\n---\n\n# Preferences and defaults\n\nPeople rely on how makeCAD behaves today. A change that makes users see or do something different out of the box is a change of a default.\n\n## The rule\n- Keep the old behaviour reachable. Add a preference whose old value gives the old behaviour, and test that it still does.\n- Fill in the PR template's `Changes a default:` line (`pr-checks.yml` fails a PR description without it, #6442; CONTRIBUTING.md, \"Sending a change\"):\n - `Changes a default: no`\n - `Changes a default: yes - , old behaviour kept behind preference `\n\n## Adding a preference\nSettings live in the `preference_settings!` table in `crates/ui-egui/src/prefs.rs`: the field, its default, the page whose reset restores it, an optional accepted range for the control channel, and the form control. Add one row there.\n- A new setting that changes nothing by default needs no `yes` on the line; one that changes what users see by default does.\n- Give it a label and help text through the catalogs (`skills/makecad-ui-text/SKILL.md`).\n- A reset on its page restores the default; fields left out of every page keep their values when defaults are restored.\n- Control channel: `ui.prefs {...}` reads and sets preferences by name (`docs/control-protocol.md`).\n- Test it in a UI scenario or a `*_tests.rs` file next to the setting (`skills/makecad-tests/SKILL.md`).\n\n## What counts as a default\nAnything a user sees or does differently on first launch after the update: a changed shortcut, camera or navigation behaviour, unit, naming, theme or autosave behaviour, or a tool that appears unasked. A changed default is when something people already rely on in the UI changes for everyone who didn't opt in: an existing control, interaction or setting value. Not defaults: bug fixes and more correct results, kernel or geometry result changes (write `Changes a default: no`), new options that are off by default, and CI or tooling config. A fix that makes the app do what it already claimed is not a default change; say so on the line.\n" } }, { @@ -112,27 +119,35 @@ "reference/report-template.md": "# Report template\n\nFill in every section and delete the hints in angle brackets. Keep it short: the script and the numbers say most of it.\n\n````markdown\n**Reproduced on:** makeCAD (), , \n>\n\n### Steps\n1. \n2. <…>\n3. \n\nMinimal script (`solidcraft-cli run repro.json`):\n\n```json\n{\"commands\":[\n \n]}\n```\n\n### Expected\n\n\n### Actual\n\n\n```text\n\n```\n\n\n\n### Attachments\n\n````\n\n## Example\n\nThe shape filled in, for a command that fails with an error. (This one is expected behaviour; a real report would be one where Actual differs from Expected.)\n\n````markdown\n**Reproduced on:** makeCAD 0.18.2 (release), Linux x86_64\n\n### Steps\n1. Box, 20 × 20 × 10 mm, corner at the origin.\n2. Fillet the top front edge, radius 12 mm.\n\nMinimal script (`solidcraft-cli run repro.json`):\n\n```json\n{\"commands\":[\n {\"command\":\"solid.box\",\"params\":{\"length\":20,\"width\":20,\"height\":10}},\n {\"command\":\"solid.fillet\",\"params\":{\"edges\":[[10,0,10]],\"radius\":12}}\n]}\n```\n\n### Expected\nThe fillet fails and names the largest radius that fits: 10 mm, the box's height.\n\n### Actual\n```text\nerror: step 2 (solid.fillet): not supported yet: the blend is larger than the neighbouring faces; the largest radius that fits is 10 mm\n```\nEvery time. Radius 2 works: volume 3982.8 mm³, as computed by hand (4000 − 20 × 2² × (1 − π/4)).\n````\n" } }, + { + "name": "makecad-sheetmetal", + "description": "Use when building or changing a sheet metal part in makeCAD through its MCP server (flange, segments, hem, fold, unfold, flat pattern, DXF, bend table), or when a request describes bends in words.", + "files": { + "SKILL.md": "---\nname: makecad-sheetmetal\ndescription: Use when building or changing a sheet metal part in makeCAD through its MCP server (flange, segments, hem, fold, unfold, flat pattern, DXF, bend table), or when a request describes bends in words.\n---\n\n# makeCAD sheet metal\n\n## Overview\nA sheet metal part is a flat sheet plus bends: base first, then flanges. Work the numbers first (rule, flat size, stock, angles, heights, segment boundaries), build in `batch` calls, then check with `measure`, `sheet.flat_pattern` and `sheet.export_bend_table`. Contract, bend arithmetic, recipes: `reference.md`.\n\n`segments` needs `feat/sheet-flange-segments`; `unfold_method` needs #9911.\n\n## Before the call\n1. `skill_reference {\"skill\":\"makecad-sheetmetal\",\"file\":\"reference.md\"}`; elsewhere read `reference.md`.\n2. `inspect_design {\"measure\":false,\"sketches\":false}`; with timeline features, ask before `new_design` or `open`.\n3. `sheet.rules` gives thickness, K-factor, radius, reliefs, gap. A flange takes none of them; `sheet.manage_rules` first when no rule fits.\n4. Plan the flat size, bend fractions, flat area times thickness (the volume you check) and the stock.\n\n## Build\n- **Rule:** `sheet.manage_rules {\"name\":\"AL2\",\"thickness\":\"2 mm\",\"k_factor\":0.5,\"bend_radius\":\"1 mm\",\"active\":true}`. Ask the shop for the K-factor; never invent it.\n- **Base:** a closed sketch profile, then `sheet.flange {\"sketch\":\"Base\"}`.\n- **Edge:** `sheet.flange {\"type\":\"edge\",\"edges\":[...],\"height\":...,\"angle\":...}`; `{point, angle, height, segments}` gives one edge its own values.\n- **Segments:** stretches `{from, to}` tiling the stretch the sheet still has, each a bend with its own angle, height and side; opposite sides are cut in the flat.\n- **Chains:** `then` bends the far edge again; refused with `segments`, naming the edge.\n- **Other:** `sheet.path_flange`, `sheet.hem`, `sheet.fold`, `sheet.convert`.\n- Parameters, not numbers; edge picks are plain numbers.\n\n## Verify\n- `sheet.flat_pattern` and `sheet.export_bend_table {\"format\":\"json\"}` give the flat size, outline, each bend's centre line, length and allowance: check where a segment landed.\n- `measure` must match the flat area times thickness; a bend that leaves the volume unchanged has not built, unless it turns the other way.\n- `inspect.interference`/`inspect.clearance` against mating bodies; `screenshot {\"source\":\"model\",\"view\":\"iso\"}`.\n\n## The AI workflow (FR-17 to FR-20)\n1. **Segments:** derive count and boundaries from the intent (stiffeners, clearances, mating faces), state the assumption and confidence, offer an alternative, compute the fractions.\n2. **Angles:** one angle labelled high (geometry), medium (shop standard) or low (inferred), plus an alternative; refuse when the geometry contradicts the words.\n3. **Words to parameters:** map the phrase, read the numbers back when ambiguous. \"90 degree flange 20 mm high on the long edge\" is `sheet.flange {\"type\":\"edge\",\"edges\":[[100,0,2]],\"angle\":\"90 deg\",\"height\":\"20 mm\"}`.\n4. **Optimisation:** at most 8 candidates over fractions, angles, heights and sides, scored by `inspect.interference` volume 0, `inspect.clearance` at least the gap, flat within stock, radii at or above the rule's. Stop at the objective; report the winner, its margin and each iteration.\n\n## Red flags\n\n| Thought | Do instead |\n|---|---|\n| \"Assume the fraction direction\" | Check the bend table, or keep the partition symmetric. |\n| \"Leave a gap between segments\" | Segments tile the edge; a set-back is a different feature. |\n| \"It reported ok\" | `measure` against flat area times thickness and the bend table. |\n", + "reference.md": "# makeCAD sheet metal reference for agents\n\nCommand shapes for sheet metal, the segment contract, the bend arithmetic the engine uses, the\nrule values a shop supplies, the inference recipes for FR-17 to FR-20, the traps and one worked\nexample. The example runs in CI (`sheetmetal_skill_example_builds_as_documented` in\n`crates/mcp/src/tests.rs`), so the numbers here stay honest.\n\nLengths are mm, angles are degrees in expressions (`\"90 deg\"`). Any numeric field that takes an\nexpression can name the design's parameters; `segments[].from` and `segments[].to` are plain\nnumbers (fractions 0…1), so an expression there is refused.\n\n## Commands\n\n### `sheet.manage_rules`\n```json\n{\"command\":\"sheet.manage_rules\",\"params\":{\"name\":\"AL2\",\"thickness\":\"2 mm\",\"k_factor\":0.5,\n \"bend_radius\":\"1 mm\",\"relief_width\":\"2 mm\",\"relief_depth\":\"1 mm\",\"gap\":\"0.5 mm\",\"active\":true}}\n```\nKeys: `name` (new or existing), `thickness`, `k_factor`, `bend_radius`, `relief_width`,\n`relief_depth`, `corner_relief`, `hem_gap`, `gap` (expressions; `Thickness` inside a rule means\nthat rule's thickness), `corner_relief_shape` (`notch`|`round`|`rectangular`|`tear`),\n`angle_display` (`bend`|`included`), `active`, `delete`.\n\n- `k_factor` is validated to 0…1, `bend_radius` to at least 0.\n- The default rule is Steel (mm), 2.5 mm thick, K 0.44, bend radius = thickness, relief width =\n thickness, relief depth = thickness × 0.5.\n- A flange refuses `thickness`, `k_factor` and `bend_radius`: they belong to the rule.\n- `sheet.rules` lists the rules and the active one.\n\n### `sheet.flange`\nBase: `sketch`, `profiles?`, `rule?`, `flip?`, `name?`, `body_name?`.\nContour: `sketch`, `curves` (an open chain of lines), `distance`, `rule?`, `flip?`, `reverse?`.\nEdge: `edges`, `height`, `angle?` (default 90°), `radius?` (default: the rule's), `height_from?`\n(`outer`|`inner`|`tangent`), `position?` (`inside`|`outside`|`middle`|`material_outside`|\n`tangent`), `flip?`, `body?`, `corner_relief_shape?`, `corner_relief?`, `then?`, `name?`,\n`body_name?`.\n\nAn `edges` entry is `[x,y,z]` on a top or bottom edge, `{x,y,z}`, or\n`{point:[x,y,z], angle?, height?, segments?}` for an edge with its own values. `then` lists up to\n16 further bends `{angle?, height, flip?}`, each on the far edge of the one before.\n\n```json\n{\"command\":\"sheet.flange\",\"params\":{\"type\":\"edge\",\"edges\":[{\"point\":[100,0,2],\"segments\":[\n {\"from\":0,\"to\":0.5,\"angle\":\"90 deg\",\"height\":\"20 mm\"},\n {\"from\":0.5,\"to\":0.75,\"angle\":\"90 deg\",\"height\":\"15 mm\"},\n {\"from\":0.75,\"to\":1,\"angle\":\"45 deg\",\"height\":\"15 mm\",\"flip\":false}]}],\n \"height\":\"20 mm\",\"angle\":\"90 deg\",\"position\":\"inside\"}}\n```\n\n### `sheet.path_flange`, `sheet.hem`, `sheet.fold`\n- `sheet.path_flange`: `edge` or `sketch`+`curves` (a chain of lines across the edge, each line one\n flange and each corner one bend), `radius?`, `body?`.\n- `sheet.hem`: `edges` (1…1000 points), `length` (to the outer face), `gap?`, `flip?`, `body?`.\n- `sheet.fold`: `line` (sketch + curve) or `points` (`[[x,y,z],[x,y,z]]`), `angle?`, `radius?`,\n `position?` (`centerline`|`start`|`end`|`mould`), `fixed?`, `flip?`, `body?`.\n\n### `sheet.unfold`, `sheet.refold`, `sheet.convert`, `sheet.perforate`\n- `sheet.unfold {\"body\":\"...\"}` unfolds every bend; `sheet.refold` folds it back.\n- `sheet.convert`: `body`, `face` (a point on the large flat face or its name), `rule?`, `bends?`.\n- `sheet.perforate`: `diameter`, `pitch`, `margin?`, `pattern?` (`staggered`|`square`), `body?`,\n `sketch?`+`profiles?`; holes go in the flat pattern, the DXF and the volume, not the B-rep.\n\n### `sheet.flat_pattern`, `sheet.export_dxf`, `sheet.export_bend_table`\n- `sheet.flat_pattern {\"body\":\"...\"}` answers `flat_size_mm` (`[x,y,thickness]`), `outline`,\n `cutouts`, `cutout_shapes`, `pockets`, `bends` (`bend`, `angle_deg`, `included_angle_deg`,\n `radius`, `direction`, `allowance`, `length`, `start`, `end` in flat coordinates),\n `bend_zones`, `perforations`, `bores` (holes drilled along a panel into its rim) and the unfolded\n body.\n- `sheet.export_dxf`: `body?`, `path?`, `curves?` (`exact`|`arcs`), `text?` (`cut`|`etch`),\n `bend_notes?`, `note_height?`, `bend_lines?`, `layers?` (`roles`|`single`), `per_body?`.\n Layers: `OUTLINE`, `CUT`, `TEXT`/`ETCH`, `BEND_UP`/`BEND_DOWN`, `BEND_NOTES`,\n `POCKET__Z_TO__MM`, `PERFORATION`.\n- `sheet.export_bend_table`: `body?`, `format?` (`csv`|`json`), `path?`. Each row gives the bend's\n angle, direction, radius, allowance, length and its flat centre line, so an agent can check\n where a bend landed.\n\n### Inspection\n- `inspect.measure`: `bodies?`, `names_only?`, or `items` (faces and edges) for lengths, areas,\n volumes, diameters, distances, centre distances and angles between two faces or edges.\n- `inspect.interference {\"bodies\":[...]}`: pairs that overlap, with volume, area and bbox.\n- `inspect.clearance {\"bodies\":[...],\"against\":[...],\"clearance\":...}`: gaps and overlaps on exact\n faces.\n- `inspect.parameter_sweep {\"parameter\":\"H\",\"from\":15,\"to\":30,\"steps\":10}`: rebuilds in a copy of\n the design and reports what fails or warns at each value; the design is not changed.\n\n## The segment contract\n\n`segments` splits one picked edge's bend into stretches. Each is\n`{from, to, angle?, height?, flip?}`; no other key. `from` and `to` are unit-less fractions of the\nstretch the sheet still has there after cut-outs, `0` one end and `1` the other. A value left out\nfalls back to the edge's own value, then the feature's.\n\n- **Partition only:** the first `from` is 0, the last `to` is 1, each `from` equals the `to` of the\n one before, and each `from` < `to`. The segments tile the edge; leaving material out is a\n set-back (FR-14), not a segment.\n- **Junction tolerance:** \"equals\" means within `SEGMENT_JOIN_EPS` = 1e-9 (`crates/doc/src/sheet.rs`),\n the same number the build merges matching stretches across and the same number it snaps a first\n `from` or a last `to` inside to the edge's ends. One number on both sides, so every list the\n command accepts tiles the edge with no gap and no overlap: stretches that match in angle, height\n and side build the bend a whole-edge flange builds, and stretches that differ build one bend\n each. A wider gap is refused.\n- **Every segment bends:** each stretch becomes a bend with its own angle, height, setback and\n side, so a bend that changes angle, height or side along one edge is one feature. Consecutive\n stretches that match in angle, height and side merge into one bend. There is no flat stretch\n between segments.\n- **Junctions are snapped shut:** a junction within `SEGMENT_JOIN_EPS` is snapped to the stretch\n before it whatever the two stretches' angle, height or side are, so no interior gap survives into\n trimming or the flat pattern; only the 1e-12 attribute comparison decides whether they are one\n bend. A list 5e-10 apart with different heights builds the same part as the exact partition.\n- **One straight line, whole:** a split edge's fractions run along a straight line of the outline\n and the whole stretch must lie on it. A cut-out that shortened the line is fine (the stretch left\n is still one line); a notch or a step between two collinear pieces is not, and is refused.\n- **Direction:** fractions run from the end of the edge where the sheet's outline enters it, along\n the outline's own direction (counter-clockwise in the flat pattern's coordinates). An\n asymmetric partition therefore depends on it: check `sheet.export_bend_table`'s flat centre\n lines, or keep the partition symmetric, and swap the fractions if the bends land mirrored.\n- **Junctions:** no bend relief is cut where two segments meet and no corner is closed there; the\n two bends butt along the junction line. Only the outermost segments take part in corner closing\n and end relief. Where the two stretches bend to opposite sides the blank is cut along their\n junction, from the inner bend line out to the nearer stretch's far edge, in the flat pattern and\n the DXF: a blank joined there cannot fold, one stretch up and the next down. Stretches at\n different angles can have different setbacks, depending on the rule's position (`inside` sets\n the bend line back, `outside` does not), so their bend lines can be offset; the cut starts at the\n inner of the two and so covers the strip between them, over which the folded part separates, and\n its outer end is the nearer far edge, past which only the longer stretch's material remains.\n Where a cut-out took that\n far edge away, the cut is clipped to the material that is left: it runs from the bend line to the\n nearest boundary the junction line meets (a notch's edge, for one), so the blank is parted as far\n as its remaining material allows; a line and a circular arc are met exactly, so a round notch ends\n the cut on the arc itself, which the DXF splits there. Only the stretch of the line from the bend\n line out to the junction's own tip belongs to that junction: past the tip the line runs on through\n material the bend never reaches (another arm of a C-shaped blank, for one), and that material keeps\n no cut. A junction with no material left outward of\n the bend line has nothing to part and is left alone. The slit is zero-width, so the DXF carries\n two coincident outline lines there: a cutter may follow both, so check the toolpath before\n cutting and tell the shop. Same-side stretches stay\n one piece. A junction the command accepts within `SEGMENT_JOIN_EPS` is snapped shut, and a\n stretch narrower than that tolerance is no bend of its own: the run before it takes that stretch\n (its angle and height do not build), so the bends still tile the edge with nothing left uncovered,\n every span the build makes runs forwards, and none reaches the flat pattern reversed. The same\n holds for stretches at the very start, with no run before them yet: they are absorbed by the run\n that follows them, and that run still starts at the edge's start (0), so the first bend covers the\n edge from 0 and the last ends at 1 however many stretches were absorbed. A junction that overlaps,\n not just one that gaps, is snapped the same way: a stretch that starts below the covered end starts\n where the edge is already covered, so the runs are sorted, contiguous and never overlap and the\n part is the partition's.\n- **Refused:** `segments` on a base or contour flange; a split edge whose stretch leaves one\n straight line of the outline (a cut-out that shortened the line is fine, a notch or a step across\n it is not); `then` with `segments` (the Flange dialog refuses it and names the edge, rather than\n dropping the chain); more than 64 segments (`MAX_SEGMENTS = 64`). Each bend costs two flat pieces\n and the flat budget is 4096 (`MAX_FLAT_PIECES`), so a design holds at most 2047 bends.\n\nThe refusals are the contract; quote them when a call fails:\n\n| Wrong | Message |\n|---|---|\n| `segments` on a base or contour flange | `segments is only for edge flanges (a base or contour flange has no edge to divide)` |\n| `segments` beside `edges` | `` `segments` belongs inside an `edges` item: edges [{point, segments}] `` |\n| not a list | `edges[i].segments must list segments {from, to, angle?, height?, flip?}` |\n| count | `edges[i].segments must list 1…64 segments` |\n| unknown key | `edges[i].segments[j]: unknown key k (a segment takes from, to, angle, height and flip)` |\n| fraction missing or out of 0…1 | `edges[i].segments[j].from must be a fraction from 0 to 1` |\n| `to` not above `from` | `edges[i].segments[j].to must be more than its from` |\n| first `from` not 0 | `edges[i].segments[0].from must be 0: the segments cover the whole edge` |\n| last `to` not 1 | `edges[i].segments[n].to must be 1: the segments cover the whole edge` |\n| gap or overlap | `edges[i].segments[j].from must equal the to of the segment before it (the segments must meet, with no gap or overlap)` |\n| `flip` not a bool | `edges[i].segments[j].flip must be true or false` |\n| angle outside 0…180° | `edges[i].segments[j]: the flange angle must be between 0 and 180°` |\n| height below the bend's minimum | `edges[i].segments[j]: the flange height must be at least X mm for this bend` |\n| `then` with `segments` | `not supported yet: then on a segmented edge (bend each segment's far edge in its own feature)` |\n| the Flange dialog's `then` with a split edge | `edge N is split into segments: a split edge takes no `then`; bend each segment's far edge in its own feature` |\n| a split curved edge | `not supported yet: segments on a curved edge (pick a straight edge of the sheet)` |\n\n## Bend arithmetic\n\nWith bend angle θ (radians), inner radius R, thickness T and K-factor k:\n\n- bend allowance: `θ · (R + k · T)` (`allowance` in the doc layer).\n- setback from the edge for `position` `inside` (default): `(R + T) · tan(θ/2)`. `outside`: 0;\n `middle`: half of inside; `material_outside`: `R · tan(θ/2)`; `tangent`: `R + T` at 90° and\n above, `(R + T) · sin θ` below.\n- leg (the flat panel past the bend): the height less what sits before it, which is\n `(R + T) · tan(θ/2)` for `height_from` `outer`, `R · tan(θ/2)` for `inner`, and `R + T` for\n `tangent` past 90°.\n- flat size: the base less its setback, plus the allowance, plus the leg. The folded volume is the\n flat area times the thickness.\n\nFor the AL2 rule above (T 2, k 0.5, R 1) at 90°: allowance π = 3.141592653589793, setback 3, so a\n20 mm flange has a 17 mm leg. At 45°: allowance π/2, setback 3·tan(22.5°) =\n1.2426406871192852, and a 15 mm flange has a 13.757359312880714 mm leg.\n\nThe worked numbers here and the volume check (flat area times thickness) assume the rule's K-factor\nis 0.5, as the example rule's is: with another K the allowance, the flat area and the volume it\nimplies all change.\n\n## Rule values and the unfold method\n\nAsk the shop for the rule: thickness, K-factor (or a 90° deduction or allowance), bend radius,\nrelief width and depth, the gap between flanges that meet at a corner, and the corner relief. Never\ninvent a K-factor: it depends on the material, the tooling and the grain direction.\n\nToday's build unfolds every bend from the rule's K-factor. OPEN DRAFT PR #9911 adds\n`unfold_method` (`KFactor`|`Deduction`|`Allowance`) and a 90° deduction or allowance value per\nrule, and derives K = (2·BA90/π − R)/T; it is not in the build from this branch. When it lands, a\nrule can take a shop's chart value instead of a K-factor, and the skill's arithmetic above stays\nthe same because the engine still unfolds from one K.\n\n## Corners and relief\n\n- Bends of one feature that meet at a corner of the base are closed toward each other, with the\n rule's `gap` between them, and the corner relief the rule (or the feature's\n `corner_relief_shape`/`corner_relief`) gives.\n- Two bends of one split edge never close toward each other at a junction.\n- Bends of separate features do not close toward each other.\n- A bend that ends beside more of the base gets the rule's bend relief there; a bend narrower than\n the relief width gets none, with a warning.\n\n## Flat pattern and exports\n\nBefore handing a part to a shop, check:\n\n1. `sheet.flat_pattern`: the flat size fits the stock; the outline and cut-outs are what you\n planned; each bend's length, angle and direction match the plan.\n2. `sheet.export_bend_table {\"format\":\"json\"}`: one row per bend, with its flat centre line; the\n allowances follow from the rule.\n3. `inspect.interference` and `inspect.clearance` against the mating bodies: zero overlap, the\n rule's gap or more.\n4. `sheet.export_dxf`: layers and bend notes; `bend_lines: false` when the cutter would cut them.\n\n## Inference recipes (FR-17 to FR-20)\n\n### Segment inference (FR-17)\n1. Take the intent: what the part must do at that edge (stiffener positions, clearances, mating\n faces, where the load is).\n2. Decide how many bends the edge carries and where their boundaries fall, in mm along the usable\n stretch. Convert to fractions from the direction rule above.\n3. State the assumption, the confidence (high when the intent gives dimensions, medium when it\n gives a count or a spacing rule, low when inferred) and one alternative partition with its\n reason.\n4. Check each stretch's length and each height against the bend's minimum, then build one flange\n feature and verify the bend table's lengths and angles.\n\n### Angle inference (FR-18)\n1. Propose one angle with a confidence: high when the mating geometry fixes it (measure the faces\n or the gap), medium for a standard shop angle (90°, 45°, 135°), low when inferred.\n2. Give at least one alternative and why it is worse (a taller leg, a clash, a non-standard tool).\n3. Refuse when the geometry contradicts the words: say what you measured (for example the mating\n face is at 45° from the base, so a 90° bend cannot sit flush) and ask, rather than bending.\n4. Verify with `inspect.clearance`/`inspect.interference` and the bend table.\n\n### Natural language (FR-19)\n| Phrase | Parameters |\n|---|---|\n| \"90 degree flange 20 mm high on the long edge\" | `{\"type\":\"edge\",\"edges\":[[100,0,2]],\"angle\":\"90 deg\",\"height\":\"20 mm\"}` on the long edge's midpoint |\n| \"fold the back up 20 mm at 90° except the last 50 mm, which stays at 45°\" | `segments` tiling the edge: the last stretch at `\"45 deg\"`, height as stated or asked |\n| \"two stiffeners side by side on that edge, 15 mm high\" | two segments with `height\":\"15 mm\"` and the split where the intent puts it |\n| \"make it from 1.5 mm aluminium with K 0.44\" | `sheet.manage_rules` with `thickness` and `k_factor`, then the flange |\n| \"hem the top edge 8 mm\" | `sheet.hem {\"edges\":[[...]],\"length\":\"8 mm\"}` |\n| \"unfold it and give me the flat\" | `sheet.unfold`, then `sheet.flat_pattern` |\n\nRead the numbers back to the user when the phrase is ambiguous (a height with no datum, a direction,\nwhich edge is \"the long edge\" on a near-square part) before building.\n\n### Multi-flange optimisation (FR-20)\n1. State the objective: zero `inspect.interference` volume between the sheet and the mating bodies,\n `inspect.clearance` at least the rule's `gap`, the flat within the stock, every radius at or\n above the rule's.\n2. Variables: segment fractions, angles, heights and sides. At most 8 candidate sets; use\n `inspect.parameter_sweep` for one parameter over a range, and `undo` to roll back a build.\n3. Score every candidate and keep the numbers; stop when the objective is met or the 8th candidate\n is scored.\n4. Report the winner, its margin over the runner-up and every iteration's objective values. Never\n claim an improvement without the numbers.\n\n## Traps\n\n- **Fractions need the direction:** an asymmetric partition can land mirrored. Check the bend\n table's centre lines against the plan, or keep the partition symmetric.\n- **Segments are not set-backs:** they tile the edge; a gap is refused.\n- **Deleting a stretch in the Flange dialog keeps the edge whole:** the gap the removed stretch\n leaves is bridged from the stretches beside it, never from the removed row (its fields may be\n mid-edit and empty): the stretch before it reaches to where the stretch after it starts, or to\n the edge's end when none follows. A boundary the user did not touch does not move, and removing\n the only stretch left makes the whole edge. The dialog never submits a list with a gap.\n- **Per-edge versus per-segment:** `angle` and `height` at the edge entry are that edge's values; a\n segment's own values override them; the feature's values are the last fallback.\n- **A named stretch keeps its name with its material:** redefining a split edge after a stretch is\n deleted or merged keeps the surviving stretch's own model parameter name (the name on the value it\n still has; failing that, the name whose span it still covers), and the deleted stretch's name goes\n away. Expressions that read the survivor's name still read its height; a deleted stretch's name\n never lands on a stretch whose value came from elsewhere. A segment input is keyed by its edge's\n pick point, the physical edge, not by the edge's place in the list: reordering the `edges` list\n keeps every name on its own edge's stretch. A pick point that moves by a hair still names the same\n edge: two picks within the document's pick tolerance (`appearance::pick_tolerance`, 1e-6 mm where\n no body applies) are the same edge, so redefining with a nudged pick keeps the edge's and its\n stretches' names; a pick that moved further still takes the nearest edge point on the same feature\n within a sane bound, and a genuinely different edge keeps its own name.\n- **`flip` is per segment:** it replaces the feature's `flip` outright for that stretch: `false` is\n the default direction and `true` the other one, whatever the feature's `flip` is. It is not a turn\n relative to the feature.\n- **`then` is refused with `segments`:** bend each segment's far edge in its own feature. The\n Flange dialog says the same, naming the edge: `edge N is split into segments: a split edge takes\n no `then`; bend each segment's far edge in its own feature`.\n- **Edge picks** are plain numbers on a top or bottom face at the sheet's thickness; a pick on the\n bottom face flips `top`. The pick snaps to the nearest edge.\n- **`segments` on a base or contour flange** is refused: there is no edge to divide.\n- **The flat budget:** 4096 flat pieces, two per bend, so at most 2047 bends.\n- **A bend narrower than the relief width** gets no relief and a warning.\n- **The flat pattern is refused** once a feature that is not sheet metal changed the body after\n its sheet metal features: remove or suppress it, or model that shape with sheet metal features.\n- **`Thickness` inside a rule** is that rule's thickness, not the design's.\n\n## Worked example: a request turned into one flange feature\n\nRequest: \"Make it from 2 mm steel, K 0.5, bend radius 1 mm. Base 200 × 100 mm. Fold the back edge\nup 20 mm at 90°, except the last 50 mm, which steps down to 45° at 15 mm.\"\n\nMapping: the back edge is the 200 mm edge from (0,0) to (200,0); its midpoint is `[100,0,2]`; the\nfirst 150 mm is one bend at 90°/20 mm, the last 50 mm another at 45°/15 mm, so two segments, with\nthe boundary at 0.75 of the stretch.\n\n```json\n{\"commands\":[\n {\"command\":\"sheet.manage_rules\",\"params\":{\"name\":\"AL2\",\"thickness\":\"2 mm\",\"k_factor\":0.5,\n \"bend_radius\":\"1 mm\",\"active\":true}},\n {\"command\":\"sketch.create\",\"params\":{\"plane\":\"XY\",\"name\":\"Base\"}},\n {\"command\":\"sketch.rectangle.two_point\",\"params\":{\"p0\":[0,0],\"p1\":[200,100]}},\n {\"command\":\"sketch.finish\",\"params\":{}},\n {\"command\":\"sheet.flange\",\"params\":{\"sketch\":\"Base\"}},\n {\"command\":\"sheet.flange\",\"params\":{\"type\":\"edge\",\"edges\":[{\"point\":[100,0,2],\"segments\":[\n {\"from\":0,\"to\":0.75,\"angle\":\"90 deg\",\"height\":\"20 mm\"},\n {\"from\":0.75,\"to\":1,\"angle\":\"45 deg\",\"height\":\"15 mm\"}]}],\n \"height\":\"20 mm\",\"angle\":\"90 deg\",\"position\":\"inside\"}}\n]}\n```\n\nExpected, by hand:\n\n- Flat area 23275.514645666284 mm²; folded volume 46551.02929133257 mm³.\n- Flat size 200 × 117.1415926535898 × 2 mm; the 45° part's flat edge reaches 114.08551495255631 mm,\n and the base's flat edge steps by 1.7573593128807148 mm at the junction.\n- `sheet.export_bend_table {\"format\":\"json\"}`: two bends, 150 mm at 90° and 50 mm at 45°, allowances\n π and π/2, both up; their flat centre lines show which end of the edge the fractions started\n from.\n- `inspect.measure` must report 46551.03 mm³ within 0.01 %; anything else means the bend did not\n build as planned.\n\nThe 3-segment variant in the command section (90°/20 mm, 90°/15 mm, 45°/15 mm at 0.5 and 0.75)\ngives three bends of 100, 50 and 50 mm and a volume of 46051.02929133257 mm³: the 15 mm stretch's\nleg is 12 mm, not the 17 mm a 20 mm stretch has, so the area is 250 mm² smaller.\n" + } + }, { "name": "makecad-tests", "description": "Use when writing, placing or running tests in makeCAD: a regression test for a bug, an engine test for a command, a UI scenario, a reference (oracle) test, goldens, or when CI fails a test you did not touch.", "files": { - "SKILL.md": "---\nname: makecad-tests\ndescription: \"Use when writing, placing or running tests in makeCAD: a regression test for a bug, an engine test for a command, a UI scenario, a reference (oracle) test, goldens, or when CI fails a test you did not touch.\"\n---\n\n# Where tests go and how to run them\n\nThe long form is `docs/book/src/dev/testing.md`.\n\n## Placement\n- A regression test goes into its area's existing test file (booleans, blends, shell, STEP, naming, ...), never a new file named after the bug (#3226).\n- Engine tests sit next to the code or in `*_tests.rs` files, measured against a value you can derive.\n- UI scenarios are JSON in `crates/ui-egui/tests/scenarios/*.json`. Put `{\"pending\": \"why\"}` in a scenario that records a bug before it is fixed, and remove it in the fixing PR.\n- Reference tests are `tests/oracle//recipe.json` with an `expected.json` beside it, run by `cargo xtask oracle`, expected values in closed form (`tools/oracle-analytic/`) or from FreeCAD as a separate program (`tools/freecad-oracle/`). A known failure names its issue (`\"known_failure\": \"#123\"`). Never change an expected value to match makeCAD's output, and never take one from a commercial CAD product.\n- Crash fixes: a regression test from the report's `design.sc` and `replay.json` (`skills/makecad-crash-safety/SKILL.md`).\n\n## Unit test or rig case\n- Unit tests assert the code's logic: which edges a chain picks, name resolution, history labels, refusal wording, hostile input, parsing and saving (`a_corner_round_wider_than_its_faces_overflows_and_takes_the_corners_other_edges`: per-edge radii, which no command takes).\n- The rig asserts geometry (exact volumes, shapes, seams, refusals) with a hand-derived answer. A test doing both keeps only its logic. `tests/kernel-cases/` only shrinks: kernel cases go to solidcore (CONTRIBUTING.md \"Tests\"); command, UI and product-rule cases stay here.\n\n## A failing test needs its fix\nA failing test cannot merge without its fix (it turns `main` red): include it, or list the test and cause in `tests/KNOWN_FAILING_TESTS` (`cargo xtask known-failing`); the fix drops the line.\n\n## Running\n- `cargo xtask test` builds with the `ci` profile and runs every test binary at once; arguments after `--` go to each binary (`cargo xtask test -- shell`). It builds several times faster than `--release`; a test failing only in a debug build: say so in the PR.\n- `SOLIDCRAFT_TEST_JOBS=N` bounds concurrent commands. `cargo xtask ci` is the gate before a commit (fmt, lints, clippy `-D warnings`, tests, wasm).\n- Tests run in their own processes: no shared state, no wall-clock timing.\n\n## Goldens, matrices and skipped tests\n- The kernel's reference is the ladder (`tests/kernel-cases/ladder/`, `cargo xtask kernel-cases --ladder`, `docs/kernel-ladder.md`).\n- Kernel PRs run `kernel-rig.yml` (areas by `PATHS` against `KNOWN_FAILING`, the ladder against its golden). In the same PR a fix drops its line, a pin bump's new failure adds one, a changed ladder result is re-recorded (`--record \"why\"`), a new command gets an `EXEMPT` line (`tests/kernel-cases/README.md`).\n- Maintainers' PRs run native, GPU and reference tests on affected packages; others wait for `approved-for-ci`. `release-gate.yml` runs all before develop replaces main.\n- The action matrix is a ratchet: bless a newly passing action (`cargo xtask action-matrix --bless`, `docs/action-matrix.md`).\n- PRs skip a few heavy tests, run in the merge queue, nightly and on `main`. Check them after merging (`.config/nextest.toml`).\n- Mutation testing: `docs/mutation-testing.md`.\n" + "SKILL.md": "---\nname: makecad-tests\ndescription: \"Use when writing, placing or running tests in makeCAD: a regression test for a bug, an engine test for a command, a UI scenario, a reference (oracle) test, goldens, or when CI fails a test you did not touch.\"\n---\n\n# Where tests go and how to run them\n\nThe long form is `docs/book/src/dev/testing.md`.\n\n## Placement\n- A regression test goes into its area's existing test file (booleans, blends, shell, STEP, naming, ...), never a new file named after the bug (#3226).\n- Engine tests sit next to the code or in `*_tests.rs` files, measured against a value you can derive.\n- UI scenarios are JSON in `crates/ui-egui/tests/scenarios/*.json`. Put `{\"pending\": \"why\"}` in a scenario that records a bug before it is fixed, and remove it in the fixing PR.\n- Reference tests are `tests/oracle//recipe.json` with an `expected.json` beside it, run by `cargo xtask oracle`, expected values in closed form (`tools/oracle-analytic/`) or from FreeCAD as a separate program (`tools/freecad-oracle/`). A known failure names its issue (`\"known_failure\": \"#123\"`). Never change an expected value to match makeCAD's output, and never take one from a commercial CAD product.\n- Crash fixes: a regression test from the report's `design.sc` and `replay.json` (`skills/makecad-crash-safety/SKILL.md`).\n\n## Unit test or rig case\n- Unit tests assert the code's logic: which edges a chain picks, name resolution, history labels, refusal wording, hostile input, parsing and saving (`a_corner_round_wider_than_its_faces_overflows_and_takes_the_corners_other_edges`: per-edge radii, which no command takes).\n- The rig asserts geometry (exact volumes, shapes, seams, refusals) with a hand-derived answer. A test doing both keeps only its logic. `tests/kernel-cases/` only shrinks: kernel cases go to solidcore (CONTRIBUTING.md \"Tests\"); command, UI and product-rule cases stay here.\n\n## A failing test needs its fix\nA failing test cannot merge without its fix (it turns `main` red): include it, or list the test and cause in `tests/KNOWN_FAILING_TESTS` (`cargo xtask known-failing`); the fix drops the line.\n\n## Running\n- `cargo xtask test` builds with the `ci` profile and runs every test binary at once; arguments after `--` go to each binary (`cargo xtask test -- shell`). It builds several times faster than `--release`; a test failing only in a debug build: say so in the PR.\n- `SOLIDCRAFT_TEST_JOBS=N` bounds concurrent commands. `cargo xtask ci` is the gate before a commit (fmt, lints, clippy `-D warnings`, tests, wasm).\n- Tests run in their own processes: no shared state, no wall-clock timing.\n\n## Goldens, matrices and skipped tests\n- The kernel's reference is the ladder (`tests/kernel-cases/ladder/`, `cargo xtask kernel-cases --ladder`, `docs/kernel-ladder.md`).\n- Kernel PRs run `kernel-rig.yml` (areas by `PATHS` against `KNOWN_FAILING`, the ladder against its golden). In the same PR a fix drops its line, a kernel update's new failure adds one, a changed ladder result is re-recorded (`--record \"why\"`), a new command gets an `EXEMPT` line (`tests/kernel-cases/README.md`).\n- Maintainers' PRs run native, GPU and reference tests on affected packages; others wait for `approved-for-ci`. `release-gate.yml` runs all before develop replaces main.\n- The action matrix is a ratchet: bless a newly passing action (`cargo xtask action-matrix --bless`, `docs/action-matrix.md`).\n- PRs skip a few heavy tests, run in the merge queue, nightly and on `main`. Check them after merging (`.config/nextest.toml`).\n- Mutation testing: `docs/mutation-testing.md`.\n" } }, { "name": "makecad-ui", "description": "Use when adding or changing a makeCAD dialog, panel, menu, overlay, canvas, camera input, slider, icon or colour in crates/ui-egui. Covers the single UI container, the UI kit, navigation::handle, theme tokens, command icons and UI scenarios.", "files": { - "SKILL.md": "---\nname: makecad-ui\ndescription: \"Use when adding or changing a makeCAD dialog, panel, menu, overlay, canvas, camera input, slider, icon or colour in crates/ui-egui. Covers the single UI container, the UI kit, navigation::handle, theme tokens, command icons and UI scenarios.\"\n---\n\n# Dialogs and UI\n\nThe UI is thin: it reads engine state and acts through `app.run(id, params)` or `app.start(id)`. A dialog is a form that builds the parameters of a command (`skills/makecad-commands/SKILL.md`). The full control list is `docs/ui-kit.md`.\n\n## One outer container\n- All panels, floating sheets, menus, overlays and platform UI windows use `ui_kit::Container`, directly or through `Panel`, `Window`, `Confirm` and `Menu`. Declare the semantic `Surface`; workspace panels use its shared layout policy and chrome.\n- System and report windows use `ui_kit::Window`; its low-level host builder is kit-private.\n- Do not construct raw egui hosts, outer popup or window frames, or shadows in feature modules.\n- `cargo xtask ui-containers` checks source and examples in all current and future crates and apps, recursively. It runs in the fast repository CI job and in `cargo xtask ci`, with no caller allowances. The inventory and the legitimate content and native exceptions are in `docs/ui-container-audit.md`.\n\n## Controls and colour\n- Colours, typography, dimensions and spacing come from `theme::Tokens` (`crates/ui-egui/src/theme.rs`). No literal colours in feature code.\n- Sliders only through `ui_kit::slider`. Form rows use `row`, `expr_row`, `text_row`, `choice_row` and `count_row` from `crate::ui_kit` (`crates/ui-egui/src/ui_kit/`).\n- Confirmations use `ui_kit::Confirm`; the old `Prompt` element is gone.\n\n## One set of camera controls\nEvery page or canvas with a camera (viewport, Render preview, a flat pattern or drawing page) calls `navigation::handle` (`crates/ui-egui/src/navigation.rs`) with its `NavCaps` (orbit off for flat 2D pages). Never hand-roll camera input from drags, the wheel or pinch; `hand_rolled_camera_input_is_rejected` fails if a page does.\n\n## Icons\nCommand icons are original SVG masters compiled through `crates/ui-egui/src/icon_svg.rs`. Read `assets/AGENTS.md`, `assets/icons/ui/AGENTS.md` and `assets/icons/ui/STYLE_GUIDE.md` first, add the ATTRIBUTION.md row, and run `cargo xtask icons` and `cargo xtask assets`. See `skills/makecad-ground-rules/SKILL.md`.\n\n## Text\nEvery label, tooltip and message goes through the catalogs: `skills/makecad-ui-text/SKILL.md`. A new behaviour that is on by default: `skills/makecad-preferences/SKILL.md`.\n\n## Look at the result\nRun the app, drive it and read the screenshot: `skills/makecad-agent-tools/SKILL.md`. A UI scenario (`crates/ui-egui/tests/scenarios/*.json`) covers the clicks; see `skills/makecad-tests/SKILL.md`. Work that takes long must not block the window: `skills/makecad-performance/SKILL.md`.\n" + "SKILL.md": "---\nname: makecad-ui\ndescription: \"Use when adding or changing a makeCAD dialog, panel, menu, overlay, canvas, camera input, slider, icon or colour in crates/ui-egui. Covers the single UI container, the UI kit, navigation::handle, theme tokens, command icons and UI scenarios.\"\n---\n\n# Dialogs and UI\n\nThe UI is thin: it reads engine state and acts through `app.run(id, params)` or `app.start(id)`. A dialog is a form that builds the parameters of a command (`skills/makecad-commands/SKILL.md`). The full control list is `docs/ui-kit.md`.\n\n## One outer container\n- All panels, floating sheets, menus, overlays and platform UI windows use `ui_kit::Container`, directly or through `Panel`, `Window`, `Confirm` and `Menu`. Declare the semantic `Surface`; workspace panels use its shared layout policy and chrome.\n- System and report windows use `ui_kit::Window`; its low-level host builder is kit-private.\n- Do not construct raw egui hosts, outer popup or window frames, or shadows in feature modules.\n- Tooltips go through `ui_kit::BackingTooltipExt` (`backing_on_hover_text` and friends), which gives them the themed backing and blur; egui's own `on_hover_*` and `show_tooltip_*` methods are not called outside the kit. A tooltip egui draws inside its own widget (an elided label) is outside this rule.\n- `cargo xtask ui-containers` checks source and examples in all current and future crates and apps, recursively, for raw hosts and raw tooltip calls. It runs in the fast repository CI job and in `cargo xtask ci`, with no caller allowances. The inventory and the legitimate content and native exceptions are in `docs/ui-container-audit.md`.\n\n## Controls and colour\n- Colours, typography, dimensions and spacing come from `theme::Tokens` (`crates/ui-egui/src/theme.rs`). No literal colours in feature code.\n- Sliders only through `ui_kit::slider`. Form rows use `row`, `expr_row`, `text_row`, `choice_row` and `count_row` from `crate::ui_kit` (`crates/ui-kit/src/`).\n- Confirmations use `ui_kit::Confirm`; the old `Prompt` element is gone.\n\n## One set of camera controls\nEvery page or canvas with a camera (viewport, Render preview, a flat pattern or drawing page) calls `navigation::handle` (`crates/ui-egui/src/navigation.rs`) with its `NavCaps` (orbit off for flat 2D pages). Never hand-roll camera input from drags, the wheel or pinch; `hand_rolled_camera_input_is_rejected` fails if a page does.\n\n## Icons\nCommand icons are original SVG masters compiled by the look crate (`crates/look/src/icons.rs`). Read `assets/AGENTS.md`, `crates/look/icons/AGENTS.md` and `crates/look/icons/STYLE_GUIDE.md` first, add the ATTRIBUTION.md row, and run `cargo xtask icons` and `cargo xtask assets`. See `skills/makecad-ground-rules/SKILL.md`.\n\n## Text\nEvery label, tooltip and message goes through the catalogs: `skills/makecad-ui-text/SKILL.md`. A new behaviour that is on by default: `skills/makecad-preferences/SKILL.md`.\n\n## Look at the result\nRun the app, drive it and read the screenshot: `skills/makecad-agent-tools/SKILL.md`. A UI scenario (`crates/ui-egui/tests/scenarios/*.json`) covers the clicks; see `skills/makecad-tests/SKILL.md`. Work that takes long must not block the window: `skills/makecad-performance/SKILL.md`.\n" } }, { "name": "makecad-ui-text", "description": "Use when adding or changing any user-visible text in makeCAD: a label, tooltip, message, command label or a new language. Covers the message catalogs in assets/locales, sorted lists, which locales a new key needs, UK English and terminology.", "files": { - "SKILL.md": "---\nname: makecad-ui-text\ndescription: \"Use when adding or changing any user-visible text in makeCAD: a label, tooltip, message, command label or a new language. Covers the message catalogs in assets/locales, sorted lists, which locales a new key needs, UK English and terminology.\"\n---\n\n# UI text and translations\n\nmakeCAD embeds its translations and works offline. The long form is `docs/localization.md`.\n\n## Adding a message\n1. Add the id and English text in a new pending file (next section); `assets/locales/en.json` itself is only edited to change an existing message. Ids are stable: keep them when you change wording.\n2. Use `app.tr(\"ui.some_id\")` for static messages and `Locale::format` for whole sentences with named placeholders. Translate the whole sentence, punctuation included, so a translator can reorder arguments. Use stable ids directly for new messages, not the English-label adapter (`app.tr_label`), which exists for older tables.\n3. Command labels live under `cmd.`; `cargo xtask i18n --add-missing` writes the ones that are missing into `en.json`.\n4. Add the UK spelling to `assets/locales/en-GB.json` when the US spelling differs (Centre, Colour, Licence, ...). That file holds only the differing messages.\n5. A new label needs `en`, `ja`, `zh`, `de` and `ko`. The other catalogs are partial and fall back to English; `cargo xtask i18n` reports their gaps without failing, and `every_complete_catalog_carries_every_english_message` fails a missing `ja` or `zh` entry.\n6. Run `cargo xtask lists --fix` before committing, then `cargo xtask i18n`.\n\n## Sorted catalogs\nCatalogs are one message per line, sorted by id, with no repeated id. `cargo xtask lists` (part of `cargo xtask ci` and the Lists workflow) fails on an unsorted file. Catalogs are no longer edited for new messages (see Pending locale files); for an edit, let `--fix` place it. Two PRs that add neighbouring keys still collide on these files; rebase and run `--fix` again.\n\n## Pending locale files\nNew strings go in a new `assets/locales/pending/.json` (lowercase, dashes, named after the change), never into the catalogs. It maps a locale code to `{\"message id\": \"text\"}`: give English and any other locale you can translate; a locale you leave out falls back to English. The id must not already be in that locale's catalog or in another pending file (the build and `cargo xtask lists` fail otherwise); to change an existing message, edit the catalog. Do not sort or fold: the app, `cargo xtask i18n` and the tests read pending files as part of the catalogs. After a merge, the Generated files workflow runs `cargo xtask fold-pending` on `main`; never run it in a PR. New ATTRIBUTION.md rows likewise go in a new `attribution/pending/.md`, never into the table. Each folder's README has the details.\n\n## Other sorted lists\n- Languages (`crates/ui-egui/src/i18n.rs`): one per line, English first, then by id; a test checks it. Adding a language is an embedded catalog plus one registration there.\n- `mod` lines: one per line, in the sorted group they belong to.\n- `docs/features.md` and `THIRD-PARTY-LICENSES.txt` are generated on `main` after each merge: never edit or regenerate them in a PR.\n\n## Wording\nUse the terms in the glossary (`docs/book/src/reference/glossary.md`); words with several meanings (Construction, Flat, Round, Normal, Gap, Clearance) have one catalogue entry per meaning. A new idea adds its glossary term. Command labels are Title Case, other text sentence case. Tests also require tabs, panels, menu labels and command labels to be in `en.json`.\n" + "SKILL.md": "---\nname: makecad-ui-text\ndescription: \"Use when adding or changing any user-visible text in makeCAD: a label, tooltip, message, command label or a new language. Covers the message catalogs in assets/locales, sorted lists, which locales a new key needs, UK English and terminology.\"\n---\n\n# UI text and translations\n\nmakeCAD embeds its translations and works offline. The long form is `docs/localization.md`.\n\n## Adding a message\n1. Add the id and English text in a new pending file (next section); `assets/locales/en.json` itself is only edited to change an existing message. Ids are stable: keep them when you change wording.\n2. Use `app.tr(\"ui.some_id\")` for static messages and `Locale::format` for whole sentences with named placeholders. Translate the whole sentence, punctuation included, so a translator can reorder arguments. Use stable ids directly for new messages, not the English-label adapter (`app.tr_label`), which exists for older tables.\n3. Command labels live under `cmd.`; `cargo xtask i18n --add-missing` writes the ones that are missing into `en.json`.\n4. Add the UK spelling to `assets/locales/en-GB.json` when the US spelling differs (Centre, Colour, Licence, ...). That file holds only the differing messages.\n5. New labels need `en`, `ar`, `he`, `ja`, `vi`, `zh`, `de` and `ko`. The complete catalogs (`ar`, `he`, `ja`, `vi`, `zh`) require every English key; others fall back to English. `cargo xtask i18n` reports gaps; tests reject gaps in complete catalogs.\n6. Run `cargo xtask lists --fix` before committing, then `cargo xtask i18n`.\n\n## Sorted catalogs\nCatalogs are one message per line, sorted by id, with no repeated id. `cargo xtask lists` (part of `cargo xtask ci` and the Lists workflow) fails on an unsorted file. Catalogs are no longer edited for new messages (see Pending locale files); for an edit, let `--fix` place it. Two PRs that add neighbouring keys still collide on these files; rebase and run `--fix` again.\n\n## Pending locale files\nNew strings go in a new `assets/locales/pending/.json` (lowercase, dashes, named after the change), never into the catalogs. It maps a locale code to `{\"message id\": \"text\"}`: give English and any other locale you can translate; a locale you leave out falls back to English. The id must not already be in that locale's catalog or in another pending file (the build and `cargo xtask lists` fail otherwise); to change an existing message, edit the catalog. Do not sort or fold: the app, `cargo xtask i18n` and the tests read pending files as part of the catalogs. After a merge, the Generated files workflow runs `cargo xtask fold-pending` on `main`; never run it in a PR. New ATTRIBUTION.md rows likewise go in a new `attribution/pending/.md`, never into the table. Each folder's README has the details.\n\n## Other sorted lists\n- Languages (`crates/ui-egui/src/i18n.rs`): one per line, English first, then by id; a test checks it. Adding a language is an embedded catalog plus one registration there.\n- `mod` lines: one per line, in the sorted group they belong to.\n- `docs/features.md` and `THIRD-PARTY-LICENSES.txt` are generated on `main` after each merge: never edit or regenerate them in a PR.\n\n## Wording\nUse the terms in the glossary (`docs/book/src/reference/glossary.md`); words with several meanings (Construction, Flat, Round, Normal, Gap, Clearance) have one catalogue entry per meaning. A new idea adds its glossary term. Command labels are Title Case, other text sentence case. Tests also require tabs, panels, menu labels and command labels to be in `en.json`.\n" } } ], - "revision": "d563936cf58580fc0da2203d30708c4869a5a5956140221e717a53d5723b6efe" + "revision": "b9c715912afefe96fa839a749f804d42d86724b258a7e56c48c32d73c2ccbca1" } diff --git a/vibemake-service/src/test/java/com/linkerbot/vibemake/service/cad/ai/ArkCadAiClientTest.java b/vibemake-service/src/test/java/com/linkerbot/vibemake/service/cad/ai/ArkCadAiClientTest.java index 104597b..c5430aa 100644 --- a/vibemake-service/src/test/java/com/linkerbot/vibemake/service/cad/ai/ArkCadAiClientTest.java +++ b/vibemake-service/src/test/java/com/linkerbot/vibemake/service/cad/ai/ArkCadAiClientTest.java @@ -302,7 +302,7 @@ class ArkCadAiClientTest { } assertThat(received.get().path("tools")).anySatisfy(tool -> { assertThat(tool.path("name").asText()).isEqualTo("skill_reference"); - assertThat(tool.path("parameters").path("properties").path("skill").path("enum")).hasSize(17); + assertThat(tool.path("parameters").path("properties").path("skill").path("enum")).hasSize(19); }); } diff --git a/vibemake-service/src/test/java/com/linkerbot/vibemake/service/cad/ai/CadAiKnowledgeUtilityTest.java b/vibemake-service/src/test/java/com/linkerbot/vibemake/service/cad/ai/CadAiKnowledgeUtilityTest.java index a63a958..810eb65 100644 --- a/vibemake-service/src/test/java/com/linkerbot/vibemake/service/cad/ai/CadAiKnowledgeUtilityTest.java +++ b/vibemake-service/src/test/java/com/linkerbot/vibemake/service/cad/ai/CadAiKnowledgeUtilityTest.java @@ -13,13 +13,13 @@ import org.junit.jupiter.api.Test; class CadAiKnowledgeUtilityTest { private final ObjectMapper json = new ObjectMapper(); - @Test void allSeventeenGenericSkillsRemainByteForByteOriginal() throws Exception { + @Test void allNineteenGenericSkillsMatchTheCurrentSourceBundle() throws Exception { byte[] bytes; try (InputStream stream = getClass().getResourceAsStream("/cad/ai/skills.json")) { bytes = stream.readAllBytes(); } assertThat(HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes))) - .isEqualTo("026284eff26c8b4be1f7864219921a54828338973317c291f7e862b1cc452ef7"); + .isEqualTo("9d71ac78011b890c182e4ef28da15a52cc9714cc777f7fef2c806e63489a90a6"); JsonNode bundle = json.readTree(bytes); - assertThat(bundle.path("skills")).hasSize(17); + assertThat(bundle.path("skills")).hasSize(19); String instructions = new CadAiTools(json).instructions(); assertThat(instructions).startsWith(bundle.path("workflow").asText()); for (JsonNode skill : bundle.path("skills")) diff --git a/vibemake-service/src/test/java/com/linkerbot/vibemake/service/cad/ai/CadAiProtocolTest.java b/vibemake-service/src/test/java/com/linkerbot/vibemake/service/cad/ai/CadAiProtocolTest.java index e126b5b..422b2bb 100644 --- a/vibemake-service/src/test/java/com/linkerbot/vibemake/service/cad/ai/CadAiProtocolTest.java +++ b/vibemake-service/src/test/java/com/linkerbot/vibemake/service/cad/ai/CadAiProtocolTest.java @@ -286,9 +286,9 @@ class CadAiProtocolTest { try (InputStream input = new ClassPathResource("cad/ai/skills.json").getInputStream()) { bundle = json.readTree(input); } - assertThat(bundle.path("skills")).hasSize(17); + assertThat(bundle.path("skills")).hasSize(19); CadAiTool definition = tools.definitions().stream().filter(tool -> "skill_reference".equals(tool.name())).findFirst().orElseThrow(); - assertThat(definition.parameters().path("properties").path("skill").path("enum")).hasSize(17); + assertThat(definition.parameters().path("properties").path("skill").path("enum")).hasSize(19); assertThat(definition.parameters().path("properties").path("file").path("default").asText()).isEqualTo("SKILL.md"); assertThat(tools.instructions()).contains(bundle.path("workflow").asText()).doesNotContain("SolidCraft"); for (JsonNode skill : bundle.path("skills")) {