Metadata-Version: 2.1
Name: simplecadapi
Version: 2.2.7b1
Summary: A simplified OpenCASCADE-native CAD modeling Python API
Keywords: cad,modeling,3d,design,ocp,opencascade
Author-Email: 倪旌哲 <nijingzhe@zju.edu.cn>
Maintainer-Email: 倪旌哲 <nijingzhe@zju.edu.cn>
License: 
                                          Apache License
                                    Version 2.0, January 2004
                                 http://www.apache.org/licenses/
         
            TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
         
            1. Definitions.
         
               "License" shall mean the terms and conditions for use, reproduction,
               and distribution as defined by Sections 1 through 9 of this document.
         
               "Licensor" shall mean the copyright owner or entity authorized by
               the copyright owner that is granting the License.
         
               "Legal Entity" shall mean the union of the acting entity and all
               other entities that control, are controlled by, or are under common
               control with that entity. For the purposes of this definition,
               "control" means (i) the power, direct or indirect, to cause the
               direction or management of such entity, whether by contract or
               otherwise, or (ii) ownership of fifty percent (50%) or more of the
               outstanding shares, or (iii) beneficial ownership of such entity.
         
               "You" (or "Your") shall mean an individual or Legal Entity
               exercising permissions granted by this License.
         
               "Source" form shall mean the preferred form for making modifications,
               including but not limited to software source code, documentation
               source, and configuration files.
         
               "Object" form shall mean any form resulting from mechanical
               transformation or translation of a Source form, including but
               not limited to compiled object code, generated documentation,
               and conversions to other media types.
         
               "Work" shall mean the work of authorship, whether in Source or
               Object form, made available under the License, as indicated by a
               copyright notice that is included in or attached to the work
               (an example is provided in the Appendix below).
         
               "Derivative Works" shall mean any work, whether in Source or Object
               form, that is based on (or derived from) the Work and for which the
               editorial revisions, annotations, elaborations, or other modifications
               represent, as a whole, an original work of authorship. For the purposes
               of this License, Derivative Works shall not include works that remain
               separable from, or merely link (or bind by name) to the interfaces of,
               the Work and Derivative Works thereof.
         
               "Contribution" shall mean any work of authorship, including
               the original version of the Work and any modifications or additions
               to that Work or Derivative Works thereof, that is intentionally
               submitted to Licensor for inclusion in the Work by the copyright owner
               or by an individual or Legal Entity authorized to submit on behalf of
               the copyright owner. For the purposes of this definition, "submitted"
               means any form of electronic, verbal, or written communication sent
               to the Licensor or its representatives, including but not limited to
               communication on electronic mailing lists, source code control systems,
               and issue tracking systems that are managed by, or on behalf of, the
               Licensor for the purpose of discussing and improving the Work, but
               excluding communication that is conspicuously marked or otherwise
               designated in writing by the copyright owner as "Not a Contribution."
         
               "Contributor" shall mean Licensor and any individual or Legal Entity
               on behalf of whom a Contribution has been received by Licensor and
               subsequently incorporated within the Work.
         
            2. Grant of Copyright License. Subject to the terms and conditions of
               this License, each Contributor hereby grants to You a perpetual,
               worldwide, non-exclusive, no-charge, royalty-free, irrevocable
               copyright license to reproduce, prepare Derivative Works of,
               publicly display, publicly perform, sublicense, and distribute the
               Work and such Derivative Works in Source or Object form.
         
            3. Grant of Patent License. Subject to the terms and conditions of
               this License, each Contributor hereby grants to You a perpetual,
               worldwide, non-exclusive, no-charge, royalty-free, irrevocable
               (except as stated in this section) patent license to make, have made,
               use, offer to sell, sell, import, and otherwise transfer the Work,
               where such license applies only to those patent claims licensable
               by such Contributor that are necessarily infringed by their
               Contribution(s) alone or by combination of their Contribution(s)
               with the Work to which such Contribution(s) was submitted. If You
               institute patent litigation against any entity (including a
               cross-claim or counterclaim in a lawsuit) alleging that the Work
               or a Contribution incorporated within the Work constitutes direct
               or contributory patent infringement, then any patent licenses
               granted to You under this License for that Work shall terminate
               as of the date such litigation is filed.
         
            4. Redistribution. You may reproduce and distribute copies of the
               Work or Derivative Works thereof in any medium, with or without
               modifications, and in Source or Object form, provided that You
               meet the following conditions:
         
               (a) You must give any other recipients of the Work or
                   Derivative Works a copy of this License; and
         
               (b) You must cause any modified files to carry prominent notices
                   stating that You changed the files; and
         
               (c) You must retain, in the Source form of any Derivative Works
                   that You distribute, all copyright, patent, trademark, and
                   attribution notices from the Source form of the Work,
                   excluding those notices that do not pertain to any part of
                   the Derivative Works; and
         
               (d) If the Work includes a "NOTICE" text file as part of its
                   distribution, then any Derivative Works that You distribute must
                   include a readable copy of the attribution notices contained
                   within such NOTICE file, excluding those notices that do not
                   pertain to any part of the Derivative Works, in at least one
                   of the following places: within a NOTICE text file distributed
                   as part of the Derivative Works; within the Source form or
                   documentation, if provided along with the Derivative Works; or,
                   within a display generated by the Derivative Works, if and
                   wherever such third-party notices normally appear. The contents
                   of the NOTICE file are for informational purposes only and
                   do not modify the License. You may add Your own attribution
                   notices within Derivative Works that You distribute, alongside
                   or as an addendum to the NOTICE text from the Work, provided
                   that such additional attribution notices cannot be construed
                   as modifying the License.
         
               You may add Your own copyright statement to Your modifications and
               may provide additional or different license terms and conditions
               for use, reproduction, or distribution of Your modifications, or
               for any such Derivative Works as a whole, provided Your use,
               reproduction, and distribution of the Work otherwise complies with
               the conditions stated in this License.
         
            5. Submission of Contributions. Unless You explicitly state otherwise,
               any Contribution intentionally submitted for inclusion in the Work
               by You to the Licensor shall be under the terms and conditions of
               this License, without any additional terms or conditions.
               Notwithstanding the above, nothing herein shall supersede or modify
               the terms of any separate license agreement you may have executed
               with Licensor regarding such Contributions.
         
            6. Trademarks. This License does not grant permission to use the trade
               names, trademarks, service marks, or product names of the Licensor,
               except as required for reasonable and customary use in describing the
               origin of the Work and reproducing the content of the NOTICE file.
         
            7. Disclaimer of Warranty. Unless required by applicable law or
               agreed to in writing, Licensor provides the Work (and each
               Contributor provides its Contributions) on an "AS IS" BASIS,
               WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
               implied, including, without limitation, any warranties or conditions
               of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
               PARTICULAR PURPOSE. You are solely responsible for determining the
               appropriateness of using or redistributing the Work and assume any
               risks associated with Your exercise of permissions under this License.
         
            8. Limitation of Liability. In no event and under no legal theory,
               whether in tort (including negligence), contract, or otherwise,
               unless required by applicable law (such as deliberate and grossly
               negligent acts) or agreed to in writing, shall any Contributor be
               liable to You for damages, including any direct, indirect, special,
               incidental, or consequential damages of any character arising as a
               result of this License or out of the use or inability to use the
               Work (including but not limited to damages for loss of goodwill,
               work stoppage, computer failure or malfunction, or any and all
               other commercial damages or losses), even if such Contributor
               has been advised of the possibility of such damages.
         
            9. Accepting Warranty or Additional Liability. While redistributing
               the Work or Derivative Works thereof, You may choose to offer,
               and charge a fee for, acceptance of support, warranty, indemnity,
               or other liability obligations and/or rights consistent with this
               License. However, in accepting such obligations, You may act only
               on Your own behalf and on Your sole responsibility, not on behalf
               of any other Contributor, and only if You agree to indemnify,
               defend, and hold each Contributor harmless for any liability
               incurred by, or claims asserted against, such Contributor by reason
               of your accepting any such warranty or additional liability.
         
            END OF TERMS AND CONDITIONS
         
            APPENDIX: How to apply the Apache License to your work.
         
               To apply the Apache License to your work, attach the following
               boilerplate notice, with the fields enclosed by brackets "[]"
               replaced with your own identifying information. (Don't include
               the brackets!)  The text should be enclosed in the appropriate
               comment syntax for the file format. We also recommend that a
               file or class name and description of purpose be included on the
               same "printed page" as the copyright notice for easier
               identification within third-party archives.
         
            Copyright [yyyy] [name of copyright owner]
         
            Licensed under the Apache License, Version 2.0 (the "License");
            you may not use this file except in compliance with the License.
            You may obtain a copy of the License at
         
                http://www.apache.org/licenses/LICENSE-2.0
         
            Unless required by applicable law or agreed to in writing, software
            distributed under the License is distributed on an "AS IS" BASIS,
            WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            See the License for the specific language governing permissions and
            limitations under the License.
         
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Manufacturing
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Visualization
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Project-URL: Homepage, https://github.com/PhySpace/SimpleCADAPI
Project-URL: Repository, https://github.com/PhySpace/SimpleCADAPI
Project-URL: Documentation, https://github.com/PhySpace/SimpleCADAPI#readme
Project-URL: Issues, https://github.com/PhySpace/SimpleCADAPI/issues
Requires-Python: <3.14,>=3.10
Requires-Dist: numpy>=1.21.0
Requires-Dist: pillow>=10.0
Requires-Dist: rich>=14.0.0
Requires-Dist: jsonschema<5.0.0,>=4.25.1
Requires-Dist: rfc8785<0.2.0,>=0.1.4
Requires-Dist: typing-extensions<5,>=4.12
Requires-Dist: tomli<3,>=2.0; python_version < "3.11"
Requires-Dist: ezdxf>=1.4.4
Requires-Dist: marimo>=0.25.0
Requires-Dist: plotly>=7.1.0
Requires-Dist: cryptography>=42.0.0
Requires-Dist: matplotlib>=3.7.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Requires-Dist: isort>=5.0; extra == "dev"
Requires-Dist: pymupdf>=1.28.2; extra == "dev"
Provides-Extra: drawing
Requires-Dist: pymupdf>=1.28.2; extra == "drawing"
Provides-Extra: editor
Requires-Dist: starlette>=1.7.0; extra == "editor"
Requires-Dist: uvicorn>=0.54.0; extra == "editor"
Requires-Dist: websockets>=16.1.1; extra == "editor"
Provides-Extra: inspect
Provides-Extra: whucad
Requires-Dist: h5py>=3.8; extra == "whucad"
Provides-Extra: gmsh
Requires-Dist: gmsh<5,>=4.15; extra == "gmsh"
Provides-Extra: fem
Requires-Dist: gmsh<5,>=4.15; extra == "fem"
Requires-Dist: ccx2paraview[VTK]<4,>=3.2; extra == "fem"
Description-Content-Type: text/markdown

