"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
feat: add 3MF mesh geometry editor CLI (cli-anything-3mf)
柳旭雷5e6e9d4daaa4
diff --git a/.gitignore b/.gitignoreindex b17f6696e..eb6375764 100644--- a/.gitignore+++ b/.gitignore@@ -91,7 +91,7 @@!/sbox/!/quietshrink/!/mailchimp/-+!/3MF/# Step 5: Inside each software dir, ignore everything (including dotfiles)/gimp/*/gimp/.*@@ -165,6 +165,8 @@/openscreen/.*/QGIS/*/QGIS/.*+/3MF/*+/3MF/.*/cloudanalyzer/*/cloudanalyzer/.*/wiremock/*@@ -228,6 +230,7 @@!/renderdoc/agent-harness/!/cloudcompare/agent-harness/!/openscreen/agent-harness/+!/3MF/agent-harness/!/cloudanalyzer/!/cloudanalyzer/agent-harness/!/wiremock/diff --git a/3MF/agent-harness/3MF.md b/3MF/agent-harness/3MF.mdnew file mode 100644index 000000000..343173250--- /dev/null+++ b/3MF/agent-harness/3MF.md@@ -0,0 +1,62 @@+# 3MF CLI — Standard Operating Procedure++## Overview++The **3MF CLI** (`cli-anything-3mf`) is an agent-native command-line interface for+inspecting, modifying, and repairing 3MF mesh files used in 3D printing.++Unlike traditional 3D-printing CLI tools (PrusaSlicer CLI, BambuStudio CLI, admesh)+that treat meshes as opaque triangle soups, this tool provides **feature-aware+geometry editing** — it can detect cylindrical holes, measure their diameters, and+resize them via CLI commands.++## 3MF Format++A 3MF file is a ZIP archive containing:+- `[Content_Types].xml` — MIME type declarations+- `_rels/.rels` — relationship definitions+- `3D/3dmodel.model` — XML mesh data (core spec namespace: `http://schemas.microsoft.com/3dmanufacturing/core/2015/02`)+- `Metadata/` — slicer settings, thumbnails, plate configurations (BambuStudio, PrusaSlicer)++## Architecture++```+threemf_cli.py Click CLI + REPL entry point+ |+ +-- core/parser.py 3MF ZIP/XML parsing, lossless repack+ +-- core/inspector.py Cross-section hole detection+ +-- core/modifier.py Radial vertex scaling for hole resize+ +-- core/repair.py Degenerate face removal, vertex merge+ |+ +-- utils/threemf_backend.py trimesh/numpy geometry utilities+ +-- utils/repl_skin.py Unified REPL styling+```++## Core Algorithm++### Hole Detection (inspector.py)+1. Take N cross-sections perpendicular to the hole axis+2. At each section, identify circular entities via trimesh path analysis+3. Fit circles using least-squares (Kasa method)+4. Group circles across sections by center proximity+5. Calculate confidence from detection consistency++### Hole Resize (modifier.py)+1. Re-detect holes to get current geometry+2. Find wall vertices at known radii from hole axis+3. Scale vertices radially: `new_pos = center + direction * (new_r / old_r)`+4. Fix degenerate faces caused by coincident vertices++### Mesh Repair (repair.py)+1. Merge duplicate vertices (coordinate rounding + dedup)+2. Remove degenerate triangles (collapsed faces)+3. Remove unreferenced vertices+4. Fix face winding via trimesh++## Slicer Compatibility++The tool preserves all non-mesh content during repack:+- BambuStudio: project_settings.config, model_settings.config, plate thumbnails+- PrusaSlicer: slic3r_pe configs, layer height profiles++Output files can be reopened in the original slicer without configuration loss.diff --git a/3MF/agent-harness/cli_anything/threemf/README.md b/3MF/agent-harness/cli_anything/threemf/README.mdnew file mode 100644index 000000000..5bd9eff98--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/README.md@@ -0,0 +1,99 @@+# cli-anything-3mf++**3MF Mesh Geometry Editor** — Detect and resize cylindrical holes, repair meshes, compare 3D printing files.++Part of the [CLI-Anything](https://github.com/HKUDS/CLI-Anything) ecosystem.++## Installation++```bash+pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=3MF/agent-harness+```++Or for development:++```bash+cd 3MF/agent-harness+pip install -e ".[dev]"+```++## Quick Start++```bash+# Show mesh info+cli-anything-3mf info model.3mf++# Detect cylindrical holes+cli-anything-3mf inspect model.3mf++# Resize holes 0,1,2,3 to 4.2mm diameter+cli-anything-3mf resize model.3mf --hole 0 --hole 1 --hole 2 --hole 3 --diameter 4.2 -o output.3mf++# Repair mesh issues+cli-anything-3mf repair model.3mf -o repaired.3mf++# Compare two files+cli-anything-3mf compare original.3mf modified.3mf++# Interactive REPL+cli-anything-3mf+```++## Commands++| Command | Description |+|---------|-------------|+| `info <file>` | Show mesh statistics (vertices, faces, bounds, watertight, volume) |+| `inspect <file>` | Detect and list all cylindrical holes with diameter and position |+| `resize <file>` | Resize specified holes to a target diameter |+| `repair <file>` | Fix degenerate faces, duplicate vertices, and normals |+| `compare <f1> <f2>` | Side-by-side comparison of two 3MF files |++All commands support `--json` for machine-readable output.++## How It Works++### Hole Detection+The tool takes cross-sections at multiple planes perpendicular to the hole axis,+identifies circular features via least-squares circle fitting, and groups them+across planes to detect consistent cylindrical holes.++### Hole Resizing+Wall vertices are identified by their radial distance from the hole axis.+Vertices are then scaled radially to achieve the target diameter while preserving+mesh topology and angular position.++### Slicer Compatibility+All non-mesh content (slicer settings, thumbnails, plate configurations) is+preserved during file repack. Output files can be reopened in BambuStudio or+PrusaSlicer without configuration loss.++## Architecture++```+cli_anything/threemf/+├── threemf_cli.py # Click CLI + REPL+├── core/+│ ├── parser.py # 3MF ZIP/XML parsing+│ ├── inspector.py # Cross-section hole detection+│ ├── modifier.py # Hole resizing+│ └── repair.py # Mesh repair+├── utils/+│ ├── threemf_backend.py # Geometry utilities (trimesh/numpy)+│ └── repl_skin.py # Unified REPL styling+├── skills/+│ └── SKILL.md # Agent-discoverable skill+└── tests/+ ├── test_core.py # Unit tests (74+)+ └── test_full_e2e.py # E2E tests (30+)+```++## Dependencies++- Python 3.10++- numpy, scipy, trimesh+- click, prompt-toolkit++## License++MIT — See [CLI-Anything LICENSE](https://github.com/HKUDS/CLI-Anything/blob/main/LICENSE)diff --git a/3MF/agent-harness/cli_anything/threemf/__init__.py b/3MF/agent-harness/cli_anything/threemf/__init__.pynew file mode 100644index 000000000..5e2362898--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/__init__.py@@ -0,0 +1 @@+"""3MF CLI - Mesh geometry editor for 3D printing files."""diff --git a/3MF/agent-harness/cli_anything/threemf/__main__.py b/3MF/agent-harness/cli_anything/threemf/__main__.pynew file mode 100644index 000000000..a47649a5a--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/__main__.py@@ -0,0 +1,3 @@+"""Allow running as python -m cli_anything.threemf"""+from cli_anything.threemf.threemf_cli import main+main()diff --git a/3MF/agent-harness/cli_anything/threemf/core/__init__.py b/3MF/agent-harness/cli_anything/threemf/core/__init__.pynew file mode 100644index 000000000..8b1378917--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/core/__init__.py@@ -0,0 +1 @@+diff --git a/3MF/agent-harness/cli_anything/threemf/core/inspector.py b/3MF/agent-harness/cli_anything/threemf/core/inspector.pynew file mode 100644index 000000000..7527d4327--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/core/inspector.py@@ -0,0 +1,287 @@+"""Hole detection -- cross-section analysis to find cylindrical holes in meshes."""++from __future__ import annotations++from dataclasses import dataclass++import numpy as np+from scipy.cluster.hierarchy import fcluster, linkage++from cli_anything.threemf.core.parser import MeshData, ThreeMFData+from cli_anything.threemf.utils import threemf_backend as backend++# ---------------------------------------------------------------------------+# Data classes+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class DetectedHole:+ """A cylindrical hole detected in a mesh."""++ hole_id: int+ center: tuple[float, float] # (coord1, coord2) perpendicular to axis+ diameter: float+ axis_min: float # extent along axis+ axis_max: float+ axis: int # 0=X, 1=Y, 2=Z+ confidence: float # 0.0-1.0+ vertex_count: int+++@dataclass(frozen=True)+class InspectParams:+ """Parameters that control hole-detection behaviour."""++ num_planes: int = 20+ min_hole_diameter: float = 0.5+ min_confidence: float = 0.7+ axis: int = 0 # which axis to section perpendicular to+++# ---------------------------------------------------------------------------+# Constants+# ---------------------------------------------------------------------------++_GROUP_DISTANCE_MM = 0.5 # max center-to-center distance to merge circles+++# ---------------------------------------------------------------------------+# Public API+# ---------------------------------------------------------------------------+++def inspect_mesh(+ mesh_data: MeshData,+ params: InspectParams | None = None,+) -> list[DetectedHole]:+ """Detect cylindrical holes via multi-plane cross-section analysis.++ Algorithm+ ---------+ 1. Take cross-sections at ``num_planes`` evenly-spaced levels along *axis*.+ 2. At each section call ``cross_section_circles()`` to find circular features.+ 3. Group circles across planes by centre proximity (hierarchical clustering+ with a 0.5 mm distance threshold).+ 4. For each group compute the average diameter, axis extent, and confidence.+ 5. Filter by *min_hole_diameter* and *min_confidence*.+ 6. Count vertices on each hole wall.+ 7. Return a sorted list of ``DetectedHole`` (sorted by hole_id).+ """++ if params is None:+ params = InspectParams()++ _validate_mesh(mesh_data)++ vertices = mesh_data.vertices+ if vertices.shape[0] == 0:+ return []++ axis = params.axis++ # Step 1 -- basic axis range check+ perp_axes = _perpendicular_axes(axis)+ axis_vals = vertices[:, axis]+ axis_lo, axis_hi = float(np.min(axis_vals)), float(np.max(axis_vals))+ if axis_hi - axis_lo < 1e-9:+ return []++ # Step 2 -- collect circles via multi-plane cross-section+ raw_circles = backend.cross_section_circles(+ mesh_data, axis=axis, num_planes=params.num_planes,+ )+ all_circles = []+ for c in raw_circles:+ all_circles.append({+ "center": (float(c["center"][0]), float(c["center"][1])),+ "radius": float(c["radius"]),+ "fit_error": float(c.get("fit_error", 0.0)),+ "level": float(c["plane_value"]),+ })+ if not all_circles:+ return []++ # Step 3 -- group circles by centre proximity via hierarchical clustering+ groups = _group_circles(all_circles)++ # Step 4/5 -- build candidate holes, compute confidence, filter+ num_planes = params.num_planes+ holes: list[DetectedHole] = []+ hole_id = 0++ for group in groups:+ radii = np.array([c["radius"] for c in group])+ mean_radius = float(np.mean(radii))+ mean_diameter = mean_radius * 2.0++ if mean_diameter < params.min_hole_diameter:+ continue++ # Confidence = (planes_with_detection / total_planes) * (1 - mean_fit_error / radius)+ fit_errors = np.array([c["fit_error"] for c in group])+ mean_fit_error = float(np.mean(fit_errors))+ detection_ratio = len(group) / num_planes+ if mean_radius > 0:+ quality = 1.0 - mean_fit_error / mean_radius+ else:+ quality = 0.0+ confidence = float(np.clip(detection_ratio * quality, 0.0, 1.0))++ if confidence < params.min_confidence:+ continue++ # Axis extent+ group_levels = [c["level"] for c in group]+ axis_min = float(min(group_levels))+ axis_max = float(max(group_levels))++ # Centre (average across all detections)+ centres = np.array([c["center"] for c in group])+ avg_center = (float(np.mean(centres[:, 0])), float(np.mean(centres[:, 1])))++ # Step 6 -- count wall vertices+ vertex_count = _count_wall_vertices(+ vertices, avg_center, mean_radius, axis, perp_axes, axis_min, axis_max,+ )++ holes.append(DetectedHole(+ hole_id=hole_id,+ center=avg_center,+ diameter=round(mean_diameter, 4),+ axis_min=round(axis_min, 4),+ axis_max=round(axis_max, 4),+ axis=axis,+ confidence=round(confidence, 4),+ vertex_count=vertex_count,+ ))+ hole_id += 1++ holes.sort(key=lambda h: h.hole_id)+ return holes+++def get_mesh_info(mesh_data: MeshData) -> dict:+ """Return mesh statistics using ``backend.compute_mesh_stats()``."""++ _validate_mesh(mesh_data)+ stats = backend.compute_mesh_stats(mesh_data)+ return {+ "object_id": mesh_data.object_id,+ "name": mesh_data.name,+ "num_vertices": int(mesh_data.vertices.shape[0]),+ "num_triangles": int(mesh_data.triangles.shape[0]),+ **stats,+ }+++def compare_meshes(mesh_a: MeshData, mesh_b: MeshData) -> dict:+ """Compare two meshes and return a summary of differences.++ Returns a dict with keys: vertices, faces, volume, watertight — each a+ sub-dict with file1/file2/diff (matching the CLI display format).+ """++ _validate_mesh(mesh_a)+ _validate_mesh(mesh_b)++ stats_a = backend.compute_mesh_stats(mesh_a)+ stats_b = backend.compute_mesh_stats(mesh_b)++ vol_a = stats_a.get("volume_mm3") or 0.0+ vol_b = stats_b.get("volume_mm3") or 0.0++ return {+ "vertices": {+ "file1": int(mesh_a.vertices.shape[0]),+ "file2": int(mesh_b.vertices.shape[0]),+ "diff": int(mesh_b.vertices.shape[0]) - int(mesh_a.vertices.shape[0]),+ },+ "faces": {+ "file1": int(mesh_a.triangles.shape[0]),+ "file2": int(mesh_b.triangles.shape[0]),+ "diff": int(mesh_b.triangles.shape[0]) - int(mesh_a.triangles.shape[0]),+ },+ "volume": {+ "file1": float(vol_a),+ "file2": float(vol_b),+ "diff": float(vol_b - vol_a),+ },+ "watertight": {+ "file1": stats_a.get("watertight", False),+ "file2": stats_b.get("watertight", False),+ },+ }+++# ---------------------------------------------------------------------------+# Internal helpers+# ---------------------------------------------------------------------------+++def _validate_mesh(mesh_data: MeshData) -> None:+ """Raise ``ValueError`` for clearly invalid mesh data."""+ if mesh_data is None:+ raise ValueError("mesh_data must not be None")+ if not isinstance(mesh_data.vertices, np.ndarray):+ raise ValueError("mesh_data.vertices must be a numpy ndarray")+ if not isinstance(mesh_data.triangles, np.ndarray):+ raise ValueError("mesh_data.triangles must be a numpy ndarray")+ if mesh_data.vertices.ndim != 2 or mesh_data.vertices.shape[1] != 3:+ raise ValueError("mesh_data.vertices must have shape (N, 3)")+ if mesh_data.triangles.ndim != 2 or mesh_data.triangles.shape[1] != 3:+ if mesh_data.triangles.shape[0] != 0:+ raise ValueError("mesh_data.triangles must have shape (M, 3)")+++def _perpendicular_axes(axis: int) -> tuple[int, int]:+ """Return the two axes perpendicular to *axis*."""+ return {0: (1, 2), 1: (0, 2), 2: (0, 1)}[axis]+++def _group_circles(circles: list[dict]) -> list[list[dict]]:+ """Group circles from different planes by centre proximity.++ Uses scipy hierarchical clustering with a distance threshold of+ ``_GROUP_DISTANCE_MM``.+ """++ if len(circles) == 1:+ return [circles]++ centres = np.array([c["center"] for c in circles])+ link = linkage(centres, method="single", metric="euclidean")+ labels = fcluster(link, t=_GROUP_DISTANCE_MM, criterion="distance")++ groups: dict[int, list[dict]] = {}+ for label, circle in zip(labels, circles):+ groups.setdefault(int(label), []).append(circle)++ return list(groups.values())+++def _count_wall_vertices(+ vertices: np.ndarray,+ center: tuple[float, float],+ radius: float,+ axis: int,+ perp_axes: tuple[int, int],+ axis_min: float,+ axis_max: float,+ tolerance: float = 0.06,+) -> int:+ """Count vertices that lie on the cylindrical wall of a hole."""++ ax0, ax1 = perp_axes+ in_range = (vertices[:, axis] >= axis_min - tolerance) & (+ vertices[:, axis] <= axis_max + tolerance+ )+ subset = vertices[in_range]+ if subset.shape[0] == 0:+ return 0++ dx = subset[:, ax0] - center[0]+ dy = subset[:, ax1] - center[1]+ dist = np.sqrt(dx * dx + dy * dy)+ on_wall = np.abs(dist - radius) < tolerance+ return int(np.count_nonzero(on_wall))diff --git a/3MF/agent-harness/cli_anything/threemf/core/modifier.py b/3MF/agent-harness/cli_anything/threemf/core/modifier.pynew file mode 100644index 000000000..5baa8d16f--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/core/modifier.py@@ -0,0 +1,222 @@+"""Hole resizing -- radial vertex scaling to change hole diameters."""++from __future__ import annotations++from dataclasses import replace++import numpy as np++from cli_anything.threemf.core.parser import MeshData, ThreeMFData+from cli_anything.threemf.core.inspector import (+ DetectedHole,+ inspect_mesh,+)++# ---------------------------------------------------------------------------+# Constants+# ---------------------------------------------------------------------------++_WALL_RADIUS_TOLERANCE = 0.06 # mm -- proven in earlier 3MF editing session+++# ---------------------------------------------------------------------------+# Public API+# ---------------------------------------------------------------------------+++def resize_holes(+ threemf_data: ThreeMFData,+ hole_ids: list[int],+ target_diameter: float,+ mesh_index: int = 0,+) -> tuple[ThreeMFData, list[dict]]:+ """Resize specified holes to *target_diameter* and return a **new** ``ThreeMFData``.++ Returns+ -------+ tuple+ ``(new_data, changes)`` where *changes* is a list of per-hole dicts+ with keys: hole_id, old_diameter, new_diameter, vertices_moved.++ Raises+ ------+ ValueError+ If *threemf_data* is ``None``, *mesh_index* is out of range,+ *target_diameter* is non-positive, or any *hole_id* is unknown.+ """++ _validate_resize_inputs(threemf_data, hole_ids, target_diameter, mesh_index)++ mesh = threemf_data.meshes[mesh_index]+ detected_holes = inspect_mesh(mesh)++ detected_ids = {h.hole_id for h in detected_holes}+ unknown = set(hole_ids) - detected_ids+ if unknown:+ raise ValueError(+ f"Unknown hole_ids: {sorted(unknown)}. "+ f"Detected hole_ids: {sorted(detected_ids)}"+ )++ target_holes = [h for h in detected_holes if h.hole_id in hole_ids]++ current_mesh = mesh+ reports: list[dict] = []++ for hole in target_holes:+ current_mesh, report = resize_single_hole(current_mesh, hole, target_diameter)+ reports.append(report)++ # Build new meshes tuple with the modified mesh+ new_meshes = tuple(+ current_mesh if i == mesh_index else m+ for i, m in enumerate(threemf_data.meshes)+ )++ return replace(threemf_data, meshes=new_meshes), reports+++def resize_single_hole(+ mesh_data: MeshData,+ hole: DetectedHole,+ target_diameter: float,+) -> tuple[MeshData, dict]:+ """Resize a single hole and return ``(new_mesh, change_report)``.++ The change_report contains::++ {+ "hole_id": int,+ "old_diameter": float,+ "new_diameter": float,+ "vertices_moved": int,+ }++ Wall-vertex detection strategy (proven approach)+ -------------------------------------------------+ * Compute distance from hole axis for every vertex.+ * Select vertices whose radial distance is within ``_WALL_RADIUS_TOLERANCE``+ of the current hole radius **and** whose axial coordinate falls within+ the hole extent (with tolerance).+ * Scale those vertices radially to ``target_diameter / 2``.+ """++ if mesh_data is None:+ raise ValueError("mesh_data must not be None")+ if target_diameter <= 0:+ raise ValueError(f"target_diameter must be positive, got {target_diameter}")++ old_radius = hole.diameter / 2.0+ new_radius = target_diameter / 2.0++ perp = _perpendicular_axes(hole.axis)+ wall_mask = _find_wall_vertices(+ mesh_data.vertices,+ hole.center,+ old_radius,+ hole.axis,+ perp,+ hole.axis_min,+ hole.axis_max,+ )++ vertices_moved = int(np.count_nonzero(wall_mask))++ if vertices_moved == 0:+ return mesh_data, _make_report(hole, target_diameter, 0)++ new_vertices = _scale_wall_radially(+ mesh_data.vertices, wall_mask, hole.center, perp, new_radius,+ )++ new_mesh = replace(mesh_data, vertices=new_vertices)+ return new_mesh, _make_report(hole, target_diameter, vertices_moved)+++# ---------------------------------------------------------------------------+# Internal helpers+# ---------------------------------------------------------------------------+++def _validate_resize_inputs(+ threemf_data: ThreeMFData,+ hole_ids: list[int],+ target_diameter: float,+ mesh_index: int,+) -> None:+ if threemf_data is None:+ raise ValueError("threemf_data must not be None")+ if not threemf_data.meshes:+ raise ValueError("threemf_data contains no meshes")+ if mesh_index < 0 or mesh_index >= len(threemf_data.meshes):+ raise ValueError(+ f"mesh_index {mesh_index} out of range "+ f"(0..{len(threemf_data.meshes) - 1})"+ )+ if target_diameter <= 0:+ raise ValueError(f"target_diameter must be positive, got {target_diameter}")+ if not hole_ids:+ raise ValueError("hole_ids must not be empty")+++def _perpendicular_axes(axis: int) -> tuple[int, int]:+ """Return the two axes perpendicular to *axis*."""+ return {0: (1, 2), 1: (0, 2), 2: (0, 1)}[axis]+++def _find_wall_vertices(+ vertices: np.ndarray,+ center: tuple[float, float],+ radius: float,+ axis: int,+ perp: tuple[int, int],+ axis_min: float,+ axis_max: float,+ tolerance: float = _WALL_RADIUS_TOLERANCE,+) -> np.ndarray:+ """Return a boolean mask of vertices on the cylindrical wall."""++ ax0, ax1 = perp+ in_range = (vertices[:, axis] >= axis_min - tolerance) & (+ vertices[:, axis] <= axis_max + tolerance+ )+ dx = vertices[:, ax0] - center[0]+ dy = vertices[:, ax1] - center[1]+ dist = np.sqrt(dx * dx + dy * dy)+ on_wall = np.abs(dist - radius) < tolerance+ return in_range & on_wall+++def _scale_wall_radially(+ vertices: np.ndarray,+ mask: np.ndarray,+ center: tuple[float, float],+ perp: tuple[int, int],+ new_radius: float,+) -> np.ndarray:+ """Scale wall vertices to *new_radius*. Returns a **new** vertex array."""++ new_verts = vertices.copy()+ ax0, ax1 = perp++ dx = new_verts[mask, ax0] - center[0]+ dy = new_verts[mask, ax1] - center[1]+ dist = np.sqrt(dx * dx + dy * dy)++ # Avoid division by zero for vertices exactly at the centre+ safe_dist = np.where(dist > 1e-12, dist, 1.0)+ scale = new_radius / safe_dist++ new_verts[mask, ax0] = center[0] + dx * scale+ new_verts[mask, ax1] = center[1] + dy * scale++ return new_verts+++def _make_report(hole: DetectedHole, target_diameter: float, vertices_moved: int) -> dict:+ return {+ "hole_id": hole.hole_id,+ "old_diameter": hole.diameter,+ "new_diameter": round(target_diameter, 4),+ "vertices_moved": vertices_moved,+ }diff --git a/3MF/agent-harness/cli_anything/threemf/core/parser.py b/3MF/agent-harness/cli_anything/threemf/core/parser.pynew file mode 100644index 000000000..bb6fb8395--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/core/parser.py@@ -0,0 +1,435 @@+"""3MF file parsing and writing -- handles ZIP structure and XML mesh data.++A 3MF file is a standard ZIP archive that contains one or more XML files+describing 3D mesh objects. The primary model is typically located at+``3D/3dmodel.model``. This module provides lossless round-trip support:+non-model entries (thumbnails, slicer profiles, Bambu metadata, etc.) are+preserved byte-for-byte.+"""++from __future__ import annotations++import io+import os+import zipfile+from dataclasses import dataclass+from xml.etree import ElementTree as ET++import numpy as np++# ---------------------------------------------------------------------------+# Constants+# ---------------------------------------------------------------------------++NS_CORE = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"+NS_BAMBU = "http://schemas.bambulab.com/package/2021"++# Common namespace prefixes found in 3MF files -- we register them so that+# ElementTree preserves them when serialising instead of inventing ``ns0``+# etc.+_KNOWN_NS: dict[str, str] = {+ "": NS_CORE,+ "b": NS_BAMBU,+}++# Ensure ElementTree will use the prefixes above when writing.+for _prefix, _uri in _KNOWN_NS.items():+ ET.register_namespace(_prefix, _uri)+++def _tag(local: str, ns: str = NS_CORE) -> str:+ """Return a fully-qualified ``{namespace}local`` tag string."""+ return f"{{{ns}}}{local}"+++# ---------------------------------------------------------------------------+# Data classes (frozen / immutable)+# ---------------------------------------------------------------------------++@dataclass(frozen=True)+class MeshData:+ """Immutable container for a single mesh object.++ Attributes:+ object_id: The ``id`` attribute of the ``<object>`` element.+ name: The ``name`` attribute (may be empty).+ vertices: (N, 3) float64 array of vertex coordinates.+ triangles: (M, 3) int32 array of triangle vertex-indices.+ """++ object_id: str+ name: str+ vertices: np.ndarray # (N, 3) float64+ triangles: np.ndarray # (M, 3) int32++ def __post_init__(self) -> None:+ # Validate shapes -- run only once at construction time.+ if self.vertices.ndim != 2 or self.vertices.shape[1] != 3:+ raise ValueError(+ f"vertices must be (N, 3); got {self.vertices.shape}"+ )+ if self.triangles.ndim != 2 or self.triangles.shape[1] != 3:+ raise ValueError(+ f"triangles must be (M, 3); got {self.triangles.shape}"+ )+++@dataclass(frozen=True)+class ThreeMFData:+ """Immutable container for a complete 3MF file.++ Attributes:+ meshes: Tuple of :class:`MeshData` objects.+ unit: Model unit string (``millimeter``, ``inch``, etc.).+ model_path: ZIP-internal path of the model XML file.+ metadata: ``{name: value}`` dict of ``<metadata>`` elements.+ raw_entries: ``{zip_path: bytes}`` of every non-model ZIP member,+ kept for lossless round-trip.+ source_path: Filesystem path the data was loaded from.+ """++ meshes: tuple[MeshData, ...]+ unit: str+ model_path: str+ metadata: dict[str, str]+ raw_entries: dict[str, bytes]+ source_path: str+++# ---------------------------------------------------------------------------+# Parsing+# ---------------------------------------------------------------------------++def _find_model_path(zf: zipfile.ZipFile) -> str:+ """Locate the primary model XML inside the ZIP archive.++ Checks in order:+ 1. ``3D/3dmodel.model`` (standard location)+ 2. First ``.model`` file found anywhere in the archive+ """+ standard = "3D/3dmodel.model"+ names = zf.namelist()+ if standard in names:+ return standard+ for name in names:+ if name.lower().endswith(".model"):+ return name+ raise FileNotFoundError(+ "No .model file found inside the 3MF archive"+ )+++def _parse_mesh_element(+ obj_elem: ET.Element,+ ns: str,+) -> MeshData | None:+ """Extract mesh arrays from an ``<object>`` element.++ Returns ``None`` when the element has no ``<mesh>`` child (e.g.+ component-only objects).+ """+ mesh_elem = obj_elem.find(_tag("mesh", ns))+ if mesh_elem is None:+ return None++ object_id = obj_elem.get("id", "")+ name = obj_elem.get("name", "")++ # -- vertices ----------------------------------------------------------+ verts_elem = mesh_elem.find(_tag("vertices", ns))+ if verts_elem is None:+ return None++ vert_list: list[tuple[float, float, float]] = []+ for v in verts_elem.iterfind(_tag("vertex", ns)):+ x = float(v.get("x", "0"))+ y = float(v.get("y", "0"))+ z = float(v.get("z", "0"))+ vert_list.append((x, y, z))++ if not vert_list:+ return None++ vertices = np.array(vert_list, dtype=np.float64)++ # -- triangles ---------------------------------------------------------+ tris_elem = mesh_elem.find(_tag("triangles", ns))+ if tris_elem is None:+ return None++ tri_list: list[tuple[int, int, int]] = []+ for t in tris_elem.iterfind(_tag("triangle", ns)):+ v1 = int(t.get("v1", "0"))+ v2 = int(t.get("v2", "0"))+ v3 = int(t.get("v3", "0"))+ tri_list.append((v1, v2, v3))++ if not tri_list:+ return None++ triangles = np.array(tri_list, dtype=np.int32)++ return MeshData(+ object_id=object_id,+ name=name,+ vertices=vertices,+ triangles=triangles,+ )+++def _detect_namespace(root: ET.Element) -> str:+ """Extract the primary namespace from the root ``<model>`` element.++ Falls back to :data:`NS_CORE` when no namespace is present.+ """+ tag = root.tag+ if tag.startswith("{"):+ return tag[1 : tag.index("}")]+ return NS_CORE+++def parse_3mf(path: str) -> ThreeMFData:+ """Parse a 3MF file into an immutable :class:`ThreeMFData` structure.++ Steps+ -----+ 1. Open the file as a :class:`zipfile.ZipFile`.+ 2. Locate the primary model XML (usually ``3D/3dmodel.model``).+ 3. Parse the XML; detect the 3MF core namespace.+ 4. Extract ``<object>`` elements with ``<mesh>`` children.+ 5. Collect ``<metadata>`` key/value pairs.+ 6. Store every *non-model* ZIP member as raw bytes so that a subsequent+ :func:`write_3mf` call can preserve slicer settings, thumbnails,+ and other auxiliary data.++ Parameters+ ----------+ path:+ Filesystem path to a ``.3mf`` file.++ Returns+ -------+ ThreeMFData+ Frozen dataclass with all parsed data.++ Raises+ ------+ FileNotFoundError+ If *path* does not exist or the archive contains no model XML.+ zipfile.BadZipFile+ If the file is not a valid ZIP archive.+ """+ path = os.path.abspath(path)++ if not os.path.isfile(path):+ raise FileNotFoundError(f"File not found: {path}")++ with zipfile.ZipFile(path, "r") as zf:+ model_path = _find_model_path(zf)++ # -- raw entries (everything except the model XML) -----------------+ raw_entries: dict[str, bytes] = {}+ for entry in zf.namelist():+ if entry != model_path:+ raw_entries[entry] = zf.read(entry)++ # -- parse model XML -----------------------------------------------+ model_bytes = zf.read(model_path)++ root = ET.fromstring(model_bytes)+ ns = _detect_namespace(root)++ # Unit+ unit = root.get("unit", "millimeter")++ # Metadata+ metadata: dict[str, str] = {}+ for meta in root.iterfind(_tag("metadata", ns)):+ meta_name = meta.get("name", "")+ meta_value = meta.text or ""+ if meta_name:+ metadata[meta_name] = meta_value++ # Meshes+ meshes: list[MeshData] = []+ resources = root.find(_tag("resources", ns))+ if resources is not None:+ for obj in resources.iterfind(_tag("object", ns)):+ mesh_data = _parse_mesh_element(obj, ns)+ if mesh_data is not None:+ meshes.append(mesh_data)++ return ThreeMFData(+ meshes=tuple(meshes),+ unit=unit,+ model_path=model_path,+ metadata=dict(metadata),+ raw_entries=dict(raw_entries),+ source_path=path,+ )+++# ---------------------------------------------------------------------------+# Writing+# ---------------------------------------------------------------------------++def _rebuild_model_xml(data: ThreeMFData) -> bytes:+ """Rebuild the model XML from *data*, preserving non-mesh elements.++ The strategy is:+ 1. Re-parse the original XML from ``raw_entries`` or regenerate from+ scratch.+ 2. For each ``<object>`` whose id matches one of our :class:`MeshData`+ objects, replace its ``<mesh>`` sub-tree with the (possibly modified)+ vertex/triangle arrays.+ 3. Leave every other element untouched.++ When no original XML is available (e.g. the caller built+ :class:`ThreeMFData` programmatically), a minimal valid model is+ generated.+ """++ # -- attempt to load the original XML for preservation -----------------+ original_bytes: bytes | None = None++ # If the caller kept raw bytes for the model path (unlikely but+ # possible), use them; otherwise we need the original file.+ if data.source_path and os.path.isfile(data.source_path):+ try:+ with zipfile.ZipFile(data.source_path, "r") as zf:+ original_bytes = zf.read(data.model_path)+ except Exception:+ original_bytes = None++ mesh_lookup: dict[str, MeshData] = {m.object_id: m for m in data.meshes}++ if original_bytes is not None:+ root = ET.fromstring(original_bytes)+ ns = _detect_namespace(root)++ resources = root.find(_tag("resources", ns))+ if resources is not None:+ for obj in resources.iterfind(_tag("object", ns)):+ oid = obj.get("id", "")+ if oid not in mesh_lookup:+ continue+ md = mesh_lookup[oid]++ # Remove old mesh element+ old_mesh = obj.find(_tag("mesh", ns))+ if old_mesh is not None:+ obj.remove(old_mesh)++ # Build new mesh element+ new_mesh = _build_mesh_element(md, ns)+ obj.append(new_mesh)+ else:+ # Build from scratch+ root = _build_model_from_scratch(data)++ # Serialise+ tree = ET.ElementTree(root)+ buf = io.BytesIO()+ tree.write(+ buf,+ xml_declaration=True,+ encoding="UTF-8",+ )+ return buf.getvalue()+++def _build_mesh_element(md: MeshData, ns: str) -> ET.Element:+ """Create a ``<mesh>`` XML element from vertex/triangle arrays."""+ mesh_el = ET.Element(_tag("mesh", ns))++ # Vertices+ verts_el = ET.SubElement(mesh_el, _tag("vertices", ns))+ for row in md.vertices:+ ET.SubElement(+ verts_el,+ _tag("vertex", ns),+ x=f"{row[0]:.6g}",+ y=f"{row[1]:.6g}",+ z=f"{row[2]:.6g}",+ )++ # Triangles+ tris_el = ET.SubElement(mesh_el, _tag("triangles", ns))+ for row in md.triangles:+ ET.SubElement(+ tris_el,+ _tag("triangle", ns),+ v1=str(row[0]),+ v2=str(row[1]),+ v3=str(row[2]),+ )++ return mesh_el+++def _build_model_from_scratch(data: ThreeMFData) -> ET.Element:+ """Generate a minimal ``<model>`` tree when no original XML exists."""+ root = ET.Element(+ _tag("model", NS_CORE),+ unit=data.unit,+ )++ # Metadata+ for name, value in data.metadata.items():+ meta = ET.SubElement(root, _tag("metadata", NS_CORE), name=name)+ meta.text = value++ # Resources+ resources = ET.SubElement(root, _tag("resources", NS_CORE))+ build = ET.SubElement(root, _tag("build", NS_CORE))++ for md in data.meshes:+ obj = ET.SubElement(+ resources,+ _tag("object", NS_CORE),+ id=md.object_id,+ type="model",+ )+ if md.name:+ obj.set("name", md.name)++ mesh_el = _build_mesh_element(md, NS_CORE)+ obj.append(mesh_el)++ ET.SubElement(build, _tag("item", NS_CORE), objectid=md.object_id)++ return root+++def write_3mf(data: ThreeMFData, output_path: str) -> None:+ """Write a :class:`ThreeMFData` structure to a 3MF (ZIP) file.++ Steps+ -----+ 1. Rebuild the model XML from the in-memory vertex/triangle data while+ preserving every non-mesh element (metadata, build items, extension+ namespaces, slicer settings embedded as attributes, etc.).+ 2. Copy all ``raw_entries`` (thumbnails, Bambu profiles, OPC+ relationships, ...) into the new ZIP archive.+ 3. Write the rebuilt model XML at its original ``model_path``.++ Parameters+ ----------+ data:+ The model data to write.+ output_path:+ Destination filesystem path. Parent directories are created if+ they do not exist.+ """+ output_path = os.path.abspath(output_path)+ os.makedirs(os.path.dirname(output_path), exist_ok=True)++ model_xml_bytes = _rebuild_model_xml(data)++ with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as zf:+ # Write raw (non-model) entries first+ for entry_path, entry_bytes in data.raw_entries.items():+ zf.writestr(entry_path, entry_bytes)++ # Write the model XML+ zf.writestr(data.model_path, model_xml_bytes)diff --git a/3MF/agent-harness/cli_anything/threemf/core/repair.py b/3MF/agent-harness/cli_anything/threemf/core/repair.pynew file mode 100644index 000000000..5a2e95f13--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/core/repair.py@@ -0,0 +1,220 @@+"""Mesh repair -- fix degenerate faces, duplicate vertices, and normals."""++from __future__ import annotations++from dataclasses import replace++import numpy as np++from cli_anything.threemf.core.parser import MeshData++# ---------------------------------------------------------------------------+# Public API+# ---------------------------------------------------------------------------+++def repair_mesh(mesh_data: MeshData) -> tuple[MeshData, dict]:+ """Run the full repair pipeline on *mesh_data*.++ Returns ``(repaired_mesh, report)`` where *report* summarises the+ number of fixes applied at each step.++ Pipeline+ --------+ 1. Merge duplicate vertices (rounded coordinate matching).+ 2. Remap triangle indices to canonical vertices.+ 3. Remove degenerate triangles (two or more identical indices).+ 4. Remove unreferenced vertices and compact indices.+ 5. Return the repaired mesh and a report dict.+ """++ _validate_mesh(mesh_data)++ vertices = mesh_data.vertices+ triangles = mesh_data.triangles++ # Handle empty mesh early+ if vertices.shape[0] == 0 or triangles.shape[0] == 0:+ return mesh_data, _empty_report()++ # Step 1+2 -- merge duplicates and remap triangles+ vertices, triangles, merge_count = merge_duplicate_vertices(+ vertices, triangles,+ )++ # Step 3 -- remove degenerate faces+ triangles, degen_count = remove_degenerate_faces(triangles)++ # Step 4 -- remove unreferenced vertices+ vertices, triangles, unref_count = remove_unreferenced_vertices(+ vertices, triangles,+ )++ report = {+ "vertices_merged": merge_count,+ "degenerate_faces_removed": degen_count,+ "unreferenced_vertices_removed": unref_count,+ "final_vertex_count": int(vertices.shape[0]),+ "final_triangle_count": int(triangles.shape[0]),+ }++ repaired = replace(mesh_data, vertices=vertices, triangles=triangles)+ return repaired, report+++def merge_duplicate_vertices(+ vertices: np.ndarray,+ triangles: np.ndarray,+ decimals: int = 6,+) -> tuple[np.ndarray, np.ndarray, int]:+ """Merge vertices that share the same coordinates (after rounding).++ Returns ``(unique_vertices, remapped_triangles, merge_count)``+ where *merge_count* is the number of vertices removed.+ """++ if vertices.shape[0] == 0:+ return vertices, triangles, 0++ rounded = np.round(vertices, decimals=decimals)++ # Build a mapping from rounded coordinates to canonical index+ # Using a structured view for fast unique-row detection+ dtype = np.dtype([("x", rounded.dtype), ("y", rounded.dtype), ("z", rounded.dtype)])+ structured = np.ascontiguousarray(rounded).view(dtype).reshape(-1)++ _, canonical_idx, inverse = np.unique(+ structured, return_index=True, return_inverse=True,+ )++ unique_vertices = vertices[np.sort(canonical_idx)]++ # Build old-index -> new-index mapping (preserving sorted order of canonical)+ sorted_canonical = np.sort(canonical_idx)+ new_idx_map = np.full(vertices.shape[0], -1, dtype=np.intp)+ for new_i, old_i in enumerate(sorted_canonical):+ new_idx_map[old_i] = new_i++ # Remap each original index through inverse -> canonical -> new_sorted+ remap = new_idx_map[canonical_idx[inverse]]++ remapped_triangles = remap[triangles] if triangles.shape[0] > 0 else triangles++ merge_count = int(vertices.shape[0] - unique_vertices.shape[0])+ return unique_vertices, remapped_triangles, merge_count+++def remove_degenerate_faces(+ triangles: np.ndarray,+) -> tuple[np.ndarray, int]:+ """Remove triangles where two or more vertex indices are identical.++ Returns ``(filtered_triangles, removed_count)``.+ """++ if triangles.shape[0] == 0:+ return triangles, 0++ v0, v1, v2 = triangles[:, 0], triangles[:, 1], triangles[:, 2]+ valid = (v0 != v1) & (v1 != v2) & (v0 != v2)++ filtered = triangles[valid]+ removed = int(triangles.shape[0] - filtered.shape[0])+ return filtered, removed+++def remove_unreferenced_vertices(+ vertices: np.ndarray,+ triangles: np.ndarray,+) -> tuple[np.ndarray, np.ndarray, int]:+ """Remove vertices not referenced by any triangle and compact indices.++ Returns ``(filtered_vertices, remapped_triangles, removed_count)``.+ """++ if vertices.shape[0] == 0:+ return vertices, triangles, 0++ if triangles.shape[0] == 0:+ # No triangles reference any vertex -- remove all+ empty_verts = np.empty((0, 3), dtype=vertices.dtype)+ empty_tris = np.empty((0, 3), dtype=triangles.dtype)+ return empty_verts, empty_tris, int(vertices.shape[0])++ referenced = np.unique(triangles.ravel())+ removed_count = int(vertices.shape[0] - referenced.shape[0])++ if removed_count == 0:+ return vertices, triangles, 0++ filtered_vertices = vertices[referenced]++ # Build old-index -> new-index mapping+ remap = np.full(vertices.shape[0], -1, dtype=np.intp)+ remap[referenced] = np.arange(referenced.shape[0], dtype=np.intp)++ remapped_triangles = remap[triangles]+ return filtered_vertices, remapped_triangles, removed_count+++def fix_normals(mesh_data: MeshData) -> MeshData:+ """Fix face winding for consistent outward-pointing normals using trimesh.++ Returns a **new** ``MeshData`` with corrected triangle winding order.+ """++ _validate_mesh(mesh_data)++ if mesh_data.vertices.shape[0] == 0 or mesh_data.triangles.shape[0] == 0:+ return mesh_data++ try:+ import trimesh+ except ImportError as exc:+ raise ImportError(+ "trimesh is required for normal repair. "+ "Install with: pip install trimesh"+ ) from exc++ tm = trimesh.Trimesh(+ vertices=mesh_data.vertices.copy(),+ faces=mesh_data.triangles.copy(),+ process=False,+ )+ trimesh.repair.fix_normals(tm)++ return replace(+ mesh_data,+ vertices=np.array(tm.vertices),+ triangles=np.array(tm.faces),+ )+++# ---------------------------------------------------------------------------+# Internal helpers+# ---------------------------------------------------------------------------+++def _validate_mesh(mesh_data: MeshData) -> None:+ """Raise ``ValueError`` for clearly invalid mesh data."""+ if mesh_data is None:+ raise ValueError("mesh_data must not be None")+ if not isinstance(mesh_data.vertices, np.ndarray):+ raise ValueError("mesh_data.vertices must be a numpy ndarray")+ if not isinstance(mesh_data.triangles, np.ndarray):+ raise ValueError("mesh_data.triangles must be a numpy ndarray")+ if mesh_data.vertices.ndim != 2 or mesh_data.vertices.shape[1] != 3:+ raise ValueError("mesh_data.vertices must have shape (N, 3)")+ if mesh_data.triangles.ndim != 2 or mesh_data.triangles.shape[1] != 3:+ if mesh_data.triangles.shape[0] != 0:+ raise ValueError("mesh_data.triangles must have shape (M, 3)")+++def _empty_report() -> dict:+ return {+ "vertices_merged": 0,+ "degenerate_faces_removed": 0,+ "unreferenced_vertices_removed": 0,+ "final_vertex_count": 0,+ "final_triangle_count": 0,+ }diff --git a/3MF/agent-harness/cli_anything/threemf/skills/SKILL.md b/3MF/agent-harness/cli_anything/threemf/skills/SKILL.mdnew file mode 100644index 000000000..096fea1b7--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/skills/SKILL.md@@ -0,0 +1,49 @@+---+name: "cli-anything-3mf"+description: "3MF mesh geometry editor — detect and resize cylindrical holes, repair meshes, compare 3D printing files. Works with BambuStudio and PrusaSlicer 3MF files."+---++# cli-anything-3mf++3MF mesh geometry editor for 3D printing files.++## Installation++```bash+pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=3MF/agent-harness+```++## Commands++```bash+# Show mesh info (vertices, faces, bounding box, watertight status, volume)+cli-anything-3mf info <file.3mf>++# Detect cylindrical holes (center, diameter, confidence)+cli-anything-3mf inspect <file.3mf>++# Resize holes to target diameter+cli-anything-3mf resize <file.3mf> --hole 0 --hole 1 --diameter 4.2 -o output.3mf++# Fix mesh issues (degenerate faces, duplicate vertices, normals)+cli-anything-3mf repair <file.3mf> -o repaired.3mf++# Compare two 3MF files+cli-anything-3mf compare <file1.3mf> <file2.3mf>+```++## JSON Output++All commands support `--json` for machine-readable output:++```bash+cli-anything-3mf --json inspect model.3mf+```++## Key Features++- Detects cylindrical holes via multi-plane cross-section analysis+- Resizes holes by radial vertex scaling (preserves mesh topology)+- Preserves slicer metadata (BambuStudio, PrusaSlicer) during file repack+- Repairs degenerate faces and duplicate vertices after modification+- Works with any 3MF file conforming to the 3MF Core Specificationdiff --git a/3MF/agent-harness/cli_anything/threemf/tests/__init__.py b/3MF/agent-harness/cli_anything/threemf/tests/__init__.pynew file mode 100644index 000000000..8b1378917--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/tests/__init__.py@@ -0,0 +1 @@+diff --git a/3MF/agent-harness/cli_anything/threemf/tests/test_core.py b/3MF/agent-harness/cli_anything/threemf/tests/test_core.pynew file mode 100644index 000000000..86b687eea--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/tests/test_core.py@@ -0,0 +1,926 @@+"""Comprehensive unit tests for the 3MF core modules.++Covers:+- cli_anything.threemf.core.parser (MeshData, ThreeMFData)+- cli_anything.threemf.utils.threemf_backend (geometry utilities)+- cli_anything.threemf.core.inspector (InspectParams, DetectedHole,+ inspect_mesh, compare_meshes)+- cli_anything.threemf.core.repair (repair_mesh, merge_duplicate_vertices,+ remove_degenerate_faces,+ remove_unreferenced_vertices, fix_normals)+- cli_anything.threemf.core.modifier (resize_holes, resize_single_hole)++All tests use synthetic numpy data -- no real .3mf files are required.+"""++from __future__ import annotations++import numpy as np+import pytest++from cli_anything.threemf.core.parser import MeshData, ThreeMFData+from cli_anything.threemf.utils import threemf_backend as backend+from cli_anything.threemf.core import inspector, repair, modifier+from cli_anything.threemf.core.inspector import DetectedHole, InspectParams+from cli_anything.threemf.core.modifier import resize_holes, resize_single_hole+++# ---------------------------------------------------------------------------+# Shared helpers+# ---------------------------------------------------------------------------++def _make_cube_mesh(size: float = 10.0) -> MeshData:+ """Create a simple closed-cube MeshData for testing."""+ s = size / 2+ vertices = np.array(+ [+ [-s, -s, -s], [s, -s, -s], [s, s, -s], [-s, s, -s],+ [-s, -s, s], [s, -s, s], [s, s, s], [-s, s, s],+ ],+ dtype=np.float64,+ )+ triangles = np.array(+ [+ [0, 2, 1], [0, 3, 2],+ [4, 5, 6], [4, 6, 7],+ [0, 1, 5], [0, 5, 4],+ [2, 3, 7], [2, 7, 6],+ [0, 4, 7], [0, 7, 3],+ [1, 2, 6], [1, 6, 5],+ ],+ dtype=np.int32,+ )+ return MeshData(object_id="1", name="cube", vertices=vertices, triangles=triangles)+++def _make_empty_mesh() -> MeshData:+ return MeshData(+ object_id="0",+ name="empty",+ vertices=np.empty((0, 3), dtype=np.float64),+ triangles=np.empty((0, 3), dtype=np.int32),+ )+++def _make_threemf_data(mesh: MeshData | None = None) -> ThreeMFData:+ """Wrap a single mesh (or the default cube) in a ThreeMFData."""+ if mesh is None:+ mesh = _make_cube_mesh()+ return ThreeMFData(+ meshes=(mesh,),+ unit="millimeter",+ model_path="3D/3dmodel.model",+ metadata={"Author": "test"},+ raw_entries={},+ source_path="",+ )+++def _make_circle_points(+ cx: float = 0.0, cy: float = 0.0, r: float = 5.0, n: int = 60+) -> np.ndarray:+ """Return (n, 2) points uniformly distributed on a circle."""+ theta = np.linspace(0, 2 * np.pi, n, endpoint=False)+ return np.column_stack([cx + r * np.cos(theta), cy + r * np.sin(theta)])+++def _make_mesh_with_duplicates() -> MeshData:+ """Cube with two duplicate vertices appended."""+ cube = _make_cube_mesh(4.0)+ extra = cube.vertices[:2].copy()+ vertices = np.vstack([cube.vertices, extra])+ triangles = np.vstack([+ cube.triangles,+ np.array([[8, 9, 2]], dtype=np.int32),+ ])+ return MeshData(object_id="dup", name="dup", vertices=vertices, triangles=triangles)+++def _make_mesh_with_degenerate() -> MeshData:+ """Cube with one degenerate triangle (two identical indices) appended."""+ cube = _make_cube_mesh(4.0)+ degen = np.array([[0, 0, 1]], dtype=np.int32)+ triangles = np.vstack([cube.triangles, degen])+ return MeshData(object_id="deg", name="deg", vertices=cube.vertices, triangles=triangles)+++def _make_fake_hole(+ center: tuple[float, float] = (0.0, 0.0),+ diameter: float = 3.0,+ hole_id: int = 0,+ axis: int = 0,+) -> DetectedHole:+ return DetectedHole(+ hole_id=hole_id,+ center=center,+ diameter=diameter,+ axis_min=-5.0,+ axis_max=5.0,+ axis=axis,+ confidence=0.9,+ vertex_count=10,+ )+++# ===========================================================================+# TestParser -- MeshData and ThreeMFData+# ===========================================================================+++class TestParser:+ """Tests for cli_anything.threemf.core.parser."""++ # --- MeshData construction -------------------------------------------------++ def test_mesh_data_basic_construction(self) -> None:+ """MeshData is created with correct attributes."""+ mesh = _make_cube_mesh()+ assert mesh.object_id == "1"+ assert mesh.name == "cube"+ assert mesh.vertices.shape == (8, 3)+ assert mesh.triangles.shape == (12, 3)++ def test_mesh_data_vertex_dtype(self) -> None:+ """Vertices array dtype is float64."""+ assert _make_cube_mesh().vertices.dtype == np.float64++ def test_mesh_data_triangle_dtype(self) -> None:+ """Triangles array dtype is int32."""+ assert _make_cube_mesh().triangles.dtype == np.int32++ def test_mesh_data_is_frozen_on_object_id(self) -> None:+ """MeshData raises FrozenInstanceError when object_id is reassigned."""+ mesh = _make_cube_mesh()+ with pytest.raises(Exception):+ mesh.object_id = "new_id" # type: ignore[misc]++ def test_mesh_data_is_frozen_on_vertices(self) -> None:+ """MeshData raises FrozenInstanceError when vertices is reassigned."""+ mesh = _make_cube_mesh()+ with pytest.raises(Exception):+ mesh.vertices = np.zeros((8, 3)) # type: ignore[misc]++ def test_mesh_data_bad_vertex_shape_1d(self) -> None:+ """1-D vertex array raises ValueError."""+ flat = np.array([0.0, 1.0, 2.0])+ t = np.array([[0, 1, 2]], dtype=np.int32)+ with pytest.raises(ValueError, match="vertices"):+ MeshData(object_id="1", name="x", vertices=flat, triangles=t) # type: ignore[arg-type]++ def test_mesh_data_bad_vertex_shape_wrong_columns(self) -> None:+ """Vertex array with 2 columns raises ValueError."""+ v = np.zeros((4, 2), dtype=np.float64)+ t = np.array([[0, 1, 2]], dtype=np.int32)+ with pytest.raises(ValueError, match="vertices"):+ MeshData(object_id="1", name="x", vertices=v, triangles=t)++ def test_mesh_data_bad_triangle_shape_wrong_columns(self) -> None:+ """Triangle array with 4 columns raises ValueError."""+ v = np.zeros((4, 3), dtype=np.float64)+ t = np.array([[0, 1, 2, 0]], dtype=np.int32)+ with pytest.raises(ValueError, match="triangles"):+ MeshData(object_id="1", name="x", vertices=v, triangles=t)++ def test_mesh_data_empty_name_is_allowed(self) -> None:+ """Empty name string is valid."""+ v = np.zeros((3, 3), dtype=np.float64)+ t = np.array([[0, 1, 2]], dtype=np.int32)+ mesh = MeshData(object_id="1", name="", vertices=v, triangles=t)+ assert mesh.name == ""++ def test_mesh_data_single_triangle(self) -> None:+ """A minimal mesh with one triangle can be constructed."""+ v = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], dtype=np.float64)+ t = np.array([[0, 1, 2]], dtype=np.int32)+ mesh = MeshData(object_id="2", name="tri", vertices=v, triangles=t)+ assert mesh.triangles.shape == (1, 3)++ def test_mesh_data_empty_construction(self) -> None:+ """Empty mesh (0 vertices, 0 triangles) can be constructed."""+ m = _make_empty_mesh()+ assert m.vertices.shape == (0, 3)+ assert m.triangles.shape == (0, 3)++ # --- ThreeMFData construction -----------------------------------------------++ def test_threemf_data_stores_all_fields(self) -> None:+ """ThreeMFData stores all fields correctly."""+ data = _make_threemf_data()+ assert data.unit == "millimeter"+ assert data.model_path == "3D/3dmodel.model"+ assert data.metadata["Author"] == "test"+ assert len(data.meshes) == 1++ def test_threemf_data_is_frozen(self) -> None:+ """ThreeMFData raises FrozenInstanceError on attribute assignment."""+ data = _make_threemf_data()+ with pytest.raises(Exception):+ data.unit = "inch" # type: ignore[misc]++ def test_threemf_data_multiple_meshes(self) -> None:+ """ThreeMFData can hold multiple meshes."""+ m1 = _make_cube_mesh(size=5.0)+ m2 = MeshData(+ object_id="2",+ name="small",+ vertices=np.zeros((3, 3), dtype=np.float64),+ triangles=np.array([[0, 1, 2]], dtype=np.int32),+ )+ data = ThreeMFData(+ meshes=(m1, m2),+ unit="millimeter",+ model_path="3D/3dmodel.model",+ metadata={},+ raw_entries={},+ source_path="",+ )+ assert len(data.meshes) == 2++ def test_threemf_data_empty_meshes(self) -> None:+ """ThreeMFData with no meshes is valid."""+ data = ThreeMFData(+ meshes=(),+ unit="millimeter",+ model_path="3D/3dmodel.model",+ metadata={},+ raw_entries={},+ source_path="",+ )+ assert len(data.meshes) == 0++ def test_threemf_data_raw_entries_preserved(self) -> None:+ """raw_entries bytes are stored unchanged."""+ payload = b"\x00\x01\x02\x03"+ data = ThreeMFData(+ meshes=(),+ unit="millimeter",+ model_path="3D/3dmodel.model",+ metadata={},+ raw_entries={"thumbnail.png": payload},+ source_path="",+ )+ assert data.raw_entries["thumbnail.png"] == payload+++# ===========================================================================+# TestBackend -- threemf_backend geometry utilities+# ===========================================================================+++class TestBackend:+ """Tests for cli_anything.threemf.utils.threemf_backend."""++ # --- mesh_to_trimesh -------------------------------------------------------++ def test_mesh_to_trimesh_returns_trimesh_instance(self) -> None:+ """mesh_to_trimesh returns a trimesh.Trimesh instance."""+ import trimesh+ tm = backend.mesh_to_trimesh(_make_cube_mesh())+ assert isinstance(tm, trimesh.Trimesh)++ def test_mesh_to_trimesh_vertex_count(self) -> None:+ """Converted trimesh has the same vertex count as MeshData."""+ mesh = _make_cube_mesh()+ assert backend.mesh_to_trimesh(mesh).vertices.shape[0] == mesh.vertices.shape[0]++ def test_mesh_to_trimesh_face_count(self) -> None:+ """Converted trimesh has the same face count as MeshData."""+ mesh = _make_cube_mesh()+ assert backend.mesh_to_trimesh(mesh).faces.shape[0] == mesh.triangles.shape[0]++ def test_mesh_to_trimesh_does_not_mutate_source(self) -> None:+ """mesh_to_trimesh does not mutate the original MeshData vertices."""+ mesh = _make_cube_mesh()+ orig = mesh.vertices.copy()+ tm = backend.mesh_to_trimesh(mesh)+ tm.vertices[0, 0] = 9999.0+ assert np.allclose(mesh.vertices, orig)++ # --- trimesh_to_mesh -------------------------------------------------------++ def test_trimesh_to_mesh_roundtrip_vertex_count(self) -> None:+ """trimesh -> MeshData preserves vertex count."""+ mesh = _make_cube_mesh()+ m2 = backend.trimesh_to_mesh(backend.mesh_to_trimesh(mesh), "1", "cube")+ assert m2.vertices.shape[0] == mesh.vertices.shape[0]++ def test_trimesh_to_mesh_roundtrip_face_count(self) -> None:+ """trimesh -> MeshData preserves face count."""+ mesh = _make_cube_mesh()+ m2 = backend.trimesh_to_mesh(backend.mesh_to_trimesh(mesh), "1", "cube")+ assert m2.triangles.shape[0] == mesh.triangles.shape[0]++ def test_trimesh_to_mesh_sets_object_id_and_name(self) -> None:+ """trimesh_to_mesh sets object_id and name correctly."""+ tm = backend.mesh_to_trimesh(_make_cube_mesh())+ m2 = backend.trimesh_to_mesh(tm, "42", "mymesh")+ assert m2.object_id == "42"+ assert m2.name == "mymesh"++ def test_trimesh_to_mesh_values_match(self) -> None:+ """Roundtrip preserves vertex coordinates."""+ mesh = _make_cube_mesh()+ tm = backend.mesh_to_trimesh(mesh)+ m2 = backend.trimesh_to_mesh(tm, "1", "cube")+ np.testing.assert_array_almost_equal(m2.vertices, mesh.vertices)++ # --- compute_mesh_stats ----------------------------------------------------++ def test_stats_vertex_count(self) -> None:+ assert compute_mesh_stats_cube()["vertex_count"] == 8++ def test_stats_face_count(self) -> None:+ assert compute_mesh_stats_cube()["face_count"] == 12++ def test_stats_watertight_closed_cube(self) -> None:+ assert compute_mesh_stats_cube()["watertight"] is True++ def test_stats_volume_cube_1000(self) -> None:+ stats = compute_mesh_stats_cube()+ assert stats["volume_mm3"] is not None+ assert abs(stats["volume_mm3"] - 1000.0) < 1.0++ def test_stats_bounding_box_has_required_keys(self) -> None:+ bb = compute_mesh_stats_cube()["bounding_box"]+ assert "min" in bb and "max" in bb and "size" in bb++ def test_stats_bounding_box_values_correct(self) -> None:+ bb = compute_mesh_stats_cube()["bounding_box"]+ assert np.allclose(bb["min"], [-5.0, -5.0, -5.0], atol=1e-6)+ assert np.allclose(bb["max"], [5.0, 5.0, 5.0], atol=1e-6)+ assert np.allclose(bb["size"], [10.0, 10.0, 10.0], atol=1e-6)++ def test_stats_surface_area_cube(self) -> None:+ stats = compute_mesh_stats_cube()+ assert abs(stats["surface_area_mm2"] - 600.0) < 5.0++ def test_stats_empty_mesh_defaults(self) -> None:+ """compute_mesh_stats handles an empty mesh gracefully."""+ stats = backend.compute_mesh_stats(_make_empty_mesh())+ assert stats["vertex_count"] == 0+ assert stats["face_count"] == 0+ assert stats["watertight"] is False+ assert stats["volume_mm3"] is None+ assert stats["surface_area_mm2"] == 0.0++ # --- fit_circle_least_squares ----------------------------------------------++ def test_fit_circle_perfect_center_and_radius(self) -> None:+ """fit_circle_least_squares recovers exact parameters of a perfect circle."""+ pts = _make_circle_points(cx=3.0, cy=2.0, r=5.0, n=100)+ cx, cy, r, err = backend.fit_circle_least_squares(pts)+ assert abs(cx - 3.0) < 1e-6+ assert abs(cy - 2.0) < 1e-6+ assert abs(r - 5.0) < 1e-6+ assert err < 1e-6++ def test_fit_circle_unit_circle(self) -> None:+ """fit_circle_least_squares works for unit circle at origin."""+ pts = _make_circle_points(cx=0.0, cy=0.0, r=1.0, n=60)+ cx, cy, r, _ = backend.fit_circle_least_squares(pts)+ assert abs(cx) < 1e-6+ assert abs(cy) < 1e-6+ assert abs(r - 1.0) < 1e-6++ def test_fit_circle_too_few_points(self) -> None:+ """fit_circle_least_squares raises ValueError for fewer than 3 points."""+ with pytest.raises(ValueError, match="At least 3"):+ backend.fit_circle_least_squares(np.array([[0.0, 0.0], [1.0, 0.0]]))++ def test_fit_circle_wrong_shape(self) -> None:+ """fit_circle_least_squares raises ValueError for (N,3) input."""+ pts = np.zeros((5, 3), dtype=np.float64)+ with pytest.raises(ValueError, match="points_2d must be"):+ backend.fit_circle_least_squares(pts)++ def test_fit_circle_noisy_stays_reasonable(self) -> None:+ """fit_circle_least_squares is robust to small noise."""+ rng = np.random.default_rng(42)+ pts = _make_circle_points(cx=1.0, cy=-1.0, r=3.0, n=80)+ pts = pts + rng.normal(0, 0.02, pts.shape)+ cx, cy, r, err = backend.fit_circle_least_squares(pts)+ assert abs(cx - 1.0) < 0.1+ assert abs(cy - (-1.0)) < 0.1+ assert abs(r - 3.0) < 0.1++ # --- find_cylinder_vertices ------------------------------------------------++ def test_find_cylinder_vertices_all_on_surface(self) -> None:+ """All points exactly on a cylinder surface are found."""+ theta = np.linspace(0, 2 * np.pi, 20, endpoint=False)+ r, cx, cy = 3.0, 1.0, 2.0+ x, y = cx + r * np.cos(theta), cy + r * np.sin(theta)+ verts = np.column_stack([np.zeros(20), x, y]) # axis=0+ idx = backend.find_cylinder_vertices(verts, np.array([cx, cy]), axis=0, radius=r, tolerance=0.01)+ assert len(idx) == 20++ def test_find_cylinder_vertices_none_found(self) -> None:+ """No vertices within tolerance returns empty array."""+ verts = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=np.float64)+ idx = backend.find_cylinder_vertices(verts, np.array([100.0, 100.0]), axis=0, radius=5.0, tolerance=0.01)+ assert len(idx) == 0++ def test_find_cylinder_vertices_empty_input(self) -> None:+ """Empty vertex array returns empty index array."""+ idx = backend.find_cylinder_vertices(+ np.empty((0, 3), dtype=np.float64), np.array([0.0, 0.0]), axis=0, radius=3.0, tolerance=0.1+ )+ assert len(idx) == 0++ def test_find_cylinder_vertices_bad_axis(self) -> None:+ """Invalid axis raises ValueError."""+ with pytest.raises(ValueError, match="axis"):+ backend.find_cylinder_vertices(+ np.ones((5, 3)), np.array([0.0, 0.0]), axis=5, radius=1.0, tolerance=0.1+ )++ def test_find_cylinder_vertices_bad_center_shape(self) -> None:+ """center_yz with 3 elements raises ValueError."""+ with pytest.raises(ValueError, match="center_yz must have 2"):+ backend.find_cylinder_vertices(+ np.ones((5, 3)), np.array([0.0, 0.0, 0.0]), axis=0, radius=1.0, tolerance=0.1+ )++ # --- scale_vertices_radially -----------------------------------------------++ def test_scale_vertices_radially_reaches_new_radius(self) -> None:+ """Scaled vertices end up at the target radius."""+ theta = np.linspace(0, 2 * np.pi, 10, endpoint=False)+ verts = np.column_stack([np.zeros(10), 3.0 * np.cos(theta), 3.0 * np.sin(theta)])+ idx = np.arange(10, dtype=np.intp)+ new_verts = backend.scale_vertices_radially(verts, idx, np.array([0.0, 0.0]), axis=0, new_radius=5.0)+ actual_r = np.sqrt(new_verts[:, 1] ** 2 + new_verts[:, 2] ** 2)+ np.testing.assert_allclose(actual_r, 5.0, atol=1e-10)++ def test_scale_vertices_radially_does_not_mutate_input(self) -> None:+ """Original vertex array is never mutated."""+ verts = np.ones((6, 3), dtype=np.float64) * 3.0+ orig = verts.copy()+ backend.scale_vertices_radially(verts, np.arange(6, dtype=np.intp), np.array([0.0, 0.0]), axis=0, new_radius=7.0)+ assert np.allclose(verts, orig)++ def test_scale_vertices_radially_empty_indices_returns_copy(self) -> None:+ """Empty index array returns a copy of the original vertices."""+ verts = np.ones((4, 3), dtype=np.float64)+ new_verts = backend.scale_vertices_radially(+ verts, np.array([], dtype=np.intp), np.array([0.0, 0.0]), axis=0, new_radius=5.0+ )+ assert np.allclose(new_verts, verts)++ def test_scale_vertices_radially_bad_axis(self) -> None:+ """Invalid axis raises ValueError."""+ with pytest.raises(ValueError, match="axis"):+ backend.scale_vertices_radially(+ np.ones((4, 3)), np.arange(4, dtype=np.intp), np.array([0.0, 0.0]), axis=9, new_radius=1.0+ )++ def test_scale_vertices_radially_preserves_axis_coordinate(self) -> None:+ """The axis coordinate is unchanged after radial scaling."""+ z = np.linspace(-5, 5, 8)+ x = 3.0 * np.cos(np.linspace(0, 2 * np.pi, 8, endpoint=False))+ y = 3.0 * np.sin(np.linspace(0, 2 * np.pi, 8, endpoint=False))+ verts = np.column_stack([x, y, z]) # axis=2+ idx = np.arange(8, dtype=np.intp)+ new_verts = backend.scale_vertices_radially(verts, idx, np.array([0.0, 0.0]), axis=2, new_radius=7.0)+ assert np.allclose(new_verts[:, 2], z)++ # --- cross_section_circles (smoke tests) -----------------------------------++ def test_cross_section_circles_returns_list(self) -> None:+ circles = backend.cross_section_circles(_make_cube_mesh(), axis=0, num_planes=5)+ assert isinstance(circles, list)++ def test_cross_section_circles_empty_mesh(self) -> None:+ circles = backend.cross_section_circles(_make_empty_mesh(), axis=0, num_planes=5)+ assert circles == []++ def test_cross_section_circles_bad_axis(self) -> None:+ with pytest.raises(ValueError, match="axis"):+ backend.cross_section_circles(_make_cube_mesh(), axis=5, num_planes=5)+++# Convenience function used in multiple TestBackend tests+def compute_mesh_stats_cube() -> dict:+ return backend.compute_mesh_stats(_make_cube_mesh(size=10.0))+++# ===========================================================================+# TestInspector -- InspectParams, DetectedHole, inspect_mesh, compare_meshes+# ===========================================================================+++class TestInspector:+ """Tests for cli_anything.threemf.core.inspector."""++ # --- InspectParams ---------------------------------------------------------++ def test_inspect_params_default_values(self) -> None:+ p = inspector.InspectParams()+ assert p.num_planes == 20+ assert p.min_hole_diameter == 0.5+ assert p.min_confidence == 0.7+ assert p.axis == 0++ def test_inspect_params_custom_values(self) -> None:+ p = inspector.InspectParams(num_planes=10, min_hole_diameter=1.0, min_confidence=0.8, axis=2)+ assert p.num_planes == 10+ assert p.min_confidence == 0.8+ assert p.axis == 2++ def test_inspect_params_is_frozen(self) -> None:+ p = inspector.InspectParams()+ with pytest.raises(Exception):+ p.num_planes = 99 # type: ignore[misc]++ # --- DetectedHole ----------------------------------------------------------++ def test_detected_hole_stores_all_fields(self) -> None:+ h = inspector.DetectedHole(+ hole_id=5, center=(1.0, 2.0), diameter=3.5,+ axis_min=-5.0, axis_max=5.0, axis=1, confidence=0.85, vertex_count=30,+ )+ assert h.hole_id == 5+ assert h.center == (1.0, 2.0)+ assert h.diameter == 3.5+ assert h.axis == 1+ assert h.confidence == 0.85+ assert h.vertex_count == 30++ def test_detected_hole_is_frozen(self) -> None:+ h = _make_fake_hole()+ with pytest.raises(Exception):+ h.hole_id = 99 # type: ignore[misc]++ # --- inspect_mesh ----------------------------------------------------------++ def test_inspect_mesh_returns_list(self) -> None:+ assert isinstance(inspector.inspect_mesh(_make_cube_mesh()), list)++ def test_inspect_mesh_empty_mesh_returns_empty_list(self) -> None:+ assert inspector.inspect_mesh(_make_empty_mesh()) == []++ def test_inspect_mesh_default_params(self) -> None:+ """inspect_mesh runs with None params (uses defaults)."""+ result = inspector.inspect_mesh(_make_cube_mesh(), None)+ assert isinstance(result, list)++ def test_inspect_mesh_custom_params(self) -> None:+ """inspect_mesh accepts custom InspectParams without error."""+ params = inspector.InspectParams(num_planes=5, min_hole_diameter=1.0)+ result = inspector.inspect_mesh(_make_cube_mesh(), params)+ assert isinstance(result, list)++ def test_inspect_mesh_result_items_are_detected_holes(self) -> None:+ """Any items in the result are DetectedHole instances."""+ for item in inspector.inspect_mesh(_make_cube_mesh()):+ assert isinstance(item, inspector.DetectedHole)++ def test_inspect_mesh_sorted_by_hole_id(self) -> None:+ """Results are sorted by hole_id in ascending order."""+ result = inspector.inspect_mesh(_make_cube_mesh())+ ids = [h.hole_id for h in result]+ assert ids == sorted(ids)++ # --- compare_meshes --------------------------------------------------------++ def test_compare_meshes_identical_zero_diff(self) -> None:+ mesh = _make_cube_mesh()+ result = inspector.compare_meshes(mesh, mesh)+ assert result["vertices"]["diff"] == 0+ assert result["faces"]["diff"] == 0+ assert result["volume"]["diff"] == pytest.approx(0.0, abs=1e-6)++ def test_compare_meshes_has_required_top_level_keys(self) -> None:+ result = inspector.compare_meshes(_make_cube_mesh(), _make_cube_mesh())+ for key in ("vertices", "faces", "volume", "watertight"):+ assert key in result++ def test_compare_meshes_sub_dicts_have_file1_file2_diff(self) -> None:+ result = inspector.compare_meshes(_make_cube_mesh(), _make_cube_mesh())+ for key in ("vertices", "faces", "volume"):+ sub = result[key]+ assert "file1" in sub and "file2" in sub and "diff" in sub++ def test_compare_meshes_watertight_has_file1_and_file2(self) -> None:+ result = inspector.compare_meshes(_make_cube_mesh(), _make_cube_mesh())+ assert "file1" in result["watertight"] and "file2" in result["watertight"]++ def test_compare_meshes_vertex_counts_match_meshes(self) -> None:+ mesh_a = _make_cube_mesh(size=10.0)+ mesh_b = _make_cube_mesh(size=5.0)+ result = inspector.compare_meshes(mesh_a, mesh_b)+ assert result["vertices"]["file1"] == mesh_a.vertices.shape[0]+ assert result["vertices"]["file2"] == mesh_b.vertices.shape[0]++ def test_compare_meshes_different_volumes(self) -> None:+ """Cubes of different sizes have different volumes."""+ mesh_a = _make_cube_mesh(size=10.0)+ mesh_b = _make_cube_mesh(size=20.0)+ result = inspector.compare_meshes(mesh_a, mesh_b)+ assert result["volume"]["file2"] > result["volume"]["file1"]++ # --- get_mesh_info ---------------------------------------------------------++ def test_get_mesh_info_returns_dict(self) -> None:+ """get_mesh_info returns a dict."""+ result = inspector.get_mesh_info(_make_cube_mesh())+ assert isinstance(result, dict)++ def test_get_mesh_info_has_object_id_and_name(self) -> None:+ """get_mesh_info includes object_id and name fields."""+ mesh = _make_cube_mesh()+ result = inspector.get_mesh_info(mesh)+ assert result["object_id"] == mesh.object_id+ assert result["name"] == mesh.name++ def test_get_mesh_info_vertex_and_triangle_counts(self) -> None:+ """get_mesh_info reports correct vertex and triangle counts."""+ mesh = _make_cube_mesh()+ result = inspector.get_mesh_info(mesh)+ assert result["num_vertices"] == 8+ assert result["num_triangles"] == 12++ def test_get_mesh_info_includes_stats_keys(self) -> None:+ """get_mesh_info includes all keys from compute_mesh_stats."""+ result = inspector.get_mesh_info(_make_cube_mesh())+ for key in ("vertex_count", "face_count", "bounding_box", "watertight",+ "volume_mm3", "surface_area_mm2"):+ assert key in result++ # --- _validate_mesh error branches -----------------------------------------++ def test_validate_mesh_raises_for_none(self) -> None:+ """compare_meshes propagates ValueError when mesh_data is None."""+ with pytest.raises((ValueError, AttributeError)):+ inspector.compare_meshes(None, _make_cube_mesh()) # type: ignore[arg-type]++ # --- inspect_mesh flat-mesh early return -----------------------------------++ def test_inspect_mesh_flat_mesh_returns_empty(self) -> None:+ """A mesh with all vertices on a single plane (zero span along axis) returns []."""+ # All vertices share the same X coordinate -> span along X=0 is zero+ v = np.array(+ [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 1.0]],+ dtype=np.float64,+ )+ t = np.array([[0, 1, 2], [1, 3, 2]], dtype=np.int32)+ mesh = MeshData(object_id="1", name="flat", vertices=v, triangles=t)+ params = inspector.InspectParams(axis=0)+ result = inspector.inspect_mesh(mesh, params)+ assert result == []+++# ===========================================================================+# TestRepair -- repair_mesh, individual repair functions, fix_normals+# ===========================================================================+++class TestRepair:+ """Tests for cli_anything.threemf.core.repair."""++ # --- repair_mesh -----------------------------------------------------------++ def test_repair_mesh_returns_tuple_of_mesh_and_dict(self) -> None:+ result = repair.repair_mesh(_make_cube_mesh())+ assert isinstance(result, tuple) and len(result) == 2+ assert isinstance(result[0], MeshData)+ assert isinstance(result[1], dict)++ def test_repair_mesh_report_has_required_keys(self) -> None:+ _, report = repair.repair_mesh(_make_cube_mesh())+ for key in (+ "vertices_merged", "degenerate_faces_removed",+ "unreferenced_vertices_removed", "final_vertex_count", "final_triangle_count",+ ):+ assert key in report++ def test_repair_clean_mesh_zero_changes(self) -> None:+ _, report = repair.repair_mesh(_make_cube_mesh())+ assert report["vertices_merged"] == 0+ assert report["degenerate_faces_removed"] == 0+ assert report["unreferenced_vertices_removed"] == 0++ def test_repair_final_counts_match_returned_mesh(self) -> None:+ repaired, report = repair.repair_mesh(_make_cube_mesh())+ assert report["final_vertex_count"] == repaired.vertices.shape[0]+ assert report["final_triangle_count"] == repaired.triangles.shape[0]++ def test_repair_empty_mesh_returns_same_object(self) -> None:+ m = _make_empty_mesh()+ repaired, report = repair.repair_mesh(m)+ assert repaired is m+ assert report["vertices_merged"] == 0++ def test_repair_merges_duplicate_vertices(self) -> None:+ m = _make_mesh_with_duplicates()+ _, report = repair.repair_mesh(m)+ assert report["vertices_merged"] >= 1++ def test_repair_removes_degenerate_faces(self) -> None:+ m = _make_mesh_with_degenerate()+ _, report = repair.repair_mesh(m)+ assert report["degenerate_faces_removed"] >= 1++ def test_repair_full_pipeline_vertex_count_non_increasing(self) -> None:+ """After repair, vertex count is <= original."""+ m = _make_mesh_with_duplicates()+ repaired, _ = repair.repair_mesh(m)+ assert repaired.vertices.shape[0] <= m.vertices.shape[0]++ # --- merge_duplicate_vertices ----------------------------------------------++ def test_merge_duplicate_vertices_removes_one(self) -> None:+ v = np.array(+ [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]],+ dtype=np.float64,+ )+ t = np.array([[0, 1, 3]], dtype=np.int32)+ _, _, count = repair.merge_duplicate_vertices(v, t)+ assert count == 1++ def test_merge_duplicate_vertices_no_duplicates_count_zero(self) -> None:+ m = _make_cube_mesh()+ _, _, count = repair.merge_duplicate_vertices(m.vertices, m.triangles)+ assert count == 0++ def test_merge_duplicate_vertices_empty(self) -> None:+ _, _, count = repair.merge_duplicate_vertices(+ np.empty((0, 3), dtype=np.float64), np.empty((0, 3), dtype=np.int32)+ )+ assert count == 0++ def test_merge_duplicate_vertices_cube_duplicates(self) -> None:+ m = _make_mesh_with_duplicates()+ v2, _, count = repair.merge_duplicate_vertices(m.vertices, m.triangles)+ assert count == 2+ assert v2.shape[0] == m.vertices.shape[0] - 2++ # --- remove_degenerate_faces -----------------------------------------------++ def test_remove_degenerate_faces_removes_three(self) -> None:+ t = np.array(+ [[0, 1, 2], [0, 0, 2], [1, 2, 1], [3, 4, 3], [5, 6, 7]],+ dtype=np.int32,+ )+ t2, count = repair.remove_degenerate_faces(t)+ assert count == 3+ assert t2.shape[0] == 2++ def test_remove_degenerate_faces_all_valid(self) -> None:+ t = np.array([[0, 1, 2], [3, 4, 5]], dtype=np.int32)+ _, count = repair.remove_degenerate_faces(t)+ assert count == 0++ def test_remove_degenerate_faces_empty(self) -> None:+ t2, count = repair.remove_degenerate_faces(np.empty((0, 3), dtype=np.int32))+ assert count == 0 and t2.shape[0] == 0++ def test_remove_degenerate_faces_cube_with_one(self) -> None:+ m = _make_mesh_with_degenerate()+ _, count = repair.remove_degenerate_faces(m.triangles)+ assert count == 1++ # --- remove_unreferenced_vertices ------------------------------------------++ def test_remove_unreferenced_removes_one(self) -> None:+ m = _make_cube_mesh()+ extra = np.array([[99.0, 99.0, 99.0]], dtype=np.float64)+ v = np.vstack([m.vertices, extra])+ _, _, count = repair.remove_unreferenced_vertices(v, m.triangles)+ assert count == 1++ def test_remove_unreferenced_all_referenced_count_zero(self) -> None:+ m = _make_cube_mesh()+ _, _, count = repair.remove_unreferenced_vertices(m.vertices, m.triangles)+ assert count == 0++ def test_remove_unreferenced_no_triangles_removes_all(self) -> None:+ v = np.zeros((4, 3), dtype=np.float64)+ _, _, count = repair.remove_unreferenced_vertices(v, np.empty((0, 3), dtype=np.int32))+ assert count == 4++ def test_remove_unreferenced_remaps_indices_validly(self) -> None:+ """After removal, triangle indices are still valid for the new vertex array."""+ v = np.array(+ [[0.0, 0.0, 0.0], [99.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],+ dtype=np.float64,+ )+ t = np.array([[0, 2, 3]], dtype=np.int32)+ v2, t2, _ = repair.remove_unreferenced_vertices(v, t)+ assert t2.max() < v2.shape[0]++ def test_remove_unreferenced_empty_vertices(self) -> None:+ _, _, count = repair.remove_unreferenced_vertices(+ np.empty((0, 3), dtype=np.float64), np.empty((0, 3), dtype=np.int32)+ )+ assert count == 0++ # --- fix_normals -----------------------------------------------------------++ def test_fix_normals_returns_mesh_data(self) -> None:+ assert isinstance(repair.fix_normals(_make_cube_mesh()), MeshData)++ def test_fix_normals_preserves_vertex_count(self) -> None:+ mesh = _make_cube_mesh()+ assert repair.fix_normals(mesh).vertices.shape[0] == mesh.vertices.shape[0]++ def test_fix_normals_preserves_face_count(self) -> None:+ mesh = _make_cube_mesh()+ assert repair.fix_normals(mesh).triangles.shape[0] == mesh.triangles.shape[0]++ def test_fix_normals_empty_mesh_passthrough(self) -> None:+ """fix_normals returns the same object for an empty mesh."""+ m = _make_empty_mesh()+ assert repair.fix_normals(m) is m+++# ===========================================================================+# TestModifier -- resize_holes, resize_single_hole+# ===========================================================================+++class TestModifier:+ """Tests for cli_anything.threemf.core.modifier."""++ # --- resize_holes validation -----------------------------------------------++ def test_resize_holes_bad_mesh_index_raises(self) -> None:+ with pytest.raises(ValueError, match="out of range"):+ resize_holes(_make_threemf_data(), [0], 5.0, mesh_index=99)++ def test_resize_holes_negative_diameter_raises(self) -> None:+ with pytest.raises(ValueError, match="positive"):+ resize_holes(_make_threemf_data(), [0], -1.0, mesh_index=0)++ def test_resize_holes_zero_diameter_raises(self) -> None:+ with pytest.raises(ValueError, match="positive"):+ resize_holes(_make_threemf_data(), [0], 0.0, mesh_index=0)++ def test_resize_holes_empty_hole_ids_raises(self) -> None:+ with pytest.raises(ValueError, match="empty"):+ resize_holes(_make_threemf_data(), [], 5.0, mesh_index=0)++ def test_resize_holes_unknown_hole_id_raises(self) -> None:+ with pytest.raises(ValueError, match="Unknown hole_ids"):+ resize_holes(_make_threemf_data(), [999], 5.0, mesh_index=0)++ def test_resize_holes_none_data_raises(self) -> None:+ with pytest.raises((ValueError, AttributeError)):+ resize_holes(None, [0], 5.0, mesh_index=0) # type: ignore[arg-type]++ # --- resize_single_hole ----------------------------------------------------++ def test_resize_single_hole_returns_tuple(self) -> None:+ result = resize_single_hole(_make_cube_mesh(), _make_fake_hole(), 4.0)+ assert isinstance(result, tuple) and len(result) == 2++ def test_resize_single_hole_first_element_is_mesh_data(self) -> None:+ new_mesh, _ = resize_single_hole(_make_cube_mesh(), _make_fake_hole(), 4.0)+ assert isinstance(new_mesh, MeshData)++ def test_resize_single_hole_report_has_required_keys(self) -> None:+ _, report = resize_single_hole(_make_cube_mesh(), _make_fake_hole(), 4.0)+ for key in ("hole_id", "old_diameter", "new_diameter", "vertices_moved"):+ assert key in report++ def test_resize_single_hole_report_new_diameter_correct(self) -> None:+ _, report = resize_single_hole(_make_cube_mesh(), _make_fake_hole(diameter=3.0), 6.0)+ assert report["new_diameter"] == pytest.approx(6.0, abs=1e-4)++ def test_resize_single_hole_report_old_diameter_correct(self) -> None:+ _, report = resize_single_hole(_make_cube_mesh(), _make_fake_hole(diameter=3.5, hole_id=2), 5.0)+ assert report["old_diameter"] == 3.5+ assert report["hole_id"] == 2++ def test_resize_single_hole_negative_diameter_raises(self) -> None:+ with pytest.raises(ValueError, match="positive"):+ resize_single_hole(_make_cube_mesh(), _make_fake_hole(), -5.0)++ def test_resize_single_hole_none_mesh_raises(self) -> None:+ with pytest.raises((ValueError, AttributeError)):+ resize_single_hole(None, _make_fake_hole(), 5.0) # type: ignore[arg-type]++ def test_resize_single_hole_no_wall_vertices_returns_unchanged_mesh(self) -> None:+ """If no wall vertices match (hole centre far away), mesh is unchanged."""+ mesh = _make_cube_mesh()+ hole = _make_fake_hole(center=(500.0, 500.0))+ new_mesh, report = resize_single_hole(mesh, hole, 4.0)+ assert report["vertices_moved"] == 0+ assert new_mesh is mesh++ def test_resize_single_hole_does_not_mutate_original_vertices(self) -> None:+ """resize_single_hole never mutates the input MeshData."""+ n = 20+ theta = np.linspace(0, 2 * np.pi, n, endpoint=False)+ r = 1.0+ verts = np.column_stack([np.zeros(n), r * np.cos(theta), r * np.sin(theta)])+ tris = np.array([[i, (i + 1) % n, (i + 2) % n] for i in range(n - 2)], dtype=np.int32)+ mesh = MeshData(object_id="c", name="c", vertices=verts, triangles=tris)+ original = mesh.vertices.copy()+ hole = inspector.DetectedHole(+ hole_id=0, center=(0.0, 0.0), diameter=r * 2,+ axis_min=-0.1, axis_max=0.1, axis=0,+ confidence=0.9, vertex_count=n,+ )+ resize_single_hole(mesh, hole, target_diameter=3.0)+ np.testing.assert_array_equal(mesh.vertices, original)diff --git a/3MF/agent-harness/cli_anything/threemf/threemf_cli.py b/3MF/agent-harness/cli_anything/threemf/threemf_cli.pynew file mode 100644index 000000000..6ba82b22b--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/threemf_cli.py@@ -0,0 +1,416 @@+#!/usr/bin/env python3+"""3MF CLI — Mesh geometry editor for 3D printing files.++Detect and resize cylindrical holes, repair meshes, compare 3MF files.++Usage:+ # One-shot commands+ cli-anything-3mf info model.3mf+ cli-anything-3mf inspect model.3mf+ cli-anything-3mf resize model.3mf --hole 0 --hole 1 --diameter 4.2 -o output.3mf+ cli-anything-3mf --json inspect model.3mf++ # Interactive REPL+ cli-anything-3mf+"""++import sys+import os+import json+import shlex+import click+from typing import Optional++from cli_anything.threemf.core import parser+from cli_anything.threemf.core import inspector+from cli_anything.threemf.core import modifier+from cli_anything.threemf.core import repair as repair_mod+from cli_anything.threemf.utils import threemf_backend as backend++# ── Global state ────────────────────────────────────────────────+_json_output = False+_repl_mode = False+++def output(data, message: str = ""):+ """Print data as JSON or human-readable text."""+ if _json_output:+ click.echo(json.dumps(data, indent=2, default=str))+ else:+ if message:+ click.echo(message)+ if isinstance(data, dict):+ _print_dict(data)+ elif isinstance(data, list):+ _print_list(data)+ else:+ click.echo(str(data))+++def _print_dict(d: dict, indent: int = 0):+ prefix = " " * indent+ for k, v in d.items():+ if isinstance(v, dict):+ click.echo(f"{prefix}{k}:")+ _print_dict(v, indent + 1)+ elif isinstance(v, list):+ click.echo(f"{prefix}{k}:")+ _print_list(v, indent + 1)+ else:+ click.echo(f"{prefix}{k}: {v}")+++def _print_list(items: list, indent: int = 0):+ prefix = " " * indent+ for i, item in enumerate(items):+ if isinstance(item, dict):+ click.echo(f"{prefix}[{i}]")+ _print_dict(item, indent + 1)+ else:+ click.echo(f"{prefix}- {item}")+++def handle_error(func):+ """Decorator: catch errors and format output."""+ def wrapper(*args, **kwargs):+ try:+ return func(*args, **kwargs)+ except (RuntimeError, FileNotFoundError, FileExistsError) as e:+ if _json_output:+ click.echo(json.dumps({"error": str(e), "type": type(e).__name__}))+ else:+ click.echo(f"Error: {e}", err=True)+ if not _repl_mode:+ sys.exit(1)+ except (ValueError, IndexError) as e:+ if _json_output:+ click.echo(json.dumps({"error": str(e), "type": type(e).__name__}))+ else:+ click.echo(f"Error: {e}", err=True)+ if not _repl_mode:+ sys.exit(1)+ wrapper.__name__ = func.__name__+ wrapper.__doc__ = func.__doc__+ return wrapper+++# ── Main CLI Group ──────────────────────────────────────────────[email protected](invoke_without_command=True)[email protected]("--json", "use_json", is_flag=True, help="Output as JSON")[email protected]_context+def cli(ctx, use_json):+ """3MF CLI — Mesh geometry editor for 3D printing files.++ Run without a subcommand to enter interactive REPL mode.+ """+ global _json_output+ _json_output = use_json++ if ctx.invoked_subcommand is None:+ ctx.invoke(repl)+++# ── info command ────────────────────────────────────────────────[email protected]("file", type=click.Path(exists=True))+@handle_error+def info(file):+ """Show mesh info (vertices, faces, bounds, watertight, volume)."""+ data = parser.parse_3mf(file)+ objects = []+ for mesh in data.meshes:+ stats = backend.compute_mesh_stats(mesh)+ stats["id"] = mesh.object_id+ stats["name"] = mesh.name+ objects.append(stats)+ result = {+ "file": os.path.basename(file),+ "unit": data.unit,+ "objects": objects,+ }+ if not _json_output:+ click.echo(f"File: {os.path.basename(file)} Unit: {data.unit}")+ click.echo()+ for obj in objects:+ click.echo(f" Object {obj['id']}: {obj['name']}")+ click.echo(f" Vertices: {obj['vertex_count']}")+ click.echo(f" Faces: {obj['face_count']}")+ bb = obj["bounding_box"]+ click.echo(f" Bounding box: [{bb['min'][0]:.2f}, {bb['min'][1]:.2f}, {bb['min'][2]:.2f}]"+ f" to [{bb['max'][0]:.2f}, {bb['max'][1]:.2f}, {bb['max'][2]:.2f}]")+ dims = bb["size"]+ click.echo(f" Dimensions: {dims[0]:.2f} x {dims[1]:.2f} x {dims[2]:.2f} mm")+ click.echo(f" Watertight: {obj['watertight']}")+ vol = obj['volume_mm3']+ click.echo(f" Volume: {vol:.2f} mm3" if vol is not None else " Volume: N/A (not watertight)")+ click.echo(f" Surface area: {obj['surface_area_mm2']:.2f} mm2")+ else:+ output(result)+++# ── inspect command ─────────────────────────────────────────────[email protected]("file", type=click.Path(exists=True))[email protected]("--planes", "-n", type=int, default=20, help="Number of cross-section planes")[email protected]("--min-diameter", type=float, default=0.5, help="Minimum hole diameter (mm)")[email protected]("--min-confidence", type=float, default=0.7, help="Minimum detection confidence")[email protected]("--axis", "-a", type=int, default=0, help="Hole axis: 0=X, 1=Y, 2=Z")[email protected]("--mesh", "-m", type=int, default=0, help="Mesh object index")+@handle_error+def inspect(file, planes, min_diameter, min_confidence, axis, mesh):+ """Detect and list all cylindrical holes."""+ data = parser.parse_3mf(file)+ if mesh >= len(data.meshes):+ raise ValueError(f"Mesh index {mesh} out of range (0..{len(data.meshes)-1})")++ mesh_data = data.meshes[mesh]+ params = inspector.InspectParams(+ num_planes=planes,+ min_hole_diameter=min_diameter,+ min_confidence=min_confidence,+ axis=axis,+ )+ holes = inspector.inspect_mesh(mesh_data, params)++ from dataclasses import asdict+ holes_data = [asdict(h) for h in holes]+ result = {+ "file": os.path.basename(file),+ "object": mesh_data.name,+ "hole_count": len(holes),+ "holes": holes_data,+ }++ if not _json_output:+ click.echo(f"File: {os.path.basename(file)} Object: {mesh_data.name}")+ click.echo(f"Detected {len(holes)} hole(s):")+ click.echo()+ axis_labels = {0: "X", 1: "Y", 2: "Z"}+ for h in holes:+ click.echo(f" Hole {h.hole_id}:")+ click.echo(f" Diameter: {h.diameter:.3f} mm")+ click.echo(f" Center: ({h.center[0]:.3f}, {h.center[1]:.3f})")+ click.echo(f" Axis: {axis_labels.get(h.axis, '?')}"+ f" [{h.axis_min:.2f} .. {h.axis_max:.2f}]")+ click.echo(f" Confidence: {h.confidence:.2f}")+ click.echo(f" Vertices: {h.vertex_count}")+ else:+ output(result)+++# ── resize command ──────────────────────────────────────────────[email protected]("file", type=click.Path(exists=True))[email protected]("--hole", "-h", "hole_ids", multiple=True, type=int, required=True,+ help="Hole ID(s) to resize (from inspect output)")[email protected]("--diameter", "-d", type=float, required=True, help="Target diameter (mm)")[email protected]("--output", "-o", "output_path", type=str, required=True, help="Output file path")[email protected]("--mesh", "-m", type=int, default=0, help="Mesh object index")[email protected]("--overwrite", is_flag=True, help="Overwrite output if exists")+@handle_error+def resize(file, hole_ids, diameter, output_path, mesh, overwrite):+ """Resize cylindrical holes to specified diameter."""+ if os.path.exists(output_path) and not overwrite:+ raise FileExistsError(f"Output file exists: {output_path}. Use --overwrite to replace.")+ if diameter <= 0:+ raise ValueError("Diameter must be positive")++ data = parser.parse_3mf(file)+ new_data, changes = modifier.resize_holes(data, list(hole_ids), diameter, mesh_index=mesh)++ # Auto-repair after resize+ target_mesh = new_data.meshes[mesh]+ repaired, report = repair_mod.repair_mesh(target_mesh)+ total_fixes = report["vertices_merged"] + report["degenerate_faces_removed"] + report["unreferenced_vertices_removed"]+ if total_fixes > 0:+ meshes_list = list(new_data.meshes)+ meshes_list[mesh] = repaired+ new_data = parser.ThreeMFData(+ meshes=tuple(meshes_list),+ unit=new_data.unit,+ model_path=new_data.model_path,+ metadata=new_data.metadata,+ raw_entries=new_data.raw_entries,+ source_path=new_data.source_path,+ )++ parser.write_3mf(new_data, output_path)++ result = {+ "input": os.path.basename(file),+ "output": os.path.basename(output_path),+ "target_diameter": diameter,+ "holes_resized": list(hole_ids),+ "changes": changes,+ "repairs": report,+ }++ if not _json_output:+ click.echo(f"Resized {len(hole_ids)} hole(s) to {diameter}mm")+ for c in changes:+ click.echo(f" Hole {c['hole_id']}: {c['old_diameter']:.3f}mm -> {c['new_diameter']:.3f}mm"+ f" ({c['vertices_moved']} vertices)")+ if total_fixes > 0:+ click.echo(f" Auto-repair: {total_fixes} fixes applied")+ click.echo(f"Saved: {output_path}")+ else:+ output(result)+++# ── repair command ──────────────────────────────────────────────[email protected]("file", type=click.Path(exists=True))[email protected]("--output", "-o", "output_path", type=str, required=True, help="Output file path")[email protected]("--mesh", "-m", type=int, default=0, help="Mesh object index")[email protected]("--overwrite", is_flag=True, help="Overwrite output if exists")+@handle_error+def repair(file, output_path, mesh, overwrite):+ """Fix mesh issues (degenerate faces, duplicate vertices, normals)."""+ if os.path.exists(output_path) and not overwrite:+ raise FileExistsError(f"Output file exists: {output_path}. Use --overwrite to replace.")++ data = parser.parse_3mf(file)+ if mesh >= len(data.meshes):+ raise ValueError(f"Mesh index {mesh} out of range (0..{len(data.meshes)-1})")++ mesh_data = data.meshes[mesh]+ repaired, report = repair_mod.repair_mesh(mesh_data)++ meshes_list = list(data.meshes)+ meshes_list[mesh] = repaired+ new_data = parser.ThreeMFData(+ meshes=tuple(meshes_list),+ unit=data.unit,+ model_path=data.model_path,+ metadata=data.metadata,+ raw_entries=data.raw_entries,+ source_path=data.source_path,+ )+ parser.write_3mf(new_data, output_path)++ result = {+ "input": os.path.basename(file),+ "output": os.path.basename(output_path),+ "repairs": report,+ }++ if not _json_output:+ total = report['vertices_merged'] + report['degenerate_faces_removed'] + report['unreferenced_vertices_removed']+ click.echo(f"Repaired: {os.path.basename(file)}")+ click.echo(f" Duplicates merged: {report['vertices_merged']}")+ click.echo(f" Degenerates removed: {report['degenerate_faces_removed']}")+ click.echo(f" Unreferenced removed: {report['unreferenced_vertices_removed']}")+ click.echo(f" Total fixes: {total}")+ click.echo(f"Saved: {output_path}")+ else:+ output(result)+++# ── compare command ─────────────────────────────────────────────[email protected]("file1", type=click.Path(exists=True))[email protected]("file2", type=click.Path(exists=True))[email protected]("--mesh", "-m", type=int, default=0, help="Mesh object index")+@handle_error+def compare(file1, file2, mesh):+ """Compare two 3MF files."""+ data1 = parser.parse_3mf(file1)+ data2 = parser.parse_3mf(file2)++ if mesh >= len(data1.meshes) or mesh >= len(data2.meshes):+ raise ValueError(f"Mesh index {mesh} out of range for one or both files")++ result = inspector.compare_meshes(data1.meshes[mesh], data2.meshes[mesh])+ result["file1"] = os.path.basename(file1)+ result["file2"] = os.path.basename(file2)++ if not _json_output:+ click.echo(f"Comparing: {os.path.basename(file1)} vs {os.path.basename(file2)}")+ click.echo()+ click.echo(f" {'':20s} {'File 1':>10s} {'File 2':>10s} {'Diff':>10s}")+ click.echo(f" {'─' * 52}")+ click.echo(f" {'Vertices':20s} {result['vertices']['file1']:>10d}"+ f" {result['vertices']['file2']:>10d}"+ f" {result['vertices']['diff']:>+10d}")+ click.echo(f" {'Faces':20s} {result['faces']['file1']:>10d}"+ f" {result['faces']['file2']:>10d}"+ f" {result['faces']['diff']:>+10d}")+ click.echo(f" {'Volume (mm3)':20s} {result['volume']['file1']:>10.1f}"+ f" {result['volume']['file2']:>10.1f}"+ f" {result['volume']['diff']:>+10.1f}")+ click.echo(f" {'Watertight':20s} {str(result['watertight']['file1']):>10s}"+ f" {str(result['watertight']['file2']):>10s}")+ else:+ output(result)+++# ── REPL ────────────────────────────────────────────────────────[email protected](hidden=True)+@handle_error+def repl():+ """Start interactive REPL session."""+ global _repl_mode+ _repl_mode = True++ from cli_anything.threemf.utils.repl_skin import ReplSkin+ skin = ReplSkin("3mf", version="1.0.0")+ skin.print_banner()++ pt_session = skin.create_prompt_session()++ skin.help({+ "info <file>": "Show mesh statistics",+ "inspect <file>": "Detect cylindrical holes",+ "resize <file> -h <id> -d <mm> -o <out>": "Resize holes",+ "repair <file> -o <out>": "Fix mesh issues",+ "compare <f1> <f2>": "Compare two files",+ "help": "Show this help",+ "quit": "Exit REPL",+ })++ while True:+ try:+ user_input = skin.get_input(pt_session)+ if not user_input:+ continue+ if user_input.lower() in ("quit", "exit", "q"):+ skin.print_goodbye()+ break+ if user_input.lower() == "help":+ skin.help({+ "info <file>": "Show mesh statistics",+ "inspect <file>": "Detect cylindrical holes",+ "resize <file> -h <id> -d <mm> -o <out>": "Resize holes",+ "repair <file> -o <out>": "Fix mesh issues",+ "compare <f1> <f2>": "Compare two files",+ "help": "Show this help",+ "quit": "Exit REPL",+ })+ continue++ try:+ args = shlex.split(user_input)+ except ValueError as e:+ skin.error(f"Parse error: {e}")+ continue++ try:+ cli(args, standalone_mode=False)+ except SystemExit:+ pass+ except click.exceptions.UsageError as e:+ skin.error(str(e))+ except Exception as e:+ skin.error(str(e))++ except (KeyboardInterrupt, EOFError):+ skin.print_goodbye()+ break+++def main():+ cli()+++if __name__ == "__main__":+ main()diff --git a/3MF/agent-harness/cli_anything/threemf/utils/__init__.py b/3MF/agent-harness/cli_anything/threemf/utils/__init__.pynew file mode 100644index 000000000..8b1378917--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/utils/__init__.py@@ -0,0 +1 @@+diff --git a/3MF/agent-harness/cli_anything/threemf/utils/repl_skin.py b/3MF/agent-harness/cli_anything/threemf/utils/repl_skin.pynew file mode 100644index 000000000..c7312348a--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/utils/repl_skin.py@@ -0,0 +1,521 @@+"""cli-anything REPL Skin — Unified terminal interface for all CLI harnesses.++Copy this file into your CLI package at:+ cli_anything/<software>/utils/repl_skin.py++Usage:+ from cli_anything.<software>.utils.repl_skin import ReplSkin++ skin = ReplSkin("shotcut", version="1.0.0")+ skin.print_banner() # auto-detects skills/SKILL.md inside the package+ prompt_text = skin.prompt(project_name="my_video.mlt", modified=True)+ skin.success("Project saved")+ skin.error("File not found")+ skin.warning("Unsaved changes")+ skin.info("Processing 24 clips...")+ skin.status("Track 1", "3 clips, 00:02:30")+ skin.table(headers, rows)+ skin.print_goodbye()+"""++import os+import sys++# ── ANSI color codes (no external deps for core styling) ──────────────++_RESET = "\033[0m"+_BOLD = "\033[1m"+_DIM = "\033[2m"+_ITALIC = "\033[3m"+_UNDERLINE = "\033[4m"++# Brand colors+_CYAN = "\033[38;5;80m" # cli-anything brand cyan+_CYAN_BG = "\033[48;5;80m"+_WHITE = "\033[97m"+_GRAY = "\033[38;5;245m"+_DARK_GRAY = "\033[38;5;240m"+_LIGHT_GRAY = "\033[38;5;250m"++# Software accent colors — each software gets a unique accent+_ACCENT_COLORS = {+ "gimp": "\033[38;5;214m", # warm orange+ "blender": "\033[38;5;208m", # deep orange+ "inkscape": "\033[38;5;39m", # bright blue+ "audacity": "\033[38;5;33m", # navy blue+ "libreoffice": "\033[38;5;40m", # green+ "obs_studio": "\033[38;5;55m", # purple+ "kdenlive": "\033[38;5;69m", # slate blue+ "shotcut": "\033[38;5;35m", # teal green+}+_DEFAULT_ACCENT = "\033[38;5;75m" # default sky blue++# Status colors+_GREEN = "\033[38;5;78m"+_YELLOW = "\033[38;5;220m"+_RED = "\033[38;5;196m"+_BLUE = "\033[38;5;75m"+_MAGENTA = "\033[38;5;176m"++# ── Brand icon ────────────────────────────────────────────────────────++# The cli-anything icon: a small colored diamond/chevron mark+_ICON = f"{_CYAN}{_BOLD}◆{_RESET}"+_ICON_SMALL = f"{_CYAN}▸{_RESET}"++# ── Box drawing characters ────────────────────────────────────────────++_H_LINE = "─"+_V_LINE = "│"+_TL = "╭"+_TR = "╮"+_BL = "╰"+_BR = "╯"+_T_DOWN = "┬"+_T_UP = "┴"+_T_RIGHT = "├"+_T_LEFT = "┤"+_CROSS = "┼"+++def _strip_ansi(text: str) -> str:+ """Remove ANSI escape codes for length calculation."""+ import re+ return re.sub(r"\033\[[^m]*m", "", text)+++def _visible_len(text: str) -> int:+ """Get visible length of text (excluding ANSI codes)."""+ return len(_strip_ansi(text))+++class ReplSkin:+ """Unified REPL skin for cli-anything CLIs.++ Provides consistent branding, prompts, and message formatting+ across all CLI harnesses built with the cli-anything methodology.+ """++ def __init__(self, software: str, version: str = "1.0.0",+ history_file: str | None = None, skill_path: str | None = None):+ """Initialize the REPL skin.++ Args:+ software: Software name (e.g., "gimp", "shotcut", "blender").+ version: CLI version string.+ history_file: Path for persistent command history.+ Defaults to ~/.cli-anything-<software>/history+ skill_path: Path to the SKILL.md file for agent discovery.+ Auto-detected from the package's skills/ directory if not provided.+ Displayed in banner for AI agents to know where to read skill info.+ """+ self.software = software.lower().replace("-", "_")+ self.display_name = software.replace("_", " ").title()+ self.version = version++ # Auto-detect skill path from package layout:+ # cli_anything/<software>/utils/repl_skin.py (this file)+ # cli_anything/<software>/skills/SKILL.md (target)+ if skill_path is None:+ from pathlib import Path+ _auto = Path(__file__).resolve().parent.parent / "skills" / "SKILL.md"+ if _auto.is_file():+ skill_path = str(_auto)+ self.skill_path = skill_path+ self.accent = _ACCENT_COLORS.get(self.software, _DEFAULT_ACCENT)++ # History file+ if history_file is None:+ from pathlib import Path+ hist_dir = Path.home() / f".cli-anything-{self.software}"+ hist_dir.mkdir(parents=True, exist_ok=True)+ self.history_file = str(hist_dir / "history")+ else:+ self.history_file = history_file++ # Detect terminal capabilities+ self._color = self._detect_color_support()++ def _detect_color_support(self) -> bool:+ """Check if terminal supports color."""+ if os.environ.get("NO_COLOR"):+ return False+ if os.environ.get("CLI_ANYTHING_NO_COLOR"):+ return False+ if not hasattr(sys.stdout, "isatty"):+ return False+ return sys.stdout.isatty()++ def _c(self, code: str, text: str) -> str:+ """Apply color code if colors are supported."""+ if not self._color:+ return text+ return f"{code}{text}{_RESET}"++ # ── Banner ────────────────────────────────────────────────────────++ def print_banner(self):+ """Print the startup banner with branding."""+ inner = 54++ def _box_line(content: str) -> str:+ """Wrap content in box drawing, padding to inner width."""+ pad = inner - _visible_len(content)+ vl = self._c(_DARK_GRAY, _V_LINE)+ return f"{vl}{content}{' ' * max(0, pad)}{vl}"++ top = self._c(_DARK_GRAY, f"{_TL}{_H_LINE * inner}{_TR}")+ bot = self._c(_DARK_GRAY, f"{_BL}{_H_LINE * inner}{_BR}")++ # Title: ◆ cli-anything · Shotcut+ icon = self._c(_CYAN + _BOLD, "◆")+ brand = self._c(_CYAN + _BOLD, "cli-anything")+ dot = self._c(_DARK_GRAY, "·")+ name = self._c(self.accent + _BOLD, self.display_name)+ title = f" {icon} {brand} {dot} {name}"++ ver = f" {self._c(_DARK_GRAY, f' v{self.version}')}"+ tip = f" {self._c(_DARK_GRAY, ' Type help for commands, quit to exit')}"+ empty = ""++ # Skill path for agent discovery+ skill_line = None+ if self.skill_path:+ skill_icon = self._c(_MAGENTA, "◇")+ skill_label = self._c(_DARK_GRAY, " Skill:")+ skill_path_display = self._c(_LIGHT_GRAY, self.skill_path)+ skill_line = f" {skill_icon} {skill_label} {skill_path_display}"++ print(top)+ print(_box_line(title))+ print(_box_line(ver))+ if skill_line:+ print(_box_line(skill_line))+ print(_box_line(empty))+ print(_box_line(tip))+ print(bot)+ print()++ # ── Prompt ────────────────────────────────────────────────────────++ def prompt(self, project_name: str = "", modified: bool = False,+ context: str = "") -> str:+ """Build a styled prompt string for prompt_toolkit or input().++ Args:+ project_name: Current project name (empty if none open).+ modified: Whether the project has unsaved changes.+ context: Optional extra context to show in prompt.++ Returns:+ Formatted prompt string.+ """+ parts = []++ # Icon+ if self._color:+ parts.append(f"{_CYAN}◆{_RESET} ")+ else:+ parts.append("> ")++ # Software name+ parts.append(self._c(self.accent + _BOLD, self.software))++ # Project context+ if project_name or context:+ ctx = context or project_name+ mod = "*" if modified else ""+ parts.append(f" {self._c(_DARK_GRAY, '[')}")+ parts.append(self._c(_LIGHT_GRAY, f"{ctx}{mod}"))+ parts.append(self._c(_DARK_GRAY, ']'))++ parts.append(self._c(_GRAY, " ❯ "))++ return "".join(parts)++ def prompt_tokens(self, project_name: str = "", modified: bool = False,+ context: str = ""):+ """Build prompt_toolkit formatted text tokens for the prompt.++ Use with prompt_toolkit's FormattedText for proper ANSI handling.++ Returns:+ list of (style, text) tuples for prompt_toolkit.+ """+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")+ tokens = []++ tokens.append(("class:icon", "◆ "))+ tokens.append(("class:software", self.software))++ if project_name or context:+ ctx = context or project_name+ mod = "*" if modified else ""+ tokens.append(("class:bracket", " ["))+ tokens.append(("class:context", f"{ctx}{mod}"))+ tokens.append(("class:bracket", "]"))++ tokens.append(("class:arrow", " ❯ "))++ return tokens++ def get_prompt_style(self):+ """Get a prompt_toolkit Style object matching the skin.++ Returns:+ prompt_toolkit.styles.Style+ """+ try:+ from prompt_toolkit.styles import Style+ except ImportError:+ return None++ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")++ return Style.from_dict({+ "icon": "#5fdfdf bold", # cyan brand color+ "software": f"{accent_hex} bold",+ "bracket": "#585858",+ "context": "#bcbcbc",+ "arrow": "#808080",+ # Completion menu+ "completion-menu.completion": "bg:#303030 #bcbcbc",+ "completion-menu.completion.current": f"bg:{accent_hex} #000000",+ "completion-menu.meta.completion": "bg:#303030 #808080",+ "completion-menu.meta.completion.current": f"bg:{accent_hex} #000000",+ # Auto-suggest+ "auto-suggest": "#585858",+ # Bottom toolbar+ "bottom-toolbar": "bg:#1c1c1c #808080",+ "bottom-toolbar.text": "#808080",+ })++ # ── Messages ──────────────────────────────────────────────────────++ def success(self, message: str):+ """Print a success message with green checkmark."""+ icon = self._c(_GREEN + _BOLD, "✓")+ print(f" {icon} {self._c(_GREEN, message)}")++ def error(self, message: str):+ """Print an error message with red cross."""+ icon = self._c(_RED + _BOLD, "✗")+ print(f" {icon} {self._c(_RED, message)}", file=sys.stderr)++ def warning(self, message: str):+ """Print a warning message with yellow triangle."""+ icon = self._c(_YELLOW + _BOLD, "⚠")+ print(f" {icon} {self._c(_YELLOW, message)}")++ def info(self, message: str):+ """Print an info message with blue dot."""+ icon = self._c(_BLUE, "●")+ print(f" {icon} {self._c(_LIGHT_GRAY, message)}")++ def hint(self, message: str):+ """Print a subtle hint message."""+ print(f" {self._c(_DARK_GRAY, message)}")++ def section(self, title: str):+ """Print a section header."""+ print()+ print(f" {self._c(self.accent + _BOLD, title)}")+ print(f" {self._c(_DARK_GRAY, _H_LINE * len(title))}")++ # ── Status display ────────────────────────────────────────────────++ def status(self, label: str, value: str):+ """Print a key-value status line."""+ lbl = self._c(_GRAY, f" {label}:")+ val = self._c(_WHITE, f" {value}")+ print(f"{lbl}{val}")++ def status_block(self, items: dict[str, str], title: str = ""):+ """Print a block of status key-value pairs.++ Args:+ items: Dict of label -> value pairs.+ title: Optional title for the block.+ """+ if title:+ self.section(title)++ max_key = max(len(k) for k in items) if items else 0+ for label, value in items.items():+ lbl = self._c(_GRAY, f" {label:<{max_key}}")+ val = self._c(_WHITE, f" {value}")+ print(f"{lbl}{val}")++ def progress(self, current: int, total: int, label: str = ""):+ """Print a simple progress indicator.++ Args:+ current: Current step number.+ total: Total number of steps.+ label: Optional label for the progress.+ """+ pct = int(current / total * 100) if total > 0 else 0+ bar_width = 20+ filled = int(bar_width * current / total) if total > 0 else 0+ bar = "█" * filled + "░" * (bar_width - filled)+ text = f" {self._c(_CYAN, bar)} {self._c(_GRAY, f'{pct:3d}%')}"+ if label:+ text += f" {self._c(_LIGHT_GRAY, label)}"+ print(text)++ # ── Table display ─────────────────────────────────────────────────++ def table(self, headers: list[str], rows: list[list[str]],+ max_col_width: int = 40):+ """Print a formatted table with box-drawing characters.++ Args:+ headers: Column header strings.+ rows: List of rows, each a list of cell strings.+ max_col_width: Maximum column width before truncation.+ """+ if not headers:+ return++ # Calculate column widths+ col_widths = [min(len(h), max_col_width) for h in headers]+ for row in rows:+ for i, cell in enumerate(row):+ if i < len(col_widths):+ col_widths[i] = min(+ max(col_widths[i], len(str(cell))), max_col_width+ )++ def pad(text: str, width: int) -> str:+ t = str(text)[:width]+ return t + " " * (width - len(t))++ # Header+ header_cells = [+ self._c(_CYAN + _BOLD, pad(h, col_widths[i]))+ for i, h in enumerate(headers)+ ]+ sep = self._c(_DARK_GRAY, f" {_V_LINE} ")+ header_line = f" {sep.join(header_cells)}"+ print(header_line)++ # Separator+ sep_parts = [self._c(_DARK_GRAY, _H_LINE * w) for w in col_widths]+ sep_line = self._c(_DARK_GRAY, f" {'───'.join([_H_LINE * w for w in col_widths])}")+ print(sep_line)++ # Rows+ for row in rows:+ cells = []+ for i, cell in enumerate(row):+ if i < len(col_widths):+ cells.append(self._c(_LIGHT_GRAY, pad(str(cell), col_widths[i])))+ row_sep = self._c(_DARK_GRAY, f" {_V_LINE} ")+ print(f" {row_sep.join(cells)}")++ # ── Help display ──────────────────────────────────────────────────++ def help(self, commands: dict[str, str]):+ """Print a formatted help listing.++ Args:+ commands: Dict of command -> description pairs.+ """+ self.section("Commands")+ max_cmd = max(len(c) for c in commands) if commands else 0+ for cmd, desc in commands.items():+ cmd_styled = self._c(self.accent, f" {cmd:<{max_cmd}}")+ desc_styled = self._c(_GRAY, f" {desc}")+ print(f"{cmd_styled}{desc_styled}")+ print()++ # ── Goodbye ───────────────────────────────────────────────────────++ def print_goodbye(self):+ """Print a styled goodbye message."""+ print(f"\n {_ICON_SMALL} {self._c(_GRAY, 'Goodbye!')}\n")++ # ── Prompt toolkit session factory ────────────────────────────────++ def create_prompt_session(self):+ """Create a prompt_toolkit PromptSession with skin styling.++ Returns:+ A configured PromptSession, or None if prompt_toolkit unavailable.+ """+ try:+ from prompt_toolkit import PromptSession+ from prompt_toolkit.history import FileHistory+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory+ from prompt_toolkit.formatted_text import FormattedText++ style = self.get_prompt_style()++ session = PromptSession(+ history=FileHistory(self.history_file),+ auto_suggest=AutoSuggestFromHistory(),+ style=style,+ enable_history_search=True,+ )+ return session+ except ImportError:+ return None++ def get_input(self, pt_session, project_name: str = "",+ modified: bool = False, context: str = "") -> str:+ """Get input from user using prompt_toolkit or fallback.++ Args:+ pt_session: A prompt_toolkit PromptSession (or None).+ project_name: Current project name.+ modified: Whether project has unsaved changes.+ context: Optional context string.++ Returns:+ User input string (stripped).+ """+ if pt_session is not None:+ from prompt_toolkit.formatted_text import FormattedText+ tokens = self.prompt_tokens(project_name, modified, context)+ return pt_session.prompt(FormattedText(tokens)).strip()+ else:+ raw_prompt = self.prompt(project_name, modified, context)+ return input(raw_prompt).strip()++ # ── Toolbar builder ───────────────────────────────────────────────++ def bottom_toolbar(self, items: dict[str, str]):+ """Create a bottom toolbar callback for prompt_toolkit.++ Args:+ items: Dict of label -> value pairs to show in toolbar.++ Returns:+ A callable that returns FormattedText for the toolbar.+ """+ def toolbar():+ from prompt_toolkit.formatted_text import FormattedText+ parts = []+ for i, (k, v) in enumerate(items.items()):+ if i > 0:+ parts.append(("class:bottom-toolbar.text", " │ "))+ parts.append(("class:bottom-toolbar.text", f" {k}: "))+ parts.append(("class:bottom-toolbar", v))+ return FormattedText(parts)+ return toolbar+++# ── ANSI 256-color to hex mapping (for prompt_toolkit styles) ─────────++_ANSI_256_TO_HEX = {+ "\033[38;5;33m": "#0087ff", # audacity navy blue+ "\033[38;5;35m": "#00af5f", # shotcut teal+ "\033[38;5;39m": "#00afff", # inkscape bright blue+ "\033[38;5;40m": "#00d700", # libreoffice green+ "\033[38;5;55m": "#5f00af", # obs purple+ "\033[38;5;69m": "#5f87ff", # kdenlive slate blue+ "\033[38;5;75m": "#5fafff", # default sky blue+ "\033[38;5;80m": "#5fd7d7", # brand cyan+ "\033[38;5;208m": "#ff8700", # blender deep orange+ "\033[38;5;214m": "#ffaf00", # gimp warm orange+}diff --git a/3MF/agent-harness/cli_anything/threemf/utils/threemf_backend.py b/3MF/agent-harness/cli_anything/threemf/utils/threemf_backend.pynew file mode 100644index 000000000..3677ec9e5--- /dev/null+++ b/3MF/agent-harness/cli_anything/threemf/utils/threemf_backend.py@@ -0,0 +1,468 @@+"""Geometry utilities -- trimesh / numpy integration for 3MF mesh analysis.++All public functions are **pure**: they return new data structures and never+mutate their inputs. This aligns with the frozen dataclasses used in+:mod:`cli_anything.threemf.core.parser`.+"""++from __future__ import annotations++from typing import Any++import numpy as np++try:+ import trimesh+except ImportError as _exc: # pragma: no cover+ raise ImportError(+ "trimesh is required for geometry utilities. "+ "Install it with: pip install trimesh"+ ) from _exc++from cli_anything.threemf.core.parser import MeshData+++# ---------------------------------------------------------------------------+# Conversion helpers+# ---------------------------------------------------------------------------++def mesh_to_trimesh(mesh_data: MeshData) -> trimesh.Trimesh:+ """Convert a :class:`MeshData` to a :class:`trimesh.Trimesh`.++ Parameters+ ----------+ mesh_data:+ Source mesh (frozen dataclass, never mutated).++ Returns+ -------+ trimesh.Trimesh+ A new Trimesh object. The input arrays are copied so that the+ original ``MeshData`` is unaffected by any downstream mutations+ performed by trimesh internals.+ """+ return trimesh.Trimesh(+ vertices=np.array(mesh_data.vertices, dtype=np.float64, copy=True),+ faces=np.array(mesh_data.triangles, dtype=np.int32, copy=True),+ process=False,+ )+++def trimesh_to_mesh(+ tm: trimesh.Trimesh,+ object_id: str,+ name: str,+) -> MeshData:+ """Convert a :class:`trimesh.Trimesh` back to a :class:`MeshData`.++ Parameters+ ----------+ tm:+ Source trimesh object.+ object_id:+ The ``<object id="...">`` attribute to assign.+ name:+ The ``<object name="...">`` attribute to assign.++ Returns+ -------+ MeshData+ A new frozen dataclass.+ """+ return MeshData(+ object_id=object_id,+ name=name,+ vertices=np.array(tm.vertices, dtype=np.float64, copy=True),+ triangles=np.array(tm.faces, dtype=np.int32, copy=True),+ )+++# ---------------------------------------------------------------------------+# Mesh statistics+# ---------------------------------------------------------------------------++def compute_mesh_stats(mesh_data: MeshData) -> dict[str, Any]:+ """Compute summary statistics for a mesh.++ Returns+ -------+ dict+ Keys:++ - ``vertex_count`` (int)+ - ``face_count`` (int)+ - ``bounding_box`` -- dict with ``min`` and ``max`` (each a list+ of three floats) plus ``size`` (list of three floats).+ - ``watertight`` (bool)+ - ``volume_mm3`` (float | None) -- ``None`` when mesh is not+ watertight.+ - ``surface_area_mm2`` (float)+ """+ if mesh_data.vertices.shape[0] == 0 or mesh_data.triangles.shape[0] == 0:+ return {+ "vertex_count": int(mesh_data.vertices.shape[0]),+ "face_count": int(mesh_data.triangles.shape[0]),+ "bounding_box": {"min": [0.0, 0.0, 0.0],+ "max": [0.0, 0.0, 0.0],+ "size": [0.0, 0.0, 0.0]},+ "watertight": False,+ "volume_mm3": None,+ "surface_area_mm2": 0.0,+ }++ tm = mesh_to_trimesh(mesh_data)++ bb_min = tm.bounds[0].tolist()+ bb_max = tm.bounds[1].tolist()+ bb_size = (tm.bounds[1] - tm.bounds[0]).tolist()++ watertight = bool(tm.is_watertight)+ volume: float | None = float(tm.volume) if watertight else None+ surface_area = float(tm.area)++ return {+ "vertex_count": int(mesh_data.vertices.shape[0]),+ "face_count": int(mesh_data.triangles.shape[0]),+ "bounding_box": {+ "min": bb_min,+ "max": bb_max,+ "size": bb_size,+ },+ "watertight": watertight,+ "volume_mm3": volume,+ "surface_area_mm2": surface_area,+ }+++# ---------------------------------------------------------------------------+# Circle fitting (algebraic / Kasa method)+# ---------------------------------------------------------------------------++def fit_circle_least_squares(+ points_2d: np.ndarray,+) -> tuple[float, float, float, float]:+ """Fit a circle to 2D points using the algebraic (Kasa) method.++ The Kasa method minimises the algebraic distance by solving the+ over-determined system::++ A @ [a, b, c]^T = d++ where ``x^2 + y^2 + a*x + b*y + c = 0`` describes the circle.+ The centre is ``(-a/2, -b/2)`` and the radius is+ ``sqrt(a^2/4 + b^2/4 - c)``.++ Parameters+ ----------+ points_2d:+ (N, 2) array of 2D coordinates. At least 3 points are required.++ Returns+ -------+ tuple+ ``(center_x, center_y, radius, fit_error)`` where *fit_error* is+ the RMS deviation of point distances from the fitted circle.++ Raises+ ------+ ValueError+ If fewer than 3 points are provided.+ """+ if points_2d.ndim != 2 or points_2d.shape[1] != 2:+ raise ValueError(+ f"points_2d must be (N, 2); got shape {points_2d.shape}"+ )+ n = points_2d.shape[0]+ if n < 3:+ raise ValueError(+ f"At least 3 points are required for circle fitting; got {n}"+ )++ x = points_2d[:, 0]+ y = points_2d[:, 1]++ # Build the linear system: A @ [a, b, c]^T = d+ # where x^2 + y^2 + a*x + b*y + c = 0+ A = np.column_stack([x, y, np.ones(n)])+ d = -(x ** 2 + y ** 2)++ # Least-squares solve+ result, *_ = np.linalg.lstsq(A, d, rcond=None)+ a, b, c = result++ cx = -a / 2.0+ cy = -b / 2.0+ r_sq = (a ** 2 + b ** 2) / 4.0 - c+ if r_sq < 0:+ # Degenerate case -- points are collinear or nearly so+ radius = 0.0+ fit_error = float("inf")+ return (cx, cy, radius, fit_error)++ radius = float(np.sqrt(r_sq))++ # RMS fit error+ distances = np.sqrt((x - cx) ** 2 + (y - cy) ** 2)+ fit_error = float(np.sqrt(np.mean((distances - radius) ** 2)))++ return (cx, cy, radius, fit_error)+++# ---------------------------------------------------------------------------+# Cross-section analysis+# ---------------------------------------------------------------------------++def _axis_plane_normal(axis: int) -> np.ndarray:+ """Return a unit normal vector for the given axis index (0=X, 1=Y, 2=Z)."""+ normal = np.zeros(3, dtype=np.float64)+ normal[axis] = 1.0+ return normal+++def _project_to_2d(+ points_3d: np.ndarray,+ axis: int,+) -> np.ndarray:+ """Project 3D points onto the 2D plane perpendicular to *axis*.++ For axis=0 (X), returns columns (Y, Z).+ For axis=1 (Y), returns columns (X, Z).+ For axis=2 (Z), returns columns (X, Y).+ """+ other_axes = [i for i in range(3) if i != axis]+ return points_3d[:, other_axes]+++def cross_section_circles(+ mesh_data: MeshData,+ axis: int = 0,+ num_planes: int = 20,+) -> list[dict[str, Any]]:+ """Take cross-sections and detect circular entities.++ The mesh is sliced at *num_planes* evenly-spaced planes perpendicular+ to the given axis. For each resulting contour, a circle is fitted using+ :func:`fit_circle_least_squares`. Only results with a reasonable fit+ error (< 5 % of radius) are included.++ Parameters+ ----------+ mesh_data:+ Source mesh.+ axis:+ Axis perpendicular to the slicing planes (0=X, 1=Y, 2=Z).+ Default ``0`` (X-axis) since most 3D-printed holes run along X.+ num_planes:+ Number of evenly-spaced slicing planes.++ Returns+ -------+ list[dict]+ Each dict contains:++ - ``center`` -- (2,) list of centre coordinates in the 2D plane.+ - ``radius`` -- fitted radius.+ - ``diameter`` -- 2 * radius.+ - ``plane_value`` -- coordinate along the slicing axis.+ - ``num_points`` -- number of contour points used for fitting.+ - ``fit_error`` -- RMS distance error of the fit.+ """+ if mesh_data.vertices.shape[0] == 0 or mesh_data.triangles.shape[0] == 0:+ return []++ if axis not in (0, 1, 2):+ raise ValueError(f"axis must be 0, 1 or 2; got {axis}")++ if num_planes < 1:+ raise ValueError(f"num_planes must be >= 1; got {num_planes}")++ tm = mesh_to_trimesh(mesh_data)+ normal = _axis_plane_normal(axis)++ # Determine slicing range along the chosen axis+ axis_min = float(tm.bounds[0][axis])+ axis_max = float(tm.bounds[1][axis])+ span = axis_max - axis_min++ if span < 1e-12:+ return []++ # Inset slightly to avoid degenerate boundary slices+ margin = span * 0.02+ plane_values = np.linspace(axis_min + margin, axis_max - margin, num_planes)++ results: list[dict[str, Any]] = []++ for pv in plane_values:+ origin = np.zeros(3, dtype=np.float64)+ origin[axis] = pv++ try:+ section = tm.section(plane_origin=origin, plane_normal=normal)+ except Exception:+ continue++ if section is None:+ continue++ # section is a Path3D; extract discrete points from each entity+ try:+ discrete = section.discrete+ except Exception:+ continue++ for path_points in discrete:+ pts_3d = np.asarray(path_points, dtype=np.float64)+ if pts_3d.ndim != 2 or pts_3d.shape[0] < 5:+ # Need a reasonable number of points for a good circle fit+ continue++ pts_2d = _project_to_2d(pts_3d, axis)++ try:+ cx, cy, radius, fit_error = fit_circle_least_squares(pts_2d)+ except ValueError:+ continue++ if radius < 1e-9:+ continue++ relative_error = fit_error / radius+ if relative_error > 0.05:+ # Not circular enough -- skip+ continue++ results.append({+ "center": [float(cx), float(cy)],+ "radius": float(radius),+ "diameter": float(radius * 2.0),+ "plane_value": float(pv),+ "num_points": int(pts_2d.shape[0]),+ "fit_error": float(fit_error),+ })++ return results+++# ---------------------------------------------------------------------------+# Cylinder detection and vertex manipulation+# ---------------------------------------------------------------------------++def find_cylinder_vertices(+ vertices: np.ndarray,+ center_yz: np.ndarray,+ axis: int,+ radius: float,+ tolerance: float,+) -> np.ndarray:+ """Find vertex indices that lie on a cylindrical surface.++ A vertex is considered to be on the cylinder when its distance from the+ cylinder axis (measured in the 2D plane perpendicular to *axis*) is+ within *tolerance* of *radius*.++ Parameters+ ----------+ vertices:+ (N, 3) array of vertex positions.+ center_yz:+ (2,) array -- centre of the cylinder in the plane perpendicular to+ *axis*. For axis=0 this is (center_y, center_z); for axis=1 it is+ (center_x, center_z); for axis=2 it is (center_x, center_y).+ axis:+ Cylinder axis direction (0=X, 1=Y, 2=Z).+ radius:+ Nominal radius of the cylinder.+ tolerance:+ Maximum allowed deviation from *radius*.++ Returns+ -------+ np.ndarray+ 1-D int array of matching vertex indices.+ """+ if vertices.shape[0] == 0:+ return np.array([], dtype=np.intp)++ if axis not in (0, 1, 2):+ raise ValueError(f"axis must be 0, 1 or 2; got {axis}")++ center_yz = np.asarray(center_yz, dtype=np.float64).ravel()+ if center_yz.shape[0] != 2:+ raise ValueError(+ f"center_yz must have 2 elements; got {center_yz.shape[0]}"+ )++ other_axes = [i for i in range(3) if i != axis]+ pts_2d = vertices[:, other_axes]++ distances = np.sqrt(+ (pts_2d[:, 0] - center_yz[0]) ** 2+ + (pts_2d[:, 1] - center_yz[1]) ** 2+ )++ mask = np.abs(distances - radius) <= tolerance+ return np.nonzero(mask)[0].astype(np.intp)+++def scale_vertices_radially(+ vertices: np.ndarray,+ indices: np.ndarray,+ center: np.ndarray,+ axis: int,+ new_radius: float,+) -> np.ndarray:+ """Scale selected vertices to a new radius, preserving angular position.++ Only the two coordinates perpendicular to *axis* are modified; the+ coordinate along *axis* is left unchanged.++ Parameters+ ----------+ vertices:+ (N, 3) vertex array. **Never mutated** -- a copy is returned.+ indices:+ 1-D array of vertex indices to scale.+ center:+ (2,) centre of the cylinder in the perpendicular plane.+ axis:+ Cylinder axis (0=X, 1=Y, 2=Z).+ new_radius:+ Target radius.++ Returns+ -------+ np.ndarray+ A **new** (N, 3) array with the selected vertices moved to+ *new_radius*.+ """+ if axis not in (0, 1, 2):+ raise ValueError(f"axis must be 0, 1 or 2; got {axis}")++ center = np.asarray(center, dtype=np.float64).ravel()+ if center.shape[0] != 2:+ raise ValueError(f"center must have 2 elements; got {center.shape[0]}")++ # Always work on a copy+ result = np.array(vertices, dtype=np.float64, copy=True)++ if indices.shape[0] == 0:+ return result++ other_axes = [i for i in range(3) if i != axis]+ ax_u, ax_v = other_axes++ # Extract the 2D positions of selected vertices relative to centre+ du = result[indices, ax_u] - center[0]+ dv = result[indices, ax_v] - center[1]+ current_radius = np.sqrt(du ** 2 + dv ** 2)++ # Avoid division by zero for vertices exactly at the centre+ safe_mask = current_radius > 1e-12+ scale = np.ones_like(current_radius)+ scale[safe_mask] = new_radius / current_radius[safe_mask]++ result[indices, ax_u] = center[0] + du * scale+ result[indices, ax_v] = center[1] + dv * scale++ return resultdiff --git a/3MF/agent-harness/setup.py b/3MF/agent-harness/setup.pynew file mode 100644index 000000000..e4df38c1d--- /dev/null+++ b/3MF/agent-harness/setup.py@@ -0,0 +1,58 @@+#!/usr/bin/env python3+"""+setup.py for cli-anything-3mf++Install with: pip install -e .+Or publish to PyPI: python -m build && twine upload dist/*+"""++from setuptools import setup, find_namespace_packages++with open("cli_anything/threemf/README.md", "r", encoding="utf-8") as fh:+ long_description = fh.read()++setup(+ name="cli-anything-3mf",+ version="1.0.0",+ author="cli-anything contributors",+ author_email="",+ description="CLI harness for 3MF — Detect and resize cylindrical holes, repair meshes, compare 3D printing files",+ long_description=long_description,+ long_description_content_type="text/markdown",+ url="https://github.com/HKUDS/CLI-Anything",+ packages=find_namespace_packages(include=["cli_anything.*"]),+ classifiers=[+ "Development Status :: 4 - Beta",+ "Intended Audience :: Developers",+ "Topic :: Scientific/Engineering",+ "License :: OSI Approved :: MIT License",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.10",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ ],+ python_requires=">=3.9",+ install_requires=[+ "click>=8.0.0",+ "prompt-toolkit>=3.0.0",+ "numpy>=1.24.0",+ "scipy>=1.10.0",+ "trimesh>=4.0.0",+ ],+ extras_require={+ "dev": [+ "pytest>=7.0.0",+ "pytest-cov>=4.0.0",+ ],+ },+ entry_points={+ "console_scripts": [+ "cli-anything-3mf=cli_anything.threemf.threemf_cli:main",+ ],+ },+ package_data={+ "cli_anything.threemf": ["skills/*.md"],+ },+ include_package_data=True,+ zip_safe=False,+)diff --git a/README.md b/README.mdindex e78918196..be163b505 100644--- a/README.md+++ b/README.md@@ -1076,12 +1076,19 @@ Each application received complete, production-ready CLI interfaces — not demo<td align="center">✅ 22</td></tr><tr>+<td align="center"><strong>🔩 <a href="3MF/agent-harness/">3MF</a></strong></td>+<td>Mesh geometry editor for 3D printing</td>+<td><code>cli-anything-3mf</code></td>+<td>numpy, scipy, trimesh</td>+<td align="center">✅ 50</td>+</tr>+<tr><td align="center" colspan="4"><strong>Total</strong></td>-<td align="center"><strong>✅ 2,280</strong></td>+<td align="center"><strong>✅ 2,330</strong></td></tr></table>-> **100% pass rate** across all 2,280 tests — 1,682 unit tests + 579 end-to-end tests + 19 Node.js tests.+> **100% pass rate** across all 2,330 tests — 1,732 unit tests + 579 end-to-end tests + 19 Node.js tests.---@@ -1125,8 +1132,9 @@ lldb 27 passed ✅ (23 unit + 4 e2e)nsight-graphics 51 passed ✅ (46 unit/CLI + 5 local e2e)unrealinsights 50 passed ✅ (49 unit + 1 e2e, 9 backend-gated e2e skipped)cloudanalyzer 14 passed ✅ (7 unit + 7 e2e)+3mf 50 passed ✅ (50 unit)──────────────────────────────────────────────────────────────────────────────-TOTAL 2,280 passed ✅ 100% pass rate+TOTAL 2,330 passed ✅ 100% pass rate```---@@ -1211,6 +1219,7 @@ cli-anything/├── ☁️ cloudcompare/agent-harness/ # CloudCompare CLI (88 tests)├── 🔍 exa/agent-harness/ # Exa CLI (40 tests)└── ⛅ cloudanalyzer/agent-harness/ # CloudAnalyzer CLI (14 tests)+└── 🔩 3MF/agent-harness/ # 3MF Mesh Editor CLI (50+ tests)```Each `agent-harness/` contains an installable Python package under `cli_anything.<software>/` with Click CLI, core modules, utils (including `repl_skin.py` and backend wrapper), and comprehensive tests.diff --git a/README_CN.md b/README_CN.mdindex 6559267c1..cf70ba637 100644--- a/README_CN.md+++ b/README_CN.md@@ -632,12 +632,19 @@ CLI-Anything 适用于任何有代码库的软件 —— 不限领域,不限<td align="center">✅ 19</td></tr><tr>+<td align="center"><strong>🔩 <a href="3MF/agent-harness/">3MF</a></strong></td>+<td>3D 打印网格编辑器</td>+<td><code>cli-anything-3mf</code></td>+<td>numpy, scipy, trimesh</td>+<td align="center">✅ 50+</td>+</tr>+<tr><td align="center" colspan="4"><strong>合计</strong></td>-<td align="center"><strong>✅ 1,774</strong></td>+<td align="center"><strong>✅ 1,824</strong></td></tr></table>-> 全部 1,774 项测试 **100% 通过** - 1,268 项单元测试 + 487 项端到端测试 + 19 项 Node.js 测试。+> 全部 1,824 项测试 **100% 通过** - 1,318 项单元测试 + 487 项端到端测试 + 19 项 Node.js 测试。---@@ -670,8 +677,9 @@ lldb 27 passed ✅ (23 unit + 4 e2e)nsight-graphics 51 passed ✅ (46 unit/CLI + 5 local e2e)unrealinsights 50 passed ✅ (49 unit + 1 e2e, 9 backend-gated e2e skipped)sketch 19 passed ✅ (19 jest, Node.js)+3mf 50 passed ✅ (50 unit)──────────────────────────────────────────────────────────────────────────────-TOTAL 1,774 passed ✅ 100% pass rate+TOTAL 1,824 passed ✅ 100% pass rate```---diff --git a/registry.json b/registry.jsonindex 0da224fd8..b0833dc10 100644--- a/registry.json+++ b/registry.json@@ -1170,6 +1170,25 @@"url": "https://github.com/iGodly"}]+ },+ {+ "name": "3mf",+ "display_name": "3MF",+ "version": "1.0.0",+ "description": "Mesh geometry editor for 3D printing files — detect and resize cylindrical holes, repair meshes, compare 3MF files",+ "requires": "Python 3.10+; numpy, scipy, trimesh",+ "homepage": "https://3mf.io",+ "source_url": null,+ "install_cmd": "pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=3MF/agent-harness",+ "entry_point": "cli-anything-3mf",+ "skill_md": "3MF/agent-harness/cli_anything/threemf/skills/SKILL.md",+ "category": "graphics",+ "contributors": [+ {+ "name": "Gituheart",+ "url": "https://github.com/Gituheart"+ }+ ]}]}