# cadquery-modeling

Adopt this skill: https://proskills.md/skills/other/0okevino0-claude-cad-claude-skills-cadquery-modeling

Page: https://proskills.md/skills/other/0okevino0-claude-cad-claude-skills-cadquery-modeling
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: .claude/skills/cadquery-modeling/SKILL.md
size: 14310
sha: 4a2ad1afd296c83983408f86c950f016f3e9d9ab
upstream: https://github.com/0okevino0/claude-cad/blob/main/.claude/skills/cadquery-modeling/SKILL.md

````text
---
name: cadquery-modeling
description: "Create, edit, or debug parametric 3D CAD parts in CadQuery (Python) that export to STEP for SolidWorks. Use when the request involves CadQuery, .step/.stl export, or modelling a physical part — enclosure, bracket, PCB, motor mount, cam, gear. Also use when a STEP will not open in CAD, or geometry looks correct in STL but is invalid as a solid. Applies a verification discipline before export and documented OCC pitfalls."
---

# CadQuery Modeling for Manufacturable CAD

This skill turns natural-language part requests into clean, verified, parametric
CadQuery code whose STEP output reliably opens in SolidWorks. It encodes hard-won
rules from real multi-part product design.

## Core philosophy

1. **Parametric first** — every dimension is a named variable at the top of the file.
2. **Verify before trusting** — a script that printed `[OK]` is NOT proof of success.
   Always check geometry validity and solid count before declaring done.
3. **Avoid OCC fragility** — prefer simple primitives + boolean operations over
   fragile chained features. See `references/occ_pitfalls.md`.
4. **One part, one file** — each part is its own `.py` producing its own STEP/STL.
   Assemblies are done in SolidWorks, not baked into a single STEP.

## Before creating anything: confirm where

Files land in whatever directory Claude Code was started in — that is the single
thing that determines whether the user finds their STEP later. Before creating a
project or the first part, **state the absolute path you are about to write to**,
and stop to confirm if it looks wrong:

- a cloud-synced path (`OneDrive`, `Dropbox`, `iCloud` — note that on Windows the
  Desktop and Documents folders usually ARE OneDrive)
- `Downloads`, a home directory root, or a system folder
- the `claude-cad` toolkit repo itself
- a path containing spaces, parentheses, or non-ASCII characters

If any of those apply, say so and suggest a clean location such as
`C:\cad_project` before writing files. Getting this wrong is silent: everything
succeeds, and the user simply can't find the output.

## The standard workflow

When the user asks for a part, follow this loop:

1. **Match the questions to how specified the request is.** Never invent a
   critical dimension — ask instead. Default to millimeters.
   - **Underspecified** (e.g. "a bracket to hold a 60 mm pipe"): don't guess, and
     don't refuse. Ask one focused batch of questions covering only what you truly
     can't proceed without — typically overall size, thickness/wall, the
     coordinate system/orientation, and any dimension that must match another part
     or a real component. Keep it short; propose sensible defaults the user can
     accept ("I'll assume 4 mm thick unless you say otherwise").
   - **Fully specified**: don't interrogate. Build it, and list any assumption you
     had to make in the final report.
   - If the user asks you to **write a spec first**, produce it as text (coordinate
     system, overall dimensions, every feature with size + position, interfaces)
     and get approval before writing code.
2. **Write the part file** following the structure in
   `references/part_file_structure.md`.
3. **Run it** and read the full terminal output, not just the last line.
4. **Verify** geometry validity, solid count, volume, and bounding box (see below).
5. **Report** the verification numbers to the user and note any assumptions made.

Read `references/occ_pitfalls.md` before writing any code that uses shell, fillet
after shell, countersinks, or lofts — the operations with a history of silent
corruption. Each pitfall now carries a **Verified behaviour** block saying what
the current kernel actually does; the one reliably reproduced silent failure is
shelling a solid whose removed face was filleted (Pitfall 4b).

## Project layout

Always use this structure so STEP files collect in one place for SolidWorks:

```
project/
├── parts/        # one .py per part
│   ├── housing.py
│   └── pcb.py
├── output/       # STEP + STL land here (git-ignored)
└── docs/
    └── assembly_guide.md
```

Resolve the output path **relative to the script file**, not the working
directory. A bare `"../output/..."` breaks the moment the script is run from the
project root instead of from `parts/` — the export silently lands one folder too
high. Always use this pattern:

```python
from pathlib import Path
OUT = Path(__file__).resolve().parent.parent / "output"
OUT.mkdir(parents=True, exist_ok=True)

cq.exporters.export(part, str(OUT / "housing.step"))
cq.exporters.export(part, str(OUT / "housing.stl"))
print(f"[OK] exported to {OUT}")
```

This works whether the user runs `py -3.11 parts/housing.py` from the project
root or `py -3.11 housing.py` from inside `parts/`. Printing the resolved path
also makes it obvious where the files went.

## Mandatory verification block