<p align="center">
  <img src="img/repocover.png" alt="SimpleCADAPI repository cover">
</p>

# SimpleCADAPI

[中文说明](README.zh-CN.md)

**Start here.** Paste this line to your coding agent (Claude Code, Codex, OpenCode, …):

```text
Read physpace.dev/sca/landing.md and landing me on this sdk.
```

It installs the SDK, installs the skill for itself, opens a real example in the
code-first editor, and shows you how to work with it. SimpleCADAPI is a
parametric CAD SDK built for agents: a model is a notebook of code, every
dimension is a named parameter, selection is by what geometry *is*, and every
step reports back why it worked or failed.

## What Can It Do

Four capability pillars. Every case below is a **real, reproducible session**:
the replay demos are single-file offline HTML pages that faithfully replay the
full recorded conversation (user turns, agent thinking, every tool call and
patch, role switches) next to the exported 3D model — open them directly in a
browser.

### 1 · Single-Part Modeling

Parametric parts authored as readable [Feature Tree
Convention](docs/skill/references/discipline/feature-tree-convention.md)
feature blocks — named parameters with units, verifier-first staged modeling,
deterministic face tags that survive re-parameterization, and synchronized
`.scadpkg` / STEP AP242 / STL / editable FreeCAD exports.

<table>
<tr>
<th width="18%">Case</th>
<th width="40%">First-turn requirement (excerpt)</th>
<th width="42%">Delivered model · BRep turntable</th>
</tr>
<tr>
<td><b>Robotic-arm U-link + motor mount</b><br/>15 user turns · 601 tool calls<br/><a href="examples/u_link_motor_mount/demo/index.html">▶ Full session replay</a></td>
<td>"Build a parametric robotic-arm link that adapts to length changes and mounts motors generically: sweep a circular profile down D → right L → up D into a U; cut motor sockets with spheres; the mounting face must carry a deterministic name indexable by the query language; split the bottom cylinder into a half cylinder; then fillet everything."</td>
<td><img src="img/capability/ulink_turntable.gif" width="420" alt="u_link turntable"></td>
</tr>
<tr>
<td><b>Parametric flange plate</b><br/>2 user turns · 66 tool calls<br/><a href="examples/flange_plate/demo/index.html">▶ Full session replay</a></td>
<td>"Parametric flange: OD 100, thickness 10, hub ⌀55 top +30, bore ⌀30, 6×⌀11 bolt holes on PCD 78, hub-root R3 / rim R2 fillets; every dimension a named parameter; edge-selection cards printed before each fillet; parameter-feasibility guards; one feature per block."<br/><br/><i>GIF shows the final 8-hole @PCD 84.5 state: turn 2 re-parameterized 6→8 holes; PCD 88 was rejected live by the guards and 85 excluded for fillet tangency.</i></td>
<td><img src="img/capability/flange_turntable.gif" width="420" alt="flange turntable"></td>
</tr>
<tr>
<td><b>Ribbed L-bracket (FEM main model)</b><br/>2 user turns · 49 tool calls<br/><a href="examples/ap242_gmsh_volume_mesh/demo/index.html">▶ Full session replay</a></td>
<td>"Formalize the existing legacy L-bracket script through the single-part workflow: rebuild with FTC feature blocks and named parameters; geometric equivalence to the legacy model (volume delta < 0.1%); the <code>interface.*</code> FEM boundary tags must survive untouched — the downstream Gmsh/CalculiX pipeline selects faces by them."</td>
<td><img src="img/capability/bracket_turntable.gif" width="420" alt="bracket turntable"></td>
</tr>
</table>

