feat(skill): per-harness skillbuild toolchain replaces skill-pack (#18)

* feat(skill): replace skill-pack with per-harness conditional compiler

skillbuild compiles the skill tree into per-target harness builds:
- <!-- skill:if omp,!claude --> blocks include text only for matching
  targets; name-list conditions only, no else/nesting, fail-loud on
  unknown targets and unpaired/nested directives
- fence-aware: directive-looking lines inside code fences are literal
- layout is the filesystem; tree root configured in skillproj.toml
- post-build assertion: zero directive residue, SKILL.md frontmatter
  name check

Migration to the new model:
- docs/skill/ becomes the self-contained source root (SKILL.md,
  references/, generated api/stdlib/core/guides now under
  references/docs/; SDK_OVERVIEW/LICENSE/inspect are ordinary tree
  files)
- auto_docs_gen output redirected into the tree (docs/api ->
  docs/skill/references/docs/api, likewise stdlib)
- skills/simplecadapi/ is now the compiled omp target output;
  dist/generic/simplecadapi the generic target
- dropped skill-pack entry point (plus dangling evolve/make-export
  entries and their orphaned test), release workflow builds via
  skillbuild + tar; README updated

First real conditional block: harness reading paths in SKILL.md
(skill:// mount on omp vs disk-relative on generic).

Verified: 59 tests pass (skillbuild 31, auto_docs_gen 19, persistence
regression 9); both targets build; outputs residue-clean; full suite
collects (1376 tests).

* refactor(tools): auto_docs_gen moves out of the installed package

tools/ scripts are repo-checkout dev scripts, not packaged CLIs:
- auto_docs_gen.py now lives in tools/ beside the other generators;
  auto_tools/ package removed entirely
- path resolution simplifies: repo root = parent of tools/, fail-loud
  if pyproject.toml missing; site-packages/cwd fallback branches were
  dead code once the script stopped shipping in the wheel
- auto-docs-gen console script dropped from [project.scripts];
  release.yml and README invoke python tools/auto_docs_gen.py
- MANIFEST.in stale src/auto_tools include removed; CadQuery-free
  runtime scan no longer needs the auto_tools filter
- run_examples.py retired (user removal): README example-runner text
  updated to direct examples/ scripts; dangling runner-contract test
  (runpy.run_path into the deleted script) removed

Verified: 53 tests pass (auto_docs_gen + skill_build + ocp runtime
scan) and test_example_model_contract passes; regeneration from
tools/ is byte-identical (zero docs drift).

* refactor(skill): strip harness and build-tool content from the skill tree

The skill is plain harness-neutral content again:
- SKILL.md 'Reading skill files' section removed (the omp skill://
  mount block and its !omp complement were the only conditional
  blocks; the tree compiles identically for every target now)
- references/README.md: build-tool meta removed ('per-harness
  conditional compilation', skillbuild packaging/validation claims —
  link validation was never implemented, so the claim was false)
- live test now asserts the tree stays harness-neutral (zero blocks)
- skillproj.toml targets aligned with the user's output table
  (omp -> skills/simplecadapi-omp, opencode -> skills/simplecadapi-opencode;
  leftover 'generic' entry had no output and failed the build)
- compiled outputs are regenerable artifacts: skills/simplecadapi/
  untracked from git, skills/simplecadapi-*/ gitignored, release.yml
  and README build via skillbuild and tar the omp output directly
  (bsdtar has no --transform; inner dir keeps its suffixed name)

Verified: 49 tests pass; both targets build 372 files with zero
conditional blocks; no omp/conditional/directive residue in the tree
or outputs.

* chore(docs): drop stale architecture review and design notes
This commit is contained in:
Ni Jingzhe
2026-08-22 20:20:49 +08:00
committed by GitHub
parent dbcb145125
commit c454a3af10
770 changed files with 876 additions and 17893 deletions
+4 -2
View File
@@ -80,8 +80,10 @@ jobs:
run: uv run twine check dist/*
- name: Build and verify Agent Skill archive
run: |
uv run skill-pack --refresh-docs --archive
uv run pytest test/test_skill_pack.py -q
uv run python tools/auto_docs_gen.py --quiet
uv run python tools/skillbuild.py --target omp
uv run pytest test/test_skill_build.py -q
tar -C skills -czf skills/simplecadapi.tar.gz simplecadapi-omp
- name: Create GitHub release
+3
View File
@@ -20,6 +20,9 @@ design-doc/
# Generated skills archives
skills/*.tar.gz
# Compiled per-harness skill outputs (built by tools/skillbuild.py)
skills/simplecadapi-*/
.DS_Store
# CAD/export artifacts
-2
View File
@@ -11,8 +11,6 @@ recursive-include src *.py
recursive-include src/simplecadapi/scene/contracts *.json *.md
include src/simplecadapi/py.typed
recursive-include src/auto_tools *.py
# 排除不需要的文件
exclude .python-version
exclude uv.lock
+20 -18
View File
@@ -17,8 +17,7 @@ See the [full English update notes](docs/updates/2.0.4b3.md) for contracts,
cache modes, diagnostics, limitations, and verification coverage.
All formal single-script examples emit a synchronized `.scadpkg`, AP242
`.step`, and editable `.FCStd` from the same product package. Run
`uv run python tools/run_examples.py` to rebuild and validate that set. The
`.step`, and editable `.FCStd` from the same product package. The
split AP242/Gmsh example under `examples/12_ap242_gmsh_volume_mesh/` exposes
each build and export stage as a separate directly runnable script.
@@ -393,32 +392,35 @@ uv run python examples/20_integrated_bldc_joint_actuator/main.py
## Releasing the Agent Skill
The repository includes a thin Agent Skill under `skills/simplecadapi/`. It
contains generated API and modeling references, but does not bundle the SDK
source code.
The skill source tree lives under `docs/skill/` and stays harness-neutral.
`tools/skillbuild.py` compiles it per harness target (targets and output
directories are configured in `skillproj.toml`; the outputs under
`skills/simplecadapi-*/` are regenerable build artifacts and are not
committed). Harness-specific text, when it is ever needed, is marked with
`<!-- skill:if ... -->` conditional blocks that compile per target.
From a clean checkout, update the project version and documentation, then build
and validate the release artifacts:
From a clean checkout, update the project version and documentation, then
build and validate the release artifacts:
```bash
uv sync --group dev
uv run skill-pack --refresh-docs --archive
uv run python -m pytest test/test_skill_pack.py
uv run python tools/auto_docs_gen.py --quiet
uv run python tools/skillbuild.py --target omp
uv run pytest test/test_skill_build.py
tar -C skills -czf skills/simplecadapi.tar.gz simplecadapi-omp
```
The command refreshes the generated docs, rewrites `skills/simplecadapi/`, and
creates `skills/simplecadapi.tar.gz`. Review the generated `SKILL.md` and
references before release:
The commands regenerate the API references inside the skill tree, recompile
the omp target, and create `skills/simplecadapi.tar.gz`. Review the source
tree and the compiled output before release:
```bash
git diff -- skills/simplecadapi docs
tar -tzf skills/simplecadapi.tar.gz
git diff -- docs/skill
tar -tzf skills/simplecadapi.tar.gz | head
```
Commit the generated `skills/simplecadapi/` directory and refreshed `docs/`
with the release. The archive is intentionally ignored by Git; attach
`skills/simplecadapi.tar.gz` to the corresponding GitHub release or distribute
it through the target Agent Skills registry.
Commit only the `docs/skill/` source tree; the release workflow builds the
harness outputs and uploads the archive to the GitHub release.
## Development
@@ -1,365 +0,0 @@
# SimpleCADAPI SDK 架构评价报告
日期:2026-05-21
视角:函数式风格 programmer + CAD 软件架构师
前提:本报告认同并保留 SimpleCADAPI 的顶层 API 风格。`make_*_r*`、`*_rsolid`、`*_rwire`、`GraphSession`、`export_model_json` 这一套方向不是问题本身,反而是这个 SDK 最有价值的部分。真正的问题在于:内部实现还没有完全配得上这个顶层风格所暗示的稳定性、可组合性和可重放性。
## 总结判断
SimpleCADAPI 的顶层 API 选择是正确的:它没有把用户拖进传统 CAD kernel 的继承层级和 builder 生命周期,而是用一组接近纯函数的建模函数表达几何变换。这是适合 Python、适合自动化、适合 LLM/脚本生成、也适合未来 GUI 低代码编排的 API 形态。
但当前架构的真实状态是:顶层像函数式 CAD DSL,底层仍是“带全局上下文、带隐藏运行时元数据、带 OCC 对象身份、带启发式 replay”的工程拼装体。它能跑通大量示例,但还没有形成足够硬的 CAD SDK 契约。最危险的地方不是 primitive 建模能力,而是拓扑命名、选择语义、replay 严格性、装配求解、schema 稳定性和测试强度。
如果用一句话评价:这是一个有正确 API 直觉的 OCP-native CAD SDK 原型,已经越过玩具阶段,但还没有越过“可靠参数化 CAD 平台”的门槛。
## 评价边界
本报告基于当前仓库源码、文档、示例和测试,不评价尚未落地的设想。
主要检查对象:
- `src/simplecadapi/__init__.py`
- `src/simplecadapi/core.py`
- `src/simplecadapi/operations.py`
- `src/simplecadapi/graph.py`
- `src/simplecadapi/serializer.py`
- `src/simplecadapi/topology.py`
- `src/simplecadapi/tracking.py`
- `src/simplecadapi/ql.py`
- `src/simplecadapi/tagging.py`
- historical assembly/constraint implementation, now removed from the active public/support surface
- historical scalar-field/SDF implementation, now removed from the active public/support surface
- `docs/core/serialization/`
- `docs/core/operation_graph_json_spec.md`
- retained replayable examples under `examples/`
- `test/` 与 `tests/`
## 顶层 API 评价
顶层 API 的方向值得保留。
`make_box_rsolid(...)`、`make_line_redge(...)`、`extrude_rsolid(...)`、`union_rsolid(...)` 这种命名确实有点“硬”,但它有一个重要优点:它把 CAD 操作建模成从参数到几何值的映射,返回类型在名字里显式出现。对脚本、生成式建模、图记录、schema 生成和 IDE 补全来说,这比传统 OOP fluent builder 更稳定。
强项:
- `__init__.py` 明确导出建模函数、核心类型、graph/session、serializer、expression 和 `ql` 子模块,公开面可见性好。参考:`src/simplecadapi/__init__.py`。
- 大多数核心创建函数遵守返回类型后缀,例如 `make_point_rvertex -> Vertex`、`make_line_redge -> Edge`、`make_circle_rwire -> Wire`、`make_box_rsolid -> Solid`。参考:`src/simplecadapi/operations.py:691`、`src/simplecadapi/operations.py:723`、`src/simplecadapi/operations.py:1465`。
- composite convenience API 在 `GraphSession` 内降低为 canonical low-level graph,这个设计非常正确。用户调用 `make_box_rsolid`,图里记录 rectangle/profile/extrude,这是 CAD DSL 和 replay IR 分层的正确方式。参考:`src/simplecadapi/operations.py` 与 `test/test_serialization.py`。
- `union_rsolid(...)` 明确返回单个 `Solid`,失败就报错,不默默返回多个实体。这对机械 CAD 是正确的默认语义。参考:`src/simplecadapi/operations.py:2856`、`src/simplecadapi/operations.py:2876`。
- `GraphSession` + `export_model_json` + `replay_model_json` 的主线是对的。它把脚本建模提升为可交换、可 replay 的模型记录。参考:`src/simplecadapi/graph.py:44`、`src/simplecadapi/serializer.py:416`、`src/simplecadapi/serializer.py:732`。
- `ql` 被放到子模块而非全部塞进顶层,是正确的边界意识。参考:`src/simplecadapi/__init__.py`、`docs/api/README.md:5`。
当前问题与已完成清理:
- 已完成:顶层 convenience aliases 以及 `export_step`、`export_stl`、`to_step`、`to_stl` 已从公开面移除,不保留兼容转发。
- 已完成:持久产品只通过 `capture(result, path)` 写出 `.scadpkg`;STEP、STL 和原生 CAD 输出从该产品包显式派生。
- 仍需关注:`rsolidlist` 命名混杂了“参数类型”和“返回类型”:`cut_rsolid`、`intersect_rsolid` 实际返回 `Solid`,而 `linear_pattern_rsolidlist` 返回 `List[Solid]`。
- 仍需关注:public op 名和 graph op 名不完全一致,例如 `translate_shape` 记录为 `make_translate_rshape`,`extrude_rsolid` 记录为 `make_extrude_rsolid`;这种分层需要稳定的 source API 到 canonical IR 映射。
- 仍需关注:部分非 session 分支记录的 graph op 命名与 canonical `make_*_r*` 形式不一致,需要继续收敛。
后续重点是稳定 source API 到 canonical graph op 的映射,并在下一次不兼容版本中清理剩余历史命名。
## 函数式架构评价
顶层是函数式的,底层不是。
从函数式 programmer 的角度看,这套 SDK 最好的设计是“操作返回新几何值,而不是用户手动驱动 mutable builder”。但当前实现中,几何值本身携带大量隐藏可变状态:tags、metadata、runtime graph node、topo refs、track summary。这不是不能接受,但必须承认它是 effect system,而不是纯函数系统。
可取之处:
- `operations.py` 的 `_finalize_primitive_shape`、`_finalize_derived_shape`、`_finalize_tracked_solid` 把 graph recording、semantic delta、tracking summary 收敛到少数 finalizer。这个方向正确。参考:`src/simplecadapi/operations.py:597`、`src/simplecadapi/operations.py:629`、`src/simplecadapi/operations.py:650`。
- 旧 `ScalarField` 尝试用 frozen dataclass 表达隐式建模 AST;该 surface 已移除,后续如恢复需先统一 SDF 语义。
- `ShapeSelector`、`SerializablePredicate`、`SerializableKey` 都是 dataclass/frozen 风格,QL 作为可序列化 AST 的方向正确。参考:`src/simplecadapi/ql.py:258`、`src/simplecadapi/ql.py:320`、`src/simplecadapi/ql.py:396`。
问题:
- 已解决:`GraphSession` 的 active session 与 recording suspend depth 使用 `ContextVar`,嵌套和异步任务按执行上下文隔离。
- 已解决:`SimpleWorkplane` 使用 `ContextVar` 帧栈;上下文退出通过 token 精确恢复父帧。
- `attach_graph_node` 会把 graph node、node id、output slot、topo ref 写入 shape runtime/metadata。这个副作用是设计核心,但它破坏了“同样输入得到同样纯值”的直觉。参考:`src/simplecadapi/graph.py:231`、`src/simplecadapi/graph.py:247`、`src/simplecadapi/graph.py:259`。
- tagging 已收敛到 `apply_tag(shape, tag)` / `list_tags(shape)` 的 functional public surface;底层仍然是对 shape tag store 的受控 mutation,需要在 docs 中明确这是 controlled tagging effect。
- 已解决:`GraphSession` 节点记录完整合成的 `context`,replay 通过 `use_coordinate_system(node.context)` 恢复工作平面;嵌套 Workplane 与 sketch creation frame 已有 model JSON 回归。
函数式层面的根本建议:把 `GraphSession`、workplane、tag/metadata/runtime 都明确视为 effect context,并用 `contextvars` 或显式 session 参数隔离;公开文档不要暗示全纯函数,而要说“functional surface with controlled recording/tagging effects”。
## CAD Kernel 边界评价
这套 SDK 是 OCP-native,不是 kernel-agnostic。这一点没有问题,但必须讲清楚。
优点:
- wrapper 很薄,直接包 OCP TopoDS,性能和能力不会被中间抽象拖死。参考:`src/simplecadapi/core.py:422`、`src/simplecadapi/core.py:465`、`src/simplecadapi/core.py:597`、`src/simplecadapi/core.py:713`。
- `kernel/` 目录已经把 builders、booleans、curves、features、mesh、properties、topology、transforms、export 分层出来,比把所有 OCP 调用塞到 `operations.py` 更可维护。参考:`src/simplecadapi/kernel/ocp_booleans.py:1`、`src/simplecadapi/kernel/ocp_features.py`、`src/simplecadapi/kernel/ocp_transforms.py`。
- tests 已经明确防止 CadQuery 依赖回流,这是好边界。参考:`tests/test_ocp_core_no_cadquery.py:9`。
问题:
- `.wrapped` 是公开事实,docs 也承认 public geometry wrappers expose `.wrapped`。这不是错,但这意味着 SDK 没有真正封装 kernel,只是提供了 OCP-native convenience layer。参考:`docs/core/README.md:5`、`src/simplecadapi/core.py:427`、`src/simplecadapi/core.py:718`。
- QL 内部直接用 OCP adaptor 判断 curve/surface type。这个实现合理,但进一步证明 QL 当前绑定 OCP 语义,而不是中立 CAD 语义。参考:`src/simplecadapi/ql.py:193`。
- 旧 constraints 实现直接用 OCP transform 重建 solid,装配层和 kernel 层耦合很深;该 public/support surface 已移除,等待新契约重做。
- `operations.py` 仍然直接 import OCP builder 类型并手写部分 kernel 操作。kernel adapter 层还没有完全收敛。参考:`src/simplecadapi/operations.py:14`、`src/simplecadapi/operations.py:17`。
建议:不要假装 kernel-agnostic。短期应该明确定位为 OCP-native functional SDK。中期把 `operations.py` 中剩余 OCP 直接调用继续下沉到 `kernel/`,让 public ops 只做参数验证、effect finalization 和 semantic recording。
## 拓扑身份与命名
这是当前最核心的 CAD 风险。
CAD SDK 真正难的不是画 box、cylinder、extrude,而是模型变化后还能稳定地说“我要这个孔的圆边”“我要这个安装面”。当前 SimpleCADAPI 已经意识到这个问题,但实现还没有解决它。
已有基础:
- `_TopologyEntityCache` 用 OCC `HashCode` bucket 加 `IsSame` 做同一 shape occurrence 的合并,能让一个 box 的 shared edge occurrences 共享 topo id。参考:`src/simplecadapi/core.py:42`、`tests/test_topology_identity.py:16`。
- `TopoRef`、`TopoDelta`、`TopoEntry`、`SemanticDelta` 数据模型已经存在,说明架构上知道需要 graph-aware topology references。参考:`src/simplecadapi/topology.py:60`、`src/simplecadapi/topology.py:203`、`src/simplecadapi/topology.py:223`。
- `tracking.py` 直接查询 OCC builder 的 `Modified()`、`Generated()`、`IsDeleted()`、`SectionEdges()`,方向正确。参考:`src/simplecadapi/tracking.py:1`、`src/simplecadapi/tracking.py:107`。
硬伤:
- `TopoRef.topo_id` 文档自己承认 implementation-defined,可能是 sequential integer、hash 等。这不够 durable。参考:`src/simplecadapi/topology.py:69`。
- `_safe_shape_hash` 使用 `HashCode(1000000)`,fallback 是 `hash(shape)`。这只能做运行期/构建期身份辅助,不能做跨 replay 稳定身份。参考:`src/simplecadapi/core.py:22`。
- `TaggedMixin.topo_id` 在无 entity 时 fallback 到 `id(self)`,这是进程内对象身份,不是 CAD 拓扑身份。参考:`src/simplecadapi/core.py:321`。
- `tracking._topo_id` 也使用 OCC hash,并且注释叫 “Stable-ish”。这句话本身就是风险说明。参考:`src/simplecadapi/tracking.py:80`。
- `TopoEntry` 支持 richer lineage,但 `tracking._build_boolean_result` 只把 rich entries 放进 `delta_entries` dict,没有填入 `TopoDelta.entries`。导出时 `export_model_json` 只序列化 `node.topo_delta`,丰富 lineage 没有成为 durable graph contract。参考:`src/simplecadapi/tracking.py:283`、`src/simplecadapi/tracking.py:291`、`src/simplecadapi/serializer.py:480`。
- boolean、fillet、chamfer、shell 后的 topology tracking 是有用的,但不是 stable topology naming system。它记录了 OCC 的历史回答,不等于建立了语义身份。
结论:当前拓扑身份适合调试、局部 selection replay 和轻量 semantic tagging,不适合作为长期参数化模型的核心契约。必须尽快把 QL/SelectionSpec 作为 primary identity,把 raw topo refs 降级为 fallback。
## QL 与选择语义
QL 是架构上最应该继续投资的部分。
好处:
- QL 已经有 serializable predicate、serializable key、selector、order、limit、exactly cardinality。参考:`src/simplecadapi/ql.py:258`、`src/simplecadapi/ql.py:320`、`src/simplecadapi/ql.py:396`。
- QL 支持 tag/meta/property/curve_type/surface_type/normal/center/length/area/volume 等基础语义。参考:`src/simplecadapi/ql.py:77`、`src/simplecadapi/ql.py:94`、`src/simplecadapi/ql.py:125`。
- fillet/chamfer/shell 现在会把 QL selector 的运行时结果编译为 `make_select_*` geo select nodes;`selection_query` 仅保留为旧 payload fallback。参考:`test/test_serialization.py:443`、`src/simplecadapi/serializer.py:1365`。
问题:
- QL graph scope 现在通过 `make_select_*` 节点的 source input 表达,而不是只靠 query AST;未来还需要把这个契约扩展到非 detail-feature 的通用 selection 工作流。
- 当前 replay resolution order 已经变为 geo select nodes -> selection_query fallback -> topo refs -> indices -> hint;后续风险主要是外部 adapter 需要跟进新顺序。
- 只有 `exactly(n)`,没有 `at_least`、`at_most`,cardinality 还不够表达真实 CAD 选择约束。参考:`src/simplecadapi/ql.py:457`。
- ordering 只有单 key,不支持 lexicographic multi-key。复杂 CAD 选择里单 key 很容易产生不稳定 tie。参考:`src/simplecadapi/ql.py:429`。
- `_shape_identity` 仍然优先用 topo id 或 topo_ref metadata,说明 QL 运行时仍被当前 topology identity 牵引。参考:`src/simplecadapi/ql.py:566`。
建议:把 `SelectionSpec` 做成正式 schema:source scope、query AST、多 key order、limit、cardinality、fallback。所有接受 `List[Edge]`、`List[Face]` 的 feature API,在 GraphSession 内都应该 normalize 成 SelectionSpec。replay 必须 QL first,topo refs/indices/hints 只能 fallback。
## Graph、Serialization 与 Replay
这是 SDK 的战略性资产,也是当前最需要变硬的契约。
做得好的地方:
- `OperationGraph` 是 DAG,节点保存 op、params、param_exprs、inputs、context、semantic_delta、topo_delta、tags。结构完整。参考:`src/simplecadapi/topology.py:318`、`src/simplecadapi/topology.py:476`。
- `export_model_json` 输出 graph、leaf_ids、expression_graph、frame_graph、registries、delta logs、canonical contract。方向很对。参考:`src/simplecadapi/serializer.py:627`。
- `_assert_graph_is_canonical` 在 export model 前拒绝非 canonical ops,这是保持 IR 干净的正确动作。参考:`src/simplecadapi/serializer.py:246`、`src/simplecadapi/serializer.py:624`。
- `test/test_serialization.py` 系统覆盖 source API 到 operation tree 的映射,是该契约的主要回归入口。
严重问题:
- replay 过于宽松。多个 replay 分支在输入缺失时 `continue`,最终 leaf collection 用 `outputs.get(node_id, [])`。坏图可能静默变成少输出或空输出。参考:`src/simplecadapi/serializer.py:1018`、`src/simplecadapi/serializer.py:1051`、`src/simplecadapi/serializer.py:1294`。
- primitive replay 使用 permissive defaults。缺少 `x` 就默认为 0,缺少 radius 就默认为 1。这会把坏 JSON 变成错误几何,而不是报错。参考:`src/simplecadapi/serializer.py:767`。
- `OperationGraph.from_dict` 对 edges 和 inputs 的缺失引用采取静默跳过。对 interchange schema 来说这太软。参考:`src/simplecadapi/topology.py:692`、`src/simplecadapi/topology.py:701`。
- graph schema version 是 `1.0`,model schema 是 `2.0-draft`,canonical contract 是 `2.0-final-state`。这三个版本信号混在一起,会让外部消费者不知道哪个才是稳定承诺。参考:`src/simplecadapi/topology.py:19`、`src/simplecadapi/serializer.py:221`、`src/simplecadapi/serializer.py:628`。
- 已解决:node replay 进入记录时的完整合成 `context`;`frame_graph` 保留相同的绝对帧快照供外部消费者使用。
- `leaf_ids` 自动来自 graph leaves,而不是用户显式声明的 final outputs。debug/intermediate 独立节点会成为 replay 输出。参考:`src/simplecadapi/serializer.py:624`、`src/simplecadapi/topology.py:563`。
- expression replay 是 numeric snapshot,不是 parametric replay。这个可以接受,但必须在 SDK 主文档里反复强调。参考:`test/test_serialization.py`。
建议:replay 应该默认 strict。所有 missing input、missing param、unknown op、leaf missing output、selection cardinality mismatch 都应该 hard failure。需要宽松模式时显式 `strict=False`。
## Boolean 与 Feature Tracking
当前 boolean API 的用户语义比很多 CAD wrapper 都清楚,但 tracking 和 replay 还不够可信。
优点:
- `union_rsolid` flatten nested inputs,使用 scale-aware fuzzy tolerance,支持 glue,默认 clean,并强制单 solid。参考:`src/simplecadapi/operations.py:221`、`src/simplecadapi/operations.py:2856`、`src/simplecadapi/kernel/ocp_booleans.py:40`。
- `fuse_shapes` 使用 OCC Fuse、parallel、OBB、fuzzy value、GlueShift 和 same-domain cleanup,基本工程判断正确。参考:`src/simplecadapi/kernel/ocp_booleans.py:45`。
- `tracked_cut`、`tracked_union`、`tracked_intersect` 使用 OCC history,这比只比较结果 faces 靠谱。参考:`src/simplecadapi/tracking.py:308`、`src/simplecadapi/tracking.py:338`、`src/simplecadapi/tracking.py:374`。
问题:
- `tracked_union` 接收 `glue` 和 `tol`,但没有把它们设置到 `BRepAlgoAPI_Fuse`。也就是说用于结果的 union 和用于 tracking 的 union 参数可能不一致。参考:`src/simplecadapi/tracking.py:338`、`src/simplecadapi/tracking.py:352`。
- `union_rsolid` replay 忽略记录过的 `clean`、`glue`、`tol`,只调用 `ops.union_rsolid(all_solids)`。参数不 faithful。参考:`src/simplecadapi/operations.py:2946`、`src/simplecadapi/serializer.py:1029`。
- `cut_rsolid` 对无交集 tool 直接跳过,这对 modeling convenience 可能友好,但对 replay/diagnostic 来说可能隐藏错误。参考:`src/simplecadapi/operations.py:3033`。
- 多 tool cut/intersect 只保留最后一次 delta,前面 tool 的 lineage 丢失。参考:`src/simplecadapi/operations.py:3020`、`src/simplecadapi/operations.py:3127`。
- extrude face classification 使用 center 精确相等、normal dot 精确等于 0、angle 精确等于 pi,这在 CAD 数值几何里非常脆弱。参考:`src/simplecadapi/operations.py:2631`、`src/simplecadapi/operations.py:2646`、`src/simplecadapi/operations.py:2653`。
建议:boolean result 和 boolean tracking 必须用同一 builder 或至少同一参数配置;replay 必须重放 boolean params;feature tagging 不应靠 exact float equality,应使用 tolerance 和 topology history。
## Tagging 与 Metadata
tagging 的目标是对的,但现在新旧体系混在一起。
优点:
- `tagging.py` 定义了 normalized tag grammar 和 `TagPolicy`,这是 QL 和 anchor semantics 的基础。参考:`src/simplecadapi/tagging.py:8`、`src/simplecadapi/tagging.py:58`。
- `apply_tag(shape, tag)` / `list_tags(shape)` 是唯一推荐的 public tagging surface,`list_tags` 输出稳定排序。
- 当前约定是不在 tags 中存数字,而是在 metadata[`geo`] 中保存结构化几何事实。
问题:
- QL、anchor lookup、auto tagging、metadata[`geo`] 之间还需要一个正式 schema 文档把它们串起来。
- tagging 仍然是 shape-local side effect;graph/session replay 文档应继续明确哪些 tags 会进入 serialized selector hints。
建议:建立 tag schema version。新代码只产生 normalized tags,旧 tags 标成 `legacy.*` 或仅作为 lookup fallback。
## Assembly 与 Constraints
旧装配 API 的顶层形态有可取之处,但 solver 只是 MVP;该 surface 已移除,等待基于新 assembly IR / constraint graph 重做。
优点:
- assembly 层和 geometry construction 分开,这是正确的 CAD 架构。geometry API 做 integrated parts,未来 assembly constraints 做最终空间关系。
- anchor/part handle 这类表达形式可以作为新设计参考,但不能直接恢复旧实现。
- solved snapshot 的函数式方向可以保留,但需要新的 solver contract 支撑。
问题:
- 旧 solver 是顺序应用约束的迭代 pose adjustment,不是 DOF solver、不是约束图求解器、没有 Jacobian/least-squares、没有 overconstraint/underconstraint 严格诊断。
- 旧 diagnostics 主要只有 non-convergence 和 unconstrained parts。对真实机械装配不够。
- 旧 bbox anchor 基于 local AABB,旋转或复杂形体下语义会很粗糙。
- 旧 `export_model_json` assembly frame 摘要不完整,因此已从当前 schema 中撤回。
建议:把当前 assembly 文档称为 “layout constraints” 或 “MVP rigid pose helper”,不要称成熟 assembly solver。下一步优先修 export frame rotation,然后再谈 DOF solver。
## Scalar Field 与 Implicit Modeling
旧 scalar field/SDF surface 已移除;下面记录的是移除前的历史评审结论。
优点:
- 旧 `ScalarField` tree 曾尝试做可序列化/replay 的隐式建模表达。
- 旧 `make_field_surface_rsolid` 曾区分 replayable scalar field tree 和 opaque callable。
问题:
- sphere 返回平方距离减 `r^2`,box/capsule 接近 signed distance。smooth union/subtract 假设 field value 单位可比,但这里不成立。
- `scale` 使用 min scale 乘回 field value,对非 SDF field 更不稳定。
- 这意味着 implicit smooth operations 目前更像 demo/experimental,而不是可靠 SDF modeling kernel。
建议:明确 `ScalarField` 是 algebraic implicit field 还是 true SDF。若要支持 smooth booleans,必须统一到 SDF 或至少在每个 primitive 标记 value metric,并拒绝不兼容 smooth blend。
## 错误模型与 Developer Experience
优点:
- public operations 大量使用 `raise_harness_error` 包装上下文,错误信息对脚本用户友好。参考:`src/simplecadapi/operations.py:204`。
- import/replay 的错误也有 what happened / possible causes / how to fix,这对 SDK 很有价值。参考:`src/simplecadapi/serializer.py:345`、`src/simplecadapi/serializer.py:743`。
问题:
- 一些地方直接 `print` warning,而不是走 warning/error policy。参考:`src/simplecadapi/core.py:787`、`src/simplecadapi/core.py:808`。
- 一些 tracking 异常被吞掉,例如 union tracking 失败就继续记录无 delta。这对 robustness 友好,但对 auditability 很差。参考:`src/simplecadapi/operations.py:2930`。
- replay 对 malformed graph 静默跳过比报错更危险。参考:`src/simplecadapi/serializer.py:1018`。
建议:区分 user modeling error、kernel failure、replay schema error、tracking degraded warning。replay/schema 默认必须严格。
## 测试体系评价
测试覆盖了很多 API,但 CAD robustness 测试还不够狠。
已有价值:
- 有 no-CadQuery boundary test。参考:`tests/test_ocp_core_no_cadquery.py:9`。
- 有 topology occurrence identity test。参考:`tests/test_topology_identity.py:16`。
- 有 graph serialization/replay tests,包括 QL selector replay、mirror、sweep、pattern 等。参考:`test/test_serialization.py:233`、`test/test_serialization.py:420`、`test/test_serialization.py:491`。
不足:
- 一些断言是无效断言,如 `len(modified) >= 0`、`len(tagged) >= 0`,这永远成立。参考:`test/test_original_api_integration.py:23`、`test/test_original_api_integration.py:50`。
- topology identity 测试只证明单个 box 内 shared edge occurrence,不证明跨 operation、跨 replay、跨 boolean 的 durable identity。参考:`tests/test_topology_identity.py:16`。
- replay 已覆盖 malformed graph、missing inputs、schema rejection、嵌套 workplane context 和 selection ambiguity;跨 translator 的 frame 语义仍需持续验证。
- assembly tests没有证明 overconstraint/underconstraint、DOF、rotation frame export 的正确性。
建议优先加这些测试:
- [x] GraphSession active session、recording suspension 与嵌套恢复使用 context-local 状态。
- [x] SimpleWorkplane 内记录后在 world context replay,结果一致,包括两层非共轴嵌套和退出上下文后的 sketch promotion。
- replay missing param 必须报错,不允许默认生成几何。
- replay missing input 必须报错。
- union clean/glue/tol 参数 replay faithful。
- QL selection ambiguity 必须按 cardinality 报错。
- boolean tracking result 和 actual result 用同一参数。
- assembly frame export 必须保留旋转轴。
- scalar field smooth union 拒绝混合非同量纲 field 或统一 SDF。
## 最重要的架构矛盾
SimpleCADAPI 当前最大的矛盾不是“函数式 API vs OOP core”。薄 wrapper core 可以接受。
真正的矛盾是:顶层 API 和 v2 model JSON 暗示了稳定、可 replay、可交换的 CAD DSL,但底层仍依赖隐式全局状态、runtime metadata、OCC hash、fallback indices、permissive defaults 和非严格 replay。
这会带来一个危险结果:demo 看起来很强,复杂模型一旦进入参数变化、拓扑变化、跨进程 replay、GUI roundtrip、自动生成代码迭代,就会出现“没报错但选错面/少输出/变成不同模型”的问题。对 CAD 来说,静默错误比显式失败更糟。
## 优先级建议
P0:把 replay 变 strict。
- 缺参数直接报错。
- 缺输入直接报错。
- leaf id 没 output 直接报错。
- unknown op 直接报错。
- selection cardinality mismatch 直接报错。
- 保留 permissive replay 也必须显式 opt-in。
P0:修 GraphSession 和 workplane context。
- `_active_session` 已改为 `ContextVar`,并用 token 恢复父 session。
- `_recording_suspend_depth` 已改为 context-local 计数器。
- `_current_cs` 已改为 `ContextVar` 栈,并在子 Workplane 创建时合成父帧。
- replay 已使用 `node.context` 重建坐标上下文;`frame_graph` 保留供外部转译器消费。
P0:把 QL/SelectionSpec 升为 canonical selection。
- SelectionSpec 加 source node/output slot。
- replay 改成 QL first。
- topo refs、indices、hints 只做 fallback。
- 支持 multi-key order。
- 支持 `at_least`、`at_most`。
P1:统一 canonical op 和 schema version。
- 明确 source API、canonical graph op、model JSON schema 三层。
- 移除或隔离 legacy op names。
- `2.0-draft`、`2.0-final-state` 不要混用。
- canonical op coverage 变成测试强约束。
P1:修 boolean/tracking/replay faithful。
- tracking builder 和 actual boolean builder 使用相同参数。
- union replay 传回 `clean`、`glue`、`tol`。
- multi-tool cut/intersect 保留完整 delta chain。
- 无交集 tool 是否跳过应由参数控制,Graph replay 默认不跳过。
P1:收敛 tag schema。
- normalized tags 成为默认。
- legacy numeric tags 移出 tags,放 metadata[`geo`]。
- anchor lookup 明确 role > anchor > face/edge/wire > legacy。
- QL docs 使用 normalized tags。
P2:装配系统诚实命名并逐步增强。
- 当前称 layout solver,不称完整 assembly solver。
- 先修 frame export rotation。
- 再做 DOF/overconstraint diagnostics。
P2:scalar field 数学语义统一。
- 决定是否承诺 SDF。
- smooth booleans 只允许可比 distance fields。
- surface extraction 对 closure/validity 给硬失败或明确 warning。
## 最终评价
这套 SDK 最值得肯定的是 API 直觉:用函数表达 CAD 操作,用返回类型后缀表达几何类型,用 GraphSession 捕获建模过程,用 model JSON 做 replay 边界。这条路线是对的,不应该推翻。
最需要批评的是工程契约:它现在过于相信 OCC runtime identity,过于容忍 replay 缺失,过于依赖 hidden mutable metadata,过早把 draft schema 包装成 canonical contract,过少用失败来保护用户。
CAD 软件架构里,能建出模型只是第一层;能在参数变化后稳定找到同一个语义面,能跨进程 replay 出同一个设计,能在选择歧义时拒绝继续,能在 schema 损坏时报错,才是 SDK 级别的可靠性。
SimpleCADAPI 已经有正确的外形和几块关键骨架。下一阶段不应该继续堆更多 primitive,而应该把 graph、selection、topology、schema、test 这些基础层做硬。否则 API 越漂亮,用户越容易误以为它已经是稳定 CAD 平台。
最终判断:保留顶层 API,收紧内部契约;少加功能,多加确定性;少相信对象身份,多表达语义选择;少 silent fallback,多 fail fast。
@@ -1,103 +0,0 @@
# Translator Backend Contract
This contract defines the package structure and dependency boundaries for every
SimpleCAD translator backend.
## Backend Naming
Backend packages live under `simplecadapi.translator` and use the name
`<backend>_translator`, where `<backend>` is a stable lowercase backend ID.
Examples:
- `freecad_translator`
- `openscad_translator`
- `onshape_translator`
Backends are exported explicitly from `simplecadapi.translator`. Importing a
backend package must not require the target CAD runtime to be installed.
## Required Files
Every backend package contains:
| File | Responsibility |
| --- | --- |
| `__init__.py` | Defines the complete public backend surface through `__all__`. |
| `api.py` | Contains public convenience functions and user-facing error boundaries. |
| `translator.py` | Contains the `<Backend>Translator` implementation. |
| `capabilities.py` | Declares backend targets and support for every canonical operation. |
The translator class must inherit `BaseTranslator`. `capabilities.py` exports
`BACKEND_NAME`, `CAPABILITIES`, and `OP_SUPPORT`. The operation support map must
contain exactly the canonical operation set. Unsupported operations require a
non-empty reason.
## Conditional Files
Use these standard names when the corresponding responsibility exists:
| File or directory | Responsibility |
| --- | --- |
| `exporter.py` | File output, external process or remote API execution, and output validation. |
| `context.py` | State owned by one translation invocation. |
| `analysis.py` | Backend-specific graph analysis and lowering decisions. |
| `codegen.py` | Pure target-code formatting and literal helpers. |
| `emitters/` | Canonical operation emitters and their single registry. |
| `runtime/` | Source fragments embedded into an artifact for execution in the target runtime. |
An `emitters/registry.py` file is the only operation-to-emitter mapping. Runtime
fragments must remain valid Python source, must not execute target APIs when the
SimpleCAD package is imported, and must be assembled in one declared order.
## Translation And Export
Translation is an in-memory operation over a validated product-package closure.
It consumes `ProductPackageInput` and returns a `TranslationArtifact` containing
the target script or native artifact description.
Export is an effectful operation. It may write files, invoke an executable, or
call a remote API. Neutral product file effects belong in `simplecadapi.exporter`;
backend-specific executable effects belong in the backend exporter module.
Public naming follows these forms:
- `translate_product_package_to_<artifact>` for in-memory product translation.
- `export_product_package_to_<format>` for neutral product file output.
Standalone model JSON translation and export entrances are removed. Model JSON
remains a graph replay and inspection format, not a downstream CAD contract.
## Dependencies
The allowed dependency direction is:
```text
backend/__init__.py -> api.py, translator.py, capabilities.py
api.py -> translator.py, exporter.py
translator.py -> context.py, analysis.py, emitters/, runtime/
emitters/ -> context and pure code-generation helpers
exporter.py -> shared types/errors and external execution
```
The following reverse dependencies are prohibited:
- Translator or emitters importing `api.py`.
- Translator importing `exporter.py`.
- Emitters importing the public translator class.
- Runtime fragments importing the backend package.
- Capabilities importing translator implementation modules.
## Compatibility
The generated artifact and its persisted target metadata are treated as a
compatibility boundary. Pure module moves must not rename generated runtime
helpers, registries, target object properties, or public import paths. Behavior
fixes are made separately from structural migrations.
## Verification
The shared backend contract test verifies required files, public exports,
translator inheritance, backend naming, and canonical operation coverage.
Backend tests additionally verify generated artifact syntax and, where the
target runtime is available, real exported files.
-82
View File
@@ -1,82 +0,0 @@
# Public Connector Refactor
Status: complete
## Decision
An Assembly public connector is an interface declaration, not a second `Connector` object.
Users create the real connector on the direct child component first, then mark that connector as public:
```python
assembly = scad.set_public_connector_rassembly(
assembly,
public_connector_id="output_axis",
source_component_id="rotor",
source_connector_id="axis",
)
```
`set_public_connector_rassembly`:
- does not create or clone a `Connector`;
- does not accept an offset or geometry;
- does not move the source component;
- records only the public interface name and the direct-child source reference;
- requires the source component to already exist and the source connector to already exist;
- requires public IDs to be unique within the Assembly.
The source is a direct child component. A direct child Assembly may be used only through a connector that it exposes publicly; the public boundary remains one level at a time.
## Runtime contract
`Assembly` does not own a connector collection. Public declarations live in `Assembly.public_connectors` as immutable `PublicConnectorRef` values, while concrete `Connector` values remain owned by leaf `Part` instances.
A public reference contains:
```text
public_connector_id
source_component_id
source_connector_id
name (optional)
```
No offset is stored. The source connector owns its complete frame.
Resolving a parent constraint against a child Assembly public connector returns the real source connector plus its composed frame. The frame includes each direct component placement encountered while crossing nested public boundaries.
## Durable package contract
`AssemblyDefinition` stores public connector declarations under `public_connectors`. Each declaration stores the public ID, direct-child source reference, optional name, and a resolved frame snapshot used for validation and standalone consumers. It does not use `anchor_kind="forwarded"`, `forwarded_from`, or an offset.
The declaration and source connector are hashed as part of the Assembly interface. Changing the public name, source component, source connector, or resolved frame changes the Assembly interface hash and invalidates dependent builds.
## Solver contract
The solver resolves a public connector reference to the actual leaf connector and its world frame. Public declarations do not create a new rigid body, motion edge, or constraint. A public connector cannot make an internal component movable merely because a parent constraint references it; movement follows the existing assembly constraint graph.
This deliberately removes the old special case that descended through forwarded connectors to mutate a nested leaf placement. Nested mechanisms must expose and solve their own constraints before a parent consumes their public interface.
## Scene and exporters
Scene records distinguish connector ownership from public declarations. A public record references the source connector snapshot and carries the resolved frame for validation. Exporters use the source connector for semantic ownership and the resolved public frame for sites/joint consumers.
MJCF must not infer a joint from public exposure. Public declarations only identify externally visible sites/endpoints. Hinge/prismatic edges come from explicit assembly constraints.
## Translator and replay
The replay operation is `make_set_public_connector_rassembly`. Its parameters contain the public ID, source component ID, source connector ID, and optional name. There is no placement input and no offset branch.
## Migration policy
This is a clean cutover on the branch. Remove `forward_connector_rassembly`, the forwarded anchor kind, forwarded offsets, and translator/replay branches after all callers and durable schemas migrate. Do not leave aliases or deprecated compatibility paths.
## Progress
- [x] Confirm public semantics: declaration, no clone, no offset, direct child source.
- [x] Replace runtime Assembly public connector storage and resolution.
- [x] Migrate durable AssemblyDefinition and schemas.
- [x] Migrate solver and product-package construction.
- [x] Migrate scene compiler/validation and exporters.
- [x] Migrate serializer/replay and translators.
- [x] Migrate callers/tests and run end-to-end verification.
@@ -1,265 +0,0 @@
# STEP BREP Reverse Engineering
This document is the normative STEP BREP reverse-engineering reference shipped
with the SDK (repo path `docs/guides/step-brep-reverse-engineering.md`).
The inspection APIs live in:
```text
src/simplecadapi/inspect/brep/
```
All of these functions are diagnostic APIs, not modeling
operations: they do not record graph nodes and must not run inside a
`GraphSession`. Export or obtain the geometry under test first, then call them
outside the modeling script:
```python
from simplecadapi.inspect import brep
report = brep.inspect_step_rbrepinspection(path="part.step")
summary = brep.inspect_step_rsummary(path="part.step")
face = brep.inspect_step_entity_rdescriptor(
path="part.step",
entity_id="face:0",
)
neighborhood = brep.inspect_topology_neighborhood_rdescriptor(
model_or_path="part.step",
entity_id="face:0",
depth=2,
)
section = brep.inspect_section_rdescriptor(
model_or_path="part.step",
origin=[0, 0, 10],
normal=[0, 0, 1],
)
comparison = brep.compare_global_properties_rdescriptor(
target="target.step",
current="candidate.step",
)
evaluation = brep.evaluate_reconstruction_rdescriptor(
target="target.step",
current="candidate.step",
replay_succeeded=True,
)
fit = brep.fit_face_analytic_rdescriptor(
model_or_path="part.step",
face_id="face:0",
tolerance=1.0e-3,
)
tracks = brep.track_section_contours_rdescriptor(sections=[section_a, section_b])
image = brep.render_step_comparison_rpath(
target_step_path="target.step",
current_step_path="candidate.step",
output_path="comparison.png",
)
```
In `exact_brep_transcription` work, selected target faces can be copied outside
the modeling graph into a content-addressed `.scadbrep` sidecar:
```python
snapshot = brep.copy_step_region_rpath(
path="target.step",
output_path="freeform-body.scadbrep",
face_ids=["face:0", "face:1", "face:2"],
)
```
The selected face IDs must form one connected, valid Shell. The snapshot keeps
the existing carrier surfaces, trims, pcurves, shared edges/vertices,
orientations, and tolerances. It does not infer feature history and remains
target-derived. Omit `face_ids` to snapshot one complete valid Solid.
The replayable modeling program loads the hash-pinned sidecar without reading
the target STEP:
```python
import simplecadapi as scad
copied = scad.load_brep_region_rshell(
path="freeform-body.scadbrep",
sha256="sha256:...",
)
```
Model JSON records a relative sidecar path and SHA-256 but does not embed its
bytes; replay therefore resolves that path from the replay working directory.
GraphSession rejects absolute sidecar paths to avoid machine-specific model
JSON. Native BREP bytes are exact for the snapshot's pinned OCCT profile, not a
cross-version geometry hash. Use material and topology comparisons for
acceptance.
`inspect_step_rsummary` returns entity counts, bounding box, material
volume/area, centroid, and surface/curve type statistics.
`inspect_step_entity_rdescriptor` uses stable zero-based IDs (`body:0`,
`face:0`, `edge:0`, `vertex:0`) and returns geometry type, analytic
parameters, measurements, and adjacency. To reuse an index across many
queries, load the model first:
```python
model = brep.load_step_rbrepmodel(path="part.step")
summary = model.summary()
face = model.describe_entity("face:0")
neighbors = model.adjacency_details("face:0")
```
These IDs stay deterministic across repeated loads of the same unmodified
BREP, but they do not imply semantic correspondence between two different
models. Degenerate edges are reported uniformly as `DEGENERATE`, with the
underlying carrier type preserved in `underlying_curve_type`.
## Mindset: APIs are not a pipeline
The built-in inspect functions are composable APIs, not a fixed workflow, and
they do not guarantee coverage of every question. Reverse engineering has no
"standard pipeline": for a specific case, the agent must write case-by-case
inspection code as needed — load the model and traverse entities directly,
compose multiple queries, and write model-specific
sampling/projection/adjacency analysis — to obtain more detailed information
about that model that the built-in primitives do not cover. Primitives are the
starting point, not the endpoint.
## Acceptance and stopping conditions (descending priority)
1. **BREP topology identity = complete reverse engineering (best endpoint)**:
the geometric point set matches and the face-edge-vertex adjacency
structure matches. Reach it when you can.
2. **Identical BREP structure with slightly different parameters:
acceptable.** Export/serialization introduces floating-point error; minor
parameter-level deviations (last-digit differences in radii, distances,
etc.) are not failures and should not trigger further idle optimization.
3. **Structurally different but visually close BREP: a valid stopping
condition only when "genuinely unable to optimize further".**
"Genuinely unable to optimize further" is limited to the following two
reasons, with evidence recorded:
- no better feature operation order/combination can be found (feature-tree
hypotheses are exhausted);
- the required operation type is not yet supported by the SDK.
Otherwise, "looks close" is not a reason to stop; keep iterating.
## Choosing an inspection strategy per problem
There is no fixed reverse-engineering workflow to apply mechanically. First
clarify the current unknown and the acceptance evidence, then compose the
smallest set of primitives; for details the primitives do not cover, write
case-by-case inspection code for the model:
| Question | Preferred primitives |
|---|---|
| Global size, mass properties, topology scale | `inspect_step_rsummary`, `compare_global_properties_rdescriptor` |
| Single face/edge parameters and adjacency | `inspect_step_entity_rdescriptor`, `inspect_topology_neighborhood_rdescriptor` |
| Map stable geometry IDs to visual entities | `render_entity_map_rpath` (opaque depth-preserving context with type-specific edge/face/point marks, distinct colors, and anchored `entity_id · geometry.type` callouts) |
| Section profile, wall thickness, or local cut | `inspect_section_rdescriptor`, `compare_sections_rdescriptor` |
| Test whether a face has an analytic carrier | `fit_face_analytic_rdescriptor` (require `accepted=True` and inspect residuals) |
| Track contour topology across ordered sections | `track_section_contours_rdescriptor` |
| Assembly tree and interface visualization | `inspect_step_components_rdescriptorlist`, `render_step_components_rpath` |
| Side-by-side multi-part observation | `render_step_components_colored_rpath` (direct `{component name: color name}` mapping, highlights multiple solids at once, with legend) |
| Where the difference is | `compare_material_rdescriptor`, `inspect_difference_regions_rdescriptor` |
| Local geometric error | `compare_boundary_distance_rdescriptor`, `compare_entities_rdescriptor` |
| Closure, manifoldness, edge uses, and tolerances | `inspect_topology_rdescriptor` |
| Material difference inside one ROI | `compare_material_region_rdescriptor` |
| Ordered section sweep | `compare_sections_batch_rdescriptor` |
| Atomic STEP write/reload evidence | `validate_step_roundtrip_rdescriptor` |
| Final exact-BREP gate | `compare_shapes_rbrepcomparison`, `compare_steps_rbrepcomparison` |
| Shared-scale visual comparison | `render_step_comparison_rpath` |
| Copy an exact connected face region | `copy_step_region_rpath`, then `load_brep_region_rshell` |
Start from cheap, bounded facts; add boundary sampling, boolean difference,
sections, rendering, or strict topology comparison only when the current
question requires them. The generic schema registry and fixed dispatch have
been removed: pick and call these composable APIs directly per task.
`inspect_topology_rdescriptor` reports generic BREP validity separately from
shell closure and manifoldness. It classifies face-local edge occurrences as
free, manifold, seam, non-manifold, orphan, degenerate, or orientation-defective,
and also reports wire closure, shell orientation, small faces, and tolerance
ranges.
`validate_step_roundtrip_rdescriptor` writes to a temporary sibling, reloads
the STEP, checks property and topology-count drift, and replaces the destination
only after validation succeeds.
`inspect_step_rbrepinspection()` keeps the full knot, multiplicity, control
point, and rational weight data of B-spline curves/surfaces in its report.
`inspect_step_entity_rdescriptor()` defaults to low-latency local
investigation and returns only degree and count summaries. For a single
B-spline/Bezier edge set `include_curve_definition=True`; for a B-spline/
Bezier face set `include_surface_definition=True` and bound the control net
with `max_surface_control_points`. Surfaces return untrimmed carrier
definitions; trimming is still described by `u_range`, `v_range`, and the
face boundary.
For an initial inventory, call `inspect_step_rsummary(...,
include_parameter_groups=True)` to get carrier groups by analytic radius or
B-spline degree, multi-solid canonical axes, and Face/Edge adjacency
signatures. Each group is bounded by `max_parameter_groups` and
`examples_per_group`. These only describe multiplicities; they do not infer
arrays, symmetry, or repeated features — validate pattern hypotheses with
spatial positions and spacing.
For large outlines prefer `inspect_face_boundaries_rdescriptor(...,
compact=True)`. Compact mode keeps coedge order, orientation, type, length,
endpoints, and key parameters without returning 3D/UV sample arrays; request
detailed mode only when fitting or error measurement actually needs it. For
exact carriers add `include_curve_definitions=True` and optionally
`curve_definition_edge_ids=[...]`.
`inspect_section_rdescriptor(..., compact=True)` still completes contour
connectivity, nesting, and area computation, but returns only endpoints/exact
lengths of each section edge plus a contour summary. Set
`connection_tolerance` explicitly when section endpoints have tiny gaps;
section-local edge indexes are not stable IDs across models. Use `face_ids` to
restrict a section to an already identified carrier set. Align contour samples
in case-specific extraction code only when a loft hypothesis requires it.
Use `fit_face_analytic_rdescriptor(...)` when an imported face may be supported
by a plane, sphere, cylinder, or cone. Keep the candidate type, parameters,
residuals, and tolerance as evidence; do not treat the fit as recovered feature
history. Use `track_section_contours_rdescriptor(...)` on ordered section
results before selecting a loft strategy. Birth, death, split, or merge events
after the initial section make one global loft unsafe.
Use `render_step_comparison_rpath(...)` for final visual comparison. It locks
both models to the union of their bounds so independent camera fitting cannot
hide size or placement differences. The rendered image remains diagnostic and
does not replace the strict BREP gate.
After `compare_steps_rbrepcomparison(...)`, use
`comparison.to_error_summary()` to collect every failed validity, bounds,
material, topology, and carrier-type check. Errors are grouped by plausible
common root cause. One iteration may change multiple related operations or
code locations in a group, but must then rerun Direct modeling, strict replay,
STEP export, and the complete comparison.
`compare_material_rdescriptor(..., include_components=False)` does a fast
volume estimate with a single intersection; subtracting a common volume can
lose a small residual on large-scale models and cannot by itself prove strict
material equality. For strict acceptance, difference-region localization, or
STEP difference export set `include_components=True` and
`boolean_tolerance=None`. Fuzzy booleans are diagnostic only.
Rendering and image-section features need the optional dependency:
```bash
uv sync --extra inspect
```
Performance principle: for closed solids, iterative acceptance prefers
validity, global properties, and bidirectional material difference to quickly
rule out large errors; but topology identity is the **best endpoint**, not an
optional extra — when the candidate is close in material and global
properties, check structural identity (see "Acceptance and stopping
conditions") and stop under the degraded conditions only after confirming
topology identity is unreachable.
`evaluate_reconstruction_rdescriptor()` includes global boundary sampling and
is not part of the cheap iteration path.
`compare_boundary_distance_rdescriptor`, `compare_sections_rdescriptor`,
`inspect_difference_regions_rdescriptor`, and local rendering should be called
per suspicious region as needed.
`compare_boundary_distance_rdescriptor` defaults to at most 200 samples and
supports `target_face_ids`/`current_face_ids` local ranges. Set
`include_records=True` explicitly when handing results to
`inspect_difference_regions_rdescriptor`; then pass the result as
`boundary_result` to avoid recomputation. Center slices remain available via
`compare_step_slices_rslicecomparison` but are not a default step.
@@ -1,8 +1,7 @@
# Skill Documentation Structure
This directory is the source of the task-routed skill layer packaged into
`skills/simplecadapi/` by `skill-pack`. It sits between the SDK's generated
API references and the top-level `SKILL.md` router.
This directory is the task-routed skill layer. It sits between the SDK's
generated
```text
docs/skill/
@@ -73,5 +72,4 @@ Modeling reasoning and invariants, independent of any single API:
- Workflow files compose domains; they never duplicate discipline content.
- Discipline files state reasoning and invariants; they avoid CLI- or
tool-specific detail that belongs in domains/workflows.
- Every `references/...` path written here must exist in the packaged skill;
`skill-pack` validates them (`test_skill_pack.py` enforces the same).
- Every `references/...` path written here must exist in the packaged skill.
@@ -19,9 +19,9 @@
## Main SDK surfaces
- Geometry and modeling operations in `docs/api/`.
- Standard parts library in `docs/stdlib/`, including `scad.std.gear` gear, ring gear, rack, and cycloidal disc factories plus `scad.std.bearing` bearing assembly factories.
- Core shape/type semantics in `docs/core/`.
- Geometry and modeling operations in `references/docs/api/`.
- Standard parts library in `references/docs/stdlib/`, including `scad.std.gear` gear, ring gear, rack, and cycloidal disc factories plus `scad.std.bearing` bearing assembly factories.
- Core shape/type semantics in `references/docs/core/`.
- Graph/model serialization and replay APIs.
- Expression, parameter, and semantic reference types.
- Functional tagging with `apply_tag(shape=..., tag=...)`, `list_tags(shape=...)`, and QL tag predicates.

Some files were not shown because too many files have changed in this diff Show More