Every part file MUST verify before export — either with this inline block, or
(preferred) with the `check()` helper from `scripts/diagnose.py` shown after it.
One of the two is required; a bare `[OK]` print is never sufficient. STL is
forgiving and hides geometry errors that survive into the STEP — and CAD import
is no safety net either: SolidWorks has opened a provably invalid STEP without
warning (`references/occ_pitfalls.md`, "Do not count on CAD import to reject
bad geometry").

```python
# ===== Verification (do not skip) =====
from OCP.BRepCheck import BRepCheck_Analyzer

solid = part.val()
shape = solid.wrapped

# 1. Geometry validity — catches silent OCC corruption
analyzer = BRepCheck_Analyzer(shape)
is_valid = analyzer.IsValid()
print(f"[verify] IsValid = {is_valid}")
if not is_valid:
    raise RuntimeError("Invalid geometry — part is unusable; CAD may still open it without warning.")

# 2. Single-body check — catches stray cut/union debris
n_solids = len(solid.Solids())
print(f"[verify] solid count = {n_solids}")
if n_solids != 1:
    raise RuntimeError(f"Expected 1 solid, found {n_solids}.")

# 3. Volume — ASSERT it against a range DERIVED FROM YOUR PARAMETERS, not the
#    built result. Validity and solid count both pass on a part whose hollow/cut
#    silently did nothing (bbox too); volume is the tell. Compute expected_lo/hi from
#    the dimensions above (e.g. solid block minus the intended cavity, +/-15%).
#    NEVER run the build first and paste Volume()'s output back here.
vol = solid.Volume()
print(f"[verify] volume   = {vol:.2f} mm^3")
assert expected_lo <= vol <= expected_hi, (
    f"Volume {vol:.1f} outside derived range — a hollow/cut may have done nothing.")
print(f"[verify] bbox     = {solid.BoundingBox()}")

# Signature — always end with this line. Its presence in the output is how the
# user can tell the skill's checks actually ran (vs a part written with none).
print("[verify] claude-cad — checks applied")
```

### Prefer the diagnostic helper

The block above is the minimum. For real work, use `scripts/diagnose.py`, which
does the same checks but also *classifies* what's wrong and *safely auto-repairs*
the unambiguous cases (e.g. discarding tiny offcut debris from a multibody result):

**Setup (once per project):** copy `scripts/diagnose.py` from this skill into the
project's `parts/` folder, next to the part files. Python puts a script's own
directory on the import path, so `from diagnose import check` then resolves when
running `py -3.11 parts/<name>.py`. Without this copy the import fails with
`ModuleNotFoundError: No module named 'diagnose'`. (`project_init` also keeps a
canonical copy in `claude-cad/` alongside `preflight.py`; the `parts/` copy is the
one imports resolve against — keep them in sync, and `preflight.py` warns if they
drift.)

**Prefer `export_verified()` — it runs the checks and raises before it writes, so a
failing part is not written *by this function*.** This is a rule you follow, not a
mechanism that prevents export: `cq.exporters.export` is a plain function, so a
script that skips this helper bypasses every check. Prefer it so the safe path is
the easy one.

```python
from pathlib import Path
from diagnose import export_verified        # diagnose.py must be in parts/

OUT = Path(__file__).resolve().parent.parent / "output"

# expect_volume is DERIVED from the parameters above — e.g. solid block minus the
# intended cavity, +/-15%. A range is the honest form; NEVER paste Volume()'s output.
export_verified(part, OUT, "bottom_housing",
    expect_volume=(28000, 38500),           # derived band (preferred over a scalar)
    expect_bbox=(94, 65, 27.2),             # from the stated dimensions
    inside=[(0, 0, 1)],                     # design intent: floor is solid here
    outside=[(47, -12, 10)],                # design intent: this port is void here
    regression_volume=32163.55,             # optional: labelled re-run baseline
)
```

This verifies, exports STEP + STL, and writes `bottom_housing.verified.txt` beside
them — a durable record of what was checked, since terminal output vanishes when
the window closes. Use the lower-level `check()` / `assert_points()` directly only
for intermediate steps mid-build.

**The independent checks are `expect_bbox` and the `assert_points` — lead with
those.** The bounding box is read straight off the stated dimensions, and the
inside/outside points encode design intent (which wall a port is on) — they catch
a feature that is missing, misplaced, or on the wrong face, which validity cannot
see (they caught a microSD port cut into the wrong wall in the sbc-case example).

**`expect_volume` is the weakest check — DERIVE it, don't measure it.** Validity,
solid-count, and bbox all PASS on a part whose `.shell()` silently did nothing (the
outer box is unchanged), so among those numbers volume is the tell for that failure
(`references/occ_pitfalls.md`, Pitfall 4b) — an interior spot-check catches it too.
But volume only helps if it is computed from the parameters *before* building, as a
range (a silent no-op reads several times too high; ±15% catches it). If you omit
it, the report prints "VOLUME UNCHECKED" instead of a clean PASS.
Keep the exact measured figure only as a separate, labelled `regression_volume`.

**Use `assert_points` for anything with a position that matters** — ports, holes,
bosses, openings on specific walls. Geometry can be valid, single-bodied, and the
right volume while a feature sits on the *wrong face*; no topological check sees
that. Sample the middle of each opening (expect outside) and the wall beside it
(expect inside).

When a part fails, **don't guess** — follow the symptom→diagnosis→fix decision tree
in `references/diagnosis.md`. Auto-repair only touches safe, unambiguous cases;
invalid topology is reported (not patched) so a real design error is never hidden.

## Verification, in SolidWorks

After import, the user should confirm in SolidWorks:

- **Mass Properties** — center of mass on expected symmetry axes (X/Y ≈ 0 for a
  symmetric part) is the fastest correctness check.
- **Principal moments of inertia** — the relative sizes confirm which axis is
  long/short, catching swapped dimensions.
- The part opens as a **solid body**, not a surface.

See `references/solidworks_checks.md` for the exact menu paths and what each
number tells you.

## Reference files

Load these as needed:

| File | When to read |
|------|--------------|
| `references/occ_pitfalls.md` | **Before** any shell, fillet, countersink, or loft. This is the most important reference. |
| `references/diagnosis.md` | When a part fails verification — the symptom→diagnosis→fix decision tree, and how to auto-repair. |
| `references/part_file_structure.md` | When writing a new part file from scratch. |
| `references/verification.md` | When a STEP won't open, or geometry looks wrong. |
| `references/solidworks_checks.md` | When validating a part inside SolidWorks. |
| `references/environment.md` | When `cadquery` or `OCP` import fails, or on first setup. |

## Scripts

| Script | Purpose |
|--------|---------|
| `scripts/diagnose.py` | **The intelligence layer.** Diagnoses a part (classifies validity / multibody / degenerate issues) and safely auto-repairs what it can. Use `from diagnose import check` inside a build, or run it on a `.step` from the CLI. |
| `scripts/preflight.py` | Project-level: runs and verifies every `parts/*.py`, then writes a committable `VERIFICATION.md` summary at the project root. Copy it into the project's `claude-cad/` folder and run `py -3.11 claude-cad/preflight.py`. |
| `scripts/verify_step.py` | Lightweight standalone check of any STEP/STL: validity, solid count, volume, bbox. |

## Hard rules (never violate)

- Never invent a critical/interface dimension. Ask instead.
- Never declare success on `[OK]` alone — only after the verification block passes.
- Never use `cskHole` on a shelled (thin-wall) face — build a cutter solid
  instead. (Portability rule: the historical failure does not reproduce on the
  current kernel — see Pitfall 1's Verified behaviour — but the cutter pattern
  is explicit, uniform across hole types, and version-proof, at zero cost.)
- Never bake a multi-part assembly into a single STEP unless the user explicitly
  wants a static snapshot; do assemblies in SolidWorks.
- Always default to millimeters and state the unit.
- Always print the absolute output directory after exporting, so the user never
  has to guess where the file went.
- Never treat `IsValid` + single-solid as sufficient. Always check volume against
  a range **derived from the named parameters** (solid block minus intended
  cavity, or bbox volume × a stated fill fraction) — it is the only check that
  catches a hollow or cut that silently did nothing.
- Never derive `expect_volume` by running the build and pasting `Volume()`'s
  output back as the expectation — that checks the geometry against itself.
  Compute it from the dimensions, in a comment above it, as a range. Keep any
  measured figure only as a separate, labelled `regression_volume`.
- For any feature whose *position* matters, verify it with point classification
  (`assert_points`), not just topology — this is the strongest intent check, not
  an afterthought.
````

## File: .claude/skills/cadquery-modeling/scripts/diagnose.py
size: 26520
sha: 8fac6d23cc78cd96add40cb9fcecc66745d2bed6
upstream: https://github.com/0okevino0/claude-cad/blob/main/.claude/skills/cadquery-modeling/scripts/diagnose.py

```text
#!/usr/bin/env python3
"""
diagnose.py — diagnose and (where safe) auto-repair CadQuery geometry.

This is the "intelligence layer" of claude-cad. Instead of just reporting that a
part is invalid, it identifies WHAT is wrong, classifies it, and applies a safe
fix when one exists.

Two ways to use it:

1. As a library, inside a part file (recommended):

       from diagnose import check, export_verified

       part = check(part, "after shell")          # per-step gate
       part = export_verified(                    # final gate + export + record
           part, OUT, "housing",
           # expect_volume is DERIVED from the parameter block, never measured:
           # e.g. solid block minus the intended cavity, as a wide band.
           expect_volume=(28000, 38500),          # mm^3 range (preferred form)
           expect_bbox=(94.0, 65.0, 27.2),        # mm — from the stated footprint
           inside=[(5, 10, 1.25)],                # points that MUST be material
           outside=[(0, 0, 10)],                  # points that MUST be air
           regression_volume=32163.55,            # optional labelled re-run baseline
       )

   Validity + solid-count show the part is *a* clean solid. The independent
   checks test whether it is *the intended* solid: expect_bbox is read off the
   stated dimensions, and the inside/outside points encode design intent (which
   wall a port sits on) — they catch a feature that is missing, misplaced, or on
   the wrong wall, which validity cannot see. expect_volume is the weakest of the
   three — a range only bounds gross error — so DERIVE it from the parameters;
   do NOT measure the built result and check it against itself.

2. As a CLI, on an exported file:

       py -3.11 diagnose.py path/to/part.step

Design principle: NEVER silently change geometry in a way that could hide a real
design error. Auto-repair only handles unambiguous, safe cases (e.g. discarding
tiny offcut debris). Everything else is reported for a human/Claude to fix using
the matching OCC pitfall.
"""

import sys
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional

try:
    sys.stdout.reconfigure(encoding="utf-8")
except Exception:
    pass

# --------------------------------------------------------------------------- #
# Severity & finding model
# --------------------------------------------------------------------------- #

class Severity(Enum):
    OK = "ok"
    INFO = "info"
    WARNING = "warning"
    ERROR = "error"          # part is unusable (invalid geometry)

@dataclass
class Finding:
    code: str                # short stable id, e.g. "MULTIBODY"
    severity: Severity
    message: str             # human-readable description
    pitfall: Optional[str] = None    # which occ_pitfalls.md section
    auto_fixable: bool = False
    fixed: bool = False      # set True if auto_repair handled it

@dataclass
class Report:
    findings: list = field(default_factory=list)
    volume: Optional[float] = None
    n_solids: Optional[int] = None
    bbox: Optional[tuple] = None
    is_valid: Optional[bool] = None
    # Whether an expectation was actually COMPARED (vs the number merely measured).
    # "PASS" only claims volume/bbox were verified against intent when these are True.
    volume_checked: bool = False
    bbox_checked: bool = False

    @property
    def ok(self) -> bool:
        return not any(f.severity == Severity.ERROR and not f.fixed
                       for f in self.findings)

    def add(self, finding: Finding):
        self.findings.append(finding)

    def raise_if_unrecovered(self):
        """Raise if any ERROR remains unfixed — use to stop a build."""
        unresolved = [f for f in self.findings
                      if f.severity == Severity.ERROR and not f.fixed]
        if unresolved:
            lines = "\n".join(f"  - [{f.code}] {f.message}"
                              + (f"  (see {f.pitfall})" if f.pitfall else "")
                              for f in unresolved)
            raise RuntimeError(
                "Geometry still invalid after auto-repair:\n" + lines)

    def print_report(self):
        print("=" * 56)
        print("  claude-cad diagnostic report")
        print("=" * 56)
        if self.is_valid is not None:
            print(f"  IsValid     : {self.is_valid}")
        if self.n_solids is not None:
            print(f"  solids      : {self.n_solids}")
        if self.volume is not None:
            print(f"  volume      : {self.volume:.2f} mm^3")
        if self.bbox is not None:
            x, y, z = self.bbox
            print(f"  bbox (XYZ)  : {x:.2f} x {y:.2f} x {z:.2f} mm")
        print("-" * 56)
        if not self.findings:
            print("  No issues found.")
        for f in self.findings:
            tag = {"ok": "OK  ", "info": "INFO", "warning": "WARN",
                   "error": "FAIL"}[f.severity.value]
            fixed = "  [auto-fixed]" if f.fixed else (
                "  [auto-fixable]" if f.auto_fixable else "")
            print(f"  {tag}  {f.code}: {f.message}{fixed}")
            if f.pitfall and not f.fixed:
                print(f"        -> {f.pitfall}")
        print("-" * 56)
        if self.ok:
            checked = ["validity", "single-body"]
            if self.volume_checked:
                checked.append("volume")
            if self.bbox_checked:
                checked.append("bbox")
            fixed = [f for f in self.findings if f.fixed]
            if self.volume_checked:
                print(f"  RESULT: PASS — {', '.join(checked)} verified; "
                      "safe to export as a valid single solid")
            else:
                # Do NOT let this read as a clean, fully-verified PASS: the one
                # check that catches a silent no-op hollow (Pitfall 4b) did not run.
                print(f"  RESULT: PASS ({', '.join(checked)}) — but VOLUME UNCHECKED")
                print("          Pass a DERIVED expect_volume (a range is fine). "
                      "Without it a part")
                print("          whose hollow/cut silently did nothing (Pitfall 4b) "
                      "also reaches PASS.")
            if fixed:
                print(f"          {len(fixed)} issue(s) were caught and "
                      "auto-repaired (marked above)")
        else:
            print("  RESULT: PROBLEMS REMAIN — do not export yet")
            print("          claude-cad caught this before you spent time in CAD")
        # Signature: this line proves the skill's checks actually ran on this part.
        # If a report has no such line, the skill was not applied this turn.
        print("  claude-cad — checks applied")
        print("=" * 56)

# --------------------------------------------------------------------------- #
# Core diagnosis
# --------------------------------------------------------------------------- #

def _get_solid_and_wp(part):
    """Accept a Workplane or a Solid; return (solid, workplane_or_None)."""
    import cadquery as cq
    if isinstance(part, cq.Workplane):
        return part.val(), part
    return part, None

def diagnose(part) -> Report:
    """Inspect a CadQuery Workplane/Solid and return a structured Report."""
    from OCP.BRepCheck import BRepCheck_Analyzer

    report = Report()
    solid, _ = _get_solid_and_wp(part)

    # --- solid count ---
    try:
        solids = solid.Solids()
        report.n_solids = len(solids)
    except Exception as e:
        report.add(Finding(
            "NO_SOLID", Severity.ERROR,
            f"Could not read solids from the shape: {e}",
            pitfall="occ_pitfalls.md (Pitfall 6)"))
        return report

    if report.n_solids == 0:
        report.add(Finding(
            "NO_SOLID", Severity.ERROR,
            "Shape contains no solids — an un-extruded sketch, a failed "
            "sweep/loft, or a boolean that consumed everything.",
            pitfall="diagnosis.md (NO_SOLID)"))
    elif report.n_solids > 1:
        vols = sorted((s.Volume() for s in solids), reverse=True)
        report.add(Finding(
            "MULTIBODY", Severity.ERROR,
            f"Expected 1 solid, found {report.n_solids} "
            f"(volumes: {', '.join(f'{v:.1f}' for v in vols)}). "
            "Usually offcut debris from a cut, or a union that didn't merge.",
            pitfall="occ_pitfalls.md (Pitfall 5)",
            auto_fixable=True))

    # --- validity ---
    try:
        report.is_valid = BRepCheck_Analyzer(solid.wrapped).IsValid()
        if not report.is_valid:
            report.add(Finding(
                "INVALID_GEOMETRY", Severity.ERROR,
                "BRepCheck reports invalid geometry — the part is wrong even "
                "if CAD opens the STEP, and the STL may still look fine. "
                "Don't guess the cause: find the FIRST build step that flips "
                "IsValid by gating each step with check().",
                pitfall="diagnosis.md (INVALID_GEOMETRY)"))
    except Exception as e:
        report.add(Finding(
            "VALIDITY_CHECK_FAILED", Severity.ERROR,
            f"Could not run validity check: {e}"))

    # --- numbers (best-effort) ---
    try:
        report.volume = solid.Volume()
        if report.volume is not None and report.volume <= 0:
            report.add(Finding(
                "NONPOSITIVE_VOLUME", Severity.ERROR,
                f"Volume is {report.volume:.3f} — degenerate or inside-out "
                "solid (e.g. reversed orientation, or a shell that went the "
                "wrong direction).",
                pitfall="diagnosis.md (NONPOSITIVE_VOLUME)"))
    except Exception:
        pass

    try:
        bb = solid.BoundingBox()
        report.bbox = (bb.xlen, bb.ylen, bb.zlen)
        tiny = [n for n, v in zip("XYZ", report.bbox) if v < 1e-6]
        if tiny:
            report.add(Finding(
                "DEGENERATE_BBOX", Severity.WARNING,
                f"Bounding box is ~zero along {', '.join(tiny)} — "
                "the part may be flat/degenerate in that direction."))
    except Exception:
        pass

    if report.ok and not report.findings:
        report.add(Finding("CLEAN", Severity.OK,
                           "Valid single solid with sane volume and bbox."))
    return report

# --------------------------------------------------------------------------- #
# Auto-repair (safe cases only)
# --------------------------------------------------------------------------- #

def auto_repair(part):
    """
    Apply safe, unambiguous repairs and return the (possibly fixed) Workplane.

    Currently handles:
      - MULTIBODY: keep the largest solid, discard tiny offcut debris.

    Deliberately does NOT attempt to "fix" invalid B-rep topology — that masks
    real modeling errors. Those are reported by diagnose() for a proper fix.
    """
    import cadquery as cq
    solid, _ = _get_solid_and_wp(part)

    try:
        solids = solid.Solids()
    except Exception:
        return part  # nothing we can safely do

    if len(solids) > 1:
        largest = max(solids, key=lambda s: s.Volume())
        total = sum(s.Volume() for s in solids)
        if total <= 0:
            return part  # degenerate volumes — ambiguous, report instead of guess
        kept = largest.Volume()
        # Only auto-keep-largest when the discarded bits are clearly debris
        # (the largest body dominates). Otherwise it's ambiguous — leave it.
        if kept / total > 0.90:
            return cq.Workplane().add(largest)

    return part

def _check_expectations(report, expect_volume, expect_bbox, tol,
                        regression_volume=None):
    """Compare measured numbers against DERIVED expectations.

    `expect_volume` should be a `(lo, hi)` range derived from the parameters — a
    scalar is accepted (matched within `tol`) but a range is the honest form,
    because the failure that matters is gross (a silent no-op hollow reads several
    times too high), not a couple of percent. `regression_volume` is a separate,
    purely-informational baseline: it flags drift from a previous run/edit but is
    NOT evidence the first build was correct.
    """
    if expect_volume is not None and report.volume is not None:
        report.volume_checked = True
        if isinstance(expect_volume, (tuple, list)):
            lo, hi = expect_volume
        else:
            lo = expect_volume * (1 - tol)
            hi = expect_volume * (1 + tol)
        if not (lo <= report.volume <= hi):
            report.add(Finding(
                "VOLUME_MISMATCH", Severity.ERROR,
                f"Volume {report.volume:.1f} mm^3 is outside the expected "
                f"{lo:.1f}–{hi:.1f}. A volume far ABOVE expectation usually means a "
                "hollow/cut silently did nothing (see Pitfall 4b); far below means a "
                "feature removed more than intended.",
                pitfall="occ_pitfalls.md (Pitfall 4b)"))

    if expect_bbox is not None and report.bbox is not None:
        if any(w is not None for w in expect_bbox):
            report.bbox_checked = True
        for axis, got, want in zip("XYZ", report.bbox, expect_bbox):
            if want is None:
                continue
            if abs(got - want) > max(tol * abs(want), 0.05):
                report.add(Finding(
                    f"BBOX_MISMATCH_{axis}", Severity.ERROR,
                    f"Bounding box {axis} is {got:.2f} mm, expected {want:.2f} mm."))

    # Regression baseline — separate from the correctness gate above. Reported at
    # INFO so it never reads as first-build proof; it only catches later drift.
    if regression_volume is not None and report.volume is not None:
        drift = (report.volume - regression_volume) / regression_volume * 100.0
        if abs(drift) < 1e-6:
            drift = 0.0
        report.add(Finding(
            "VOLUME_REGRESSION", Severity.INFO,
            f"regression baseline {regression_volume:.2f} mm^3; measured "
            f"{report.volume:.2f} ({drift:+.2f}%). Informational: drift here is a "
            "re-run/edit regression to investigate, NOT proof the build matched intent."))

def check(part, label: str = "step", verbose: bool = True,
          expect_volume=None, expect_bbox=None, tol: float = 0.02,
          regression_volume=None):
    """
    Convenience for inside a build: diagnose, auto-repair safe issues, print a
    report, and stop on anything unrecoverable. Returns the (possibly repaired)
    part so you can keep chaining.

        part = check(part, "after shell")
        part = check(part, "final",
                     expect_volume=(28000, 38500),      # DERIVED range, preferred
                     expect_bbox=(94, 65, 27.2))

    `expect_volume` should be a `(lo, hi)` range **derived from the parameter
    block** — solid block minus intended cavity, or bbox volume × a stated fill
    fraction. A scalar is accepted (matched within `tol`, default ±2%) but a range
    is the honest form: the failure that matters is gross (a silent no-op hollow
    reads several times too high), not a couple of percent. Never derive the number
    by running the build and pasting `Volume()` back — that checks the geometry
    against itself. `expect_bbox` is `(x, y, z)` from the stated dimensions; use
    `None` for any axis you don't want checked. `regression_volume` is an optional,
    clearly-labelled re-run baseline reported at INFO — it catches drift, not
    first-build correctness.

    **Pass a derived expect_volume.** Validity and solid-count both PASS on a part
    whose `.shell()` silently did nothing (bbox is unchanged too), so volume is the
    only one of these numbers that catches it — an interior `assert_points` catches
    it as well. If you omit expect_volume the report says so instead of showing a
    clean PASS. See `references/occ_pitfalls.md`, Pitfall 4b.

    Transparency: the part is diagnosed BEFORE repair, so anything auto-repair
    resolved still appears in the report — marked [auto-fixed] — rather than
    being silently hidden by a clean post-repair scan.
    """
    before = diagnose(part)
    repaired = auto_repair(part)
    report = diagnose(repaired)

    # Carry over findings that auto_repair resolved, marked as fixed, so the
    # report never hides that geometry was modified.
    after_codes = {f.code for f in report.findings}
    for f in before.findings:
        if f.auto_fixable and f.code not in after_codes:
            f.fixed = True
            report.findings.insert(0, f)

    _check_expectations(report, expect_volume, expect_bbox, tol,
                        regression_volume=regression_volume)

    if verbose:
        print(f"\n[{label}]")
        report.print_report()
    report.raise_if_unrecovered()
    return repaired

# --------------------------------------------------------------------------- #
# Semantic spot checks (is the feature actually where you meant it?)
# --------------------------------------------------------------------------- #

def classify_point(part, x: float, y: float, z: float, tol: float = 1e-6) -> str:
    """Return 'in', 'out', or 'on' for a point relative to the solid."""
    from OCP.BRepClass3d import BRepClass3d_SolidClassifier
    from OCP.gp import gp_Pnt
    from OCP.TopAbs import TopAbs_IN, TopAbs_OUT

    solid, _ = _get_solid_and_wp(part)
    clf = BRepClass3d_SolidClassifier(solid.wrapped)
    clf.Perform(gp_Pnt(float(x), float(y), float(z)), tol)
    state = clf.State()
    if state == TopAbs_IN:
        return "in"
    if state == TopAbs_OUT:
        return "out"
    return "on"

def assert_points(part, inside=(), outside=(), label: str = "spot checks",
                  verbose: bool = True):
    """
    Verify features are actually WHERE you intended, by classifying sample points.

        assert_points(part,
            inside=[(0, 0, 1)],                 # floor is solid here
            outside=[(47, -12, 10)],            # USB-C opening is void here
        )

    Why this exists: geometry can be perfectly valid, a single solid, and the
    right volume — and still be WRONG. A port cut into the +X wall instead of the
    -X wall passes every topological check; only point classification catches it.
    Validity checks answer "is this a legal solid?"; this answers "is it the solid
    I asked for?"

    Pick points that would only be inside/outside if the feature landed correctly:
    the middle of each opening (expect outside), a spot on the wall beside it
    (expect inside), inside each boss (inside), inside each pilot hole (outside).

    Raises RuntimeError listing every point that came back wrong.
    """
    failures = []
    for pt in inside:
        got = classify_point(part, *pt)
        if got != "in":
            failures.append(f"expected INSIDE, got {got.upper()}: {tuple(pt)}")
    for pt in outside:
        got = classify_point(part, *pt)
        if got != "out":
            failures.append(f"expected OUTSIDE, got {got.upper()}: {tuple(pt)}")

    total = len(inside) + len(outside)
    if verbose:
        status = "PASS" if not failures else f"FAIL ({len(failures)}/{total})"
        print(f"[{label}] {total} point(s) checked -> {status}")
        for f in failures:
            print(f"    {f}")

    if failures:
        raise RuntimeError(
            f"{len(failures)} of {total} spot checks failed — a feature is in the "
            "wrong place or missing:\n  " + "\n  ".join(failures))
    return part

# --------------------------------------------------------------------------- #
# The safe export path: verify, export, leave a record
# --------------------------------------------------------------------------- #

def export_verified(part, out_dir, name, expect_volume=None, expect_bbox=None,
                    inside=(), outside=(), formats=("step", "stl"),
                    tol: float = 0.02, verbose: bool = True,
                    regression_volume=None):
    """
    Verify a part, export it, and write a verification record beside the output.

        from diagnose import export_verified
        from pathlib import Path

        OUT = Path(__file__).resolve().parent.parent / "output"
        export_verified(part, OUT, "bottom_housing",
                        expect_volume=(28000, 38500),   # DERIVED range, not measured
                        expect_bbox=(94, 65, 27.2),     # from the stated dimensions
                        inside=[(0, 0, 1)],             # design intent: solid here
                        outside=[(47, -12, 10)],        # design intent: void here
                        regression_volume=32163.55)     # optional labelled baseline

    This runs `check()` first, which raises on an unrecoverable failure — so a part
    that fails validity or single-body is not written by THIS function. That is a
    rule the model follows, not a mechanism that prevents export: `cq.exporters.export`
    is a plain public function, so calling it directly bypasses every check. Prefer
    this path so the safe route is the easy one.

    Note the check is only as strong as the expectations you pass: without a
    derived `expect_volume`, a silently un-hollowed part (Pitfall 4b) still passes,
    and the report flags that omission rather than showing a clean PASS. The
    `expect_bbox` and inside/outside points are the independent checks — bbox comes
    from the stated dimensions, the points encode design intent (which wall a port
    is on) and catch defects validity cannot see.

    It also writes `<name>.verified.txt` next to the STEP. That record is the
    durable evidence of what was checked — the terminal output disappears when you
    close the window; this doesn't. It travels with the file if you hand the STEP
    to someone else.

    Returns the (possibly auto-repaired) part.
    """
    import datetime
    from pathlib import Path
    import cadquery as cq

    out = Path(out_dir)
    out.mkdir(parents=True, exist_ok=True)

    # 1. Verify — raises if anything is unrecoverable, so nothing bad gets written
    part = check(part, f"{name} — final", verbose=verbose,
                 expect_volume=expect_volume, expect_bbox=expect_bbox, tol=tol,
                 regression_volume=regression_volume)

    n_spot = len(inside) + len(outside)
    if n_spot:
        assert_points(part, inside=inside, outside=outside,
                      label=f"{name} — spot checks", verbose=verbose)

    # 2. Snapshot the verified numbers BEFORE exporting: the STL export
    # tessellates the shape, and a mesh-backed BoundingBox() reads ~0.01 mm
    # larger than the exact B-rep. The record must carry the same numbers the
    # checks above actually verified.
    rep = diagnose(part)

    # 3. Export
    written = []
    for fmt in formats:
        target = out / f"{name}.{fmt}"
        cq.exporters.export(part, str(target))
        written.append(target.name)
    fixed = [f for f in rep.findings if f.fixed]
    stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    bbox_txt = ("%.2f x %.2f x %.2f mm" % rep.bbox) if rep.bbox else "n/a"

    # Record HOW volume was checked, honestly — a derived range, a scalar, or not
    # at all. "verified" below lists only what was actually compared to intent.
    if expect_volume is None:
        vol_basis = "volume check  : NOT CHECKED — no derived expect_volume passed"
    elif isinstance(expect_volume, (tuple, list)):
        vol_basis = ("volume check  : within derived range "
                     f"{expect_volume[0]:.0f}-{expect_volume[1]:.0f} mm^3")
    else:
        vol_basis = (f"volume check  : within +/-{tol*100:.0f}% of "
                     f"{expect_volume:.2f} mm^3 (scalar)")
    bbox_checked = expect_bbox is not None and any(w is not None for w in expect_bbox)

    verified = ["validity", "single-body"]
    if expect_volume is not None:
        verified.append("volume-in-range")
    if bbox_checked:
        verified.append("bbox")
    if n_spot:
        verified.append(f"{n_spot} spot checks")

    lines = [
        "claude-cad verification record",
        "=" * 46,
        f"part          : {name}",
        f"verified at   : {stamp}",
        "",
        f"IsValid       : {rep.is_valid}",
        f"solids        : {rep.n_solids}",
        f"volume        : {rep.volume:.2f} mm^3" if rep.volume is not None
        else "volume        : n/a",
        vol_basis,
        f"bbox (XYZ)    : {bbox_txt}",
        f"spot checks   : {n_spot} passed" if n_spot else "spot checks   : none run",
        f"auto-repaired : {len(fixed)} issue(s)" if fixed else "auto-repaired : none needed",
    ]
    if regression_volume is not None:
        lines.append(f"regression    : baseline {regression_volume:.2f} mm^3 "
                     "(informational, not first-build proof)")
    lines += [
        "",
        f"files         : {', '.join(written)}",
        f"result        : PASS — {', '.join(verified)} verified before export",
        "",
        "Re-run the part file to regenerate and re-verify.",
    ]
    (out / f"{name}.verified.txt").write_text("\n".join(lines) + "\n",
                                              encoding="utf-8")

    if verbose:
        print(f"[OK] {name}: exported {', '.join(written)} + {name}.verified.txt")
        print(f"     -> {out}")
    return part

# --------------------------------------------------------------------------- #
# CLI
# --------------------------------------------------------------------------- #

def _cli(path: str) -> int:
    from pathlib import Path
    p = Path(path)
    if not p.exists():
        print(f"[error] file not found: {p}")
        return 2
    try:
        import cadquery as cq
    except ImportError as e:
        print(f"[error] cannot import cadquery: {e}")
        print("        see docs/python_env_setup.md")
        return 3

    ext = p.suffix.lower()
    try:
        if ext in (".step", ".stp"):
            part = cq.importers.importStep(str(p))
        else:
            print(f"[error] CLI supports .step/.stp; got {ext}")
            return 2
    except Exception as e:
        print(f"[fail] could not load (likely invalid geometry): {e}")
        return 1

    report = diagnose(part)
    report.print_report()
    return 0 if report.ok else 1

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(__doc__)
        sys.exit(2)
    sys.exit(_cli(sys.argv[1]))
```

## File: .claude/skills/cadquery-modeling/scripts/preflight.py
size: 7303
sha: 037c8848f815f506ead590121b2d6467bace7540
upstream: https://github.com/0okevino0/claude-cad/blob/main/.claude/skills/cadquery-modeling/scripts/preflight.py

```text
#!/usr/bin/env python3
"""
preflight.py — run and verify every part in a project's parts/ directory.

For each parts/*.py, this runs the script with the current interpreter and reports
whether it completed and exported. Use it before committing or assembling, to catch
a part that silently stopped verifying.

This file lives in the project's claude-cad/ folder, alongside the canonical
diagnose.py. It locates parts/ and output/ relative to ITS OWN location — the
project root is its parent folder — so it works no matter the current directory:

    py -3.11 claude-cad/preflight.py      # from the project root
    py -3.11 preflight.py                 # from inside claude-cad/
    py -3.11 claude-cad/preflight.py path/to/other/parts   # explicit parts dir
"""

import subprocess
import sys
from pathlib import Path

try:
    sys.stdout.reconfigure(encoding="utf-8")
except Exception:
    pass

# This script sits in <project>/claude-cad/; the project root is one level up.
CLAUDE_CAD_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = CLAUDE_CAD_DIR.parent

def _check_diagnose_drift(parts: Path) -> None:
    """Warn if parts/diagnose.py has drifted from the canonical claude-cad/ copy.

    diagnose.py is deliberately kept in two places: the canonical copy here in
    claude-cad/, and a working copy in parts/ that a bare `from diagnose import`
    resolves against. If a skill upgrade refreshes one but not the other they
    diverge silently — this makes that loud.
    """
    canonical = CLAUDE_CAD_DIR / "diagnose.py"
    working = parts / "diagnose.py"
    try:
        if (canonical.exists() and working.exists()
                and canonical.read_bytes() != working.read_bytes()):
            print(f"[warn] {working} differs from the canonical {canonical}.")
            print("       Refresh the working copy: copy claude-cad/diagnose.py "
                  "over parts/diagnose.py so imports match the verified library.\n")
    except OSError:
        pass

def main(parts_dir: str = None) -> int:
    parts = Path(parts_dir).resolve() if parts_dir else PROJECT_ROOT / "parts"
    if not parts.is_dir():
        print(f"[error] not a directory: {parts}")
        return 2

    _check_diagnose_drift(parts)

    # Skip helper modules that live alongside the parts (diagnose.py is copied
    # into parts/ by design) and private files — they aren't parts, and running
    # them produces a spurious FAIL.
    HELPERS = {"diagnose.py", "preflight.py", "verify_step.py"}
    files = sorted(f for f in parts.glob("*.py")
                   if f.name not in HELPERS and not f.name.startswith("_"))
    if not files:
        print(f"[error] no .py files in {parts}")
        return 2

    print(f"[preflight] {len(files)} part(s) in {parts}\n")
    passed, failed = [], []

    for f in files:
        print(f"=== {f.name} ===")
        try:
            result = subprocess.run(
                [sys.executable, f.name],
                cwd=str(parts),
                capture_output=True,
                text=True,
                # Part files force their stdout to UTF-8 (the UTF-8 guard), so
                # decode the same way — the Windows default (cp1252) mangles
                # the report's em-dashes into mojibake.
                encoding="utf-8",
                errors="replace",
                timeout=300,
            )
        except subprocess.TimeoutExpired:
            print("  [FAIL] timed out (>300s)\n")
            failed.append(f.name)
            continue

        out = (result.stdout or "") + (result.stderr or "")
        # Show the verification / OK lines for quick scanning.
        for line in out.splitlines():
            if any(tag in line for tag in ("[verify]", "[OK]", "RESULT:",
                                           "auto-fixed", "Error", "error",
                                           "Traceback", "assert", "Invalid")):
                print(f"  {line}")

        # Accept both verification styles: the inline block ("[verify]") and
        # the diagnose.py helper ("RESULT: PASS").
        ok = result.returncode == 0 and (
            "[verify]" in out or "RESULT: PASS" in out)
        print(f"  -> {'PASS' if ok else 'FAIL'}\n")
        (passed if ok else failed).append(f.name)

    print("=" * 40)
    print(f"PASS: {len(passed)}   FAIL: {len(failed)}")
    if failed:
        print("Failed parts:")
        for name in failed:
            print(f"  - {name}")

    summarize(parts.parent / "output")

    return 1 if failed else 0

def summarize(out_dir: Path) -> None:
    """
    Aggregate every <name>.verified.txt into one project-level VERIFICATION.md.

    This is the artifact you can commit, screenshot, or hand to a reviewer: a
    single table showing that every part in the project was checked, with the
    numbers. Individual records are written by export_verified() at build time.

    The summary lands at the project root (not in output/, which is git-ignored)
    so it can be committed alongside the source.
    """
    if not out_dir.is_dir():
        return
    records = sorted(out_dir.glob("*.verified.txt"))
    if not records:
        return

    rows, repaired_total = [], 0
    for rec in records:
        fields = {}
        for line in rec.read_text(encoding="utf-8").splitlines():
            if ":" in line:
                k, _, v = line.partition(":")
                fields[k.strip()] = v.strip()
        rows.append(fields)
        note = fields.get("auto-repaired", "")
        if note and not note.startswith("none"):
            try:
                repaired_total += int(note.split()[0])
            except (ValueError, IndexError):
                pass

    lines = [
        "# Verification summary",
        "",
        f"Each of these {len(rows)} part(s) ran claude-cad's checks before export: "
        "validity and single-body always, plus a derived volume range, bounding box, "
        "and point spot-checks where the part declares them. These are rules the part "
        "files follow before calling the exporter, not a mechanism that blocks it.",
        "",
        "| Part | Valid | Solids | Volume (mm³) | Bounding box | Spot checks |",
        "|------|-------|--------|--------------|--------------|-------------|",
    ]
    for f in rows:
        lines.append(
            f"| {f.get('part', '?')} | {f.get('IsValid', '?')} | "
            f"{f.get('solids', '?')} | {f.get('volume', '?').replace(' mm^3', '')} | "
            f"{f.get('bbox (XYZ)', '?')} | {f.get('spot checks', '?')} |")

    if repaired_total:
        lines += ["", f"**{repaired_total} geometry issue(s)** were caught and "
                      "safely auto-repaired during these builds."]
    lines += ["", "_Regenerate by re-running the part files, then "
                  "`py -3.11 claude-cad/preflight.py` from the project root._"]

    # Written to the PROJECT ROOT, not output/ — output/ is git-ignored, and this
    # summary is meant to be committable and shareable.
    target = out_dir.parent / "VERIFICATION.md"
    target.write_text("\n".join(lines) + "\n", encoding="utf-8")
    print(f"\n[summary] {len(rows)} verification record(s) -> {target}")

if __name__ == "__main__":
    target = sys.argv[1] if len(sys.argv) > 1 else None
    sys.exit(main(target))
```

## File: .claude/skills/cadquery-modeling/scripts/verify_step.py
size: 3112
sha: 718ee6da35606cbafa7b3ae6ecc7604dc8662cd2
upstream: https://github.com/0okevino0/claude-cad/blob/main/.claude/skills/cadquery-modeling/scripts/verify_step.py

```text
#!/usr/bin/env python3
"""
verify_step.py — standalone validity check for a STEP or STL file.

Reports geometry validity, solid count, volume, and bounding box. Use it when a
file is suspect (e.g. won't open in SolidWorks) to confirm whether the geometry
itself is the problem.

Usage:
    py -3.11 verify_step.py path/to/part.step

(.stl files are reported as SKIPPED — STL is a mesh, so B-rep validity checks
don't apply; run the tool on the matching .step export.)
"""

import sys
from pathlib import Path

try:
    sys.stdout.reconfigure(encoding="utf-8")
except Exception:
    pass

def verify(path: str) -> int:
    p = Path(path)
    if not p.exists():
        print(f"[error] file not found: {p}")
        return 2

    try:
        import cadquery as cq
        from OCP.BRepCheck import BRepCheck_Analyzer
    except ImportError as e:
        print(f"[error] cannot import cadquery/OCP: {e}")
        print("        See the skill's references/environment.md (Python-version trap)")
        return 3

    ext = p.suffix.lower()
    try:
        if ext in (".step", ".stp"):
            shape = cq.importers.importStep(str(p))
        elif ext == ".stl":
            # STL is a triangle mesh — B-rep validity/solid checks don't apply.
            # CadQuery has no public STL importer; check the matching STEP instead.
            print("[warn] STL is a mesh; validity checks apply to STEP files.")
            print(f"[info] file size = {p.stat().st_size} bytes")
            print("[done]  SKIPPED — run this on the .step export for a full check")
            return 0
        else:
            print(f"[error] unsupported extension: {ext}")
            return 2
    except Exception as e:
        print(f"[fail] could not load file (likely invalid geometry): {e}")
        return 1

    solid = shape.val()
    rc = 0

    try:
        valid = BRepCheck_Analyzer(solid.wrapped).IsValid()
        print(f"[verify] IsValid    = {valid}")
        if not valid:
            rc = 1
    except Exception as e:
        print(f"[verify] IsValid    = <error: {e}>")
        rc = 1

    try:
        n = len(solid.Solids())
        print(f"[verify] solids     = {n}")
        if n != 1:
            print("         (expected 1 — multiple solids usually means stray bodies)")
            rc = 1   # same verdict diagnose.py gives this file: it's a defect
    except Exception as e:
        print(f"[verify] solids     = <error: {e}>")

    try:
        print(f"[verify] volume     = {solid.Volume():.2f} mm^3")
    except Exception as e:
        print(f"[verify] volume     = <error: {e}>")

    try:
        bb = solid.BoundingBox()
        print(f"[verify] bbox xlen  = {bb.xlen:.2f} mm")
        print(f"[verify] bbox ylen  = {bb.ylen:.2f} mm")
        print(f"[verify] bbox zlen  = {bb.zlen:.2f} mm")
    except Exception as e:
        print(f"[verify] bbox       = <error: {e}>")

    print("[done]" + ("  PASS" if rc == 0 else "  PROBLEMS FOUND"))
    return rc

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(__doc__)
        sys.exit(2)
    sys.exit(verify(sys.argv[1]))
```

## File: .claude/skills/cadquery-modeling/references/diagnosis.md
size: 7716
sha: e0fd749967ac5c8e4581a4ab92f501b1224f2d94
upstream: https://github.com/0okevino0/claude-cad/blob/main/.claude/skills/cadquery-modeling/references/diagnosis.md

````text
# Diagnosis & Repair — the decision tree

This is the intelligence layer. When a part fails, don't guess — run the symptom
through this tree to classify the problem, then apply the matching action. The
`scripts/diagnose.py` module automates most of this; this file is the reasoning
behind it (and what to do when you're working by hand).

## The principle

> **Never silently change geometry in a way that could hide a real design error.**

Auto-repair only handles *unambiguous, safe* cases (e.g. discarding tiny offcut
debris). Anything that might mask a genuine mistake is *reported*, not patched.

## Top-level flow

```
run the part
   │
   ├─ Python errored before export?  ───────────────► read the traceback;
   │                                                   usually an OCC op failed
   │                                                   (go to "Hard failures")
   │
   └─ Python finished → DIAGNOSE the result:
         │
         ├─ n_solids == 0   ─► NO_SOLID        (ERROR)  → see below
         ├─ n_solids  > 1   ─► MULTIBODY       (ERROR)  → auto-fixable, Pitfall 5
         ├─ IsValid == False ─► INVALID_GEOMETRY (ERROR) → locate the step (below)
         ├─ volume  <= 0    ─► NONPOSITIVE_VOLUME (ERROR) → see below
         ├─ bbox ~0 on an axis ─► DEGENERATE_BBOX (WARN) → check intent
         └─ none of the above ─► CLEAN (OK) → import to SolidWorks
```

## Symptom → diagnosis → action

### MULTIBODY (`n_solids > 1`)

- **Diagnosis:** a `cut` left offcut material, or a `union` didn't actually merge
  (inputs weren't overlapping).
- **Auto-repair (safe):** if the largest solid is >90% of total volume, keep it
  and discard the debris. `auto_repair()` / `check()` do this automatically.
- **If NOT dominated** (two comparable bodies): ambiguous — do **not** auto-keep.
  This usually means a real modeling mistake (a feature placed in the wrong spot).
  Fix the overlap so the union merges, or reposition the stray feature.
- **Reference:** `occ_pitfalls.md`, Pitfall 5.

### INVALID_GEOMETRY (`IsValid == False`)

- **Diagnosis:** a topological defect. Don't guess which operation caused it —
  the historically blamed culprits (countersinks on shelled walls, face-selected
  `cutThruAll`, loft domes) do **not** reproduce as failures on the current
  kernel (`occ_pitfalls.md`, Pitfalls 1–3, Verified behaviour). One *observed*
  current cause: shelling a solid whose removed face was filleted can yield an
  invalid result in some shapes (Pitfall 4, verified table).
- **Action (locate, then replace):** add per-step checks to find the FIRST step
  that flips `valid` to False:

  ```python
  from diagnose import check
  part = check(part, "after extrude")
  # ... after shell ...
  part = check(part, "after shell")
  # ... after each cut ...
  ```

  Then swap the culprit for the robust pattern:
  | Culprit step | Replace with |
  |--------------|--------------|
  | any hole/countersink feature op | cutter cylinder + `.cut()` |
  | face `.cutThruAll()` after shell | bounded cutter solid + `.cut()` |
  | `.shell()` on a fillet-topped solid | fillet kept faces only, or subtract a cavity solid |
  | `loft` dome | union/subtract a sphere/ellipsoid |
- **Not auto-fixable:** patching invalid topology would hide the real cause.
- **Reference:** `occ_pitfalls.md` — each pitfall's Verified behaviour block.

### NO_SOLID (`n_solids == 0`)

- **Diagnosis:** the result is a surface or empty — an un-extruded sketch, a
  failed sweep/loft, or a boolean that consumed everything.
- **Action:** rebuild the failing step with primitives + booleans; verify the base
  solid exists before adding features.

### NONPOSITIVE_VOLUME (`volume <= 0`)

- **Diagnosis:** an inside-out or degenerate solid (e.g. reversed orientation, a
  shell that went the wrong direction, or self-intersecting input).
- **Action:** check the shell sign/thickness and the fillet order (fillet only
  the faces the shell keeps); rebuild the step.
- **Reference:** `occ_pitfalls.md`, Pitfall 4.

### VOLUME_MISMATCH (volume far from your estimate)

- **Volume much HIGHER than expected** → a hollow or cut silently did nothing.
  The classic case is `.shell(-t)` on a solid whose **removed face was
  filleted**: OCC returns the original solid, valid and single-bodied. (The
  fillet radius vs the wall thickness is *not* the trigger.) See
  `occ_pitfalls.md`, Pitfall 4b. Fix by not filleting the face the shell
  removes, or by subtracting a cavity solid instead of shelling.
- **Volume much LOWER than expected** → a cutter was oversized or applied twice.
- **Not auto-fixable.** Both cases are modeling errors, not debris.

### Feature in the wrong place (topologically valid, semantically wrong)

- **Diagnosis:** the solid is valid, single, and the right size — but a port, hole,
  or boss landed on the wrong face or at the wrong coordinate. A hard-coded sign
  (`+X` where the loop should have used the wall's own sign) is the usual cause.
- **No topological check will catch this.** Use `assert_points()`: sample the
  middle of each opening (expect `outside`) and the wall right beside it (expect
  `inside`). A wrong-wall cut shows up immediately as an inverted result.
- **Action:** parameterize the direction instead of hard-coding it, then re-run
  the spot checks.

### DEGENERATE_BBOX (one axis ~0)

- **Diagnosis:** the part is flat in one direction. Sometimes intended (a thin
  plate), sometimes a missed extrude.
- **Action:** confirm against the intended overall size; only act if unexpected.

## Hard failures (Python raised before export)

If the script crashed (not just produced a bad result):

1. **`ModuleNotFoundError: OCP`** → wrong Python version. See the environment
   setup notes (use 3.11; `py -3.11 ...`).
2. **`UnicodeEncodeError`** → missing UTF-8 guard; the export may actually have
   succeeded. Add the guard from the standard part-file skeleton and re-run.
3. **OCC error inside an op** (`BRep_API`, `StdFail_NotDone`, "only N faces") →
   that op is one of the fragile ones. Go straight to the matching pitfall and use
   the robust pattern.

## Using the automation

**Setup (once per project):** copy the skill's `scripts/diagnose.py` into the
project's `parts/` folder, next to the part files. Python puts a running script's
own directory on the import path, so `from diagnose import check` then resolves.
(Alternative: keep it elsewhere and add that folder to `sys.path` at the top of
each part file.) Skipping this yields `ModuleNotFoundError: No module named 'diagnose'`.

In a part file (recommended):

```python
from diagnose import check, export_verified
from pathlib import Path

# ... build steps, gating the fragile ones ...
part = check(part, "after shell")

# Final gate + export + a .verified.txt record in one call — export_verified()
# raises before it writes, so a failure never reaches disk through it (calling
# cq.exporters.export yourself skips that). Resolve the output folder from the
# script file, never a bare "../output/".
OUT = Path(__file__).resolve().parent.parent / "output"
part = export_verified(part, OUT, "part",
                       expect_volume=(28000, 38500),   # DERIVED range, not measured
                       inside=[(0, 0, 1)],             # design intent: material here
                       outside=[(47, 0, 10)])          # design intent: air here
```

On an exported file:

```bash
py -3.11 diagnose.py ../output/part.step
```

The CLI prints the same structured report (validity, solids, volume, bbox, and a
classified list of findings with the pitfall to consult).
````

## File: .claude/skills/cadquery-modeling/references/environment.md
size: 3345
sha: cc75afe671d95d98b37e3b7b6a27c41ab33e7267
upstream: https://github.com/0okevino0/claude-cad/blob/main/.claude/skills/cadquery-modeling/references/environment.md

````text
# Environment Setup

Getting CadQuery installed reliably — including the version trap that wastes the
most time.

## TL;DR

- Use **Python 3.11** (or 3.12). **Avoid the newest release** (e.g. 3.13/3.14):
  CadQuery's `OCP` kernel binding often lags new Python versions, so `pip install`
  "succeeds" but `import OCP` fails.
- Install: `py -3.11 -m pip install cadquery`
- Verify: `py -3.11 -c "import cadquery, OCP; print('env OK')"`

## The version trap (read this)

**Symptom:** `ModuleNotFoundError: No module named 'OCP'` when running a part,
even though `pip install cadquery` reported success.

**Cause:** `OCP` (the OpenCASCADE Python binding CadQuery depends on) ships
prebuilt wheels that trail the latest Python release. On a too-new Python, pip
installs the pure-Python parts of CadQuery but cannot install `OCP`, so imports
fail at runtime.

**Make it worse:** having **multiple Python versions** installed (e.g. 3.11 and
3.14). An assistant or `pip` may install into one and run from another, producing
a confusing "installed but missing" state — and a tool may even *report success*
while silently using the wrong interpreter.

**Fix:**

```powershell
# See what's installed
py --list

# Install CadQuery specifically into 3.11
py -3.11 -m pip install cadquery

# Verify BOTH cadquery and OCP import on 3.11
py -3.11 -c "import cadquery, OCP; print('env OK')"

# Always run parts with the same interpreter
py -3.11 part.py
```

If a stray newer version keeps getting picked up, uninstall it or pin the default:

```powershell
# Make `py` default to 3.11 for the user
setx PY_PYTHON 3.11
# (open a new terminal afterwards)
```

## Windows terminal / UTF-8

PowerShell defaults to cp1252 and will raise `UnicodeEncodeError` when a script
`print`s non-ASCII text — which looks like a modeling crash even though export
already happened. Guard every part file:

```python
import sys
try:
    sys.stdout.reconfigure(encoding="utf-8")
except Exception:
    pass
```

## Cloud-sync folders (OneDrive / Dropbox / iCloud)

Two failure modes when your project lives in a synced folder:

1. **Cloud-only placeholders** — the file shows in Explorer but isn't on disk, so
   SolidWorks can't open it. Right-click → **Always keep on this device**, or move
   the project out of the synced folder.
2. **Sync paused / lag** — a freshly written STEP may not be materialized yet.

**On Windows, Desktop and Documents are OneDrive by default.** Users routinely
put a project "on the Desktop" without realizing that *is* OneDrive. The tell is
the Explorer path bar showing an account name (`Zhang - Personal › Desktop › …`)
rather than `C:\Users\…`. Don't just warn "avoid OneDrive" — check where the
project actually lives.

**Recommendation:** keep active CAD projects in a short, local, ASCII path such as
`C:\cad_project\` — outside any sync folder, no spaces, no non-ASCII characters,
no parentheses. This sidesteps both the sync issues and importer path quirks.

## Quick smoke test

```python
import cadquery as cq
box = cq.Workplane("XY").box(10, 10, 10)
from OCP.BRepCheck import BRepCheck_Analyzer
print("valid:", BRepCheck_Analyzer(box.val().wrapped).IsValid())
cq.exporters.export(box, "smoke.step")
print("ok")
```

If this prints `valid: True` / `ok` and `smoke.step` opens in SolidWorks, the
environment is good.
````

## File: .claude/skills/cadquery-modeling/references/occ_pitfalls.md
size: 14042
sha: d93d2726ecedbf8a573175a033b0b24c2f9d10af
upstream: https://github.com/0okevino0/claude-cad/blob/main/.claude/skills/cadquery-modeling/references/occ_pitfalls.md

````text
# OCC Pitfalls — operations that silently corrupt geometry

CadQuery is built on the OpenCASCADE (OCC) kernel. OCC will sometimes produce
**wrong or invalid geometry without raising any error**. The Python script
prints `[OK]`, the STL renders fine in a viewer — and the exported STEP is a
part that was never hollowed, carries stray bodies, or fails `BRepCheck`. Do
not expect CAD import to be the safety net: in our one direct test, SolidWorks
opened a provably invalid STEP with no dialog at all (see below).

The rules below come from debugging real parts. Read this before writing code
that shells, fillets, countersinks, or lofts.

**Provenance & testing:** every kernel-side claim below carries a **Verified
behaviour** block stating what actually happens on the recorded environment —
regenerate with `py -3.11 .claude/tests/repro_pitfalls.py` after a kernel upgrade.
Current record: **CadQuery 2.7.0 / OCP 7.8.1.1 / Python 3.11.9 / Windows
(2026-07-21).** SolidWorks-side statements (what its importer accepts or
rejects) are field reports from real debugging sessions, plus one direct
import test recorded below (2026-08-06); the script cannot re-test them.

## Why STL looks fine while the STEP is wrong

| Format | What it stores | Tolerance for errors |
|--------|----------------|----------------------|
| STL | Triangle mesh (an approximation) | High — triangulation papers over bad topology |
| STEP | Exact B-rep solid | Strict — any topological defect makes it invalid |

So **STL looking correct proves nothing** about whether the solid is valid.
Always run the `BRepCheck_Analyzer` validity check from the SKILL before export.

## Do not count on CAD import to reject bad geometry

It is tempting to assume that if the geometry were really broken, SolidWorks
would at least refuse the file. Tested once, directly (2026-08-06): it did not.

- **The file:** a 40 × 40 × 20 mm box, corner (`|Z` r=4) and top (`>Z` r=0.8)
  fillets, then `.faces(">Z").shell(-2.5)` — Pitfall 4's "corners + top" row.
  The kernel returns it silently un-hollowed with **`IsValid=False`**.
- **Why it is provably broken:** the solid reports a volume of 51,185 mm³ —
  more than its own 32,000 mm³ bounding box can contain — and re-importing the
  exported STEP with OCC yields **0 solids**.
- **What SolidWorks did:** opened it cleanly — no error dialog, no Import
  Diagnostics findings, with "Try forming solid(s)" on. Tested on a current
  SolidWorks release (2026); the exact build was not captured, so record your
  own version if you reproduce this.

**Limits of this observation:** one file, one machine, one SolidWorks version.
It does not show CAD never rejects bad geometry — real import failures happen,
and debugging them has usually traced to file access (stale/locked file,
cloud-sync placeholder, non-ASCII path; see `verification.md`). What it does
show: **import success is no evidence of valid geometry.** The verification
block before export is the only check you control.

To reproduce: the construction re-runs in `.claude/tests/repro_pitfalls.py`
(Pitfall 4, "corners+top" row); export it with `cq.exporters.export()` and
open the STEP yourself.

---

## Pitfall 1 — `cskHole` / countersinks on a shelled wall

**Historical symptom** (earlier sessions/kernels): after `.shell()`, calling
`.cskHole(...)` on the thin wall produced either an `OCC ... only 2 faces`
error, or silently invalid geometry.

**Verified behaviour (CadQuery 2.7.0 / OCP 7.8.1.1, 2026-07-21): NOT
REPRODUCED.** The AVOID example below — including a countersink cone deeper
than the 2.5 mm wall — completed without error and produced a valid single
solid that survives a STEP round-trip (`.claude/tests/repro_pitfalls.py`).

**Use the cutter pattern anyway — as the preferred construction, not because
the current kernel is known to break:** the cutter's position, direction, and
extent are explicit, whereas `cskHole` inherits the selected face's workplane
normal, which shelling has historically flipped; and one pattern covers every
hole type, so parts stay uniform and version-proof.

```python
# AVOID — works on the current kernel, but direction and validity have been
# version-dependent on shelled walls
part = part.faces("<Z").workplane().pushPoints(holes).cskHole(...)

# PREFERRED — explicit cutter, direction unambiguous
for (x, y) in holes:
    cutter = (
        cq.Workplane("XY")
        .center(x, y)
        .circle(hole_d / 2)
        .extrude(thickness + 1)   # +1 guarantees full pass-through
    )
    part = part.cut(cutter)
```

If you need a chamfer at the hole mouth, add it as a separate, small `.fillet()`
or `.chamfer()` on the resulting edge afterward, and re-verify.

---

## Pitfall 2 — face-selected `cutThruAll` after shelling

**Historical symptom** (earlier sessions/kernels): the through-cut appeared to
do nothing — the workplane normal on the shelled face pointed away from the
material, so the cut went into empty space.

**Verified behaviour (CadQuery 2.7.0 / OCP 7.8.1.1, 2026-07-21): NOT
REPRODUCED — but a different, real hazard was observed.** The AVOID example
below cut correctly, in the correct direction. However `cutThruAll` means
exactly that: with the profile overlapping a side wall, it removed the wall
material **all the way up the column**, not just the floor under the profile
(`.claude/tests/repro_pitfalls.py`, column probe). On a hollow part there is usually
material above the face you selected — a cut-through-everything is rarely what
you meant.

**Fix:** build a cutter solid — it reaches exactly as far as you make it, no
further, and its direction is explicit:

```python
# AVOID — cuts EVERYTHING in the profile's column (floor, walls, bosses
# above), and its direction has been version-dependent on shelled faces
part = part.faces("<Z").workplane().placeSketch(profile).cutThruAll()

# PREFERRED — cutter spans exactly the material you intend to remove
cutter = (
    cq.Workplane("XY")
    .rect(length, width)
    .extrude(part_height + 1)
    .edges("|Z").fillet(corner_r)
)
part = part.cut(cutter)
```

---

## Pitfall 3 — `loft` for domes / organic tops

**Historical symptom** (earlier sessions/kernels): a lofted dome looked fine in
STL but the STEP was invalid, or fillets on the lofted edge failed.

**Verified behaviour (CadQuery 2.7.0 / OCP 7.8.1.1, 2026-07-21): NOT
REPRODUCED.** A rect→circle dome loft produced a valid solid, a fillet on the
lofted edge succeeded, and the STEP round-trip re-imported valid
(`.claude/tests/repro_pitfalls.py`).

**Prefer the primitive-boolean dome anyway:** a sphere/ellipsoid dome has a
named radius you can edit — a loft's shape is implicit in its profiles, which
fights the parametric-first rule — and historical sessions did see invalid
lofts on earlier kernels. For a domed top, union a scaled sphere/ellipsoid or
subtract one to carve the dome:

```python
# Instead of lofting a flat top up to a point,
# union a half-ellipsoid, or cut the top with a large sphere.
dome = cq.Solid.makeSphere(radius).move(cq.Location(cq.Vector(0, 0, z)))
part = part.union(dome)   # then keep the half you want
```

If you must loft, verify immediately and be ready to fall back to the boolean
approach.

---

## Pitfall 4 — fillet/shell ordering

**Never fillet the face that `.shell()` is about to remove.** That is the single
rule that matters here, and getting it wrong fails *silently* — see Pitfall 4b.

Working order:

1. Build the base solid.
2. Fillet **only the outer edges on faces the shell will keep** — for
   `.faces(">Z").shell(-t)` (open top) that means the bottom `<Z` edge and the
   vertical `|Z` corners, **never the top `>Z` edge**.
3. **Then** shell.
4. Fillet the open rim afterwards if you want it broken, or skip it.
5. Then cut holes/openings with explicit cutter solids.

Filleting the kept outer form before shelling lets the wall follow the rounded
shape. Filleting an already-thinned wall after shelling is more likely to fail —
but it fails loudly, which is far better than the silent case below.

**Verified behaviour (CadQuery 2.7.0 / OCP 7.8.1.1, 2026-07-21: REPRODUCED —
`.claude/tests/repro_pitfalls.py`)** (box + `.faces(">Z").shell(-2.5)`):

| Fillet | Radius vs wall | Result |
|--------|----------------|--------|
| bottom `<Z` (kept face) | r = 0.8 < 2.5 | hollows correctly |
| bottom `<Z` (kept face) | r = 2.5 = wall | **raises `StdFail_NotDone`** — loud, easy to catch |
| top `>Z` (**removed face**) | r = 0.8 | **silent no-op** — still solid, `IsValid=True` |
| corners + top | any | **silent no-op**; validity varies — observed `IsValid=False` on a square box but `IsValid=True` on a rounded rectangle |

Note the radius relationship is *not* the trigger for the silent failure. A small
fillet on a kept face is fine; a fillet equal to the wall raises. Only a fillet on
the **removed** face fails quietly. The volume check catches **every** variant;
the validity check catches only some of them. The square-box `IsValid=False`
variant is also the file SolidWorks opened without complaint — see "Do not count
on CAD import to reject bad geometry" above.

---

## Pitfall 4b — `shell` silently returns the part **un-hollowed**

**Symptom:** `.shell(-t)` reports success, `IsValid=True`, solid count is 1, and
nothing looks wrong — but the part is still **solid**. The topological checks all
pass; the tells are the volume (it stays at the full-block figure instead of
dropping) and an interior point that should be void classifying as material.

**Why:** the offset operation can't resolve the face it is being asked to remove
once that face has been filleted, so OCC returns the **original solid** rather
than raising. In practice this means: you filleted the top rim, then shelled the
top open.

**Verified behaviour (CadQuery 2.7.0 / OCP 7.8.1.1, 2026-07-21): REPRODUCED**
— the real case below re-runs in `.claude/tests/repro_pitfalls.py`.

Real case: an enclosure with a 2.5 mm wall, filleted on the bottom edge *and* the
top edge, then `.faces(">Z").shell(-2.5)`. Reported volume ~158,000 mm³ against a
volume *derived* from the dimensions of ~33,000 (a 94×65×26 block minus the
89×60×23.5 cavity) — a green report on a solid brick, `IsValid=True`.

**Fix — pick one:**

1. **Don't fillet the face you're about to remove.** Fillet the bottom and the
   vertical corners, shell, then fillet the open rim afterwards if you want it.
2. **Cut the cavity as a boolean instead of shelling.** Build an inner solid
   (outer profile inset by `t`, inner corner radius `R − t`, floor at `+t`) and
   subtract it. Every outer fillet survives, and there is no removed face to trip
   over:

```python
cavity = (
    cq.Workplane("XY", origin=(0, 0, wall))
    .rect(length - 2*wall, width - 2*wall)
    .extrude(height)          # open top
    .edges("|Z").fillet(corner_r - wall)
)
part = part.cut(cavity)
```

**Always assert the volume dropped.** This pitfall is invisible to validity and
solid-count checks — a volume comparison against a *derived* range catches it (as
does an interior spot-check that expects void), so run at least one of them:

```python
before = part.val().Volume()
part = part.faces(">Z").shell(-wall)     # or the cavity cut above
assert part.val().Volume() < before * 0.6, "hollowing did not happen"
```

---

## Pitfall 5 — stray bodies from cut/union (multibody)

**Symptom:** the STEP imports as **multiple bodies** — the intended part plus a
small floating disc or sliver.

**Why:** a `cut` left behind offcut material, or a `union` didn't actually merge
(parts weren't overlapping), leaving two disjoint solids.

**Verified behaviour (CadQuery 2.7.0 / OCP 7.8.1.1, 2026-07-21): REPRODUCED.**
A union of non-overlapping boxes yields `solids=2` with `IsValid=True` — the
validity check alone misses it, which is exactly why the solid-count check
exists — and both bodies survive the STEP round-trip
(`.claude/tests/repro_pitfalls.py`).

**Fix:** the solid-count check in the verification block catches this. To recover,
keep the largest solid:

```python
solids = part.val().Solids()
if len(solids) > 1:
    largest = max(solids, key=lambda s: s.Volume())
    part = cq.Workplane().add(largest)
```

Better: ensure union inputs actually overlap, and that cutters fully pass through.

---

## Pitfall 6 — "it printed OK" is not success

A script that reaches its final `print("[OK] exported")` only proves the Python
ran to the end. It does **not** prove:

- the geometry is valid (Pitfalls 1–5),
- the STEP actually got rewritten (it may have been locked by an open viewer),
- the result is a single body.

Always: delete the old output first, run, then confirm the verification block
passed AND the file timestamp updated.

```bash
del ..\output\part.step ..\output\part.stl   # Windows
python part.py
dir ..\output\part.*                          # confirm fresh timestamp + size
```

---

## Quick decision table

| You want to… | Avoid | Prefer |
|--------------|-------|--------|
| Hole through a shelled wall | `cskHole` on the wall | cutter cylinder + `.cut()` |
| Through opening on bottom face | face `.cutThruAll()` | bounded cutter + `.cut()` |
| Domed / curved top | `loft` to a point | union/subtract a sphere or ellipsoid |
| Round an edge of a thin shell | fillet after shelling | fillet the outer form **before** shelling (kept faces only) |
| Hollow a filleted shell | fillet the face `.shell()` will remove | fillet only kept faces, or subtract a cavity solid |
| Trust the result | rely on `[OK]` / STL preview | run `BRepCheck_Analyzer` + solid-count **+ a volume check** |

Rows 1 and 3 are **preferred constructions** — their historical failure modes
did not reproduce on the current kernel (see each pitfall's Verified behaviour
block), but the explicit patterns are more predictable and version-proof. Row
2's hazard **is** observed on the current kernel (`cutThruAll` removes the
whole column). Rows 4–6 are verified current behaviour.
````

## File: .claude/skills/cadquery-modeling/references/part_file_structure.md
size: 4206
sha: 048cfce697ed4e371c12759c1140505d84d13fc6
upstream: https://github.com/0okevino0/claude-cad/blob/main/.claude/skills/cadquery-modeling/references/part_file_structure.md

````text
# Part File Structure

Every part file follows the same skeleton. This makes parts readable, re-runnable,
and easy to tweak — change a number at the top, re-run, re-import.

## The skeleton

```python
"""
<Part name> — one-line description.
"""

import sys
# Force UTF-8 so Windows terminals can print comments/symbols without crashing.
try:
    sys.stdout.reconfigure(encoding="utf-8")
except Exception:
    pass

import cadquery as cq

# ============ Parameters ============
# Every dimension lives here, with a comment and unit.
outer_d      = 80.0   # outer diameter (mm)
wall         = 2.5    # wall thickness (mm)
height       = 30.0   # overall height (mm)
hole_d       = 6.0    # mounting hole diameter (mm)
hole_r_circ  = 30.0   # bolt-circle radius (mm)
hole_count   = 4      # number of mounting holes

# ============ Build ============
# Keep steps small and commented. Prefer primitives + booleans.

# Step 1: base solid
part = (
    cq.Workplane("XY")
    .circle(outer_d / 2)
    .extrude(height)
)

# Step 2: outer fillets BEFORE shelling — kept faces only; never fillet the
# face .shell() will remove, that silently no-ops (occ_pitfalls.md, Pitfall 4b)
part = part.edges("<Z").fillet(2.0)

# Step 3: shell, open top
part = part.faces(">Z").shell(-wall)

# Step 4: holes via explicit cutters (never cskHole on a shelled wall)
import math
for i in range(hole_count):
    a = 2 * math.pi * i / hole_count
    x, y = hole_r_circ * math.cos(a), hole_r_circ * math.sin(a)
    cutter = (
        cq.Workplane("XY").center(x, y)
        .circle(hole_d / 2)
        .extrude(height + 1)
    )
    part = part.cut(cutter)

# ============ Verification (do not skip) ============
from OCP.BRepCheck import BRepCheck_Analyzer
solid = part.val()
analyzer = BRepCheck_Analyzer(solid.wrapped)
assert analyzer.IsValid(), "Invalid geometry — the part is wrong even if CAD opens it."
n = len(solid.Solids())
assert n == 1, f"Expected 1 solid, found {n}."
print(f"[verify] IsValid=True  solids={n}  volume={solid.Volume():.2f}  bbox={solid.BoundingBox()}")
print("[verify] claude-cad — checks applied")   # signature: shows the skill's checks ran

# ============ Export ============
# Resolve output relative to THIS FILE, so it works no matter where you run from.
from pathlib import Path
OUT = Path(__file__).resolve().parent.parent / "output"
OUT.mkdir(parents=True, exist_ok=True)

cq.exporters.export(part, str(OUT / "part.step"))
cq.exporters.export(part, str(OUT / "part.stl"))
print(f"[OK] exported part.step + part.stl -> {OUT}")
```

## Rules baked into the skeleton

1. **UTF-8 guard at the top** — Windows PowerShell defaults to cp1252 and will
   raise `UnicodeEncodeError` on a non-ASCII `print`, which *looks* like a modeling
   failure even though the STEP already exported. The guard prevents this.

2. **All parameters at the top, commented, with units.** To resize, change a number
   and re-run. Never bury a literal dimension deep in the build.

3. **Build in small, commented steps.** Each step should be understandable on its
   own. This is what lets you (and the next reader) debug step N when it breaks.

4. **Primitives + booleans over fragile features.** See `occ_pitfalls.md`.

5. **Verification block before export, every time.**

6. **Export via a `__file__`-relative path** (as above) so all parts collect in
   one `output/` folder regardless of the working directory. A bare `"../output/"`
   silently exports one level too high when the script is run from the project
   root — a classic "where did my STEP go?" bug.

## Assembly-info footer (recommended)

End multi-part projects with an assembly note so the SolidWorks mate step is
mechanical, not guesswork:

```python
# ========== Assembly info ==========
# Part: Bottom housing
# Datum: origin (0,0,0), this is the assembly base part
# Top mating face: Z = 30 mm
# Locating lip: from Z=30, +1.0 mm tall, 1.5 mm wide, follows the outer profile
# Posts: (±35, ±25), OD 5, M2 pilot hole 1.6, depth 8
# Mates to top shell: lip↔groove (concentric), posts↔through-holes (4× concentric)
# ===================================
```

Collect these footers into `docs/assembly_guide.md` as the project grows.
````

## File: .claude/skills/cadquery-modeling/references/solidworks_checks.md
size: 3206
sha: 9248cefbcd5ada874ccdf887f563646713715c94
upstream: https://github.com/0okevino0/claude-cad/blob/main/.claude/skills/cadquery-modeling/references/solidworks_checks.md

```text
# SolidWorks Validation

How to confirm an imported part is correct, using SolidWorks' own tools. These
checks catch swapped dimensions, asymmetry, and bad imports in seconds.

> **UNTESTABLE HERE:** everything in this file describes SolidWorks-side
> behaviour — menu paths, importer acceptance, error wording. It is a field
> report from real sessions and cannot be re-verified in the maintainer's
> current environment (no SolidWorks). Kernel-side claims are tested separately
> in `.claude/tests/repro_pitfalls.py`.

## Importing a STEP

**File → Open** → set type to `STEP (*.step;*.stp)` → select the file → **Open**.

Prefer opening from inside SolidWorks (not double-clicking the file). In the import
options:

- **Solids and Surfaces** → **Try forming solid(s)** — gets a solid body.
- **Automatically run Import Diagnostics (Healing)** — fixes minor issues.
- **Unit of Import: File specified unit** — respects the mm from CadQuery.

If a single part imports as several bodies, the source had a multibody problem —
fix it in CadQuery (see `occ_pitfalls.md`, Pitfall 5).

## Fast correctness checks

### Mass Properties (the best first check)

**Evaluate → Mass Properties.**

- **Center of mass** — for a symmetric part, X and Y should be ≈ 0. A non-zero
  value pinpoints an asymmetry (e.g. an off-center hole) — sometimes intended
  (a side button shifts COM), often a bug.
- **Volume** — compare to your estimate derived from the dimensions. Way off → a feature didn't apply.
- **Principal moments of inertia (Px, Py, Pz)** — their *relative* sizes confirm
  geometry:
  - A flat disc/plate has its **largest** moment about the axis normal to the
    face (the thin direction).
  - For a long box, the moment about the **long** axis is the **smallest**.
  - If these are swapped from what you expect, a dimension is swapped.
- **Products of inertia (Lxy, Lxz, Lyz)** ≈ 0 means the part is well-aligned and
  symmetric about the coordinate planes.

### Bounding box

Right-click the part name → **Bounding Box** (or **Evaluate → Bounding Box**) to
read X/Y/Z extents directly and compare to your intended overall size.

### Views

- `Ctrl+5` top, `Ctrl+6` bottom, `Ctrl+1` front, `Ctrl+7` isometric.
- The bottom view is where through-holes and openings are easiest to confirm.
- The isometric view of a near-1:1 ellipse can look almost circular — don't
  mistake that for an error; check the bounding box numbers.

## Reading inertia: worked intuition

For a part that is long in X, medium in Y, thin in Z:

- Moment about **X** (uses Y,Z extents) → smallest.
- Moment about **Y** (uses X,Z extents) → middle.
- Moment about **Z** (uses X,Y extents) → largest.

So `Px < Py < Pz` confirms "long in X, thin in Z". A mismatch flags a swap before
you ever build the assembly.

## Assembly sanity (when you get there)

- Build assemblies in SolidWorks with **mates** (concentric, coincident), not by
  baking positions into one STEP — mates stay editable and support motion studies.
- **Evaluate → Interference Detection → Calculate** finds parts that overlap.
- Keep each part's CadQuery "assembly info" footer handy so mating is mechanical.
```

## File: .claude/skills/cadquery-modeling/references/verification.md
size: 4175
sha: a00132c564f415d2aafccced0620123d55ee1ab2
upstream: https://github.com/0okevino0/claude-cad/blob/main/.claude/skills/cadquery-modeling/references/verification.md

````text
# Verification & Debugging

How to confirm a part is correct, and what to do when a STEP won't open.

## The verification block (in every part file)

```python
from OCP.BRepCheck import BRepCheck_Analyzer
solid = part.val()

# 1. Validity — the single most important check
assert BRepCheck_Analyzer(solid.wrapped).IsValid(), \
    "Invalid geometry — the part is wrong even if CAD opens it."

# 2. Solid count — catches stray bodies
n = len(solid.Solids())
assert n == 1, f"Expected 1 solid, found {n}."

# 3. Sanity numbers
print(f"[verify] volume = {solid.Volume():.2f} mm^3")
print(f"[verify] bbox   = {solid.BoundingBox()}")

# Signature — always end here, so the output shows the skill's checks ran.
print("[verify] claude-cad — checks applied")
```

## Debugging flow: "STEP won't open in SolidWorks"

Work through these in order.

### 1. Is it actually a geometry problem?

Open the matching **STL** in a viewer (e.g. https://www.viewstl.com/).

- STL is also wrong/broken → the model logic is wrong, not just export. Fix the build.
- STL looks correct → run step 2 anyway, then step 3. A won't-open STEP is
  *usually* a file/path problem (step 3) — and the converse trap is real too:
  CAD can open an **invalid** STEP without complaint (`occ_pitfalls.md`, "Do
  not count on CAD import to reject bad geometry"), so import success doesn't
  clear the geometry either.

### 2. Did the script actually pass validity?

Re-run with the verification block. If `IsValid = False`, you've confirmed silent
corruption. Locate the culprit with per-step checks — the skill's `check()` does
exactly this, with auto-repair and a structured report (copy `scripts/diagnose.py`
into `parts/` first):

```python
from diagnose import check

part = check(part, "after extrude")
# ... after shell ...
part = check(part, "after shell")
# ... after each cut ...
```

(No `diagnose.py` at hand? A minimal inline probe works too:
`print(label, BRepCheck_Analyzer(part.val().wrapped).IsValid(), len(part.val().Solids()))`
— but don't name a homemade helper `check`, or it will shadow the library one.)

The first step where `valid` flips to `False` (or `solids` jumps above 1) is the
operation to replace. Cross-reference `occ_pitfalls.md`.

### 3. Is it actually a file/path problem (not geometry)?

If `IsValid = True` but SolidWorks still won't open it:

- **Wrong folder** — a bare `"../output/..."` export path resolves against the
  *working directory*, so running `py -3.11 parts/x.py` from the project root
  writes one level above the project. Check there, then switch the part file to a
  `Path(__file__).resolve().parent.parent / "output"` path and print it.
- **Stale file** — the viewer/SolidWorks had the old STEP locked, so the new write
  failed silently. Close SolidWorks, delete the file, re-run, check the timestamp.
- **Cloud-sync placeholder** — files under OneDrive/Dropbox may be "cloud only"
  (not actually on disk). Force "Always keep on this device", or move the project
  out of the synced folder entirely.
- **Path weirdness** — non-ASCII characters or parentheses in the path can trip
  some importers. A short ASCII path like `C:\cad_project\` avoids this.

### 4. Cross-check against a *derived* volume range

Compute the expected volume from the parameters (solid block minus intended
cavity; sum of primitives minus cuts) and check the result falls in a wide band
around it — ±15% is plenty. Derive it *before* building; never run the part and
paste `Volume()`'s output back as the expectation, which just checks the geometry
against itself. If the reported volume is wildly off — a silent no-op hollow reads
several times too high — a feature didn't apply or applied twice.

## Recovering a multibody result

```python
solids = part.val().Solids()
if len(solids) > 1:
    largest = max(solids, key=lambda s: s.Volume())
    part = cq.Workplane().add(largest)
```

Then fix the root cause: ensure union inputs overlap and cutters fully pass through.

## The golden rule

A green `[OK]` only means Python finished. **Correctness = validity check passes +
single solid + sane volume + opens in SolidWorks as a solid body.**
````

## File: README.md
upstream: https://github.com/0okevino0/claude-cad/blob/main/README.md

````text
# claude-cad

**Make Claude Code verify its CAD parts — not just print `[OK]`.**

![Left, "What you type": a plain-English request for a Raspberry Pi enclosure bottom, and the cadquery-modeling skill replying with clarifying questions and defaults instead of inventing dimensions. Right, "What you get": a verified STEP solid — the sbc-case example — opened in SolidWorks. The two panels are from separate sessions.](assets/readme-hero.png)

You ask an AI for a hollow enclosure. The script prints `[OK]`, the STL preview
looks exactly right — and the exported part is a solid brick. The `.shell()`
silently did nothing: 158,048 mm³ of material where 2.5 mm walls should leave
33,370. Nothing raised, nothing warned, and from outside the two parts are
identical.

Don't count on CAD to catch it, either. In our test, a provably invalid solid —
claiming 51,185 mm³ inside a 32,000 mm³ bounding box — opened in SolidWorks
with no dialog and no import diagnostics
([the record](docs/occ_pitfalls.md#do-not-count-on-cad-import-to-reject-bad-geometry)).
Bad geometry doesn't announce itself — not in the `[OK]`, not in the STL, not
always in CAD. What catches this brick is a volume that doesn't match what the
dimensions predict; what catches a port cut into the wrong wall is a point that
should be inside the plastic and isn't.

claude-cad is a [Claude Code](https://claude.com/claude-code) **skill** — a folder
of instructions Claude Code loads automatically from `.claude/skills/` when you
open a project, so its rules are active with no install step (you confirm it loaded
by typing `/skills`). Those instructions tell Claude Code to write the checks below
into every part it builds and to treat a failing check as a stop, not an export — a
rule the model follows, like the rest of the skill:

```text
  claude-cad diagnostic report
  IsValid     : True
  solids      : 1
  volume      : 32163.55 mm^3
  bbox (XYZ)  : 94.00 x 65.00 x 27.20 mm
  RESULT: PASS — validity, single-body, volume, bbox verified;
          safe to export as a valid single solid
  claude-cad — checks applied
```

Who it's for — all three assume you're comfortable working in a terminal:

- **New to CAD.** You're comfortable with a terminal but you don't write CAD.
  Describe the part in plain English and the skill writes the
  [CadQuery](https://github.com/CadQuery/cadquery) (Python parametric-CAD), asking
  about missing dimensions instead of inventing them. You answer the occasional
  dimension question and read a few numbers to check the result — no modeling
  software to learn.
- **You want STEP, not mesh.** Most AI-CAD emits STL — a fixed triangle mesh, fine
  to print but hard to change. You get **STEP**: a real solid that imports into
  SolidWorks or Fusion as geometry you can modify (an imported solid you can cut,
  fillet, and measure — not a native feature history, but far more than a mesh).
- **You already model.** This is the verification block you'd otherwise hand-write
  for every part, plus a re-tested record of the OpenCASCADE (OCC) kernel operations
  that corrupt silently (OCC is the geometry kernel under CadQuery).

The clone is the workspace — the skill ships inside the repo, already active.
Commands below are Windows (PowerShell); on **macOS/Linux** use `python3.11` in
place of `py -3.11` (SolidWorks itself is Windows-only, but the modeling and
verification are cross-platform):

```powershell
mkdir C:\dev; cd C:\dev            # a plain path, NOT OneDrive/Desktop/Documents (breaks SolidWorks later); skip mkdir if it exists
git clone https://github.com/0oKevino0/claude-cad.git
cd claude-cad
py -3.11 -m pip install cadquery   # Python 3.11 (newer Pythons lack the OCP binding); downloads ~300 MB
```

Open the folder in VS Code, open Claude Code, describe a part —
**[QUICKSTART.md](QUICKSTART.md)** walks it end-to-end in ~10 minutes (longer
if you still need to install Python or Claude Code).

## What it checks

The skill has Claude Code end every part with a block like this and treat a failure
as a reason to fix the part, not export it:

```python
from OCP.BRepCheck import BRepCheck_Analyzer
from diagnose import assert_points               # the skill's point-classifier
solid = part.val()

# Valid B-rep, exactly one body — true or raise:
assert BRepCheck_Analyzer(solid.wrapped).IsValid(), "invalid geometry"
assert len(solid.Solids()) == 1, "expected exactly one solid"

# Volume against a range DERIVED from the dimensions of a 94×65×26 enclosure blank
# with 2.5 mm walls — the shape behind the intro's numbers. The expression is the
# check; nothing is measured off the built result and pasted back. (The shipped
# part in the report above adds a lid lip and internal features, so it measures a
# bit less — 32,163 — and stands 27.2 mm tall; a derived range absorbs that.)
L, W, H, t = 94, 65, 26, 2.5
expected = L*W*H - (L - 2*t)*(W - 2*t)*(H - t)   # solid block minus the cavity ≈ 33,370
assert 0.85*expected <= solid.Volume() <= 1.15*expected, "hollow/cut did nothing?"

# The strongest check — features where you MEANT them, not just the right bulk.
# This is what caught a port cut into the wrong wall in the worked example.
# (Coords below assume this enclosure is modelled from its footprint centre.)
assert_points(part,
    inside=[(46, 20, 13)],     # a point inside the +X wall — must be solid
    outside=[(0, 0, 13)])      # a point in the open cavity — must be hollow
```

Order matters. `IsValid` and the solid count say it's *a* clean solid;
`assert_points` is what says it's *the* solid you asked for — bulk and bounding box
can be right while a feature sits on the wrong face (see the
[worked example](examples/sbc-case/)). Volume is the weakest of the four: a derived
range, wide on purpose, to catch the gross failure — the un-hollowed brick reads
~158,000 mm³ where the walls should leave ~33,000
([Pitfall 4b](docs/occ_pitfalls.md)) — not to certify a part correct to 2%. When a
part fails, the report names the problem and the pitfall it matches, and whether it
was safely auto-repaired.

Around the checks sit the rules that make them meaningful: the OCC kernel
operations with a history of silent corruption — every claim re-tested
against the current kernel, each with a **Verified behaviour** record — and the
safe patterns that replace them. See [docs/verification.md](docs/verification.md)
and [docs/occ_pitfalls.md](docs/occ_pitfalls.md).

Why the checks are shaped this way — and how to tell a real check from one that
cannot fail — is **[docs/verification-theatre.md](docs/verification-theatre.md)**.
It stands on its own: no CAD, no CadQuery, nothing from this repo required.

## What you need

| Thing | Notes |
|-------|-------|
| **Python 3.11** | Not the newest release — the `OCP` kernel binding lags new Pythons. |
| **[Claude Code](https://claude.com/claude-code)** | VS Code extension or terminal CLI. Needs an Anthropic account with a paid plan or API billing. |
| **SolidWorks** | **Optional.** Modeling and verification run entirely in the terminal; the exported STEP is standard B-rep that other CAD (Fusion, FreeCAD) imports too. |

## What's in the repo

| Component | What it is |
|-----------|------------|
| **[Skill](.claude/skills/cadquery-modeling/)** | Applies the verification + OCC-safe rules automatically inside Claude Code. The heart of the project. |
| **[Prompts](prompts/)** | Copy-paste workflows + part-type templates, usable with any assistant. |
| **[Docs](docs/)** | Verification, the OCC pitfalls, SolidWorks integration — plus [getting-started.md](docs/getting-started.md), the no-Claude-Code path. |

## Worked example

![Bottom view of the SBC case shell: five rounded floor-vent slots down the centre, four board standoffs on an inner rectangle, and four corner screw bosses.](examples/sbc-case/images/bottom-view.png)

A single-board-computer case bottom shell — standoffs, vent slots, port
cut-outs, screw bosses — described to Claude Code in plain English and verified
before export. 
````