Turntables are rendered with BRep shading and wide edges; one full turn = 48
deterministic azimuth steps.

### 2 · Assembly Modeling

Nested durable assemblies with explicit kinematics: gear meshes, revolute
joints, and bearing interfaces are solved constraints, not eyeballed
positions. Standard parts — involute gears, ball bearings (as subassemblies
with individual balls), roller-chain sprockets, metric fasteners with real
thread profiles — come from `scad.std.*` and compose into mechanisms that
export to STEP, editable FreeCAD projects, and MJCF for physics engines.

<table>
<tr>
<td width="44%" align="center" valign="top">
<img src="img/capability/bldc_assembly.png" alt="BLDC joint actuator assembled"><br/>
<b>Integrated BLDC joint actuator</b> — assembled, studio render<br/>
29 components · 51 constraints, all solved · 20:1 two-stage planetary
</td>
<td width="56%" align="center" valign="top">
<img src="img/capability/bldc_exploded.gif" width="430" alt="BLDC joint actuator exploded turntable"><br/>
<b>Same model, exploding turntable</b> — four modules (ESC · motor ·<br/>
two-stage reducer · output shaft) separate along the axis while<br/>
concentric parts peel into radius bands; camera circles on an inclined orbit
</td>
</tr>
</table>

Reproduce it: the model is the `integrated_bldc_joint_actuator.py` assembly
notebook, composed with `scad.use` from part and sub-assembly notebooks.
`uv run python examples/integrated_bldc_joint_actuator/export_all.py` emits
the package plus STEP / editable FCStd / MJCF; `render_showcase.py` renders
the views above.

### 3 · Code-first Editor

`sca edit` opens a browser editor over a directory of notebooks, built for
working *with* an agent. The notebook's cells are on the left and the live
model is in the middle; a slider or toggle appears for every parameter. Click a
solid, face, edge or vertex and the editor writes a `scad.ql` selection cell
into the notebook file (autosaved), so your coding agent reads what you picked
from disk and "chamfer these two edges" needs no ids. Copy a cell's reference
to tell the agent which cell to change. A log dock shows which cells are being
re-evaluated. The editor and `sca run` share one runtime and one per-cell
cache.

<table>
<tr>
<td align="center" valign="top">
<img src="img/capability/editor.png" alt="sca edit on the u_link motor mount: a picked face, the selection cell it wrote, its properties"><br/>
<b>u_link motor mount in <code>sca edit</code></b> — a picked cylindrical face, the
<code>selected_face</code> cell the editor wrote for it, and its properties;
<code>sca example u_link</code> copies this workspace out
</td>
</tr>
</table>

### 4 · Simulation Plugins

The same parametric package feeds downstream solvers without manual rework:
AP242 STEP into Gmsh for volume meshing and CalculiX for static FEM (boundary
faces are selected by preserved `interface.*` tags, so simulation survives
model revisions), and MJCF into MuJoCo for mechanism dynamics — where a
virtual-collision pass catches assembly interference and drives the correction
before the mechanism runs clean.

<table>
<tr>
<td width="34%" align="center" valign="top" rowspan="2">
<img src="img/capability/ap242_gmsh_bracket_static_von_mises.png" alt="Bracket FEM von Mises"><br/>
<b>L-bracket static FEM</b> — CalculiX von Mises<br/>
meshed via Gmsh OpenCASCADE kernel from the AP242 export
</td>
<td width="33%" align="center" valign="top">
<img src="img/capability/fourbar_collision_before.gif" alt="Four-bar assembly with links crashing into each other in MuJoCo"><br/>
<b>Four-bar linkage + MuJoCo</b> — first assembly pass:<br/>
the links crash through each other mid-cycle; the assembly is wrong ·
<a href="img/capability/fourbar_collision_before.mp4">▶ full video</a>
</td>
</tr>
<tr>
<td width="33%" align="center" valign="top">
<img src="img/capability/fourbar_collision_after.gif" alt="Corrected four-bar assembly articulating clean in MuJoCo"><br/>
<b>After the virtual-collision correction</b> — corrected assembly:<br/>
the full crank cycle sweeps clean in the same sim ·
<a href="img/capability/fourbar_collision_after.mp4">▶ full video</a>
</td>
</tr>
</table>

---

## Update Notes (2.2.7b1)

> Validate generated definitions, assembly constraints, and manufacturing
> geometry before production use.

- **The geometry engine is C++ on OpenCASCADE, inside the wheel.** `pip install simplecadapi` needs no
  `cadquery-ocp`; the public API and the previous test suite are unchanged.
- **Prebuilt wheels** for Linux x86_64 and aarch64, macOS arm64 (14+) and Windows x86_64, Python 3.10-3.13,
  all on the same OpenCASCADE 7.9.3. This is a beta: the first release with prebuilt wheels.
- **Faster and smaller.** On the six-axis arm: cold build 43.8 s to 29.1 s, rebuild with nothing changed
  12.8 s to 6.0 s, `import simplecadapi` 1.6 s / 360 MB to 0.2 s / 68 MB.
- **Errors are English** and the tag and query errors render in full, like operator errors.

Full notes for this version: [`docs/updates/2.2.7b1.md`](docs/updates/2.2.7b1.md).
Earlier versions: the [changelog](CHANGELOG.md) and [`docs/updates/`](docs/updates/).

---

<div align="center">
  <h2>SimpleCADAPI Research Artifact</h2>
  <p>This repository is an artifact of</p>
  <p>
    <strong><a href="https://arxiv.org/abs/2608.00891">CADIR: A Cross-Backend Editable Intermediate Representation for Agentic CAD Generation</a></strong>
  </p>
</div>

---

SimpleCADAPI is an OpenCASCADE-native Python SDK for building CAD models with clear,
functional operations and replayable model graphs. It wraps OpenCascade geometry
in a compact public API for creating solids, applying features, tagging semantic
intent, querying topology, exporting manufacturing files, and translating recorded
models into FreeCAD workflows.

Current release: `simplecadapi==2.2.7b1`.

## What It Provides

- Models as [marimo](https://marimo.io) notebooks: plain `.py` files that are
  the only source of truth, one feature per cell, a per-cell cache for
  incremental headless runs (`sca run`), and notebook composition (`scad.use`).
- A code-first web editor, `sca edit`: live model, parameter controls, viewport
  picks written back as selection code, built for working alongside an agent.
- OpenCASCADE-native shape types: `Vertex`, `Edge`, `Wire`, `Face`, and `Solid`.
- Functional modeling operations for primitives, profiles, extrude, revolve,
  loft, sweep, booleans, transforms, patterns, fillets, chamfers, and shells.
- Canonical `.scadpkg` product packages generated from the notebooks for
  exchange and publishing; they are never read back as model input.
- Replayable operation graphs with explicit `GraphSession`,
  `export_model_json(...)`, `import_model_json(...)`, and `replay_model_json(...)`.
- Expression parameters with `var(...)`, arithmetic expressions, and serialized
  expression graphs.
- Physical units with automatic dimension inference, canonical CAD conversion,
  and manufacturing tolerance-chain validation.
- QL selectors for geometry grounding, topology queries, and stable feature
  selections.
- Semantic tags through `apply_tag(shape=..., tag=...)` and `list_tags(shape=...)`.
- STEP/STL export, editable FreeCAD product-package translation, and AP242
  product-structure export with material and named metadata properties.
- Agent-oriented STEP/BREP reconstruction with stable entity IDs, focused local
  diagnostics, highlighted region renders, and measured acceptance gates.
- Replayable open and periodic interpolated B-spline Edges/Wires for freeform
  profiles and Loft sections.

## Install

The shortest way is the line at the top of this page: paste it to your coding
agent and it does the rest.

By hand:

```bash
pip install simplecadapi
```

The code-first editor (`sca edit`) needs its extra, `pip install "simplecadapi[editor]"`;
`uv tool install "simplecadapi[editor]"` or `pipx install "simplecadapi[editor]"` put
`sca` on your PATH without a virtual environment. `sca example u_link` copies a
bundled example workspace out to open with `sca edit`.

With `uv`:

```bash
uv add simplecadapi
```

For local development from this repository:

```bash
uv sync --group dev
```

### Agent Skill

After installing with pip above, install the bundled skill for your agent
harness:

```bash
sca skill targets
# Default location (~/.agents/skills), or select ZCode's explicitly:
sca skill install --target zcode --skills-dir ~/.zcode/skills
```

`targets` lists the available harness targets. `install` compiles the bundled
source and writes it to `<skills-dir>/simplecadapi`; without `--skills-dir`,
it uses the existing addon configuration/environment resolution, falling back
to `~/.agents/skills`; `sca init` is not required. The wheel includes the
uncompiled `docs/skill/` source tree and `skillproj.toml` as package
resources — compilation happens on install, no repository checkout needed.
With `uv`, prefix these commands with `uv run`.

`install` fails if the destination already exists. Add `--force` to replace it
only if it is a directory whose `SKILL.md` declares the matching skill name
(`simplecadapi`); unrelated directories cannot be overwritten.

## Quick Start

A model is a [marimo](https://marimo.io) notebook: a plain `.py` file in your
repository, which stays the only source of truth. A `[tool.simplecadapi]`
table in its PEP 723 header names the product; each cell holds one
[feature block](docs/skill/references/discipline/feature-tree-convention.md)
and records its geometry automatically — no session or decorator boilerplate.

```python
# bracket.py
# /// script
# requires-python = ">=3.10"
# dependencies = ["simplecadapi"]
#
# [tool.simplecadapi]
# id = "bracket"
# revision = "1.0.0"
# ///
import marimo

app = marimo.App()

with app.setup:
    import simplecadapi as scad


@app.cell
def _():
    # ---- params: plate ----
    width = scad.var("width", 60.0, unit="mm")
    return (width,)


@app.cell
def _():
    # ---- params: bore ----
    hole_radius = scad.var("hole_radius", 5.0, unit="mm")
    return (hole_radius,)


@app.cell
def _(width):
    # ---- feature: base-plate (build) ----
    base = scad.make_box_rsolid(
        width=width, height=36.0, depth=8.0, bottom_face_center=(0.0, 0.0, 0.0)
    )
    return (base,)


@app.cell
def _(base, hole_radius):
    # ---- feature: bore-and-slot (subtract) ----
    _bore = scad.make_cylinder_rsolid(
        radius=hole_radius, height=14.0, bottom_face_center=(0.0, 0.0, -3.0)
    )
    _slot = scad.make_box_rsolid(
        width=18.0, height=8.0, depth=14.0, bottom_face_center=(14.0, 0.0, -3.0)
    )
    drilled = scad.cut_rsolid(base, _bore, _slot)
    return (drilled,)


@app.cell
def _(drilled):
    # ---- feature: boss (add) ----
    _boss = scad.make_cylinder_rsolid(
        radius=8.0, height=7.0, bottom_face_center=(-18.0, 0.0, 8.0)
    )
    bossed = scad.union_rsolid(drilled, _boss)
    return (bossed,)


@app.cell
def _(bossed):
    # ---- feature: role-tag (annotate) ----
    tagged = scad.apply_tag(shape=bossed, tag="role.demo.bracket")
    return (tagged,)


@app.cell
def _(tagged):
    bracket = scad.Part(part_id="bracket", body=tagged)
    return (bracket,)


if __name__ == "__main__":
    app.run()
```

The product is the top-level value whose id equals the notebook id. Edit the
notebook interactively, or run it headlessly with only `simplecadapi`
installed:

```bash
marimo edit bracket.py                                    # reactive editor
sca run bracket.py                                        # run, print a JSON report
sca run bracket.py --set width=80 --out out/bracket.scadpkg
sca export out/bracket.scadpkg --output-dir out/exports   # AP242 STEP, STL, OBJ
sca edit .                                                # web editor over this directory of notebooks
```

`sca edit` (`pip install "simplecadapi[editor]"`) is the code-first editor
described above: the notebook's cells on the left, the live model in the
middle, a slider or toggle for every parameter (`# ---- params ----` cells; a
`# ui:` comment on the line picks the control), and your viewport picks written
back as `selected_*` selection cells. See
`docs/skill/references/docs/guides/notebook-runtime.md` and
`docs/skill/references/domains/editor-collaboration.md` (how an agent works with
what you picked and which cell you mean).

## Notebook Runtime

The same runtime runs a notebook in the marimo editor, under `sca run`, and
from Python with `simplecadapi.runtime.run_notebook()`. Headless runs cache
every cell, so a rerun only executes the cells whose code, inputs, local
modules, or child notebooks changed. `--set` overrides a top-level variable
(the cell that defines it is skipped, so group parameters into cells by what
changes together); the report lists each cell as `ran`, `cached`, or
`skipped`.

Export and verification scripts are plain Python that load the product with
`run_notebook` and write packages from it:

```python
from pathlib import Path

import simplecadapi as scad
from simplecadapi.runtime import run_notebook

out = Path("out")
run = run_notebook("bracket.py", overrides={"width": 80.0})
print("volume", round(run.product.body.get_volume(), 3))
print("tags", scad.list_tags(shape=run.product.body))

package = out / "bracket.scadpkg"
scad.capture(run.definition, package)
scad.exporter.export_product_package_to_step(package, out / "bracket.step")
scad.exporter.export_product_package_to_stl(package, out / "bracket.stl")
scad.exporter.export_product_package_to_obj(package, out / "bracket.obj")
```

The `.scadpkg` embeds the definition closure, evaluated scene, feature
graphs, source snapshots, topology, and render/selection assets. It is
generated for exchange and publishing, never read back as model input.

### Composing notebooks

An assembly notebook brings in other notebooks with `scad.use`. A relative
path is relative to the calling notebook, and keyword arguments override the
child's top-level variables:

```python
@app.cell
def _():
    bracket = scad.use("bracket.py", width=80.0)
    return (bracket,)


@app.cell
def _(bracket):
    rig = scad.make_assembly_rassembly(assembly_id="rig", name="Rig")
    rig = scad.add_component_rassembly(
        assembly=rig, item=bracket, component_id="bracket",
        placement=scad.identity_placement_rplacement(),
    )
    return (rig,)
```

One notebook can describe a part family — parts that differ only in their
parameters, such as the links of a linkage. Its product takes
`part_id=scad.notebook_id()`, and each use names its member:
`scad.use("link_bar.py", id="crank", center_distance=40.0)` (or
`sca run link_bar.py --id crank`). Each member is one definition with its own
content hash and cell cache.

`@scad.part` / `@scad.assemble` remain for reusable library builders in plain
modules next to the notebooks; cells call them and take `.value`. See the
[notebook runtime and product build workflow](docs/skill/references/docs/guides/notebook-runtime.md)
for the project layout, the cell cache, and downstream targets.

### Migrating from `@scad.part` scripts

The script-anchored part cache of 2.1.2 (the `cache=` builder option, the
`.simplecad` cache directories, and the incremental assembly report) is
removed; the cell is now the unit of caching.

- Move each part into a notebook: its parameters into params cells, each FTC
  block into a cell of its own (each cell binds a new name), and the final
  `scad.Part(...)` / assembly into the last cell.
- Replace `main.py` entry points that build and export as a side effect with
  export scripts that call `run_notebook` and `scad.capture`.
- Replace direct builder calls between products with `scad.use(...)`; keep
  `@scad.part` builders only for library parts called from cells.
- Add `__marimo__/` (generated runtime state) to `.gitignore`.

### Command-line product export

Export the standard delivery set (AP242 STEP, binary STL, and OBJ) from a
validated product package with no wrapper script:

```bash
uv run sca export out/bracket.scadpkg --output-dir out/exports
```

Request additional targets explicitly.  FCStd requires `FreeCADCmd` (or an
explicit `--freecad-cmd` path); `--check` validates the package, output paths,
and selected target prerequisites without writing files.

```bash
uv run sca export out/bracket.scadpkg \
  --format fcstd --format mjcf --output-dir out/exports --check
uv run sca export out/bracket.scadpkg \
  --format fcstd --freecad-cmd /path/to/FreeCADCmd --output-dir out/exports
```

STL and OBJ share one direct OpenCASCADE tessellation of the evaluated BREP.
Both outputs contain the same oriented triangles and require no optional
remeshing dependency. Control curved-surface accuracy with `linear_deflection`
and `angular_deflection_degrees`.

### Optional CalculiX FEM workflow

The AP242/Gmsh example also includes an optional CalculiX FEM workflow. Install
the Python-side FEM dependencies with `uv sync --extra fem`, and install the
external CalculiX solver separately (on macOS: `brew install
costerwi/homebrew-calculix/calculix-ccx`). The example uses consistent `mm`,
`N`, and `MPa` units:

```bash
uv run --extra fem python examples/ap242_gmsh_volume_mesh/run_calculix.py \
  --ccx "$(brew --prefix calculix-ccx)/bin/ccx_2.23"
uv run --extra fem python examples/ap242_gmsh_volume_mesh/visualize_calculix.py
uv run --extra fem python examples/ap242_gmsh_volume_mesh/study_mesh_convergence.py \
  --ccx "$(brew --prefix calculix-ccx)/bin/ccx_2.23" \
  --linear-solver "ITERATIVE CHOLESKY" --solver-timeout 2400
```

The analysis writes CalculiX `.inp`, `.dat`, `.frd`, solver-log, summary JSON,
ParaView `.vtu`, and displaced von-Mises PNG artifacts. The preview shows the
load physical group's yellow boundary and red `-Z` force arrows without
covering the stress heatmap. The convergence study supports `--resume`; failed
solver levels are reported separately and never enter the numerical sequence.

The checked-in `-1000 N` study evaluates eleven mesh sizes from `h=3.0 mm` to
`h=0.25 mm`. A platform requires three consecutive refinement pairs below `5%`
maximum-displacement change and `10%` peak integration-point von-Mises change.
The verification level N is `h=0.25 mm` (`0.0331843 mm`, `98.6392 MPa`), so the
recommended production level N-1 is `h=0.27 mm`. Fine levels use iterative
Cholesky after a same-mesh comparison at `h=0.375 mm` matched SPOOLES within
`0.005%`; this avoids the direct solver's in-memory capacity limit.

## Replayable Operation Graphs

Use an explicit `GraphSession` when a geometry flow outside a notebook should
be inspectable, serializable, or replayable.

```python
import simplecadapi as scad
from simplecadapi import GraphSession, export_model_json, replay_model_json
from simplecadapi import ql as Q

with GraphSession(graph_id="chamfered_block") as session:
    body = scad.make_box_rsolid(
        width=40.0, height=24.0, depth=10.0,
        bottom_face_center=(0.0, 0.0, 0.0),
    )
    cutter = scad.make_cylinder_rsolid(
        radius=4.0, height=16.0, bottom_face_center=(0.0, 0.0, -3.0)
    )
    drilled = scad.cut_rsolid(body, cutter)

    bottom_circle = (
        Q.edges()
        .where(Q.curve_type(kind="circle"))
        .order_by(Q.center_axis(axis="z"))
        .take(1)
        .exactly(1)
    )
    final = scad.chamfer_rsolid(solid=drilled, edges=bottom_circle, distance=0.6)
    session.capture_result(value=final)
    model_json = export_model_json(session=session)
    recorded_nodes = session.graph.node_count

rebuilt = replay_model_json(json_str=model_json)
print("recorded_nodes", recorded_nodes)
print("replayed_outputs", len(rebuilt))
```

An explicit `GraphSession` is for inspection, serialization, and replay
outside a notebook; notebook cells already record into sessions of their own,
so do not open one there. It stays in memory until an export API is called.
A durable CAD/viewer deliverable is a notebook product captured to
`.scadpkg` (see [Notebook Runtime](#notebook-runtime)).

## STEP/BREP Inspection

Synchronized STEP views, highlighted regions and slice overlays need nothing
beyond `pip install simplecadapi`: they are drawn by the built-in software
renderer (no GPU, no display server, no VTK). Only the engineering-drawing
family (`simplecadapi.inspect.drawing`) needs the `drawing` extra.

Inspection lives under `simplecadapi.inspect.brep`. These APIs are diagnostic
tools, not modeling operations: they do not enter the graph and are rejected
inside `GraphSession`. Export or obtain the geometry first, then
inspect it outside the modeling script.

Choose calls from the evidence required by the case instead of following a
fixed reverse-engineering pipeline. Start with bounded global and local facts;
add sections, component renders, boundary distance, material difference, or
strict topology comparison only when those facts answer the current question.

```python
from simplecadapi.inspect import brep

summary = brep.inspect_step_rsummary(
    path="target.step",
    include_parameter_groups=True,
)
face = brep.inspect_step_entity_rdescriptor(
    path="target.step",
    entity_id="face:0",
)

print("faces", summary["face_count"])
print("carrier", face["geometry"]["type"])
```

Use the [Reconstruction Agent test specification](docs/skill/references/docs/guides/reconstruction-agent-test-prompt.md)
for controlled runs and the [STEP reconstruction workflow](docs/skill/references/workflows/step-reconstruction.md)
for the inspection primitives, modeling loop, replay checks, and acceptance gates.

## Physical Units And Tolerances

Declare nominal and manufacturing-tolerance units at the variable boundary.
SimpleCAD evaluates lengths in millimeters and angles in degrees while preserving
the declaration units in model JSON:

```python
import simplecadapi as scad

width = scad.var(
    "width",
    1.0,
    unit="in",
    tolerance=0.1,
    tolerance_unit="mm",
)
height = scad.var("height", 40.0, unit="mm", tolerance=0.2)
diagonal = scad.sqrt(width**2 + height**2)

analysis = scad.analyze_tolerance(diagonal)
check = scad.check_tolerance(diagonal, 0.3, tolerance_unit="mm")

print(analysis.dimension.name, analysis.unit.symbol)
print(analysis.nominal, analysis.lower_bound, analysis.upper_bound)
print("passes", check.passed)
```

Addition and subtraction require matching dimensions. Multiplication, division,
integer powers, and square root derive dimensions. Trigonometric functions require
angle or dimensionless inputs as appropriate. Legacy variables without `unit`
remain supported, but cannot be mixed with unit-declared variables in one
expression.

## Modeling Mental Model

- Start from design intent: reference axes, critical profiles, and the features
  that produce the final solid.
- Build from lower-dimensional geometry to higher-dimensional geometry: profile
  wires/faces first, then solid features such as extrude, revolve, loft, and
  sweep.
- Keep operations functional. Create new values with public functions such as
  `make_rectangle_rface(...)`, `extrude_rsolid(...)`, `cut_rsolid(...)`, and
  `fillet_rsolid(...)`.
- Use tags for semantic intent and selection anchors, for example
  `role.mounting.surface`, `anchor.datum.primary`, or `group.fasteners`.
- Store numeric and geometric facts in metadata or graph payloads, not in tags.
- Use QL to ground selections by geometry facts rather than relying on topology
  iteration order.
- When an indexed topology pick is intentional, pass the index to the plural
  child-geometry getter, such as `get_edges(index)`, `get_faces(index)`,
  `get_wires(index)`, or `get_vertices(index)`, so replayable graph workflows
  preserve the pick as a geo select node.

Use model JSON only for graph replay and inspection. External CAD translation and
file export consume the validated `.scadpkg` closure:

```python
script = scad.translator.freecad_translator.translate_product_package_to_freecad_script(
    package_path
)
scad.translator.freecad_translator.translate_product_package_to_fcstd(
    package_path, "bracket.FCStd"
)
```

Part/Assembly models are written as editable FreeCAD assembly structure: parts are
`App::Part`, assemblies are `Assembly::AssemblyObject`, and components are links.
The exporter namespace owns neutral STEP and STL file output.

## Examples

Every example is a self-contained folder: part and assembly notebooks, the
plain modules they import, export and verification scripts, and fresh
artifacts under `examples/<name>/out/`. The set covers part modeling,
assemblies, reverse engineering, and FEM — see the category index in
[`examples/README.md`](examples/README.md).

```bash
# part (quickstart FTC notebook, external verification script included)
marimo edit examples/flange_plate/flange_plate.py
uv run python examples/flange_plate/verify.py

# assembly (two-stage planetary reducer: part-family notebooks, MJCF export)
sca run examples/compact_two_stage_planetary_reducer/compact_two_stage_planetary_reducer.py
uv run python examples/compact_two_stage_planetary_reducer/export_mjcf.py

# FEM (AP242 STEP -> Gmsh volume mesh -> Calculix statics)
uv run python examples/ap242_gmsh_volume_mesh/export_step.py
uv run --extra gmsh python examples/ap242_gmsh_volume_mesh/export_fem_mesh.py
uv run --extra fem python examples/ap242_gmsh_volume_mesh/run_calculix.py
```

To try the editor on a real model, `sca example u_link` copies a motor mount
(two part notebooks and the assembly that fixes them) out of the package, and
`sca edit u_link_motor_mount` opens it; from a checkout,
`sca edit examples/u_link_motor_mount`. Reconstructing a STEP file (see
`examples/bowl_connector/`) is driven by the agent through the inspection API
and the [STEP reconstruction workflow](docs/skill/references/workflows/step-reconstruction.md).

## Documentation

- 2.2.7b1 update notes: [`docs/updates/2.2.7b1.md`](docs/updates/2.2.7b1.md)
- 2.2.6.post2 update notes: [`docs/updates/2.2.6.post2.md`](docs/updates/2.2.6.post2.md)
- 2.2.6.post1 update notes: [`docs/updates/2.2.6.post1.md`](docs/updates/2.2.6.post1.md)
- 2.2.6 update notes: [`docs/updates/2.2.6.md`](docs/updates/2.2.6.md)
- 2.2.5 update notes: [`docs/updates/2.2.5.md`](docs/updates/2.2.5.md)
- 2.2.4 update notes: [`docs/updates/2.2.4.md`](docs/updates/2.2.4.md)
- 2.2.3 update notes: [`docs/updates/2.2.3.md`](docs/updates/2.2.3.md)
- 2.2.2 update notes: [`docs/updates/2.2.2.md`](docs/updates/2.2.2.md)
- 2.2.1 update notes: [`docs/updates/2.2.1.md`](docs/updates/2.2.1.md)
- 2.1.3b1 update notes: [`docs/updates/2.1.3b1.md`](docs/updates/2.1.3b1.md)
- 2.1.2 update notes: [`docs/updates/2.1.2.md`](docs/updates/2.1.2.md)
- 2.1.1 update notes: [`docs/updates/2.1.1.md`](docs/updates/2.1.1.md)
- 2.1.0 update notes: [`docs/updates/2.1.0.md`](docs/updates/2.1.0.md)
- Reconstruction Agent test specification:
  [`docs/skill/references/docs/guides/reconstruction-agent-test-prompt.md`](docs/skill/references/docs/guides/reconstruction-agent-test-prompt.md)
- Landing script for agents: [`docs/landing.md`](docs/landing.md)
- Editor collaboration (selection, cell references, parameters):
  [`docs/skill/references/domains/editor-collaboration.md`](docs/skill/references/domains/editor-collaboration.md)
- STEP reconstruction workflow:
  [`docs/skill/references/workflows/step-reconstruction.md`](docs/skill/references/workflows/step-reconstruction.md)
- Notebook runtime and product build workflow:
  [`docs/skill/references/docs/guides/notebook-runtime.md`](docs/skill/references/docs/guides/notebook-runtime.md)
- Public API reference: [`docs/skill/references/docs/api/`](docs/skill/references/docs/api/)
- Core type and modeling notes: [`docs/skill/references/docs/core/`](docs/skill/references/docs/core/)
- Serialization and replay details:
  [`docs/skill/references/docs/core/serialization/README.md`](docs/skill/references/docs/core/serialization/README.md)
- Dimension tolerance chains:
  [`docs/core/dimension-tolerance-chains.md`](docs/skill/references/docs/core/dimension-tolerance-chains.md)
- Physical units and dimension inference:
  [`docs/core/physical-units.md`](docs/skill/references/docs/core/physical-units.md)
- Operation graph JSON spec:
  [`docs/core/operation_graph_json_spec.md`](docs/skill/references/docs/core/operation_graph_json_spec.md)
- `.scadpkg` package format:
  [`docs/skill/references/scadpkg-format.md`](docs/skill/references/scadpkg-format.md)

## Releasing the Agent Skill

The skill source tree lives under `docs/skill/` and stays harness-neutral.
`tools/skillbuild.py` wraps the same compiler the `sca skill` CLI uses, for
maintainer builds in this repository: it compiles per harness target (targets
and default 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. The wheel
itself never contains precompiled targets — end users install from the
bundled source with `sca skill install`.

From a clean checkout, update the project version and documentation, then
build and validate the release artifacts:

```bash
uv sync --group dev
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 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 -- docs/skill
tar -tzf skills/simplecadapi.tar.gz | head
```

Commit only the `docs/skill/` source tree; the release workflow builds the
harness outputs and uploads the archive to the GitHub release. Prefer
`sca skill` for installation from a pip-installed package.

## Development

```bash
uv sync --group dev
uv run python -m pytest test tests
python3 -m compileall src/simplecadapi
```

## License

Apache-2.0, see [`LICENSE`](LICENSE).

## Community

The group chat currently has too many members for direct QR-code joining. Scan the QR code below to add Teacher Du Peng on WeChat, then ask him for an invitation to the CADDesigner technical community:

<p align="center">
  <img src="img/dp个人账号.png.jpg" alt="Teacher Du Peng's personal WeChat QR code" width="420">
</p>

## Star History

<a href="https://www.star-history.com/?repos=PhySpace%2FSimpleCADAPI&type=date&legend=top-left">
 <picture>
   <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=PhySpace/SimpleCADAPI&type=date&theme=dark&legend=top-left" />
   <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=PhySpace/SimpleCADAPI&type=date&legend=top-left" />
   <img alt="Star History Chart" src="https://api.star-history.com/chart?repos=PhySpace/SimpleCADAPI&type=date&legend=top-left" />
 </picture>
</a>
