Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Rebuild OpenSCAD for checked parametric families and relist it (#137)

Deed0a9ae0152af
diff --git a/.github/workflows/experience-checks.yml b/.github/workflows/experience-checks.yml
index 5cdb7ca9b..6b902f0c3 100644
--- a/.github/workflows/experience-checks.yml
+++ b/.github/workflows/experience-checks.yml
@@ -35,6 +35,8 @@ jobs:
run: node --test store/agents/freecad/test/*.test.mjs
- name: Check Score contracts, MIDI and delivery (native suite is opt-in)
run: node --test store/agents/score/test/*.test.mjs
+ - name: Check OpenSCAD contracts and delivery (native suite is opt-in)
+ run: node --test store/agents/openscad/test/*.test.mjs
authoring-browser:
runs-on: ubuntu-latest
diff --git a/store/agents/openscad/AGENTS.md b/store/agents/openscad/AGENTS.md
index bf94f4a0d..7278dcdf8 100644
--- a/store/agents/openscad/AGENTS.md
+++ b/store/agents/openscad/AGENTS.md
@@ -1,15 +1,20 @@
# OpenSCAD
-Read the `openscad` skill. Build parametric geometry in `model.scad` and render it with
-`sh "$OPENSCAD_SKILLS/openscad/scripts/render-part.sh"`. The shared CAD Viewer opens `part.stl`.
+Read the `openscad` skill. Turn the user's dimensions into an editable parametric project,
+not just a rendered object. Keep the measured brief, tolerances, variants and process assumptions
+in `design.json`, independently of `model.scad`. Do not relax a requirement to make a model pass.
-Keep dimensions, units, tolerances and manufacturing assumptions visible. The Ripple starter is
-an editable dry-use vessel, not a certified printable, watertight or food-safe product.
-Render early, inspect the actual part, then iterate.
+Use the real build command:
-The helper stages a fresh STL, checks triangle topology, volume and bounds, and updates the verdict.
-It cannot certify wall thickness, material strength, overhangs or fit. Do not claim those checks ran
-when they did not. A failed build preserves the previous export but clears readiness.
+```sh
+sh "$OPENSCAD_SKILLS/openscad/scripts/render-part.sh"
+```
-OpenSCAD has no native STEP export. Do not run `openscad -o part.step` or promise a true B-rep from
-that command. For editable STEP geometry, use an appropriate CAD workflow such as FreeCAD.
+The CAD Viewer opens the actual print-oriented `part.stl`. The complete handoff compares variants,
+shows native sections, records measured checks and downloads separate STLs plus an independently
+rebuildable project. Open it with the local handoff helper in the skill.
+
+Inspect the real mesh and the handoff, make a substantive requested revision, and rerun checks.
+Failed builds preserve previous downloads but clear readiness. A source-only legacy project can
+still render; it cannot claim checked readiness. A closed mesh is not a strength, slicer, physical
+fit or safety certificate. OpenSCAD does not export native STEP; use a B-rep workflow when needed.
diff --git a/store/agents/openscad/PROVENANCE.md b/store/agents/openscad/PROVENANCE.md
index f2ff47326..f5ca866cd 100644
--- a/store/agents/openscad/PROVENANCE.md
+++ b/store/agents/openscad/PROVENANCE.md
@@ -1,7 +1,13 @@
# Provenance
-The Ripple vessel source, mesh inspector, staged-build helper and instructions are
-original MIT-licensed OpenHarness work. [OpenSCAD](https://openscad.org) is a
-separately installed GPL-2.0 notation-based CAD application. No OpenSCAD code or
-binary is redistributed. Native QA used OpenSCAD 2021.01. The CAD pane is the
-separate autonomous/cad-viewer package, which carries its own upstream notices.
+Drawer Grid, Bottle Bench, the retained Ripple fixture, requirement evaluator, mesh inspector,
+staged builder, handoff UI, ZIP writer and instructions are original MIT-licensed OpenHarness work.
+The ZIP writer and restricted handoff server are adapted from the original Score/FreeCAD wrappers
+in this repository; portable bundles include their tool license.
+
+[OpenSCAD](https://openscad.org) is a separately installed GPL-2.0 notation-based CAD application.
+No OpenSCAD code or binary is redistributed here. Native QA used OpenSCAD 2021.01. STL and SVG
+artifacts are generated from original example sources; Store screenshots capture actual outputs.
+No physical printing, material testing, food-safety approval or upstream endorsement is claimed.
+
+The CAD pane is the separate autonomous/cad-viewer package, which carries its own upstream notices.
diff --git a/store/agents/openscad/README.md b/store/agents/openscad/README.md
index d81e45b62..2b313dd3c 100644
--- a/store/agents/openscad/README.md
+++ b/store/agents/openscad/README.md
@@ -1,29 +1,51 @@
# OpenSCAD
-Describe a shape, then keep changing it through named dimensions. The **Ripple** starter is a
-twisted, fluted vessel: change its height, diameter, wall or rib count and inspect the actual
-3D result in the shared CAD Viewer.
+Turn “this needs to fit my drawer” into an editable family of parts. Describe the object, provide
+measurements, compare size or clearance variants, and take the checked STLs to your own slicer.
-Try: “Make this a shorter desktop organizer with a thicker base and softer ribs.”
+The **Drawer Grid** starter creates three organizer widths with the same floor, walls and pocket
+requirements. A second tested workflow builds a six-bottle craft rack and matching fit-test rings:
+try a small ring before spending material on the full rack.
-The build exports a fresh STL and checks closed-edge topology, nondegenerate triangles, bounds
-and volume. Failed exports do not leave a successful verdict. A valid mesh still needs review for
-your printer, material and intended use; the starter is not food-safe or watertight by certification.
+Try: “My drawer has 205 × 110 × 45 mm clear space. Make a four-compartment organizer with clearance
+around the outside. Show two size options and keep the floor 2.4 mm thick.”
-Requires OpenSCAD, Node 20+ and the shared CAD Viewer. `OPENSCAD_BIN` can point to a custom install.
-OpenSCAD does not export native STEP; use a B-rep CAD workflow when that is the deliverable.
+## What you take away
+
+- Editable `model.scad` and a saved `design.json` brief, parameter limits, variants and checks.
+- Separate, print-oriented STLs; native top/front/side inspection views; measured evidence.
+- A comparison/download page and a complete ZIP that rebuilds with Node + OpenSCAD outside Harness.
+- A preserved last-good handoff if the next revision fails.
+
+Checks run on the actual exported mesh: closed-edge topology, positive oriented volume, surface
+shells, specified dimensions, clearance regions, required material and relative-part interference.
+Each final STL is reopened in OpenSCAD and checked against the declared individual printer envelope.
+A successful export does **not** certify physical fit, strength, global wall thickness, supports,
+slicing or food safety. No physical print is claimed.
+
+## Run it
+
+Install OpenSCAD and Node 20+; the shared CAD Viewer is a separate dependency. Native QA used
+OpenSCAD 2021.01. Set `OPENSCAD_BIN` if it is not on PATH or at the standard macOS app location.
```sh
harness dsh install "$PWD/store/agents/openscad" --link
harness dsh doctor autonomous/openscad
```
-Upstream: [OpenSCAD](https://openscad.org). This package supplies the workspace, agent skill,
-starter and verification helpers.
+Inside a workspace, ask the agent to build the saved brief. The main pane shows the selected actual
+STL. The local handoff helper opens variant comparison and downloads; its page describes the last
+successful build, not unbuilt source edits. Extract the project ZIP and run
+`node rebuild/build.mjs .` to regenerate it with no Harness account or npm install.
+
+The old Ripple source remains in `test/fixtures/ripple.scad`. Existing SCAD-only workspaces still
+render, with readiness false until a checked brief is added. OpenSCAD has no native STEP export.
+
+See [the schema](skills/openscad/references/design.md) and [acceptance evidence](test/ACCEPTANCE.md).
## Credit and stewardship
-The original wrapper and starter are MIT-licensed OpenHarness work. See
-[PROVENANCE.md](PROVENANCE.md) for upstream tools, datasets and their separate
-licenses. No upstream ownership or endorsement is implied. Wrapper issues belong
-in OpenHarness; upstream maintainers are welcome to take stewardship of a package.
+The original wrapper, source examples and delivery tools are MIT-licensed OpenHarness work.
+[OpenSCAD](https://openscad.org) is separately installed; the shared CAD Viewer carries its own
+upstream notices. See [PROVENANCE.md](PROVENANCE.md). No upstream ownership or endorsement is implied.
+Wrapper issues belong in OpenHarness; upstream maintainers are welcome to take stewardship.
diff --git a/store/agents/openscad/harness.json b/store/agents/openscad/harness.json
index f23e0c8c6..adfc81dda 100644
--- a/store/agents/openscad/harness.json
+++ b/store/agents/openscad/harness.json
@@ -4,7 +4,7 @@
"name": "OpenSCAD",
"category": "CAD",
"author": "OpenSCAD",
- "description": "Parametric OpenSCAD geometry with a live CAD preview, fresh STL exports, and mesh topology, volume and bounds checks.",
+ "description": "Turn measurements into parametric part families: compare fit variants, verify actual meshes, and download print-oriented STLs with an independently rebuildable project.",
"engine": "claude",
"workspace": {
"template": "template",
diff --git a/store/agents/openscad/skills/openscad/SKILL.md b/store/agents/openscad/skills/openscad/SKILL.md
index 744b66f08..6708b5f6b 100644
--- a/store/agents/openscad/skills/openscad/SKILL.md
+++ b/store/agents/openscad/skills/openscad/SKILL.md
@@ -1,32 +1,56 @@
---
name: openscad
-description: Create parametric OpenSCAD models, export and inspect fresh meshes, and iterate in the shared CAD Viewer.
+description: Turn measured requirements into editable OpenSCAD part families, compare fit variants, and deliver checked STLs plus a portable project.
---
# OpenSCAD
-Use named millimetre dimensions at the top of `model.scad`, assertions for invalid combinations,
-and small reusable modules. Preserve the user's target machine/material/fit constraints.
-The Ripple starter's height, diameter, wall, ribs and twist are editable; it is not a required style.
+Build a useful object from the user's real measurements and intended process. The starter is a
+drawer-organizer family, not a prescribed shape. For multi-part mechanisms requiring a true
+B-rep/STEP deliverable, choose a suitable CAD workflow instead of relabeling an STL.
+
+Before authoring a checked project, read [references/design.md](references/design.md) for the source
+interface, requirement schema and probe semantics. Keep the brief and limits in `design.json`;
+implement `module part(id, …named parameters…)` in `model.scad`. The builder calls each part with the
+saved variant values; it ignores top-level preview geometry. Declared input files are the only
+sources copied into the portable project. Compile trusted SCAD only; this is not a sandbox.
+
+Ask for missing measurements that would change the result. Otherwise state assumptions and make
+progress. For a mating fit, useful variants often differ only in clearance; a small fit coupon
+can save a full print. Never call a generated coupon a completed physical test.
```sh
sh "$OPENSCAD_SKILLS/openscad/scripts/render-part.sh"
+node "$OPENSCAD_SKILLS/openscad/scripts/serve-handoff.mjs" "$HARNESS_WORKSPACE"
```
-Requires Node 20+ and OpenSCAD. The helper resolves `OPENSCAD_BIN`, the toolchain link, PATH or the
-standard macOS app. It runs one real export into a unique staging directory, writes the compiler
-output to `.harness/build.log`, inspects the STL, then replaces `part.stl` only on success.
-`.harness/mesh.json` reports triangles, volume, area, bounds, degenerate faces and open/non-manifold
-edges. Failure always clears the verdict's readiness and artifact rather than endorsing an old mesh.
+Requires Node 20+ and a separately installed OpenSCAD (tested 2021.01); set `OPENSCAD_BIN` for a custom
+location. The second command prints a loopback-only URL. Open that URL for variant comparison,
+native top/front/side sections, individual print-oriented STLs, the measured report and
+`handoff/project.zip`. It remains a saved snapshot after edits; rebuild before relying on it.
+The main CAD pane displays the selected `design.preview` part as `part.stl`.
+
+The helper renders every variant and part, checks repeat exports agree, then measures the actual
+saved mesh: closure/orientation/surface-shell count, required bounds/volume, empty clearance
+regions, required material and optional relative-part overlap. It orients individual STLs,
+moves them onto the bed, checks the declared build envelope and natively reimports them.
+Section planes are explicit; silhouettes are labelled. Outputs publish only after all checks
+and source-hash checks pass. A build lock prevents competing writers; previous outputs live in
+`.harness/history/`. Inspect `.harness/build.log` and `.harness/failed-mesh.json` after a failure.
+Do not remove a lock until its owner process has stopped.
-The STL check welds coordinates to five decimal places and checks paired, oppositely directed edges.
-It does not detect all self-intersections or certify wall thickness, printability, strength or fit.
-Review overhangs, intended orientation, supports, clearances and process-specific wall requirements.
-Don't describe a closed mesh as proof of manufacturing safety.
+Inspect the actual STL in the CAD Viewer (orbit, section/measure when useful), not a source-code
+screenshot. Review the handoff on the intended screen size and make a substantive revision.
+Keep the user's requirements fixed while correcting geometry. Test that a known obstruction or
+missing material is rejected; do not weaken checks to obtain a green verdict.
-For manual variants: `openscad -o tall.stl -D height=100 model.scad`. Export 2D contours with
-`openscad -o outline.dxf drawing.scad`. OpenSCAD does not natively export STEP; request/choose a
-true CAD workflow for B-rep editing or machining rather than relabeling a mesh.
+The ZIP includes source, variant wrappers, all exported parts/views and standalone rebuild tools.
+Extract it and run `node rebuild/build.mjs .` with Node and OpenSCAD installed; no Harness account
+or npm packages are required. `preview.scad` opens the selected editable configuration in OpenSCAD;
+`handoff/source-previews/` contains the other configurations. These preserve design coordinates;
+downloadable STLs use print coordinates.
-Inspect the actual STL in the CAD Viewer: orbit, fit, section and measure as appropriate.
-A source-code screenshot or a successful exit code is not visual verification.
+Checks cover only declared probe regions, not global minimum thickness or every self-intersection.
+They do not certify strength, slicing/supports, packed-plate capacity, food safety or real fit.
+Separate the digital evidence, process assumptions and physical testing still needed.
+A legacy `model.scad` without `design.json` renders a geometry preview with readiness false.
diff --git a/store/agents/openscad/skills/openscad/references/design.md b/store/agents/openscad/skills/openscad/references/design.md
new file mode 100644
index 000000000..8fcf40d56
--- /dev/null
+++ b/store/agents/openscad/skills/openscad/references/design.md
@@ -0,0 +1,120 @@
+# Checked design contract (spec 1)
+
+Use the starter `template/design.json` as a complete example. The independent bottle/ring project
+in `test/fixtures/bottles/` demonstrates cylinders, two repeat axes, two parts, clearance variants,
+negative design coordinates and an explicitly rotated print part.
+
+## Saved brief and geometry
+
+Root fields (unknown fields are rejected):
+
+- `spec: 1`; `title`; `brief`; `assumptions: string[]`; `assembly: string[]`.
+- `sourceFiles`: explicit portable input paths including `model.scad` and `design.json`. Up to 32
+ regular files, 8 MiB each / 16 MiB total; no symlinks, hidden components, traversal or generated
+ output paths. Supported suffixes: scad/json/stl/svg/dxf/txt/md.
+- `parameters`: 1–64 named numeric definitions `{value,min,max,unit,label?}`. Units are
+ `mm`, `degrees`, `count` or `ratio`. Count values are integers. `id` is reserved.
+- `variants`: 1–4 `{id,label,values,notes}` objects; `values` overrides defaults by parameter name.
+- `parts`: 1–8 `{id,label,quantity,printRotation,shells,views,notes}` objects.
+- `checks`: 1–32 independent requirements, described below.
+- `process: {material,bedMM:[x,y,z],edgeMarginMM,nozzleMM,notes}`.
+- `preview: {variant,part}` chooses the real mesh shown in the main CAD pane.
+
+IDs start with a lowercase letter, contain lowercase letters/digits/hyphens and are at most 32
+characters. Their combined export/check names must not collide. Each part's generated
+`<part>-topology`, `<part>-reopen` and `<part>-bed` check names are reserved.
+
+Implement every saved numeric parameter as a named module argument:
+
+```scad
+module part(id, width=180, depth=96, height=40, wall=2.4, floor=2.4, columns=3) {
+ // Assert meaningful parameter combinations, then construct the selected part.
+ assert(id == "tray", "Unknown part");
+ // ...
+}
+part("tray"); // optional desktop preview, not part of checked exports
+```
+
+The builder uses `use <model.scad>` and calls `part(id="tray",width=...,...)`. Do not depend on
+top-level assignments for configurable values; derive dimensions inside the module from its
+arguments. Unknown module/parameter diagnostics fail the build. Dependencies must be relative,
+declared in `sourceFiles` and portable; native dependency receipts reject outside inputs.
+Do not use unseeded random geometry. Repeated exports must agree to 0.00001 mm vertex precision.
+This check is not a proof against every possible nondeterministic program.
+
+Compile trusted source only. Dependency checking detects undeclared reads after compilation; it
+is a portability check, not an execution sandbox. Font lookup and native libraries are engine
+dependencies, not bundled inputs; disclose any reliance on locally installed fonts.
+
+## Measurements and probes
+
+All geometric checks refer to **design coordinates of the actual first exported STL**, before
+print orientation. Required dimensions come from the saved brief, never inferred back from a
+faulty export. Numeric fields accept finite numbers or bounded arithmetic strings using parameter
+names, parentheses and `+ - * /`; no functions, JavaScript, property access or units inside expressions.
+
+Every check has `{id,label,kind,part}`, plus:
+
+| Kind | Additional fields | Measured condition |
+| --- | --- | --- |
+| `bounds` | `origin:[x,y,z], size:[x,y,z], tolerance` (default 0.02 mm, max 1 mm) | Measured minimum corner and spans match; required for every part. |
+| `volume` | `range:[min,max]` in mm³ | Actual oriented-mesh volume is in range. |
+| `empty` | `region` | Native intersection of the STL and region is empty. |
+| `contains` | `region` | Native difference of the region minus STL is empty. |
+| `separated` | `other, translation:[x,y,z], rotation:[x,y,z]` | First STL does not overlap the second after rotation then translation. |
+
+A box region is `{shape:"box",origin:[x,y,z],size:[x,y,z]}`. A cylinder is
+`{shape:"cylinder",origin:[x,y,z],radius,height,axis:"z"}`; the origin is the center of its
+starting face, and the cylinder extends along the positive x/y/z axis. Cylinders use 128 facets.
+
+Either region can add `repeat:[{count,step:[x,y,z]}, ...]` for one or two repeat axes (at most
+64 probes). This checks every pocket/divider in a regular layout without duplicating requirements.
+
+Choose probe tolerances deliberately. The examples inset probe faces by 0.04 mm to avoid
+coincident-boundary numerical noise; these tests therefore prove the inset region, not the
+untested skin around it. The nozzle value is a recorded assumption, not an automatic minimum-wall
+check. Add material probes where wall/floor integrity matters; an empty pocket alone proves no wall.
+
+A diagnostic such as “unknown module” can accompany OpenSCAD's empty-object message. Only the exact
+native empty result **without warnings/errors** passes. Missing output or a generic nonzero exit
+is a build failure, never a successful clearance check.
+
+## Parts, print orientation and views
+
+`shells` is the expected number of connected **surface** shells, not the number of solids. An
+enclosed cavity may have an inner surface shell. The mesh checker welds to 0.00001 mm, checks
+oppositely directed paired edges, rejects degenerate faces and requires positive oriented total
+volume. It cannot find every self-intersection.
+
+`printRotation` is a fixed numeric [x,y,z] Euler rotation in OpenSCAD degrees. The exact exported
+mesh is rotated, translated so minimum XYZ is zero and natively reopened. The individual final
+part must fit `bedMM` with `edgeMarginMM` on both X/Y sides. Quantity is a bill-of-materials count;
+this is not a packed-plate or G-code check.
+
+`views` has `top`, `front` and `side`, each with `{at: expressionOrNull}`:
+
+- Top: XY plane; `at` selects design Z.
+- Front: XZ plane; `at` selects design Y.
+- Side: YZ plane; `at` selects design X.
+- `null` requests a silhouette, labelled as such. A section must be strictly inside the measured
+ bounds and intersect actual material.
+
+Pick planes that reveal the relevant interior, not an attractive silhouette hiding it. Native
+SVG viewboxes may be padded; displayed dimensions come from measured meshes. These are reference
+views, not certified dimensioned production drawings.
+
+## Outputs and recovery
+
+`part.stl` is the selected print-ready-coordinate preview; `preview.scad` is its editable source
+configuration. `handoff/` contains all individual STLs, views, source wrappers, a comparison page,
+`checks.json` and `project.zip`. The ZIP is bounded to 256 entries / 32 MiB uncompressed and includes
+standalone Node + OpenSCAD rebuild tools and their MIT license. It includes only declared sources
+and generated delivery files, never the rest of the workspace.
+
+A unique staging directory, source hashes and build lock guard publication. Failed builds clear
+readiness and retain prior successful downloads. History is retained in `.harness/history/`.
+Old handoff pages are explicitly saved snapshots. A single-file legacy `model.scad` still renders
+without a brief but does not become checked/ready.
+
+No physical testing is implied. Review slicing, supports, material, shrinkage and actual fit;
+use a fit coupon before a full part where worthwhile.
diff --git a/store/agents/openscad/skills/openscad/scripts/LICENSE b/store/agents/openscad/skills/openscad/scripts/LICENSE
new file mode 100644
index 000000000..d3eab18ed
--- /dev/null
+++ b/store/agents/openscad/skills/openscad/scripts/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 OpenHarness contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/store/agents/openscad/skills/openscad/scripts/archive.mjs b/store/agents/openscad/skills/openscad/scripts/archive.mjs
new file mode 100644
index 000000000..c272a8548
--- /dev/null
+++ b/store/agents/openscad/skills/openscad/scripts/archive.mjs
@@ -0,0 +1,34 @@
+// Small, bounded, deterministic ZIP writer. No global npm or Python dependency.
+import {deflateRawSync} from 'node:zlib';
+const table=Uint32Array.from({length:256},(_,value)=>{
+ for (let i=0;i<8;i++) value=value&1 ? 0xedb88320^(value>>>1) : value>>>1;
+ return value>>>0;
+});
+function crc32(bytes) {
+ let crc=0xffffffff;
+ for (const byte of bytes) crc=table[(crc^byte)&255]^(crc>>>8);
+ return (crc^0xffffffff)>>>0;
+}
+export function zip(files) {
+ if (!files.length || files.length>256) throw new Error('Archive needs 1–256 files.');
+ const chunks=[], central=[], names=new Set(); let offset=0, total=0;
+ for (const {name,bytes:input} of files) {
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(name) || name.split('/').some(p=>!p || p==='.' || p==='..') || names.has(name.toLowerCase())) throw new Error('Unsafe or duplicate archive path: '+name);
+ names.add(name.toLowerCase());
+ const bytes=Buffer.from(input), filename=Buffer.from(name), compressed=deflateRawSync(bytes), crc=crc32(bytes);
+ total+=bytes.length;
+ if (total>32*1024*1024) throw new Error('Portable project exceeds 32 MiB uncompressed.');
+ const header=Buffer.alloc(30);
+ header.writeUInt32LE(0x04034b50,0); header.writeUInt16LE(20,4); header.writeUInt16LE(0x800,6); header.writeUInt16LE(8,8);
+ header.writeUInt16LE(33,12); header.writeUInt32LE(crc,14); header.writeUInt32LE(compressed.length,18); header.writeUInt32LE(bytes.length,22); header.writeUInt16LE(filename.length,26);
+ const entry=Buffer.alloc(46);
+ entry.writeUInt32LE(0x02014b50,0); entry.writeUInt16LE(20,4); entry.writeUInt16LE(20,6); entry.writeUInt16LE(0x800,8); entry.writeUInt16LE(8,10); entry.writeUInt16LE(33,14);
+ entry.writeUInt32LE(crc,16); entry.writeUInt32LE(compressed.length,20); entry.writeUInt32LE(bytes.length,24); entry.writeUInt16LE(filename.length,28); entry.writeUInt32LE(offset,42);
+ chunks.push(header,filename,compressed); central.push(entry,filename); offset+=header.length+filename.length+compressed.length;
+ }
+ const directory=Buffer.concat(central), end=Buffer.alloc(22);
+ end.writeUInt32LE(0x06054b50,0); end.writeUInt16LE(files.length,8); end.writeUInt16LE(files.length,10); end.writeUInt32LE(directory.length,12); end.writeUInt32LE(offset,16);
+ const output=Buffer.concat([...chunks,directory,end]);
+ if (output.length>32*1024*1024) throw new Error('Portable project exceeds the 32 MiB download limit.');
+ return output;
+}
diff --git a/store/agents/openscad/skills/openscad/scripts/build.mjs b/store/agents/openscad/skills/openscad/scripts/build.mjs
index 0fb10b1ac..ee77f2272 100644
--- a/store/agents/openscad/skills/openscad/scripts/build.mjs
+++ b/store/agents/openscad/skills/openscad/scripts/build.mjs
@@ -1,37 +1,166 @@
-import { access, readFile, writeFile, mkdir, mkdtemp, rename, rm } from 'node:fs/promises';
-import { constants } from 'node:fs';
-import { spawnSync } from 'node:child_process';
-import { delimiter, join, resolve } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { inspectSTL } from './mesh.mjs';
+import {access,readFile,mkdir} from 'node:fs/promises';
+import {constants} from 'node:fs';
+import {delimiter,join,resolve} from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {inspectSTL,parseSTL,binarySTL} from './mesh.mjs';
+import {validateDesign,parametersFor,checkFor,regionScad} from './design.mjs';
+import {number} from './expression.mjs';
+import {Native,partCall,imported,projection} from './native.mjs';
+import {sha,json,exists,source,snapshot,unchanged,save,atomic,publish,transaction} from './files.mjs';
+import {zip} from './archive.mjs';
+import {handoff} from './handoff.mjs';
+
+const limitations=[
+ 'Checks measure declared regions, bounds and printer envelope on exported meshes. They do not prove global minimum wall thickness, absence of all self-intersections, strength, overhangs, food safety or physical fit.',
+ 'Build-envelope checks are per part in the saved orientation, not a packed plate, support plan or slicing result. STL dimensions are millimetres.',
+ 'Section views are inspection references, not certified manufacturing drawings. Print the fit coupon when provided; measure the real result before committing to a full batch.'
+];
+const equal=(a,b,tolerance)=>a.length===b.length&&a.every((value,i)=>Math.abs(value-b[i])<=tolerance);
+const shape=bytes=>parseSTL(bytes).map(triangle=>{
+ const vertices=triangle.map(point=>point.map(value=>Number(value.toFixed(5))).join(','));
+ return [0,1,2].map(i=>[...vertices.slice(i),...vertices.slice(0,i)].join(';')).sort()[0];
+}).sort().join('\n');
+function closed(mesh){return mesh.watertight&&mesh.volumeMM3>0&&mesh.orientedVolumeMM3>0;}
+function equivalent(a,b){
+ return closed(a)&&closed(b)&&a.shells.length===b.shells.length&&equal(a.bounds.size,b.bounds.size,.02)&&Math.abs(a.volumeMM3-b.volumeMM3)<=Math.max(.02,a.volumeMM3*1e-4);
+}
export async function findExecutable(candidates){
for(const candidate of candidates.filter(Boolean))for(const file of candidate.includes('/')?[candidate]:(process.env.PATH||'').split(delimiter).map(dir=>join(dir,candidate))){
try{await access(file,constants.X_OK);return file;}catch{}
}
- throw new Error('OpenSCAD not found. Set OPENSCAD_BIN or run harness dsh doctor autonomous/openscad.');
+ throw new Error('OpenSCAD not found. Install OpenSCAD, set OPENSCAD_BIN, or run harness dsh doctor autonomous/openscad.');
}
export async function build(workspace,{bin}={}){
- const state=join(workspace,'.harness');await mkdir(state,{recursive:true});
- const atomic=async(path,value)=>{const temporary=path+'.'+process.pid+'.tmp';await writeFile(temporary,value);await rename(temporary,path);};
- const verdict=value=>atomic(join(state,'verdict.json'),JSON.stringify({spec:1,...value,updatedAt:new Date().toISOString()},null,2)+'\n');
- let temporary;
- try{
- await verdict({ready:false,summary:'Rendering and inspecting the mesh',findings:[],artifact:null});
+ workspace=resolve(workspace);
+ return transaction(workspace,async({state,stage,verdict})=>{
+ const directory=join(stage,'native');await mkdir(directory);
const executable=bin||await findExecutable([process.env.OPENSCAD_BIN,process.env.OPENSCAD_TOOLCHAIN&&join(process.env.OPENSCAD_TOOLCHAIN,'openscad-cli'),'openscad','/Applications/OpenSCAD.app/Contents/MacOS/OpenSCAD']);
- await access(join(workspace,'model.scad'));
- temporary=await mkdtemp(join(state,'openscad-'));
- const result=spawnSync(executable,['-o',join(temporary,'part.stl'),join(workspace,'model.scad')],{cwd:workspace,encoding:'utf8',timeout:180000,maxBuffer:10*1024*1024});
- await atomic(join(state,'build.log'),(result.stdout||'')+(result.stderr||''));
- if(result.error||result.status!==0)throw new Error('OpenSCAD failed: '+(result.error?.message||'exit '+result.status)+'. See .harness/build.log.');
- const mesh=await readFile(join(temporary,'part.stl')),report=inspectSTL(mesh);
- if(!report.watertight||report.volumeMM3<=0)throw new Error('Mesh inspection failed: '+report.nonManifoldEdges+' open/non-manifold edges and '+report.degenerateTriangles+' degenerate triangles.');
- await atomic(join(workspace,'part.stl'),mesh);await atomic(join(state,'mesh.json'),JSON.stringify(report,null,2)+'\n');
- await verdict({ready:true,summary:report.triangles.toLocaleString()+' triangles · closed mesh · '+report.bounds.size.map(n=>n.toFixed(1)).join(' × ')+' mm',findings:[{severity:'info',kind:'manufacturing',message:'Closed-mesh checks do not certify wall thickness, strength, overhangs or fit. Review for the intended printer and material.'}],artifact:'part.stl'});
- return report;
- }catch(error){await verdict({ready:false,summary:'OpenSCAD build failed',findings:[{severity:'error',kind:'build',message:error.message}],artifact:null});throw error;}
- finally{if(temporary)await rm(temporary,{recursive:true,force:true});}
+ const native=new Native(executable,directory);
+ try{
+ const contract=await exists(join(workspace,'design.json'))?await source(workspace,'design.json'):null;
+ const design=contract?validateDesign(JSON.parse(contract)):null;
+ const files=await snapshot(workspace,design?.sourceFiles||['model.scad']);
+ if(contract&&!contract.equals(files.find(file=>file.name==='design.json').bytes))throw new Error('Design brief changed while reading sources.');
+ const sources=Object.fromEntries(files.map(file=>[file.name,sha(file.bytes)]).sort(([a],[b])=>a.localeCompare(b)));
+ const sourceRevision=sha(JSON.stringify(sources));
+ for(const file of files)await save(join(directory,'source',file.name),file.bytes);
+ const allowed=files.map(file=>join(directory,'source',file.name));
+ const engine=native.version();
+ if(!design){
+ const fresh=await native.render('legacy','include <source/model.scad>\n',{allowedDependencies:allowed});
+ const mesh=inspectSTL(fresh.bytes);
+ if(!closed(mesh))throw new Error('Legacy mesh is not closed, consistently wound and positive-volume.');
+ await unchanged(workspace,files);
+ await save(join(stage,'part.stl'),fresh.bytes);
+ const report={...mesh,spec:1,checked:false,engine,sourceRevision,sources,limitations};
+ report.previousArtifacts=await publish(workspace,state,stage,['part.stl']);
+ await atomic(join(state,'mesh.json'),json(report));
+ await verdict({ready:false,artifact:'part.stl',summary:'Geometry preview only: add design.json to check requirements and prepare a portable handoff',findings:[{severity:'warning',kind:'requirements',message:limitations.join(' ')}]});
+ return report;
+ }
+ const report={spec:1,checked:true,title:design.title,design,engine,sourceRevision,sources,checks:[],variants:[],limitations};
+ const meshes=new Map(),outputs=[];
+ const put=async(name,bytes)=>{await save(join(stage,name),bytes);outputs.push({name,bytes:Buffer.from(bytes)});};
+ const check=(variant,id,label,passed,detail,measured)=>report.checks.push({variant,id,label,passed,detail,...(measured===undefined?{}:{measured})});
+ for(const variant of design.variants){
+ const parameters=parametersFor(design,variant),result={id:variant.id,label:variant.label,parameters,notes:variant.notes,parts:[]};
+ report.variants.push(result);
+ for(const part of design.parts){
+ const prefix=variant.id+'-'+part.id,code='use <source/model.scad>\n'+partCall(part.id,parameters)+'\n';
+ const fresh=await native.render(prefix,code,{allowedDependencies:allowed});
+ const repeat=await native.render(prefix+'-repeat',code,{allowedDependencies:allowed});
+ if(shape(fresh.bytes)!==shape(repeat.bytes))throw new Error(prefix+': repeated source exports disagree. Remove nondeterministic geometry and rebuild.');
+ const mesh=inspectSTL(fresh.bytes);
+ const passed=closed(mesh)&&mesh.shells.length===part.shells;
+ check(variant.id,prefix+'-topology',part.label+' · mesh integrity',passed,passed?mesh.triangles+' triangles; '+mesh.shells.length+' connected surface shell(s); positive oriented volume':
+ 'Expected a closed, consistently wound mesh with '+part.shells+' surface shell(s).',mesh);
+ meshes.set(prefix,{...fresh,mesh});
+ result.parts.push({id:part.id,label:part.label,quantity:part.quantity,notes:part.notes,mesh,views:[]});
+ }
+ for(const raw of design.checks){
+ const required=checkFor(raw,parameters),part=meshes.get(variant.id+'-'+raw.part),id=variant.id+'-'+raw.id;
+ let passed,detail,measured;
+ if(required.kind==='bounds'){
+ measured=part.mesh.bounds;
+ passed=equal(measured.size,required.size,required.tolerance)&&equal(measured.min,required.origin,required.tolerance);
+ detail='Size '+measured.size.map(v=>v.toFixed(3)).join(' × ')+' mm; required '+required.size.join(' × ')+' mm, origin '+required.origin.join(', ')+'; tolerance ±'+required.tolerance+' mm.';
+ }else if(required.kind==='volume'){
+ measured=part.mesh.volumeMM3;passed=measured>=required.range[0]&&measured<=required.range[1];
+ detail=measured.toFixed(2)+' mm³; required '+required.range.join('–')+' mm³.';
+ }else{
+ let code;
+ if(required.kind==='empty')code='intersection(){'+imported(part.file)+regionScad(required.region)+'}';
+ if(required.kind==='contains')code='difference(){'+regionScad(required.region)+imported(part.file)+'}';
+ if(required.kind==='separated')code='intersection(){'+imported(part.file)+'translate('+JSON.stringify(required.translation)+') rotate('+JSON.stringify(required.rotation)+') '+imported(meshes.get(variant.id+'-'+required.other).file)+'}';
+ const probe=await native.render(id,code,{emptyAllowed:true});
+ passed=probe.empty;measured=probe.empty?0:inspectSTL(probe.bytes).volumeMM3;
+ detail=passed?(required.kind==='contains'?'Required material region is fully contained.':required.kind==='empty'?'Required clearance region is empty.':'Parts do not overlap in the declared relative placement.'):
+ 'Unexpected '+(required.kind==='contains'?'missing':'intersecting')+' material: '+measured.toFixed(4)+' mm³.';
+ }
+ check(variant.id,id,raw.label,passed,detail,measured);
+ }
+ }
+ const fail=async()=>{
+ const failures=report.checks.filter(item=>!item.passed);
+ if(failures.length){
+ await atomic(join(state,'failed-mesh.json'),json(report));
+ throw new Error(failures.map(item=>item.id+': '+item.detail).join('\n')+'\nSee .harness/failed-mesh.json. Previous successful files are unchanged.');
+ }
+ };
+ await fail();
+ for(const variant of report.variants){
+ for(const part of variant.parts){
+ const definition=design.parts.find(item=>item.id===part.id),prefix=variant.id+'-'+part.id,original=meshes.get(prefix);
+ const rotated=await native.render(prefix+'-orient','rotate('+JSON.stringify(definition.printRotation)+') '+imported(original.file));
+ const rotatedMesh=inspectSTL(rotated.bytes);
+ if(!closed(rotatedMesh)||rotatedMesh.shells.length!==part.mesh.shells.length||Math.abs(rotatedMesh.volumeMM3-part.mesh.volumeMM3)>Math.max(.02,part.mesh.volumeMM3*1e-4))throw new Error(prefix+': orientation changed mesh volume, shell count or closure.');
+ const printBytes=binarySTL(parseSTL(rotated.bytes),rotatedMesh.bounds.min.map(value=>-value));
+ const local=join(directory,prefix+'-print.stl');await save(local,printBytes);
+ const reopened=await native.render(prefix+'-reopen',imported(local));
+ const printMesh=inspectSTL(printBytes),reopenedMesh=inspectSTL(reopened.bytes);
+ if(!equivalent(printMesh,reopenedMesh)||!equal(printMesh.bounds.min,[0,0,0],.001)||!equal(reopenedMesh.bounds.min,[0,0,0],.02))throw new Error(prefix+': native re-import disagrees with the print-oriented STL.');
+ part.printMesh=printMesh;part.printRotation=definition.printRotation;part.path='handoff/parts/'+prefix+'.stl';part.sha256=sha(printBytes);
+ check(variant.id,prefix+'-reopen',part.label+' · exported STL reopens',true,'Native OpenSCAD re-import preserves volume, closure and dimensions. Print coordinates start at [0, 0, 0].');
+ const envelope=design.process.bedMM,margin=design.process.edgeMarginMM;
+ const fits=printMesh.bounds.size.every((size,i)=>size+(i<2?2*margin:0)<=envelope[i]+.001);
+ check(variant.id,prefix+'-bed',part.label+' · build envelope',fits,'Oriented size '+printMesh.bounds.size.map(v=>v.toFixed(2)).join(' × ')+' mm; printer '+envelope.join(' × ')+' mm; XY edge margin '+margin+' mm per side.',printMesh.bounds.size);
+ await put(part.path,printBytes);
+ for(const view of ['top','front','side']){
+ const raw=definition.views[view].at,at=raw===null?null:number(raw,variant.parameters,'Section position'),axis={top:2,front:1,side:0}[view];
+ if(at!==null&&(at<=part.mesh.bounds.min[axis]+.001||at>=part.mesh.bounds.max[axis]-.001))throw new Error(prefix+': '+view+' section must lie strictly inside the measured bounds.');
+ const drawing=await native.render(prefix+'-'+view,projection(original.file,view,at),{format:'svg'});
+ const svg=drawing.bytes.toString('utf8');
+ if(!/<svg\b/.test(svg)||!/<path\b/.test(svg))throw new Error(prefix+': no native geometry in '+view+' view.');
+ const name='handoff/views/'+prefix+'-'+view+'.svg';
+ await put(name,drawing.bytes);
+ part.views.push({name:view,path:name,at,axes:{top:'X / Y',front:'X / Z',side:'Y / Z'}[view]});
+ }
+ }
+ }
+ await fail();
+ const selected=report.variants.find(item=>item.id===design.preview.variant).parts.find(item=>item.id===design.preview.part);
+ await put('part.stl',await readFile(join(stage,selected.path)));
+ const selectedParameters=parametersFor(design,design.variants.find(item=>item.id===design.preview.variant));
+ await put('preview.scad','// Generated from the saved design.json; edit the brief or model, then rebuild.\nuse <model.scad>\n'+partCall(design.preview.part,selectedParameters)+'\n');
+ for(const variant of report.variants)for(const part of variant.parts)await put('handoff/source-previews/'+variant.id+'-'+part.id+'.scad','use <../../model.scad>\n'+partCall(part.id,variant.parameters)+'\n');
+ await put('handoff/checks.json',json(report));
+ await put('handoff/index.html',handoff(report));
+ await put('handoff/app.js',await readFile(new URL('handoff.js',import.meta.url)));
+ const bundle=[...files,...outputs];
+ for(const name of ['build.mjs','files.mjs','mesh.mjs','design.mjs','expression.mjs','native.mjs','archive.mjs','handoff.mjs','handoff.js','handoff.css','serve-handoff.mjs','LICENSE'])bundle.push({name:'rebuild/'+name,bytes:await readFile(new URL(name,import.meta.url))});
+ bundle.push({name:'REBUILD.md',bytes:Buffer.from('# '+design.title+'\n\nInstall Node 20+ and OpenSCAD (tested '+engine+'). In this extracted folder run:\n\n node rebuild/build.mjs .\n\nSet OPENSCAD_BIN if needed. No Harness account, npm packages or Python required. Edit design.json for requirements/variant values, model.scad for geometry. All dimensions are millimetres. Compile only trusted SCAD and dependencies; the builder is not a sandbox.\n\nOpen preview.scad in OpenSCAD for the selected editable part. Other saved parameter combinations are in handoff/source-previews/. Downloadable STLs are individually oriented and moved onto the bed; source previews retain design coordinates. The full model and all declared inputs are included.\n\nOpen handoff/index.html locally, or run node rebuild/serve-handoff.mjs . for downloads. The report records the exact source hashes. Rebuild after editing; an old handoff is a saved snapshot, not a live readiness claim. Tools in rebuild/ are MIT-licensed (see rebuild/LICENSE); source permissions remain the creator’s responsibility.\n\n'+limitations.join('\n\n')+'\n')});
+ await put('handoff/project.zip',zip(bundle));
+ await unchanged(workspace,files);
+ report.previousArtifacts=await publish(workspace,state,stage,['part.stl','preview.scad','handoff']);
+ await atomic(join(state,'mesh.json'),json(report));
+ await verdict({ready:true,artifact:'part.stl',summary:report.variants.length+' variants · '+design.parts.length+' part(s) each · '+report.checks.length+' checks passed · portable project ready',findings:[{severity:'info',kind:'manufacturing',message:limitations.join(' ')}]});
+ return report;
+ }finally{
+ await atomic(join(state,'build.log'),native.log);
+ }
+ });
}
if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){
- try{const report=await build(resolve(process.env.HARNESS_WORKSPACE||process.cwd()));console.log('Verified part.stl: '+report.triangles+' triangles, '+report.volumeMM3.toFixed(1)+' mm³');}
+ try{const report=await build(process.argv[2]||process.env.HARNESS_WORKSPACE||process.cwd());console.log(report.checked?'Ready: '+report.checks.length+' checks. Open handoff/index.html; download handoff/project.zip.':'Legacy geometry preview exported; saved requirements have not been checked.');}
catch(error){console.error(error.message);process.exitCode=1;}
}
diff --git a/store/agents/openscad/skills/openscad/scripts/design.mjs b/store/agents/openscad/skills/openscad/scripts/design.mjs
new file mode 100644
index 000000000..38ce2c144
--- /dev/null
+++ b/store/agents/openscad/skills/openscad/scripts/design.mjs
@@ -0,0 +1,170 @@
+import {number,vector} from './expression.mjs';
+const idPattern=/^[a-z][a-z0-9-]{0,31}$/;
+const variablePattern=/^[a-zA-Z_][a-zA-Z0-9_]{0,47}$/;
+function fields(value,allowed,label) {
+ if (!value || typeof value!=='object' || Array.isArray(value)) throw new Error(label+' must be an object.');
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new Error('Unknown '+label+' field: '+key);
+}
+function text(value,label,max=2000) {
+ if (typeof value!=='string' || !value.trim() || value.length>max || /[\x00-\x08\x0b-\x1f]/.test(value)) throw new Error('Invalid '+label);
+}
+function list(value,label) {
+ if (!Array.isArray(value) || value.length>30) throw new Error(label+' must be a list of at most 30 notes.');
+ for (const item of value) text(item,label,1000);
+}
+function integer(value,min,max,label) {
+ if (!Number.isInteger(value) || value<min || value>max) throw new Error(label+' must be an integer from '+min+' to '+max);
+}
+function ids(list,label) {
+ if (!Array.isArray(list)) throw new Error(label+' must be a list.');
+ const result=new Set();
+ for (const item of list) {
+ if (!item || !idPattern.test(item.id) || result.has(item.id)) throw new Error('Invalid or duplicate '+label+' ID.');
+ result.add(item.id);
+ }
+ return result;
+}
+export function parametersFor(design,variant) {
+ const parameters=Object.create(null);
+ for (const [name,definition] of Object.entries(design.parameters)) {
+ const value=Object.hasOwn(variant.values,name)?variant.values[name]:definition.value;
+ number(value,{},name);
+ if (typeof value!=='number' || value<definition.min || value>definition.max || definition.unit==='count'&&!Number.isInteger(value)) throw new Error(variant.id+': '+name+' is outside its saved limits.');
+ parameters[name]=value;
+ }
+ for (const name of Object.keys(variant.values)) if (!Object.hasOwn(parameters,name)) throw new Error('Unknown variant parameter: '+name);
+ return parameters;
+}
+export function regionFor(raw,parameters) {
+ fields(raw,['shape','origin','size','radius','height','axis','repeat'],'region');
+ const origin=vector(raw.origin,parameters,'Region origin');
+ let region;
+ if (raw.shape==='box') {
+ if (['radius','height','axis'].some(key=>raw[key]!==undefined)) throw new Error('A box uses size, not cylinder fields.');
+ region={shape:'box',origin,size:vector(raw.size,parameters,'Region size',{positive:true})};
+ } else if (raw.shape==='cylinder') {
+ if (raw.size!==undefined || !['x','y','z'].includes(raw.axis||'z')) throw new Error('Invalid cylinder region.');
+ const radius=number(raw.radius,parameters,'Region radius'),height=number(raw.height,parameters,'Region height');
+ if (radius<=0 || height<=0) throw new Error('Cylinder radius and height must be positive.');
+ region={shape:'cylinder',origin,radius,height,axis:raw.axis||'z'};
+ } else throw new Error('Region shape must be box or cylinder.');
+ let copies=[origin];
+ if (raw.repeat!==undefined) {
+ if (!Array.isArray(raw.repeat) || raw.repeat.length>2) throw new Error('Use up to two repeat axes for a region.');
+ for (const repeat of raw.repeat) {
+ fields(repeat,['count','step'],'region repeat');
+ const count=number(repeat.count,parameters,'Repeat count'),step=vector(repeat.step,parameters,'Repeat step');
+ integer(count,1,32,'Region repeat count');
+ if (copies.length*count>64) throw new Error('A region can contain at most 64 repeated probes.');
+ copies=copies.flatMap(point=>Array.from({length:count},(_,i)=>point.map((value,axis)=>value+i*step[axis])));
+ }
+ }
+ region.origins=copies; return region;
+}
+export function regionScad(region) {
+ const literal=value=>JSON.stringify(value);
+ const primitive=region.shape==='box'?'cube('+literal(region.size)+');':
+ (region.axis==='x'?'rotate([0,90,0]) ':region.axis==='y'?'rotate([-90,0,0]) ':'')+'cylinder(r='+region.radius+',h='+region.height+',$fn=128);';
+ return 'union() {\n'+region.origins.map(origin=>'translate('+literal(origin)+') '+primitive).join('\n')+'\n}';
+}
+export function checkFor(check,parameters) {
+ const result={...check};
+ if (check.kind==='bounds') {
+ result.size=vector(check.size,parameters,'Required size',{positive:true});
+ result.origin=vector(check.origin,parameters,'Required origin');
+ result.tolerance=number(check.tolerance??.02,parameters,'Bounds tolerance');
+ if (result.tolerance<=0 || result.tolerance>1) throw new Error('Bounds tolerance must be greater than zero and no more than 1 mm.');
+ }
+ if (check.kind==='volume') {
+ if (!Array.isArray(check.range) || check.range.length!==2) throw new Error('Volume range needs minimum and maximum.');
+ result.range=check.range.map(value=>number(value,parameters,'Volume limit'));
+ if (result.range[0]<=0 || result.range[1]<result.range[0]) throw new Error('Invalid volume range.');
+ }
+ if (['empty','contains'].includes(check.kind)) result.region=regionFor(check.region,parameters);
+ if (check.kind==='separated') {
+ result.translation=vector(check.translation||[0,0,0],parameters,'Second part translation');
+ result.rotation=vector(check.rotation||[0,0,0],parameters,'Second part rotation');
+ }
+ return result;
+}
+export function validateDesign(input) {
+ const design=structuredClone(input);
+ fields(design,['spec','title','brief','assumptions','assembly','sourceFiles','parameters','variants','parts','checks','process','preview'],'design');
+ if (design.spec!==1) throw new Error('design.json requires spec: 1.');
+ text(design.title,'title',100);text(design.brief,'brief',4000);
+ list(design.assumptions,'Assumptions');list(design.assembly,'Assembly/use instructions');
+ if (!Array.isArray(design.sourceFiles) || !design.sourceFiles.includes('model.scad') || !design.sourceFiles.includes('design.json') || design.sourceFiles.length>32) throw new Error('sourceFiles must include model.scad and design.json, with at most 32 files.');
+ const names=new Set();
+ for (const name of design.sourceFiles) {
+ if (typeof name!=='string' || name.length>180 || !/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(name) || name.split('/').some(component=>!component || component.startsWith('.')) || !/\.(scad|json|stl|svg|dxf|txt|md)$/i.test(name) || /^(handoff|rebuild)(\/|$)/i.test(name) || /^(part\.stl|preview\.scad|rebuild\.md)$/i.test(name)) throw new Error('Unsafe or reserved source path: '+name);
+ if (names.has(name.toLowerCase())) throw new Error('Duplicate source path: '+name);
+ names.add(name.toLowerCase());
+ }
+ if (!design.parameters || typeof design.parameters!=='object' || Array.isArray(design.parameters) || !Object.keys(design.parameters).length || Object.keys(design.parameters).length>64) throw new Error('Use 1–64 named numeric parameters.');
+ for (const [name,definition] of Object.entries(design.parameters)) {
+ if (!variablePattern.test(name) || name==='id' || name.startsWith('harness_')) throw new Error('Invalid or reserved parameter name: '+name);
+ fields(definition,['value','min','max','unit','label'],'parameter '+name);
+ for (const field of ['value','min','max']) if (typeof definition[field]!=='number') throw new Error(name+' '+field+' must be a number.');
+ number(definition.min);number(definition.max);number(definition.value);
+ if (definition.unit==='count'&&!Number.isInteger(definition.value)) throw new Error(name+' default count must be an integer.');
+ if (definition.min>definition.max || definition.value<definition.min || definition.value>definition.max || !['mm','degrees','count','ratio'].includes(definition.unit)) throw new Error('Invalid limits, default or unit for '+name);
+ if (definition.label!==undefined) text(definition.label,'parameter label',100);
+ }
+ const variants=ids(design.variants,'variant'),parts=ids(design.parts,'part');
+ integer(variants.size,1,4,'Variants');integer(parts.size,1,8,'Parts');
+ const exportNames=new Set();
+ for (const variant of variants) for (const part of parts) {
+ const name=variant+'-'+part;
+ if (exportNames.has(name)) throw new Error('Ambiguous variant/part export name: '+name+'. Choose distinct IDs.');
+ exportNames.add(name);
+ }
+ for (const variant of design.variants) {
+ fields(variant,['id','label','values','notes'],'variant');
+ text(variant.label,'variant label',100);list(variant.notes,'Variant notes');
+ if (!variant.values || typeof variant.values!=='object' || Array.isArray(variant.values)) throw new Error('Variant values must be an object.');
+ }
+ for (const part of design.parts) {
+ fields(part,['id','label','quantity','printRotation','shells','views','notes'],'part');
+ text(part.label,'part label',100);list(part.notes,'Part notes');
+ integer(part.quantity,1,100,'Part quantity');integer(part.shells,1,16,'Expected connected surface shells');
+ part.printRotation=vector(part.printRotation,{},'Print rotation');
+ fields(part.views,['top','front','side'],'part views');
+ for (const name of ['top','front','side']) {
+ fields(part.views[name],['at'],'view '+name);
+ // at=null is an external silhouette; a numeric expression is a section.
+ if (part.views[name].at===undefined) throw new Error('Each view declares at (section plane), or null for a silhouette.');
+ }
+ }
+ fields(design.preview,['variant','part'],'preview');
+ if (!variants.has(design.preview.variant)||!parts.has(design.preview.part)) throw new Error('Preview must name an exported variant and part.');
+ fields(design.process,['material','bedMM','edgeMarginMM','nozzleMM','notes'],'process');
+ text(design.process.material,'material',100);list(design.process.notes,'Process notes');
+ design.process.bedMM=vector(design.process.bedMM,{},'Printer build envelope',{positive:true});
+ design.process.edgeMarginMM=number(design.process.edgeMarginMM);design.process.nozzleMM=number(design.process.nozzleMM);
+ if (design.process.edgeMarginMM<0 || design.process.nozzleMM<=0) throw new Error('Review edge margin and nozzle diameter.');
+ const checks=ids(design.checks,'check');integer(checks.size,1,32,'Checks');
+ const checkNames=new Set();
+ for (const variant of variants) {
+ for (const name of [...checks,...[...parts].flatMap(part=>['topology','reopen','bed'].map(suffix=>part+'-'+suffix))]) {
+ const id=variant+'-'+name;
+ if (checkNames.has(id)) throw new Error('Duplicate or reserved generated check ID: '+id);
+ checkNames.add(id);
+ }
+ }
+ const permitted={
+ bounds:['size','origin','tolerance'],volume:['range'],empty:['region'],contains:['region'],separated:['other','translation','rotation']
+ };
+ for (const check of design.checks) {
+ if (!Object.hasOwn(permitted,check.kind)) throw new Error('Unknown check kind: '+check.kind);
+ fields(check,['id','label','kind','part',...permitted[check.kind]],'check '+check.id);
+ text(check.label,'check label',200);
+ if (!parts.has(check.part) || check.kind==='separated' && (!parts.has(check.other) || check.other===check.part)) throw new Error('Check names an unknown or identical second part.');
+ }
+ for (const part of design.parts) if (!design.checks.some(check=>check.part===part.id && check.kind==='bounds')) throw new Error('Every part needs a saved bounds requirement: '+part.id);
+ for (const variant of design.variants) {
+ const parameters=parametersFor(design,variant);
+ for (const part of design.parts) for (const view of Object.values(part.views)) if (view.at!==null) number(view.at,parameters,'Section position');
+ for (const check of design.checks) checkFor(check,parameters);
+ }
+ return design;
+}
diff --git a/store/agents/openscad/skills/openscad/scripts/expression.mjs b/store/agents/openscad/skills/openscad/scripts/expression.mjs
new file mode 100644
index 000000000..ffb6af5df
--- /dev/null
+++ b/store/agents/openscad/skills/openscad/scripts/expression.mjs
@@ -0,0 +1,49 @@
+// Bounded arithmetic for saved geometric requirements; no JavaScript evaluation.
+export function number(value, parameters={}, label='measurement') {
+ if (typeof value==='number') {
+ if (!Number.isFinite(value) || Math.abs(value)>1e7) throw new Error(label+' must be finite and within ±10,000,000.');
+ return value;
+ }
+ if (typeof value!=='string' || !value.trim() || value.length>300) throw new Error('Invalid '+label+' expression.');
+ const tokens=[]; let cursor=0;
+ const pattern=/\s*(?:(\d+(?:\.\d+)?|\.\d+)|([a-zA-Z_][a-zA-Z0-9_]*)|([()+*/-]))/y;
+ while (cursor<value.trimEnd().length) {
+ pattern.lastIndex=cursor; const match=pattern.exec(value);
+ if (!match) throw new Error('Unsupported '+label+' expression near '+value.slice(cursor));
+ tokens.push(match[1]!==undefined?{numeric:Number(match[1])}:match[2]!==undefined?{name:match[2]}:{op:match[3]});
+ cursor=pattern.lastIndex;
+ if (tokens.length>128) throw new Error(label+' expression is too long.');
+ }
+ let index=0,depth=0;
+ const primary=()=>{
+ if (++depth>24) throw new Error(label+' expression is too deeply nested.');
+ const token=tokens[index++]; let result;
+ if (token?.op==='+' || token?.op==='-') result=(token.op==='-'?-1:1)*primary();
+ else if (token?.op==='(') {
+ result=add();
+ if (tokens[index++]?.op!==')') throw new Error('Missing closing parenthesis in '+label);
+ } else if (token?.numeric!==undefined) result=token.numeric;
+ else if (token?.name!==undefined && Object.hasOwn(parameters,token.name)) result=parameters[token.name];
+ else throw new Error('Unknown value in '+label+': '+(token?.name||token?.op||'end of expression'));
+ depth--; return result;
+ };
+ const multiply=()=>{
+ let result=primary();
+ while (['*','/'].includes(tokens[index]?.op)) { const op=tokens[index++].op, right=primary();result=op==='*'?result*right:result/right; }
+ return result;
+ };
+ const add=()=>{
+ let result=multiply();
+ while (['+','-'].includes(tokens[index]?.op)) { const op=tokens[index++].op, right=multiply();result=op==='+'?result+right:result-right; }
+ return result;
+ };
+ const result=add();
+ if (index!==tokens.length) throw new Error('Unexpected token in '+label);
+ return number(result,{},label);
+}
+export function vector(value,parameters,label,{positive=false}={}) {
+ if (!Array.isArray(value) || value.length!==3) throw new Error(label+' needs three coordinates.');
+ const result=value.map((item,axis)=>number(item,parameters,label+'['+axis+']'));
+ if (positive && result.some(value=>value<=0)) throw new Error(label+' must be positive.');
+ return result;
+}
diff --git a/store/agents/openscad/skills/openscad/scripts/files.mjs b/store/agents/openscad/skills/openscad/scripts/files.mjs
new file mode 100644
index 000000000..ecdb80822
--- /dev/null
+++ b/store/agents/openscad/skills/openscad/scripts/files.mjs
@@ -0,0 +1,72 @@
+import {readFile,writeFile,mkdir,mkdtemp,lstat,realpath,rename,copyFile,rm} from 'node:fs/promises';
+import {createHash} from 'node:crypto';
+import {join,dirname,basename,sep} from 'node:path';
+export const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
+export const json=value=>JSON.stringify(value,null,2)+'\n';
+export async function exists(path) {
+ try {await lstat(path);return true;}catch(error){if(error.code==='ENOENT')return false;throw error;}
+}
+export async function source(workspace,name) {
+ let path=workspace;
+ for(const component of name.split('/')){
+ path=join(path,component);
+ if((await lstat(path)).isSymbolicLink())throw new Error('Source symlinks are not portable: '+name);
+ }
+ const info=await lstat(path);
+ if(!info.isFile()||info.size>8*1024*1024)throw new Error('Source must be a regular file no larger than 8 MiB: '+name);
+ if(!(await realpath(path)).startsWith(await realpath(workspace)+sep))throw new Error('Source escapes workspace: '+name);
+ return readFile(path);
+}
+export async function snapshot(workspace,names) {
+ const files=[];let total=0;
+ for(const name of names){const bytes=await source(workspace,name);total+=bytes.length;files.push({name,bytes});}
+ if(total>16*1024*1024)throw new Error('Sources exceed 16 MiB.');
+ return files;
+}
+export async function unchanged(workspace,files) {
+ for(const file of files)if(sha(await source(workspace,file.name))!==sha(file.bytes))throw new Error('Source changed during build; rebuild the saved project: '+file.name);
+}
+export async function save(path,bytes) {
+ await mkdir(dirname(path),{recursive:true});await writeFile(path,bytes);
+}
+export async function atomic(path,bytes) {
+ const temp=path+'.'+process.pid+'.tmp';await writeFile(temp,bytes);await rename(temp,path);
+}
+export async function publish(workspace,state,stage,names) {
+ const history=join(state,'history',basename(stage));await mkdir(history,{recursive:true});
+ const saved=[],installed=[];
+ try {
+ if(await exists(join(state,'mesh.json')))await copyFile(join(state,'mesh.json'),join(history,'mesh.json'));
+ for(const name of names){
+ if(await exists(join(workspace,name))){await rename(join(workspace,name),join(history,name));saved.push(name);}
+ await rename(join(stage,name),join(workspace,name));installed.push(name);
+ }
+ return history;
+ }catch(error){
+ const failures=[];
+ for(const name of installed.reverse())try{await rename(join(workspace,name),join(stage,name));}catch(error){failures.push(error.message);}
+ for(const name of saved.reverse())try{await rename(join(history,name),join(workspace,name));}catch(error){failures.push(error.message);}
+ if(failures.length)throw new Error('Publication failed; recover saved artifacts from '+history+': '+failures.join('; '));
+ throw error;
+ }
+}
+export async function transaction(workspace,run) {
+ const state=join(workspace,'.harness');
+ if(await exists(state)&&(await lstat(state)).isSymbolicLink())throw new Error('.harness must not be a symlink.');
+ await mkdir(state,{recursive:true});
+ const lock=join(state,'openscad-build.lock');
+ try{await mkdir(lock);}catch(error){if(error.code==='EEXIST')throw new Error('Another build owns .harness/openscad-build.lock. Confirm its process has stopped before removing a stale lock.');throw error;}
+ let stage;
+ const verdict=value=>atomic(join(state,'verdict.json'),json({spec:1,ready:false,findings:[],artifact:null,...value,updatedAt:new Date().toISOString()}));
+ try{
+ await writeFile(join(lock,'owner.json'),json({pid:process.pid,startedAt:new Date().toISOString()}));
+ await verdict({summary:'Building fresh variants and measuring the saved requirements'});
+ stage=await mkdtemp(join(state,'openscad-'));
+ return await run({state,stage,verdict});
+ }catch(error){
+ await verdict({summary:'OpenSCAD build failed',findings:[{severity:'error',kind:'build',message:error.message}]});throw error;
+ }finally{
+ if(stage)await rm(stage,{recursive:true,force:true});
+ await rm(lock,{recursive:true,force:true});
+ }
+}
diff --git a/store/agents/openscad/skills/openscad/scripts/handoff.css b/store/agents/openscad/skills/openscad/scripts/handoff.css
new file mode 100644
index 000000000..6ba9a5d2a
--- /dev/null
+++ b/store/agents/openscad/skills/openscad/scripts/handoff.css
@@ -0,0 +1,6 @@
+:root{color-scheme:dark;--bg:#111b20;--panel:#19262b;--line:#304147;--muted:#a8bbc1;--ink:#f0f5f3;--accent:#cafa88}
+.family-comparison{border-top:0;margin:0 0 18px;padding:0}.family-comparison .table-scroll{margin-top:12px;margin-bottom:14px}
+*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.6 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}a{color:var(--accent);text-underline-offset:3px}button,a{touch-action:manipulation}button:focus-visible,a:focus-visible,summary:focus-visible{outline:3px solid var(--accent);outline-offset:5px}header,main,footer{max-width:1280px;margin:auto;padding:30px 48px}header{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);gap:20px}.brand{display:flex;align-items:center;gap:12px;font-size:13px;letter-spacing:.1em;font-weight:700}.mark{color:var(--accent);font-size:28px;line-height:1}.snapshot{font-size:12px;color:var(--muted)}.hero{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:44px;align-items:center;padding:20px 0 32px}.eyebrow{color:var(--accent);font-size:10px;letter-spacing:.16em;font-weight:750;margin:0 0 10px}h1{font-size:clamp(30px,3.5vw,46px);line-height:1.1;letter-spacing:-.04em;margin:0 0 18px;max-width:800px}h2{font-size:27px;letter-spacing:-.025em;margin:0}h3{font-size:24px;letter-spacing:-.025em;margin:0}.brief{max-width:850px;color:var(--muted);font-size:16px;margin:0}.button{display:inline-flex;align-items:center;justify-content:center;gap:20px;background:var(--accent);color:#172319;text-decoration:none;font-size:13px;font-weight:750;padding:12px 18px;border:1px solid var(--accent);border-radius:8px;white-space:nowrap}.primary .button{font-size:14px;padding:15px 22px}.primary p{font-size:11px;text-align:center;color:var(--muted);margin:10px 0 0}.metrics{display:grid;grid-template-columns:repeat(4,1fr);border:1px solid var(--line);border-radius:12px;overflow:hidden;margin-bottom:35px}.metrics>div{padding:19px 24px;border-right:1px solid var(--line);background:var(--panel)}.metrics>div:last-child{border:0}.metrics b{font-size:23px;font-weight:600;display:block;line-height:1.3}.metrics span{font-size:11px;color:var(--muted)}.pass{color:var(--accent)}.section-heading,.part-heading{display:flex;justify-content:space-between;align-items:center;gap:20px}.section-heading{margin:32px 0 14px}.section-heading .eyebrow{color:var(--muted)}.pill{border:1px solid var(--line);border-radius:50px;padding:6px 12px;font-size:11px;color:var(--muted);white-space:nowrap}.table-scroll{overflow-x:auto;border:1px solid var(--line);border-radius:10px;margin-bottom:30px}table{width:100%;border-collapse:collapse;font-size:12px}th,td{text-align:left;padding:14px 18px;border-bottom:1px solid var(--line);vertical-align:top}thead{background:var(--panel);color:var(--muted);font-size:10px;text-transform:uppercase;letter-spacing:.07em}tbody tr:last-child>*{border-bottom:0}th{font-weight:650}td small{color:var(--muted)}.tabs{display:flex;gap:8px;flex-wrap:wrap}.tabs button{border:1px solid var(--line);border-radius:8px;background:transparent;color:var(--muted);font:600 13px system-ui;padding:10px 18px;cursor:pointer}.tabs button[aria-pressed=true]{background:var(--accent);color:#172319;border-color:var(--accent)}.parameters{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px;margin:22px 0}.parameters>div{border-left:2px solid var(--line);padding-left:12px}.parameters span{display:block;font-size:10px;text-transform:uppercase;color:var(--muted);letter-spacing:.03em}.parameters strong{font-size:17px;font-weight:550}.parameters small{font-weight:400;font-size:11px;color:var(--muted)}.part{padding:26px;background:var(--panel);border:1px solid var(--line);border-radius:12px;margin-top:22px}.part .button{background:transparent;color:var(--accent)}.part-facts{display:flex;flex-wrap:wrap;gap:24px;color:var(--muted);font-size:11px;margin:20px 0}.part-facts b{color:var(--ink);font-weight:550}.views{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}figure{margin:0;min-width:0}.view{height:190px;display:flex;align-items:center;justify-content:center;background:#edf1e9;border-radius:7px;padding:24px}.view img{max-height:100%;max-width:100%;width:100%;height:100%;object-fit:contain}figcaption{display:flex;justify-content:space-between;gap:10px;font-size:9px;color:var(--muted);padding-top:9px;text-transform:uppercase;letter-spacing:.02em}.caption{font-size:11px;color:var(--muted);margin:18px 0 0}ul{padding-left:20px;color:var(--muted);font-size:13px}details{border-top:1px solid var(--line);padding-top:14px;margin-top:20px;font-size:12px}summary{cursor:pointer;font-size:12px;font-weight:650;min-height:28px}.hash{font:10px/1.7 ui-monospace,monospace;overflow-wrap:anywhere;color:var(--muted)}.check{display:flex;gap:12px;padding:13px 0;border-bottom:1px solid var(--line)}.check b{font-size:12px}.check p{color:var(--muted);margin:3px 0 0;font-size:11px}.notes-grid{display:grid;grid-template-columns:1fr 1fr;gap:24px;border-top:1px solid var(--line);margin-top:34px;padding-top:22px}.notes-grid h3{font-size:17px}.notice{padding:18px 22px;border-left:3px solid var(--accent);background:var(--panel);margin-top:28px}.notice b{font-size:13px}.notice p{font-size:11px;color:var(--muted);margin:7px 0}.muted{color:var(--muted)}footer{padding-top:4px;font-size:11px;color:var(--muted)}footer a{margin-right:20px}.footer-row{display:flex;justify-content:space-between;gap:14px;flex-wrap:wrap}
+@media(max-width:760px){header,main,footer{padding:22px 20px}.hero{grid-template-columns:1fr;gap:22px;padding-top:10px}.primary p{text-align:left}.metrics{grid-template-columns:1fr 1fr}.metrics>div{padding:16px;border-bottom:1px solid var(--line)}.metrics>div:nth-child(2){border-right:0}.metrics>div:nth-child(3){border-bottom:0}.section-heading{align-items:flex-start;flex-direction:column;gap:10px}.part{padding:18px}.part-heading{align-items:flex-start;flex-direction:column;gap:14px}.views{grid-template-columns:1fr}.view{height:190px}figcaption{font-size:10px}.notes-grid{grid-template-columns:1fr;gap:14px}.snapshot{max-width:140px;text-align:right}.parameters{grid-template-columns:1fr 1fr}.part-facts{gap:9px;flex-direction:column}h3{font-size:22px}}
+@media print{body{background:white;color:black}.tabs,.button{display:none}.variant[hidden]{display:block}.part,.metrics>div,.notice{background:white}main,header,footer{padding:15px}.views{break-inside:avoid}.muted,.caption,li,.brief{color:#333}.pass{color:#286229}}
+@media(min-width:761px){header{padding-top:20px;padding-bottom:20px}main{padding-top:20px}.hero{padding-top:12px;padding-bottom:20px}.metrics{margin-bottom:20px}.metrics>div{padding-top:14px;padding-bottom:14px}.section-heading{margin-top:24px;margin-bottom:10px}.parameters{margin-top:14px;margin-bottom:14px}}
diff --git a/store/agents/openscad/skills/openscad/scripts/handoff.js b/store/agents/openscad/skills/openscad/scripts/handoff.js
new file mode 100644
index 000000000..4523677f3
--- /dev/null
+++ b/store/agents/openscad/skills/openscad/scripts/handoff.js
@@ -0,0 +1,6 @@
+for(const button of document.querySelectorAll('[data-variant]')){
+ button.addEventListener('click',()=>{
+ for(const tab of document.querySelectorAll('[data-variant]'))tab.setAttribute('aria-pressed',String(tab===button));
+ for(const panel of document.querySelectorAll('[data-panel]'))panel.hidden=panel.dataset.panel!==button.dataset.variant;
+ });
+}
diff --git a/store/agents/openscad/skills/openscad/scripts/handoff.mjs b/store/agents/openscad/skills/openscad/scripts/handoff.mjs
new file mode 100644
index 000000000..554e232a0
--- /dev/null
+++ b/store/agents/openscad/skills/openscad/scripts/handoff.mjs
@@ -0,0 +1,19 @@
+import {readFileSync} from 'node:fs';
+const esc=value=>String(value).replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('"','&quot;').replaceAll("'",'&#39;');
+const fmt=value=>Number(value.toFixed(2)).toLocaleString('en-US');
+const size=mesh=>mesh.bounds.size.map(fmt).join(' × ');
+const notes=items=>'<ul>'+items.map(note=>'<li>'+esc(note)+'</li>').join('')+'</ul>';
+export function handoff(report){
+ const design=report.design,total=report.checks.length;
+ const differing=Object.keys(design.parameters).filter(name=>new Set(report.variants.map(variant=>variant.parameters[name])).size>1);
+ const checksFor=variant=>report.checks.filter(c=>c.variant===variant.id);
+ const compare=report.variants.map(variant=>'<tr><th scope="row">'+esc(variant.label)+'</th>'+differing.map(name=>'<td>'+fmt(variant.parameters[name])+' <small>'+esc(design.parameters[name].unit)+'</small></td>').join('')+'<td>'+variant.parts.map(part=>esc(part.label)+': '+size(part.printMesh)+' mm').join('<br>')+'</td><td class="pass">All passed</td></tr>').join('');
+ const tabs=report.variants.map((variant,i)=>'<button type="button" data-variant="'+variant.id+'" aria-pressed="'+(variant.id===design.preview.variant)+'">'+esc(variant.label)+'</button>').join('');
+ const panels=report.variants.map((variant,i)=>'<section class="variant" id="variant-'+variant.id+'" data-panel="'+variant.id+'"'+(variant.id===design.preview.variant?'':' hidden')+'><div class="section-heading"><div><p class="eyebrow">SAVED CONFIGURATION</p><h2>'+esc(variant.label)+'</h2></div><span class="pill">'+variant.parts.length+' part'+(variant.parts.length>1?'s':'')+' · '+checksFor(variant).length+' passed checks</span></div>'+
+ (variant.notes.length?'<p class="muted">'+variant.notes.map(esc).join(' ')+'</p>':'')+
+ '<div class="parameters">'+Object.entries(variant.parameters).map(([name,value])=>'<div><span>'+esc(design.parameters[name].label||name.replaceAll('_',' '))+'</span><strong>'+fmt(value)+' <small>'+esc(design.parameters[name].unit)+'</small></strong></div>').join('')+'</div>'+
+ variant.parts.map(part=>'<article class="part"><div class="part-heading"><div><p class="eyebrow">PART · '+esc(part.id)+'</p><h3>'+esc(part.label)+'</h3></div><a class="button" download href="'+part.path.replace('handoff/','')+'">Download STL <span aria-hidden="true">↗</span></a></div><div class="part-facts"><span><b>'+size(part.printMesh)+'</b> mm · print size</span><span><b>'+fmt(part.mesh.volumeMM3/1000)+'</b> cm³ · model volume</span><span><b>'+part.quantity+'</b> needed · print separately</span></div><div class="views">'+part.views.map(view=>'<figure><div class="view"><img src="'+view.path.replace('handoff/','')+'" alt="'+esc(part.label+' '+view.name+' '+(view.at===null?'silhouette':'section at '+fmt(view.at)+' mm'))+'"></div><figcaption><span>'+view.name+' · '+view.axes+'</span><span>'+(view.at===null?'Silhouette':'Section @ '+fmt(view.at)+' mm')+'</span></figcaption></figure>').join('')+'</div><p class="caption">Reference views use design coordinates. The STL is rotated ['+part.printRotation.join(', ')+']° and moved onto the bed. Inspect the actual mesh in the CAD Viewer before slicing.</p>'+
+ (part.notes.length?notes(part.notes):'')+'<details><summary>Part dimensions &amp; file identity</summary><p>Design bounds: '+size(part.mesh)+' mm. Minimum corner: ['+part.mesh.bounds.min.map(fmt).join(', ')+'] mm.</p><p>'+part.mesh.triangles.toLocaleString('en-US')+' triangles · '+part.mesh.shells.length+' connected surface shell(s) · closed, positively oriented mesh.</p><p class="hash">STL SHA-256: '+part.sha256+'</p><a download href="source-previews/'+variant.id+'-'+part.id+'.scad">Editable configuration wrapper</a> <span class="muted">(use inside the complete project)</span></details></article>').join('')+
+ '<details class="checks"><summary>'+checksFor(variant).length+' measured checks — inspect the evidence</summary><div>'+checksFor(variant).map(check=>'<div class="check"><span class="pass" aria-label="Passed">✓</span><div><b>'+esc(check.label)+'</b><p>'+esc(check.detail)+'</p></div></div>').join('')+'</div></details></section>').join('');
+ return '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>'+esc(design.title)+' · OpenSCAD</title><style>'+readFileSync(new URL('handoff.css',import.meta.url),'utf8')+'</style><script defer src="app.js"></script></head><body><header><div class="brand"><span class="mark" aria-hidden="true">⬡</span> OPENSCAD / WORKSHOP</div><div class="snapshot">Saved build · '+esc(report.engine.replace('OpenSCAD version ',''))+'<br>Revision '+report.sourceRevision.slice(0,12)+'</div></header><main><section class="hero"><div><p class="eyebrow">YOUR MEASUREMENTS. A FAMILY OF PARTS.</p><h1>'+esc(design.title)+'</h1><p class="brief">'+esc(design.brief)+'</p></div><div class="primary"><a class="button" href="project.zip" download>Download complete project <span aria-hidden="true">↓</span></a><p>Editable source · every STL · rebuild tools</p></div></section><div class="metrics"><div><b>'+report.variants.length+'</b><span>saved size / fit variants</span></div><div><b>'+design.parts.length+'</b><span>unique parts per variant</span></div><div><b class="pass">'+total+' / '+total+'</b><span>measured checks passed</span></div><div><b>'+esc(design.process.material)+'</b><span>'+fmt(design.process.nozzleMM)+' mm nozzle · declared process</span></div></div><div class="section-heading"><h2>Compare the family</h2><span class="pill">Individual fit · '+design.process.bedMM.map(fmt).join(' × ')+' mm build envelope</span></div><details class="family-comparison"><summary>Compare dimensions across all configurations</summary><div class="table-scroll"><table><thead><tr><th scope="col">Configuration</th>'+differing.map(name=>'<th scope="col">'+esc(design.parameters[name].label||name.replaceAll('_',' '))+'</th>').join('')+'<th scope="col">Oriented part dimensions</th><th scope="col">Requirements</th></tr></thead><tbody>'+compare+'</tbody></table></div></details><div class="tabs" role="group" aria-label="Choose configuration">'+tabs+'</div>'+panels+'<section class="notes-grid"><div><h3>Measured brief &amp; assumptions</h3>'+notes(design.assumptions)+'</div><div><h3>Make &amp; use</h3>'+notes([...design.process.notes,...design.assembly])+'</div></section><aside class="notice"><b>Checked geometry. Physical validation still matters.</b>'+report.limitations.map(item=>'<p>'+esc(item)+'</p>').join('')+'<p>This is the last successful build, not a live view of current source edits. Rebuild before using a changed design.</p></aside></main><footer><div class="footer-row"><div><a href="checks.json" download>Download measured report</a><a href="project.zip" download>Portable project</a></div><span>Native OpenSCAD · no cloud dependency</span></div><p class="hash">Source SHA-256: '+report.sourceRevision+'</p></footer></body></html>';
+}
diff --git a/store/agents/openscad/skills/openscad/scripts/mesh.mjs b/store/agents/openscad/skills/openscad/scripts/mesh.mjs
index 20915e83e..87d4dbdec 100644
--- a/store/agents/openscad/skills/openscad/scripts/mesh.mjs
+++ b/store/agents/openscad/skills/openscad/scripts/mesh.mjs
@@ -1,31 +1,63 @@
-// Inspect the exported mesh, not OpenSCAD's exit code. Coordinates are millimetres.
-export function inspectSTL(buffer) {
- const triangles=[];
+// Inspect exported triangles, not a compiler exit code. All coordinates are mm.
+const cross=(a,b)=>[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]];
+export function parseSTL(input) {
+ const buffer=Buffer.from(input),triangles=[];
+ if(buffer.length>64*1024*1024)throw new Error('STL exceeds 64 MiB.');
if(buffer.length>=84 && buffer.readUInt32LE(80)*50+84===buffer.length){
+ if(buffer.readUInt32LE(80)>1000000)throw new Error('STL exceeds one million triangles.');
for(let i=84;i<buffer.length;i+=50)triangles.push([0,1,2].map(v=>[0,1,2].map(axis=>buffer.readFloatLE(i+12+v*12+axis*4))));
}else{
const source=buffer.toString('utf8');
if(!/^\s*solid\b/.test(source)||!/endsolid\b/.test(source))throw new Error('The export is not a complete STL.');
- const vertices=[...source.matchAll(/\bvertex\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)/g)].map(match=>match.slice(1).map(Number));
+ const vertices=[];
+ for(const match of source.matchAll(/\bvertex\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)/g)){
+ vertices.push(match.slice(1).map(Number));
+ if(vertices.length>3000000)throw new Error('STL exceeds one million triangles.');
+ }
if(vertices.length%3)throw new Error('The STL has an incomplete triangle.');
for(let i=0;i<vertices.length;i+=3)triangles.push(vertices.slice(i,i+3));
}
+ if(!triangles.length)throw new Error('The STL is empty.');
+ if(triangles.some(face=>face.some(point=>point.some(value=>!Number.isFinite(value)||Math.abs(value)>1e8))))throw new Error('STL coordinates must be finite and within ±100,000,000 mm.');
+ return triangles;
+}
+export function inspectTriangles(triangles) {
if(!triangles.length)throw new Error('The STL is empty.');
const min=[Infinity,Infinity,Infinity],max=[-Infinity,-Infinity,-Infinity],edges=new Map();
+ const parents=Array.from({length:triangles.length},(_,i)=>i);
+ const root=index=>{while(parents[index]!==index){parents[index]=parents[parents[index]];index=parents[index];}return index;};
let signedVolume=0,area=0,degenerateTriangles=0;
- const cross=(a,b)=>[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]];
- for(const vertices of triangles){
- if(vertices.some(point=>point.some(value=>!Number.isFinite(value))))throw new Error('The STL contains non-finite coordinates.');
+ const volumes=[];
+ for(const [index,vertices] of triangles.entries()){
for(const point of vertices)point.forEach((value,axis)=>{min[axis]=Math.min(min[axis],value);max[axis]=Math.max(max[axis],value);});
const [a,b,c]=vertices,normal=cross(b.map((v,i)=>v-a[i]),c.map((v,i)=>v-a[i])),faceArea=Math.hypot(...normal)/2;
area+=faceArea;if(faceArea<1e-10)degenerateTriangles++;
- const bc=cross(b,c);signedVolume+=a.reduce((sum,value,i)=>sum+value*bc[i],0)/6;
- const keys=vertices.map(point=>point.map(value=>value.toFixed(5)).join(','));
+ const bc=cross(b,c),volume=a.reduce((sum,value,i)=>sum+value*bc[i],0)/6;signedVolume+=volume;volumes.push(volume);
+ // Normalize -0 so welding does not split a face across the origin.
+ const keys=vertices.map(point=>point.map(value=>Number(value.toFixed(5))).join(','));
for(let i=0;i<3;i++){
const a=keys[i],b=keys[(i+1)%3],key=a<b?a+'|'+b:b+'|'+a;
- const edge=edges.get(key)||{count:0,balance:0};edge.count++;edge.balance+=a<b?1:-1;edges.set(key,edge);
+ const edge=edges.get(key)||{count:0,balance:0,face:index};
+ edge.count++;edge.balance+=a<b?1:-1;edges.set(key,edge);
+ parents[root(index)]=root(edge.face);
}
}
const nonManifoldEdges=[...edges.values()].filter(edge=>edge.count!==2||edge.balance!==0).length;
- return {triangles:triangles.length,bounds:{min,max,size:max.map((v,i)=>v-min[i])},volumeMM3:Math.abs(signedVolume),areaMM2:area,degenerateTriangles,nonManifoldEdges,watertight:!nonManifoldEdges&&!degenerateTriangles};
+ const shells=new Map();
+ triangles.forEach((_face,index)=>{
+ const id=root(index),shell=shells.get(id)||{triangles:0,orientedVolumeMM3:0};
+ shell.triangles++;shell.orientedVolumeMM3+=volumes[index];shells.set(id,shell);
+ });
+ return {triangles:triangles.length,bounds:{min,max,size:max.map((v,i)=>v-min[i])},volumeMM3:Math.abs(signedVolume),orientedVolumeMM3:signedVolume,areaMM2:area,degenerateTriangles,nonManifoldEdges,watertight:!nonManifoldEdges&&!degenerateTriangles,shells:[...shells.values()]};
+}
+export function inspectSTL(buffer) {return inspectTriangles(parseSTL(buffer));}
+export function binarySTL(triangles,translation=[0,0,0]) {
+ if(!triangles.length||triangles.length>1000000)throw new Error('Invalid triangle count.');
+ const buffer=Buffer.alloc(84+triangles.length*50);buffer.write('OpenHarness / millimetres / actual exported geometry');buffer.writeUInt32LE(triangles.length,80);
+ triangles.forEach((face,index)=>{
+ const [a,b,c]=face,normal=cross(b.map((v,i)=>v-a[i]),c.map((v,i)=>v-a[i])),length=Math.hypot(...normal);
+ for(let axis=0;axis<3;axis++)buffer.writeFloatLE(length?normal[axis]/length:0,84+index*50+axis*4);
+ face.forEach((point,vertex)=>point.forEach((value,axis)=>buffer.writeFloatLE(value+translation[axis],84+index*50+12+vertex*12+axis*4)));
+ });
+ return buffer;
}
diff --git a/store/agents/openscad/skills/openscad/scripts/native.mjs b/store/agents/openscad/skills/openscad/scripts/native.mjs
new file mode 100644
index 000000000..df78a4a49
--- /dev/null
+++ b/store/agents/openscad/skills/openscad/scripts/native.mjs
@@ -0,0 +1,74 @@
+import {readFile,writeFile,lstat,realpath} from 'node:fs/promises';
+import {spawnSync} from 'node:child_process';
+import {join,resolve} from 'node:path';
+
+// Parse OpenSCAD's make-style dependency output, including escaped spaces.
+export function dependencies(text) {
+ const joined=text.replace(/\\\r?\n/g,'');
+ const separator=joined.indexOf(': ');
+ if (separator<0) throw new Error('Invalid OpenSCAD dependency receipt.');
+ const result=[];let token='',escaped=false;
+ for (const char of joined.slice(separator+2)) {
+ if (escaped) {token+=char;escaped=false;}
+ else if (char==='\\') escaped=true;
+ else if (/\s/.test(char)) {if(token){result.push(token);token='';}}
+ else token+=char;
+ }
+ if (escaped) throw new Error('Incomplete dependency path.');
+ if(token)result.push(token);
+ if(!result.length)throw new Error('Empty OpenSCAD dependency receipt.');
+ return result;
+}
+export class Native {
+ constructor(bin,directory) {this.bin=bin;this.directory=directory;this.log='';this.serial=0;this.started=Date.now();}
+ version() {
+ const result=spawnSync(this.bin,['--version'],{cwd:this.directory,encoding:'utf8',timeout:10000,maxBuffer:1024*1024});
+ const output=(result.stdout||'')+(result.stderr||'');this.log+=output;
+ if(result.error||result.status!==0||!/^OpenSCAD version /m.test(output))throw new Error('OpenSCAD could not report its version: '+(result.error?.message||output));
+ return output.trim().split('\n')[0];
+ }
+ async render(label,code,{format='stl',emptyAllowed=false,allowedDependencies}={}) {
+ if(!/^[a-zA-Z0-9-]+$/.test(label)||!['stl','svg'].includes(format))throw new Error('Invalid native export request.');
+ if(Date.now()-this.started>600000)throw new Error('The checked build exceeded ten minutes. Simplify or split the variant batch.');
+ const name=String(++this.serial).padStart(3,'0')+'-'+label;
+ const source=join(this.directory,name+'.scad'),output=join(this.directory,name+'.'+format),deps=join(this.directory,name+'.deps');
+ await writeFile(source,code);
+ const args=['-o',output,'--hardwarnings','--check-parameters','true','--check-parameter-ranges','true'];
+ if(format==='stl')args.push('--export-format','binstl');
+ if(allowedDependencies)args.push('-d',deps);
+ args.push(source);
+ const result=spawnSync(this.bin,args,{cwd:this.directory,encoding:'utf8',timeout:180000,maxBuffer:10*1024*1024});
+ const message=(result.stdout||'')+(result.stderr||'');
+ this.log+='\n--- '+name+' ---\n'+message;
+ if(result.error)throw new Error(label+': '+result.error.message);
+ // An unknown module or an assertion can also produce "empty". Those are
+ // failures, never successful clearance/containment proofs.
+ if(/^\s*(?:ERROR|WARNING):/m.test(message))throw new Error(label+': OpenSCAD diagnostic; see .harness/build.log.');
+ let info;
+ try {info=await lstat(output);}catch(error){if(error.code!=='ENOENT')throw error;}
+ const empty=/^Current top level object is empty\.\s*$/m.test(message);
+ if(emptyAllowed && result.status===1 && empty && (!info || info.isFile()&&info.size===0))return {empty:true,bytes:null,file:null};
+ if(result.status!==0||empty||!info?.isFile()||info.isSymbolicLink()||!info.size)throw new Error(label+': no fresh '+format.toUpperCase()+' export (exit '+result.status+'). See .harness/build.log.');
+ if(info.size>64*1024*1024)throw new Error(label+': native export exceeds 64 MiB.');
+ if(allowedDependencies){
+ const permitted=new Set(await Promise.all([...allowedDependencies,source].map(path=>realpath(path))));
+ for(const path of dependencies(await readFile(deps,'utf8'))){
+ const actual=await realpath(resolve(this.directory,path));
+ if(!permitted.has(actual))throw new Error('Model read an undeclared dependency: '+path+'. Include it in sourceFiles and use a relative path.');
+ }
+ }
+ return {empty:false,file:output,bytes:await readFile(output)};
+ }
+}
+
+export function partCall(id,parameters) {
+ return 'part(id='+JSON.stringify(id)+Object.entries(parameters).map(([name,value])=>','+name+'='+JSON.stringify(value)).join('')+');';
+}
+export function imported(path) {
+ return 'import('+JSON.stringify(path.replaceAll('\\','/'))+');';
+}
+export function projection(mesh,view,at) {
+ const transform=view==='top'?'':view==='front'?'rotate([-90,0,0]) ':'multmatrix([[0,1,0,0],[0,0,1,0],[1,0,0,0],[0,0,0,1]]) ';
+ const translation=view==='top'?[0,0,-(at||0)]:view==='front'?[0,-(at||0),0]:[-(at||0),0,0];
+ return 'projection(cut='+(at!==null)+') '+transform+(at===null?'':'translate('+JSON.stringify(translation)+') ')+imported(mesh);
+}
diff --git a/store/agents/openscad/skills/openscad/scripts/serve-handoff.mjs b/store/agents/openscad/skills/openscad/scripts/serve-handoff.mjs
new file mode 100644
index 000000000..7a01b4d02
--- /dev/null
+++ b/store/agents/openscad/skills/openscad/scripts/serve-handoff.mjs
@@ -0,0 +1,57 @@
+// A loopback-only download page. Never serves a workspace directory listing or
+// arbitrary source files; the user-selected source bundle is an explicit export.
+import {createServer} from 'node:http';
+import {lstat, readFile, realpath} from 'node:fs/promises';
+import {join, resolve, sep, extname} from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const allowed = /^(?:part\.stl|handoff\/(?:index\.html|app\.js|checks\.json|project\.zip|parts\/[a-z0-9-]+\.stl|views\/[a-z0-9-]+\.svg|source-previews\/[a-z0-9-]+\.scad))$/;
+const types = {'.html':'text/html; charset=utf-8', '.js':'text/javascript; charset=utf-8', '.scad':'text/plain; charset=utf-8', '.json':'application/json; charset=utf-8', '.svg':'image/svg+xml', '.zip':'application/zip', '.step':'model/step', '.stl':'model/stl', '.FCStd':'application/octet-stream'};
+
+export async function serve(workspace, port=0) {
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('Port must be an integer from 0 to 65535');
+ const root = await realpath(resolve(workspace));
+ const server = createServer(async (request, response) => {
+ const actualPort = server.address().port;
+ if (![`127.0.0.1:${actualPort}`, `localhost:${actualPort}`].includes(request.headers.host)) {
+ response.writeHead(403).end('Loopback host required'); return;
+ }
+ if (!['GET','HEAD'].includes(request.method)) { response.writeHead(405, {Allow:'GET, HEAD'}).end(); return; }
+ try {
+ const path = decodeURIComponent(new URL(request.url, `http://127.0.0.1:${actualPort}`).pathname);
+ if (path === '/') { response.writeHead(302, {Location:'/handoff/index.html'}).end(); return; }
+ const name = path.slice(1);
+ if (!allowed.test(name)) { response.writeHead(404).end('Not a handoff artifact'); return; }
+ let target = root;
+ for (const component of name.split('/')) {
+ target = join(target, component);
+ if ((await lstat(target)).isSymbolicLink()) throw new Error('Symlink artifacts are not served');
+ }
+ if (!(await realpath(target)).startsWith(root + sep)) throw new Error('Artifact is outside the workspace');
+ const bytes = await readFile(target);
+ const extension = extname(name);
+ const headers = {
+ 'Content-Type':types[extension], 'Content-Length':bytes.length, 'Cache-Control':'no-store',
+ 'X-Content-Type-Options':'nosniff', 'Cross-Origin-Resource-Policy':'same-origin',
+ 'Content-Security-Policy':"default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; img-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
+ };
+ if (!['.html','.svg','.js'].includes(extension)) headers['Content-Disposition'] = `attachment; filename="${name.split('/').at(-1)}"`;
+ response.writeHead(200, headers).end(request.method === 'HEAD' ? undefined : bytes);
+ } catch (error) {
+ response.writeHead(404).end('Handoff artifact unavailable');
+ }
+ });
+ await new Promise((resolveReady,reject) => { server.once('error',reject); server.listen(port,'127.0.0.1',resolveReady); });
+ return server;
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ try {
+ const workspace = process.argv[2] || process.env.HARNESS_WORKSPACE || process.cwd();
+ const server = await serve(workspace, Number(process.argv[3] || 0));
+ console.log(`Saved OpenSCAD handoff: http://127.0.0.1:${server.address().port}/handoff/index.html`);
+ console.log('This page describes the last successful build. Rebuild after edits. Ctrl-C stops this local server.');
+ const close = () => server.close(() => process.exit(0));
+ process.on('SIGINT', close); process.on('SIGTERM', close);
+ } catch (error) { console.error(error.message); process.exitCode = 1; }
+}
diff --git a/store/agents/openscad/store.json b/store/agents/openscad/store.json
index d596a864e..2bed9c7b7 100644
--- a/store/agents/openscad/store.json
+++ b/store/agents/openscad/store.json
@@ -1,17 +1,24 @@
{
- "listed": false,
+ "listed": true,
"homepage": "https://openscad.org",
"upstream": "https://github.com/openscad/openscad",
"license": "MIT",
- "tagline": "The Programmers Solid 3D CAD Modeller",
+ "tagline": "Your measurements. A family of usable parts.",
"screenshots": [
- "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/openscad/starter.jpg"
+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/openscad/drawer.jpg",
+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/openscad/handoff.jpg",
+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/openscad/bottles.jpg"
],
"examples": [
{
- "prompt": "Render the included Ripple vessel and check its mesh closure, volume and dimensions.",
- "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/openscad/starter.jpg",
- "caption": "Ripple · real OpenSCAD STL, inspected closed mesh"
+ "prompt": "Make a three-compartment drawer organizer in 150, 180 and 210 mm widths. Keep the floor and walls 2.4 mm thick; show the checks and give me the editable project.",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/openscad/drawer.jpg",
+ "caption": "Drawer Grid · three verified sizes, separate STLs and an editable project"
+ },
+ {
+ "prompt": "Make a holder for six 26 mm craft-paint bottles. Compare three clearances and give me small fit-test rings before I print the rack.",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/openscad/bottles.jpg",
+ "caption": "Bottle Bench · checked bores, clearance variants and matching fit-test rings"
}
]
}
diff --git a/store/agents/openscad/template/design.json b/store/agents/openscad/template/design.json
new file mode 100644
index 000000000..6781e2dfe
--- /dev/null
+++ b/store/agents/openscad/template/design.json
@@ -0,0 +1,253 @@
+{
+ "spec": 1,
+ "title": "Drawer Grid",
+ "brief": "A three-compartment organizer, sized to your drawer. Compare three widths, keep the pocket spaces and floor intact, then take the editable design and individual STLs to your slicer.",
+ "assumptions": [
+ "Example dimensions, not measurements of your drawer: confirm clear internal width, depth and usable height before printing.",
+ "Allow additional clearance for drawer taper, seams and printer dimensional error; the outside dimensions are the requested part envelope.",
+ "Dry desk/craft storage only. No food contact, load-bearing or liquid-tightness claim."
+ ],
+ "assembly": [
+ "Print a small fit sample or the narrow version first; measure the finished result.",
+ "Use one chosen size per drawer. The three variants are alternatives, not a three-piece assembly."
+ ],
+ "sourceFiles": [
+ "model.scad",
+ "design.json"
+ ],
+ "parameters": {
+ "width": {
+ "value": 180,
+ "min": 80,
+ "max": 220,
+ "unit": "mm",
+ "label": "Outside width"
+ },
+ "depth": {
+ "value": 96,
+ "min": 40,
+ "max": 180,
+ "unit": "mm",
+ "label": "Outside depth"
+ },
+ "height": {
+ "value": 40,
+ "min": 12,
+ "max": 80,
+ "unit": "mm",
+ "label": "Outside height"
+ },
+ "wall": {
+ "value": 2.4,
+ "min": 1.6,
+ "max": 4,
+ "unit": "mm",
+ "label": "Walls / dividers"
+ },
+ "floor": {
+ "value": 2.4,
+ "min": 1.6,
+ "max": 4,
+ "unit": "mm",
+ "label": "Floor thickness"
+ },
+ "columns": {
+ "value": 3,
+ "min": 2,
+ "max": 5,
+ "unit": "count",
+ "label": "Compartments"
+ }
+ },
+ "variants": [
+ {
+ "id": "compact",
+ "label": "Compact",
+ "values": {
+ "width": 150
+ },
+ "notes": [
+ "150 mm wide for a smaller drawer or a second organizer beside it."
+ ]
+ },
+ {
+ "id": "everyday",
+ "label": "Everyday",
+ "values": {},
+ "notes": [
+ "180 mm wide. Confirm the real drawer allows clearance around the part."
+ ]
+ },
+ {
+ "id": "wide",
+ "label": "Wide",
+ "values": {
+ "width": 210
+ },
+ "notes": [
+ "210 mm wide; each compartment is wider while the wall and floor targets stay unchanged."
+ ]
+ }
+ ],
+ "parts": [
+ {
+ "id": "tray",
+ "label": "Compartment tray",
+ "quantity": 1,
+ "printRotation": [
+ 0,
+ 0,
+ 0
+ ],
+ "shells": 1,
+ "views": {
+ "top": {
+ "at": "height/2"
+ },
+ "front": {
+ "at": "depth/2"
+ },
+ "side": {
+ "at": "wall+1"
+ }
+ },
+ "notes": [
+ "Open top, continuous floor, full-height dividers. The top and front sections reveal all three pockets.",
+ "Print with the continuous floor on the bed. Review slicing, material, shrinkage and edge lifting for your machine."
+ ]
+ }
+ ],
+ "checks": [
+ {
+ "id": "envelope",
+ "label": "Outside dimensions match the saved drawer envelope",
+ "kind": "bounds",
+ "part": "tray",
+ "size": [
+ "width",
+ "depth",
+ "height"
+ ],
+ "origin": [
+ 0,
+ 0,
+ 0
+ ],
+ "tolerance": 0.02
+ },
+ {
+ "id": "pockets",
+ "label": "Every compartment has the required clear interior",
+ "kind": "empty",
+ "part": "tray",
+ "region": {
+ "shape": "box",
+ "origin": [
+ "wall+0.04",
+ "wall+0.04",
+ "floor+0.04"
+ ],
+ "size": [
+ "(width-(columns+1)*wall)/columns-0.08",
+ "depth-2*wall-0.08",
+ "height-floor"
+ ],
+ "repeat": [
+ {
+ "count": "columns",
+ "step": [
+ "(width-(columns+1)*wall)/columns+wall",
+ 0,
+ 0
+ ]
+ }
+ ]
+ }
+ },
+ {
+ "id": "floor",
+ "label": "The specified floor is present under the entire tray",
+ "kind": "contains",
+ "part": "tray",
+ "region": {
+ "shape": "box",
+ "origin": [
+ 0.04,
+ 0.04,
+ 0.04
+ ],
+ "size": [
+ "width-0.08",
+ "depth-0.08",
+ "floor-0.08"
+ ]
+ }
+ },
+ {
+ "id": "dividers",
+ "label": "Every interior divider retains the requested material",
+ "kind": "contains",
+ "part": "tray",
+ "region": {
+ "shape": "box",
+ "origin": [
+ "wall+(width-(columns+1)*wall)/columns+0.04",
+ "wall+0.04",
+ "floor+0.04"
+ ],
+ "size": [
+ "wall-0.08",
+ "depth-2*wall-0.08",
+ "height-floor-0.08"
+ ],
+ "repeat": [
+ {
+ "count": "columns-1",
+ "step": [
+ "(width-(columns+1)*wall)/columns+wall",
+ 0,
+ 0
+ ]
+ }
+ ]
+ }
+ },
+ {
+ "id": "back-wall",
+ "label": "The back wall is continuous above the floor",
+ "kind": "contains",
+ "part": "tray",
+ "region": {
+ "shape": "box",
+ "origin": [
+ 0.04,
+ "depth-wall+0.04",
+ "floor+0.04"
+ ],
+ "size": [
+ "width-0.08",
+ "wall-0.08",
+ "height-floor-0.08"
+ ]
+ }
+ }
+ ],
+ "process": {
+ "material": "PLA",
+ "bedMM": [
+ 235,
+ 235,
+ 250
+ ],
+ "edgeMarginMM": 5,
+ "nozzleMM": 0.4,
+ "notes": [
+ "Declared example process: 0.4 mm nozzle, 235 × 235 × 250 mm printer. Change these to your machine.",
+ "The checks do not generate G-code or validate supports, extrusion settings or actual layer bonding."
+ ]
+ },
+ "preview": {
+ "variant": "everyday",
+ "part": "tray"
+ }
+}
diff --git a/store/agents/openscad/template/model.scad b/store/agents/openscad/template/model.scad
index 4c670cdab..db65cb28d 100644
--- a/store/agents/openscad/template/model.scad
+++ b/store/agents/openscad/template/model.scad
@@ -1,30 +1,16 @@
-// Ripple — a parametric, open-top desktop vessel. Units: mm.
-// Set height, diameter, twist and ribs, then run render-part.sh.
-// This is a dry-use object, not a food-safe or watertight container.
-height = 76;
-diameter = 82;
-wall = 2.4;
-floor_thickness = 2.8;
-ribs = 36;
-rib_depth = 2.6;
-twist = 28;
-resolution = 180;
-
-assert(height > floor_thickness && floor_thickness > 0, "height must exceed a positive floor");
-assert(diameter > 2 * (wall + rib_depth) && wall >= 1.2, "keep a useful inner diameter and wall >= 1.2 mm");
-assert(ribs >= 3 && ribs <= 100 && rib_depth >= 0, "use 3–100 ribs and nonnegative rib depth");
-$fn = resolution;
-
-// Continuous polar outline avoids coincident seams between separate ribs.
-module outline() {
- polygon([for (i = [0:resolution-1])
- let(angle = i * 360 / resolution,
- radius = diameter / 2 + rib_depth * (0.5 + 0.5*cos(ribs*angle)))
- [radius*cos(angle), radius*sin(angle)]]);
-}
-difference() {
- linear_extrude(height=height, twist=twist, slices=ceil(height/2), convexity=10)
- outline();
- translate([0,0,floor_thickness])
- cylinder(h=height+0.1, r=diameter/2-wall);
+// Drawer Grid — an editable family of dry-use organizers. Millimetres.
+// The checked builder calls this module with the saved design.json values.
+// Top-level geometry is a desktop preview only; it is ignored during export.
+module part(id, width=180, depth=96, height=40, wall=2.4, floor=2.4, columns=3) {
+ assert(id == "tray", "Unknown part");
+ assert(columns >= 2 && floor > 0 && height > floor && wall > 0);
+ pocket_width = (width - (columns + 1) * wall) / columns;
+ assert(pocket_width > 10 && depth > 2 * wall + 10, "Compartments are too small");
+ difference() {
+ cube([width, depth, height]);
+ for (column = [0:columns-1])
+ translate([wall + column * (pocket_width + wall), wall, floor])
+ cube([pocket_width, depth - 2 * wall, height + 1]);
+ }
}
+part("tray");
diff --git a/store/agents/openscad/test/ACCEPTANCE.md b/store/agents/openscad/test/ACCEPTANCE.md
new file mode 100644
index 000000000..7fe8b5b25
--- /dev/null
+++ b/store/agents/openscad/test/ACCEPTANCE.md
@@ -0,0 +1,90 @@
+# OpenSCAD acceptance — real part families
+
+Validation date: 2026-09-20. Native engine: OpenSCAD 2021.01 on macOS. Unit/native runner:
+Node 22.23.2. The actual `render-part.sh` entrypoint was also exercised. The shared CAD pane used
+its pinned cadgen 0.5.1 viewer. No physical print or hardware test is claimed.
+
+## Complete workflows
+
+**Drawer Grid:** three sizes (150/180/210 × 96 × 40 mm), three clear compartments, 2.4 mm floor and
+walls. The native build requires agreeing repeat exports and passes 24 measured checks:
+closed/positively oriented meshes and expected surface shells, saved bounds, each pocket, floor/divider/back-wall material,
+print-envelope fit and native final-STL reopening. Three native reference sections accompany
+each variant.
+
+A substantive revision changes depth to 104 mm and the compartment count to four while retaining
+the same floor/wall requirements. It passes. Deliberately thinning the floor, obstructing a pocket
+or choosing a too-small printer fails and leaves the previous complete ZIP byte-identical.
+Extracting the ZIP into a separate directory and running its own `node rebuild/build.mjs .`
+regenerates the same source revision, checks and measured part bounds without Harness/npm/Python.
+An undeclared private workspace note is excluded from the archive.
+
+**Bottle Bench:** independent cylindrical geometry: six 26 mm craft-paint bottles; radial clearance
+variants 0.15/0.30/0.45 mm; a separate matching fit-test ring for each. All six parts pass 39 checks.
+The ring starts in negative X/Y design coordinates, is rotated 180° and exported into nonnegative
+bed coordinates. Every bore, the rack floor, ring material sample and a declared noninterfering
+placement are measured from the exported meshes. A deliberately overlapping placement fails
+without replacing the good project. The ring is an artifact for a future real fit test, not
+evidence that one happened.
+
+**Legacy:** original Ripple source still renders as a closed mesh. Without a saved checked brief,
+readiness stays false and the result is explicitly a geometry preview.
+
+## Negative and portability evidence
+
+- Native assertion failures and unknown modules cannot masquerade as a successful empty query.
+- Two differing source exports reject unseeded random geometry.
+- Native dependency receipts reject an undeclared external source; a declared relative include works.
+- Source symlinks and unsafe/reserved source paths fail. Source edits during compilation invalidate
+ the candidate and preserve the previous STL.
+- Build locking leaves another writer's verdict untouched.
+- Unknown schema fields, invalid parameter overrides, noninteger counts, missing bounds,
+ unsupported expressions and reserved/ambiguous export/check IDs are rejected.
+- STL tests cover ASCII/binary agreement, volume, bounds, opposite edge orientation, open and
+ degenerate surfaces, independent surface shells and negative signed volume.
+- Transport fixtures are labelled as fixtures; they are not used as native-render evidence.
+
+## Browser and visual evidence
+
+The actual print-oriented organizer, wide variant, bottle rack and fit ring were opened in the
+shared CAD Viewer. Zoom and reset interactions were exercised; saved screenshots were inspected.
+These are real STL loads, not reconstructed illustrations.
+
+The handoff is exercised in Chromium at 1600 × 1100 and 390 × 844. Checks cover initial selection,
+all three configuration buttons, the comparison table, every native SVG image, every evidence
+panel, no horizontal page overflow and no JavaScript errors. All three organizer STLs / six
+bottle-project STLs and both project ZIPs are downloaded through the browser and compared
+byte-for-byte with the built files. Undeclared model/state routes return 404; POST returns 405.
+The final desktop/mobile part views are visually reviewed.
+
+Store images capture the real CAD pane and handoff. Existing logo/icon assets are retained.
+
+## Reproduce
+
+```sh
+node --test store/agents/openscad/test/*.test.mjs
+
+OPENSCAD_BIN=/path/to/openscad \
+OPENSCAD_QA_ROOT=/path/to/qa-directory \
+node --test store/agents/openscad/test/*.test.mjs
+
+PLAYWRIGHT_MODULE=/path/to/playwright/index.mjs \
+node store/agents/openscad/test/browser.mjs /path/to/built-project /path/to/screenshots
+```
+
+Without `OPENSCAD_BIN` the four native cases are explicitly skipped; they are not counted as
+native proof. The suite has 21 cases (17 unit/transport, 4 native). Test setup uses its own
+temporary install location and clears inherited OpenSCAD overrides for prerequisite checks.
+
+Also run package conformance, skill validation, generated-experience/branding checks, and the
+registry/store/catalog/publisher suite from `cli/`. Native QA workspaces, browser receipts, complete
+downloads and publication receipts are retained in the release workspace, not committed generated
+model binaries.
+
+## Limits
+
+The stated brief, exported-region probes and individual build envelope are verified, not every
+possible manufacturing property. No global minimum-wall, complete self-intersection, strength,
+supports, packed-plate, slicing, food-safety or physical-fit certification is implied. STL uses
+millimetres; no native STEP export is promised. Source compilation is trusted-code execution,
+not a sandbox. A handoff page is the last successful saved snapshot; edits require a new build.
diff --git a/store/agents/openscad/test/browser.mjs b/store/agents/openscad/test/browser.mjs
new file mode 100644
index 000000000..cf920de38
--- /dev/null
+++ b/store/agents/openscad/test/browser.mjs
@@ -0,0 +1,71 @@
+import assert from 'node:assert/strict';
+import {readFile,mkdir,writeFile} from 'node:fs/promises';
+import {resolve,join} from 'node:path';
+import {pathToFileURL} from 'node:url';
+import {serve} from '../skills/openscad/scripts/serve-handoff.mjs';
+const workspace=resolve(process.argv[2]),out=resolve(process.argv[3]);
+if(!process.env.PLAYWRIGHT_MODULE)throw new Error('Set PLAYWRIGHT_MODULE to a locally installed Playwright module.');
+const {chromium}=await import(pathToFileURL(process.env.PLAYWRIGHT_MODULE).href);
+const server=await serve(workspace),url='http://127.0.0.1:'+server.address().port;
+const report=JSON.parse(await readFile(join(workspace,'handoff/checks.json')));
+await mkdir(out,{recursive:true});
+let browser;const evidence={title:report.title,sourceRevision:report.sourceRevision,viewports:[],downloads:[]};
+try{
+ browser=await chromium.launch({headless:true});
+ for(const [device,width,height] of [['desktop',1600,1100],['mobile',390,844]]){
+ const page=await browser.newPage({viewport:{width,height}}),errors=[];
+ page.on('pageerror',error=>errors.push(error.message));
+ await page.goto(url);await page.getByRole('heading',{name:report.title,exact:true}).waitFor();
+ assert.equal(await page.locator('[data-variant][aria-pressed=true]').getAttribute('data-variant'),report.design.preview.variant);
+ await page.locator('.family-comparison summary').click();
+ assert.equal(await page.locator('.family-comparison tbody tr:visible').count(),report.variants.length);
+ await page.locator('.family-comparison summary').click();
+ for(const variant of report.variants){
+ await page.locator('[data-variant="'+variant.id+'"]').click();
+ const panel=page.locator('[data-panel="'+variant.id+'"]');
+ assert.equal(await panel.isVisible(),true);
+ assert.equal(await page.locator('.variant:visible').count(),1);
+ await panel.locator('img').first().waitFor();
+ await page.waitForFunction(()=>[...document.querySelectorAll('.variant:not([hidden]) img')].every(image=>image.complete&&image.naturalWidth>0));
+ assert.equal(await panel.locator('.part').count(),variant.parts.length);
+ assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth),'horizontal overflow');
+ for(const [index,part] of variant.parts.entries()){
+ await panel.locator('.part').nth(index).screenshot({path:join(out,device+'-'+variant.id+'-'+part.id+'.png')});
+ }
+ await panel.locator('details.checks summary').click();
+ assert.equal(await panel.locator('.check:visible').count(),report.checks.filter(check=>check.variant===variant.id).length);
+ await panel.locator('details.checks summary').click();
+ }
+ await page.locator('[data-variant="'+report.design.preview.variant+'"]').click();await page.evaluate(()=>scrollTo(0,0));
+ await page.screenshot({path:join(out,device+'.png'),fullPage:true});
+ if(device==='desktop')await page.screenshot({path:join(out,'store.jpg'),type:'jpeg',quality:90});
+ if(device==='desktop'){
+ const links=await page.locator('a').evaluateAll(items=>items.map(a=>({href:a.href,download:a.hasAttribute('download')})));
+ for(const link of links){
+ const response=await page.request.get(link.href);assert.equal(response.status(),200,link.href);
+ const relative=new URL(link.href).pathname.slice(1);
+ assert.deepEqual(await response.body(),await readFile(join(workspace,relative)));
+ }
+ for(const variant of report.variants){
+ await page.locator('[data-variant="'+variant.id+'"]').click();
+ for(const part of variant.parts){
+ const link=page.locator('[data-panel="'+variant.id+'"] a[href="'+part.path.replace('handoff/','')+'"]');
+ const pending=page.waitForEvent('download');await link.click();const download=await pending;
+ assert.equal(await download.failure(),null);
+ assert.deepEqual(await readFile(await download.path()),await readFile(join(workspace,part.path)));
+ evidence.downloads.push(part.path);
+ }
+ }
+ const pending=page.waitForEvent('download');await page.locator('.primary a').click();const download=await pending;
+ assert.deepEqual(await readFile(await download.path()),await readFile(join(workspace,'handoff/project.zip')));
+ evidence.downloads.push('handoff/project.zip');
+ assert.equal((await page.request.get(url+'/model.scad')).status(),404);
+ assert.equal((await page.request.get(url+'/.harness/mesh.json')).status(),404);
+ assert.equal((await page.request.post(url+'/handoff/checks.json')).status(),405);
+ }
+ assert.deepEqual(errors,[]);evidence.viewports.push({width,height,variants:report.variants.length,errors});await page.close();
+ }
+ await writeFile(join(out,'browser-receipt.json'),JSON.stringify(evidence,null,2)+'\n');console.log(JSON.stringify(evidence));
+}finally{
+ if(browser)await browser.close();await new Promise(done=>server.close(done));
+}
diff --git a/store/agents/openscad/test/build.test.mjs b/store/agents/openscad/test/build.test.mjs
index 922da626b..aec014863 100644
--- a/store/agents/openscad/test/build.test.mjs
+++ b/store/agents/openscad/test/build.test.mjs
@@ -1,25 +1,63 @@
import assert from 'node:assert/strict';
-import { test } from 'node:test';
-import { mkdtemp, writeFile, readFile, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { build } from '../skills/openscad/scripts/build.mjs';
-const tetra='solid tetra\n'+[[[0,0,0],[0,1,0],[1,0,0]],[[0,0,0],[1,0,0],[0,0,1]],[[0,0,0],[0,0,1],[0,1,0]],[[1,0,0],[0,1,0],[0,0,1]]].map(face=>'facet normal 0 0 0\nouter loop\n'+face.map(v=>'vertex '+v.join(' ')).join('\n')+'\nendloop\nendfacet').join('\n')+'\nendsolid tetra\n';
-test('only a fresh, inspected mesh can replace an older artifact or set ready',async()=>{
- const workspace=await mkdtemp(join(tmpdir(),'openscad-build-test-'));
+import {test} from 'node:test';
+import {mkdtemp,writeFile,readFile,rm,mkdir,symlink} from 'node:fs/promises';
+import {tmpdir} from 'node:os';
+import {join} from 'node:path';
+import {build} from '../skills/openscad/scripts/build.mjs';
+import {Native} from '../skills/openscad/scripts/native.mjs';
+import {fakeCompiler} from './fixture.mjs';
+test('legacy transport exports fresh geometry but cannot claim checked readiness; failures preserve it',async()=>{
+ const workspace=await mkdtemp(join(tmpdir(),'openscad-transport-'));
try{
- await writeFile(join(workspace,'model.scad'),'cube(1);');await writeFile(join(workspace,'fixture.stl'),tetra);
- const bin=join(workspace,'fake-openscad');
- await writeFile(bin,'#!/bin/sh\ncp fixture.stl "$2"\n',{mode:0o755});
- const report=await build(workspace,{bin});assert.equal(report.watertight,true);
- assert.equal(JSON.parse(await readFile(join(workspace,'.harness/verdict.json'))).ready,true);
- const saved=await readFile(join(workspace,'part.stl'),'utf8');
- for(const command of ['exit 1','exit 0',': > "$2"']){
- await writeFile(bin,'#!/bin/sh\n'+command+'\n',{mode:0o755});
- await assert.rejects(()=>build(workspace,{bin}));
+ await writeFile(join(workspace,'model.scad'),'cube(1);');
+ let bin=await fakeCompiler(workspace);
+ const report=await build(workspace,{bin});assert.equal(report.watertight,true);assert.equal(report.checked,false);
+ assert.equal(JSON.parse(await readFile(join(workspace,'.harness/verdict.json'))).ready,false);
+ const saved=await readFile(join(workspace,'part.stl'));
+ for(const body of ['process.exit(1);','process.exit(0);','writeFileSync(a[a.indexOf("-o")+1],"");process.exit(0);','console.error("WARNING: unknown module");process.exit(1);']){
+ bin=await fakeCompiler(workspace,body);await assert.rejects(()=>build(workspace,{bin}));
const verdict=JSON.parse(await readFile(join(workspace,'.harness/verdict.json')));
assert.equal(verdict.ready,false);assert.equal(verdict.artifact,null);
- assert.equal(await readFile(join(workspace,'part.stl'),'utf8'),saved);
+ assert.deepEqual(await readFile(join(workspace,'part.stl')),saved);
}
}finally{await rm(workspace,{recursive:true,force:true});}
});
+test('empty-query transport accepts only the exact native empty condition without diagnostics',async()=>{
+ const workspace=await mkdtemp(join(tmpdir(),'openscad-empty-'));
+ try{
+ const empty='console.error("Current top level object is empty.");process.exit(1);';
+ let bin=await fakeCompiler(workspace,empty);
+ assert.equal((await new Native(bin,workspace).render('empty','cube(0);',{emptyAllowed:true})).empty,true);
+ for(const diagnostic of ['WARNING: Ignoring unknown module','ERROR: Assertion failed']){
+ bin=await fakeCompiler(workspace,'console.error('+JSON.stringify(diagnostic)+');'+empty);
+ await assert.rejects(()=>new Native(bin,workspace).render('bad','bad();',{emptyAllowed:true}),/diagnostic/);
+ }
+ }finally{await rm(workspace,{recursive:true,force:true});}
+});
+test('a build lock leaves the owner verdict alone; source symlinks fail without exporting',async()=>{
+ const workspace=await mkdtemp(join(tmpdir(),'openscad-lock-'));
+ try{
+ await mkdir(join(workspace,'.harness','openscad-build.lock'),{recursive:true});
+ const verdict='{"ready":false,"summary":"Owned by another build"}';
+ await writeFile(join(workspace,'.harness/verdict.json'),verdict);
+ await assert.rejects(()=>build(workspace),/Another build/);
+ assert.equal(await readFile(join(workspace,'.harness/verdict.json'),'utf8'),verdict);
+ await rm(join(workspace,'.harness/openscad-build.lock'),{recursive:true});
+ await writeFile(join(workspace,'external.scad'),'cube(1);');
+ await symlink(join(workspace,'external.scad'),join(workspace,'model.scad'));
+ const bin=await fakeCompiler(workspace);
+ await assert.rejects(()=>build(workspace,{bin}),/symlinks/);
+ }finally{await rm(workspace,{recursive:true,force:true});}
+});
+test('source edits during compilation invalidate the candidate and preserve the previous STL',async()=>{
+ const workspace=await mkdtemp(join(tmpdir(),'openscad-source-change-'));
+ try{
+ const model=join(workspace,'model.scad');await writeFile(model,'cube(1);');
+ await build(workspace,{bin:await fakeCompiler(workspace)});
+ const previous=await readFile(join(workspace,'part.stl'));
+ const bin=await fakeCompiler(workspace,'writeFileSync('+JSON.stringify(model)+',"cube(2);");');
+ await assert.rejects(()=>build(workspace,{bin}),/Source changed during build/);
+ assert.deepEqual(await readFile(join(workspace,'part.stl')),previous);
+ assert.equal(JSON.parse(await readFile(join(workspace,'.harness/verdict.json'))).artifact,null);
+ }finally{await rm(workspace,{recursive:true,force:true});}
+});
diff --git a/store/agents/openscad/test/design.test.mjs b/store/agents/openscad/test/design.test.mjs
new file mode 100644
index 000000000..bfdb80d76
--- /dev/null
+++ b/store/agents/openscad/test/design.test.mjs
@@ -0,0 +1,70 @@
+import {test} from 'node:test';
+import assert from 'node:assert/strict';
+import {number,vector} from '../skills/openscad/scripts/expression.mjs';
+import {regionFor,regionScad} from '../skills/openscad/scripts/design.mjs';
+import {dependencies,partCall,projection} from '../skills/openscad/scripts/native.mjs';
+import {inspectSTL,binarySTL} from '../skills/openscad/scripts/mesh.mjs';
+
+test('saved briefs reject unknown fields, unsafe sources, weakened contracts and ambiguous delivery IDs',async()=>{
+ const {readFile}=await import('node:fs/promises');
+ const {validateDesign}=await import('../skills/openscad/scripts/design.mjs');
+ const fixture=JSON.parse(await readFile(new URL('../template/design.json',import.meta.url)));
+ assert.equal(validateDesign(fixture).variants.length,3);
+ const mutations=[
+ d=>d.unchecked=true,
+ d=>d.sourceFiles.push('../private.txt'),
+ d=>d.sourceFiles.push('handoff/parts/private.stl'),
+ d=>d.parameters.columns.value=2.5,
+ d=>d.variants[0].values.unknown=1,
+ d=>d.parts[0].shells=0,
+ d=>d.parts[0].views.top.at='process.exit()',
+ d=>d.checks.splice(0,1),
+ d=>d.checks[0].tolerance=5,
+ d=>d.checks[0].id='tray-topology',
+ d=>d.checks[1].region.size[0]='0',
+ d=>d.variants[1].values.width=1000,
+ d=>d.process.bedMM[0]=-1,
+ d=>d.preview.part='unknown'
+ ];
+ for(const mutate of mutations){const invalid=structuredClone(fixture);mutate(invalid);assert.throws(()=>validateDesign(invalid));}
+ const collision=structuredClone(fixture);
+ collision.parts.push({...structuredClone(collision.parts[0]),id:'compact-tray'});
+ collision.variants.push({id:'everyday-compact',label:'Collision',values:{},notes:[]});
+ assert.throws(()=>validateDesign(collision),/Ambiguous variant\/part/);
+ const input=structuredClone(fixture),result=validateDesign(input);
+ result.variants[0].values.width=100;assert.equal(input.variants[0].values.width,150);
+});
+
+test('requirement arithmetic is bounded, has precedence and never evaluates JavaScript',()=>{
+ assert.equal(number('(width-(columns+1)*wall)/columns',{width:180,columns:3,wall:2.4}),56.800000000000004);
+ assert.equal(number(' -2 * (3 + +4) / 2 '),-7);
+ assert.deepEqual(vector([1,'2+3',6],{}),[1,5,6]);
+ for(const value of ['unknown','1/0','(1+2','1+2)','1 2','process.exit()','width.constructor','Math.max(1,2)','1e100','2**4','a[0]','1;2']){
+ assert.throws(()=>number(value,{width:1}));
+ }
+ assert.throws(()=>vector([0,1,1],{},'probe',{positive:true}),/positive/);
+});
+test('repeated box/cylinder probes are numeric and finite, with correct axis orientation',()=>{
+ const region=regionFor({shape:'box',origin:[1,2,3],size:['wall',4,5],repeat:[{count:2,step:[10,0,0]},{count:2,step:[0,20,0]}]},{wall:2});
+ assert.deepEqual(region.origins,[[1,2,3],[1,22,3],[11,2,3],[11,22,3]]);
+ assert.match(regionScad(region),/translate\(\[11,22,3\]\) cube\(\[2,4,5\]\)/);
+ assert.match(regionScad(regionFor({shape:'cylinder',origin:[0,0,0],radius:4,height:10,axis:'x'},{})),/rotate\(\[0,90,0\]\)/);
+ assert.throws(()=>regionFor({shape:'box',origin:[0,0,0],size:[1,1,1],repeat:[{count:32,step:[1,0,0]},{count:32,step:[0,1,0]}]},{}),/64 repeated/);
+});
+test('native dependency receipts handle escaped paths and named module calls ignore top-level preview',()=>{
+ assert.deepEqual(dependencies('/tmp/output.stl: \\\n\t/tmp/space\\ here/model.scad \\\n\t/tmp/source.scad\n'),['/tmp/space here/model.scad','/tmp/source.scad']);
+ assert.throws(()=>dependencies('no receipt'),/Invalid/);
+ assert.equal(partCall('tray',{width:100,depth:60}),'part(id="tray",width=100,depth=60);');
+ assert.match(projection('/tmp/model.stl','front',10),/rotate\(\[-90,0,0\]\) translate\(\[0,-10,0\]\)/);
+});
+test('mesh reports connected surface shells and signed volume; translation preserves actual size',()=>{
+ const a=[0,0,0],b=[1,0,0],c=[0,1,0],d=[0,0,1],faces=[[a,c,b],[a,b,d],[a,d,c],[b,c,d]];
+ const moved=faces.map(face=>face.map(point=>point.map((value,axis)=>value+(axis===0?5:0))));
+ const report=inspectSTL(binarySTL([...faces,...moved]));
+ assert.equal(report.shells.length,2);assert.equal(report.watertight,true);
+ assert.ok(Math.abs(report.volumeMM3-1/3)<1e-7);
+ const shifted=inspectSTL(binarySTL(faces,[-2,3,4]));
+ assert.deepEqual(shifted.bounds,{min:[-2,3,4],max:[-1,4,5],size:[1,1,1]});
+ assert.ok(Math.abs(shifted.volumeMM3-1/6)<1e-7);
+ assert.ok(inspectSTL(binarySTL(faces.map(face=>face.toReversed()))).orientedVolumeMM3<0);
+});
diff --git a/store/agents/openscad/test/fixture.mjs b/store/agents/openscad/test/fixture.mjs
new file mode 100644
index 000000000..804d7a0ff
--- /dev/null
+++ b/store/agents/openscad/test/fixture.mjs
@@ -0,0 +1,16 @@
+// A transport fixture only, never evidence of a real OpenSCAD render.
+import {writeFile} from 'node:fs/promises';
+import {join} from 'node:path';
+export const tetra='solid tetra\n'+[[[0,0,0],[0,1,0],[1,0,0]],[[0,0,0],[1,0,0],[0,0,1]],[[0,0,0],[0,0,1],[0,1,0]],[[1,0,0],[0,1,0],[0,0,1]]].map(face=>'facet normal 0 0 0\nouter loop\n'+face.map(v=>'vertex '+v.join(' ')).join('\n')+'\nendloop\nendfacet').join('\n')+'\nendsolid tetra\n';
+export function compiler(fixture,body=''){
+ return '#!'+process.execPath+'\n'+
+ 'import {copyFileSync,writeFileSync} from "node:fs";\n'+
+ 'const a=process.argv.slice(2);if(a[0]==="--version"){console.log("OpenSCAD version transport-fixture");process.exit(0);}\n'+
+ body+'\n'+
+ 'const out=a[a.indexOf("-o")+1];copyFileSync('+JSON.stringify(fixture)+',out);\n'+
+ 'if(a.includes("-d"))writeFileSync(a[a.indexOf("-d")+1],out+": "+a.at(-1)+"\\n");\n';
+}
+export async function fakeCompiler(workspace,body=''){
+ const fixture=join(workspace,'fixture.stl'),bin=join(workspace,'fake-openscad.mjs');
+ await writeFile(fixture,tetra);await writeFile(bin,compiler(fixture,body),{mode:0o755});return bin;
+}
diff --git a/store/agents/openscad/test/fixtures/bottles/design.json b/store/agents/openscad/test/fixtures/bottles/design.json
new file mode 100644
index 000000000..024f80ea6
--- /dev/null
+++ b/store/agents/openscad/test/fixtures/bottles/design.json
@@ -0,0 +1,322 @@
+{
+ "spec": 1,
+ "title": "Bottle Bench",
+ "brief": "Keep six craft-paint bottles upright, with a matching fit-test ring. Compare snug, everyday and easy-lift clearances before printing the full rack.",
+ "assumptions": [
+ "Example bottle diameter is 26 mm. Measure the largest part that must enter the pocket; do not assume the printed diameter matches CAD exactly.",
+ "Clearance is radial: 0.30 mm per side adds 0.60 mm to the bore diameter.",
+ "Dry indoor craft storage. No food contact, pressure, chemical compatibility or spill-containment claim."
+ ],
+ "assembly": [
+ "Print only the fit-test rings first, label each clearance and try the real bottle.",
+ "Choose the smallest clearance that seats and removes comfortably; print that matching rack.",
+ "Place the rack flat on a stable surface; it is not a transport restraint."
+ ],
+ "sourceFiles": [
+ "model.scad",
+ "design.json"
+ ],
+ "parameters": {
+ "bottle_diameter": {
+ "value": 26,
+ "min": 10,
+ "max": 50,
+ "unit": "mm",
+ "label": "Measured bottle Ø"
+ },
+ "clearance": {
+ "value": 0.3,
+ "min": 0.05,
+ "max": 1,
+ "unit": "mm",
+ "label": "Radial clearance"
+ },
+ "wall": {
+ "value": 2,
+ "min": 1.6,
+ "max": 4,
+ "unit": "mm",
+ "label": "Material between bores"
+ },
+ "floor": {
+ "value": 2.4,
+ "min": 1.6,
+ "max": 4,
+ "unit": "mm",
+ "label": "Rack floor"
+ },
+ "height": {
+ "value": 18,
+ "min": 8,
+ "max": 40,
+ "unit": "mm",
+ "label": "Rack height"
+ },
+ "columns": {
+ "value": 3,
+ "min": 2,
+ "max": 4,
+ "unit": "count",
+ "label": "Columns"
+ },
+ "rows": {
+ "value": 2,
+ "min": 1,
+ "max": 4,
+ "unit": "count",
+ "label": "Rows"
+ },
+ "gauge_height": {
+ "value": 4,
+ "min": 2,
+ "max": 8,
+ "unit": "mm",
+ "label": "Fit-ring height"
+ }
+ },
+ "variants": [
+ {
+ "id": "snug",
+ "label": "Snug",
+ "values": {
+ "clearance": 0.15
+ },
+ "notes": [
+ "0.30 mm diametral clearance; validate with the small ring first."
+ ]
+ },
+ {
+ "id": "everyday",
+ "label": "Everyday",
+ "values": {
+ "clearance": 0.3
+ },
+ "notes": [
+ "0.60 mm diametral clearance."
+ ]
+ },
+ {
+ "id": "easy-lift",
+ "label": "Easy lift",
+ "values": {
+ "clearance": 0.45
+ },
+ "notes": [
+ "0.90 mm diametral clearance."
+ ]
+ }
+ ],
+ "parts": [
+ {
+ "id": "rack",
+ "label": "Six-bottle rack",
+ "quantity": 1,
+ "printRotation": [
+ 0,
+ 0,
+ 0
+ ],
+ "shells": 1,
+ "views": {
+ "top": {
+ "at": "height/2"
+ },
+ "front": {
+ "at": "wall+(bottle_diameter+2*clearance)/2"
+ },
+ "side": {
+ "at": "wall+(bottle_diameter+2*clearance)/2"
+ }
+ },
+ "notes": [
+ "Six through-clear pockets above a continuous floor. The front and side sections cut through bore centers.",
+ "Rack and ring are separate prints; no packed-plate capacity is implied."
+ ]
+ },
+ {
+ "id": "gauge",
+ "label": "Fit-test ring",
+ "quantity": 1,
+ "printRotation": [
+ 180,
+ 0,
+ 0
+ ],
+ "shells": 1,
+ "views": {
+ "top": {
+ "at": "gauge_height/2"
+ },
+ "front": {
+ "at": 0
+ },
+ "side": {
+ "at": 0
+ }
+ },
+ "notes": [
+ "Print this inexpensive ring first. Its bore uses the exact same diameter and polygon resolution as the rack.",
+ "The design is centered on X/Y; the exported STL is rotated and translated into nonnegative bed coordinates."
+ ]
+ }
+ ],
+ "checks": [
+ {
+ "id": "rack-envelope",
+ "kind": "bounds",
+ "label": "Rack envelope matches the declared layout",
+ "part": "rack",
+ "size": [
+ "columns*(bottle_diameter+2*clearance)+(columns+1)*wall",
+ "rows*(bottle_diameter+2*clearance)+(rows+1)*wall",
+ "height"
+ ],
+ "origin": [
+ 0,
+ 0,
+ 0
+ ],
+ "tolerance": 0.02
+ },
+ {
+ "id": "rack-bores",
+ "kind": "empty",
+ "label": "Every bottle pocket has the required clear bore",
+ "part": "rack",
+ "region": {
+ "shape": "cylinder",
+ "origin": [
+ "wall+(bottle_diameter+2*clearance)/2",
+ "wall+(bottle_diameter+2*clearance)/2",
+ "floor+0.04"
+ ],
+ "radius": "(bottle_diameter+2*clearance)/2-0.04",
+ "height": "height-floor",
+ "repeat": [
+ {
+ "count": "columns",
+ "step": [
+ "bottle_diameter+2*clearance+wall",
+ 0,
+ 0
+ ]
+ },
+ {
+ "count": "rows",
+ "step": [
+ 0,
+ "bottle_diameter+2*clearance+wall",
+ 0
+ ]
+ }
+ ]
+ }
+ },
+ {
+ "id": "rack-floor",
+ "kind": "contains",
+ "label": "Continuous rack floor is present",
+ "part": "rack",
+ "region": {
+ "shape": "box",
+ "origin": [
+ 0.04,
+ 0.04,
+ 0.04
+ ],
+ "size": [
+ "columns*(bottle_diameter+2*clearance)+(columns+1)*wall-0.08",
+ "rows*(bottle_diameter+2*clearance)+(rows+1)*wall-0.08",
+ "floor-0.08"
+ ]
+ }
+ },
+ {
+ "id": "gauge-envelope",
+ "kind": "bounds",
+ "label": "Ring dimensions match the chosen fit",
+ "part": "gauge",
+ "size": [
+ "2*((bottle_diameter+2*clearance)/2+wall)",
+ "2*((bottle_diameter+2*clearance)/2+wall)",
+ "gauge_height"
+ ],
+ "origin": [
+ "-((bottle_diameter+2*clearance)/2+wall)",
+ "-((bottle_diameter+2*clearance)/2+wall)",
+ 0
+ ],
+ "tolerance": 0.02
+ },
+ {
+ "id": "gauge-bore",
+ "kind": "empty",
+ "label": "The fit ring has an unobstructed bore",
+ "part": "gauge",
+ "region": {
+ "shape": "cylinder",
+ "origin": [
+ 0,
+ 0,
+ -0.1
+ ],
+ "radius": "(bottle_diameter+2*clearance)/2-0.04",
+ "height": "gauge_height+0.2"
+ }
+ },
+ {
+ "id": "gauge-wall",
+ "kind": "contains",
+ "label": "A radial wall sample retains the specified material",
+ "part": "gauge",
+ "region": {
+ "shape": "box",
+ "origin": [
+ "(bottle_diameter+2*clearance)/2+0.1",
+ -0.1,
+ 0.04
+ ],
+ "size": [
+ "wall-0.2",
+ 0.2,
+ "gauge_height-0.08"
+ ]
+ }
+ },
+ {
+ "id": "separate-layout",
+ "kind": "separated",
+ "label": "Ring placed beside the rack does not collide",
+ "part": "rack",
+ "other": "gauge",
+ "translation": [
+ "columns*(bottle_diameter+2*clearance)+(columns+1)*wall+(bottle_diameter+2*clearance)/2+wall+5",
+ "(bottle_diameter+2*clearance)/2+wall",
+ 0
+ ],
+ "rotation": [
+ 0,
+ 0,
+ 0
+ ]
+ }
+ ],
+ "process": {
+ "material": "PLA",
+ "bedMM": [
+ 220,
+ 220,
+ 250
+ ],
+ "edgeMarginMM": 5,
+ "nozzleMM": 0.4,
+ "notes": [
+ "Example 220 × 220 × 250 mm printer with 0.4 mm nozzle; confirm your actual machine and material.",
+ "Use the same slicing settings and material for the fit ring and final rack. Neither has been physically printed in this validation."
+ ]
+ },
+ "preview": {
+ "variant": "everyday",
+ "part": "rack"
+ }
+}
diff --git a/store/agents/openscad/test/fixtures/bottles/model.scad b/store/agents/openscad/test/fixtures/bottles/model.scad
new file mode 100644
index 000000000..486d6b6bb
--- /dev/null
+++ b/store/agents/openscad/test/fixtures/bottles/model.scad
@@ -0,0 +1,25 @@
+// Bottle Bench. Original millimetre design; dry craft use only.
+module part(id, bottle_diameter=26, clearance=0.3, wall=2, floor=2.4,
+ height=18, columns=3, rows=2, gauge_height=4) {
+ bore = bottle_diameter + 2 * clearance;
+ width = columns * bore + (columns+1) * wall;
+ depth = rows * bore + (rows+1) * wall;
+ assert(bore > 0 && wall > 0 && floor > 0 && height > floor);
+ $fn = 128;
+ if (id == "rack")
+ difference() {
+ cube([width,depth,height]);
+ for (x=[0:columns-1], y=[0:rows-1])
+ translate([wall+bore/2+x*(bore+wall),
+ wall+bore/2+y*(bore+wall), floor])
+ cylinder(d=bore,h=height+1);
+ }
+ else if (id == "gauge")
+ difference() {
+ cylinder(d=bore+2*wall,h=gauge_height);
+ translate([0,0,-0.1]) cylinder(d=bore,h=gauge_height+0.2);
+ }
+ else assert(false,"Unknown part");
+}
+part("rack");
+translate([115,20,0]) part("gauge");
diff --git a/store/agents/openscad/test/fixtures/empty/.gitkeep b/store/agents/openscad/test/fixtures/empty/.gitkeep
new file mode 100644
index 000000000..8b1378917
--- /dev/null
+++ b/store/agents/openscad/test/fixtures/empty/.gitkeep
@@ -0,0 +1 @@
+
diff --git a/store/agents/openscad/test/fixtures/ripple.scad b/store/agents/openscad/test/fixtures/ripple.scad
new file mode 100644
index 000000000..4c670cdab
--- /dev/null
+++ b/store/agents/openscad/test/fixtures/ripple.scad
@@ -0,0 +1,30 @@
+// Ripple — a parametric, open-top desktop vessel. Units: mm.
+// Set height, diameter, twist and ribs, then run render-part.sh.
+// This is a dry-use object, not a food-safe or watertight container.
+height = 76;
+diameter = 82;
+wall = 2.4;
+floor_thickness = 2.8;
+ribs = 36;
+rib_depth = 2.6;
+twist = 28;
+resolution = 180;
+
+assert(height > floor_thickness && floor_thickness > 0, "height must exceed a positive floor");
+assert(diameter > 2 * (wall + rib_depth) && wall >= 1.2, "keep a useful inner diameter and wall >= 1.2 mm");
+assert(ribs >= 3 && ribs <= 100 && rib_depth >= 0, "use 3–100 ribs and nonnegative rib depth");
+$fn = resolution;
+
+// Continuous polar outline avoids coincident seams between separate ribs.
+module outline() {
+ polygon([for (i = [0:resolution-1])
+ let(angle = i * 360 / resolution,
+ radius = diameter / 2 + rib_depth * (0.5 + 0.5*cos(ribs*angle)))
+ [radius*cos(angle), radius*sin(angle)]]);
+}
+difference() {
+ linear_extrude(height=height, twist=twist, slices=ceil(height/2), convexity=10)
+ outline();
+ translate([0,0,floor_thickness])
+ cylinder(h=height+0.1, r=diameter/2-wall);
+}
diff --git a/store/agents/openscad/test/native.test.mjs b/store/agents/openscad/test/native.test.mjs
new file mode 100644
index 000000000..a7e65e60b
--- /dev/null
+++ b/store/agents/openscad/test/native.test.mjs
@@ -0,0 +1,102 @@
+import assert from 'node:assert/strict';
+import {test} from 'node:test';
+import {mkdtemp,readFile,writeFile,cp,mkdir,access} from 'node:fs/promises';
+import {tmpdir} from 'node:os';
+import {join} from 'node:path';
+import {spawnSync} from 'node:child_process';
+import {build} from '../skills/openscad/scripts/build.mjs';
+import {Native} from '../skills/openscad/scripts/native.mjs';
+const bin=process.env.OPENSCAD_BIN,root=process.env.OPENSCAD_QA_ROOT||tmpdir();
+const fixture=new URL('fixtures/bottles/',import.meta.url),template=new URL('../template/',import.meta.url);
+async function workspace(name,source){
+ await mkdir(root,{recursive:true});
+ const target=await mkdtemp(join(root,'openscad-'+name+'-'));
+ await cp(source,target,{recursive:true});console.log('Native QA workspace: '+target);return target;
+}
+const readJSON=async path=>JSON.parse(await readFile(path,'utf8'));
+const saveJSON=(path,value)=>writeFile(path,JSON.stringify(value,null,2)+'\n');
+test('native drawer family, substantive revision, and failed clearance/material/bed revisions preserve good downloads',{skip:!bin},async()=>{
+ const dir=await workspace('drawer',template),designPath=join(dir,'design.json'),modelPath=join(dir,'model.scad');
+ await writeFile(join(dir,'private-notes.txt'),'This undeclared file must not enter the portable project.');
+ const first=await build(dir,{bin});
+ assert.equal(first.variants.length,3);assert.equal(first.checks.length,24);assert.ok(first.checks.every(c=>c.passed));
+ const firstRevision=first.sourceRevision,brief=await readJSON(designPath);
+ brief.parameters.depth.value=104;brief.parameters.columns.value=4;
+ brief.title='Drawer Grid — four compartments';brief.brief='Revise to four compartments, 104 mm deep; keep the saved floor and wall thicknesses.';
+ await saveJSON(designPath,brief);
+ const revision=await build(dir,{bin});
+ assert.notEqual(revision.sourceRevision,firstRevision);
+ assert.ok(revision.variants.every(v=>v.parts[0].mesh.bounds.size[1]===104));
+ const saved=await readFile(join(dir,'handoff/project.zip')),goodModel=await readFile(modelPath,'utf8');
+ await writeFile(modelPath,goodModel.replace(', wall, floor])',', wall, floor/2])'));
+ await assert.rejects(()=>build(dir,{bin}),/floor/);
+ assert.deepEqual(await readFile(join(dir,'handoff/project.zip')),saved);
+ assert.equal((await readJSON(join(dir,'.harness/verdict.json'))).ready,false);
+ assert.ok((await readJSON(join(dir,'.harness/failed-mesh.json'))).checks.some(c=>c.id.endsWith('-floor')&&!c.passed));
+ await writeFile(modelPath,goodModel.replace('cube([width, depth, height]);','cube([width, depth, height]);').replace('module part(', 'module geometry(').replace('part("tray");','')+
+ '\nmodule part(id,width=180,depth=96,height=40,wall=2.4,floor=2.4,columns=3){union(){geometry(id,width,depth,height,wall,floor,columns);translate([wall,wall,floor])cube([2,2,2]);}}\n');
+ await assert.rejects(()=>build(dir,{bin}),/pockets/);
+ assert.deepEqual(await readFile(join(dir,'handoff/project.zip')),saved);
+ await writeFile(modelPath,goodModel);
+ const tooSmall=structuredClone(brief);tooSmall.process.bedMM[0]=140;tooSmall.variants=[brief.variants[0]];tooSmall.preview.variant='compact';
+ await saveJSON(designPath,tooSmall);
+ await assert.rejects(()=>build(dir,{bin}),/bed/);
+ assert.deepEqual(await readFile(join(dir,'handoff/project.zip')),saved);
+ await saveJSON(designPath,brief);
+ const restored=await build(dir,{bin});assert.equal(restored.sourceRevision,revision.sourceRevision);
+ const listing=spawnSync('/usr/bin/unzip',['-Z1',join(dir,'handoff/project.zip')],{encoding:'utf8'});
+ assert.equal(listing.status,0);assert.ok(!listing.stdout.includes('private-notes'));
+ const extracted=await workspace('portable',new URL('fixtures/empty/',import.meta.url));
+ const unzip=spawnSync('/usr/bin/unzip',['-q',join(dir,'handoff/project.zip'),'-d',extracted],{encoding:'utf8'});
+ assert.equal(unzip.status,0,unzip.stderr);
+ const rebuilt=spawnSync(process.execPath,['rebuild/build.mjs','.'],{cwd:extracted,env:{...process.env,OPENSCAD_BIN:bin},encoding:'utf8',timeout:600000,maxBuffer:4*1024*1024});
+ assert.equal(rebuilt.status,0,rebuilt.stderr);
+ const proof=await readJSON(join(extracted,'.harness/mesh.json'));
+ assert.equal(proof.sourceRevision,restored.sourceRevision);assert.equal(proof.checks.length,24);
+ assert.deepEqual(proof.variants.map(v=>v.parts.map(p=>p.printMesh.bounds)),restored.variants.map(v=>v.parts.map(p=>p.printMesh.bounds)));
+ await access(join(extracted,'preview.scad'));
+});
+test('native independent bottle rack and rotated negative-coordinate fit ring',{skip:!bin},async()=>{
+ const dir=await workspace('bottles',fixture),report=await build(dir,{bin});
+ assert.equal(report.checks.length,39);assert.ok(report.checks.every(c=>c.passed));
+ for(const variant of report.variants){
+ const ring=variant.parts.find(p=>p.id==='gauge');
+ assert.ok(ring.mesh.bounds.min[0]<0);assert.deepEqual(ring.printMesh.bounds.min,[0,0,0]);
+ assert.deepEqual(ring.printRotation,[180,0,0]);assert.equal(variant.parts.length,2);
+ }
+ const designPath=join(dir,'design.json'),brief=await readJSON(designPath);
+ const saved=await readFile(join(dir,'handoff/project.zip'));
+ const bad=structuredClone(brief);bad.variants=[bad.variants[1]];
+ bad.checks.find(c=>c.id==='separate-layout').translation=[20,20,0];
+ await saveJSON(designPath,bad);
+ await assert.rejects(()=>build(dir,{bin}),/separate-layout/);
+ assert.deepEqual(await readFile(join(dir,'handoff/project.zip')),saved);
+ await saveJSON(designPath,brief);
+ await build(dir,{bin});
+});
+test('native empty assertions/unknown modules cannot pass a query; undeclared inputs and random geometry are rejected',{skip:!bin},async()=>{
+ const dir=await workspace('guards',template),query=join(dir,'query');await mkdir(query);
+ for(const code of ['missing_module();','assert(false,"Deliberate failure");']){
+ await assert.rejects(()=>new Native(bin,query).render('invalid',code,{emptyAllowed:true}),/diagnostic/);
+ }
+ assert.equal((await new Native(bin,query).render('empty','intersection(){cube(1);translate([2,0,0])cube(1);}',{emptyAllowed:true})).empty,true);
+ const brief=await readJSON(join(dir,'design.json'));brief.variants=[brief.variants[1]];await saveJSON(join(dir,'design.json'),brief);
+ const original=await readFile(join(dir,'model.scad'),'utf8');
+ const outside=join(dir,'external.scad');await writeFile(outside,'module external(){cube(1);}\n');
+ await writeFile(join(dir,'model.scad'),'use <'+outside+'>\n'+original.replace('cube([width, depth, height]);','union(){cube([width, depth, height]);external();}'));
+ await assert.rejects(()=>build(dir,{bin}),/undeclared dependency/);
+ await writeFile(join(dir,'model.scad'),original.replace('cube([width, depth, height]);','cube([width+rands(1,10,1)[0], depth, height]);'));
+ await assert.rejects(()=>build(dir,{bin}),/repeated source exports disagree/);
+ await writeFile(join(dir,'geometry.scad'),original);
+ await writeFile(join(dir,'model.scad'),'include <geometry.scad>\n');
+ brief.sourceFiles.push('geometry.scad');await saveJSON(join(dir,'design.json'),brief);
+ const portableInput=await build(dir,{bin});
+ assert.equal(portableInput.checks.length,8);assert.ok(portableInput.sources['geometry.scad']);
+});
+test('native legacy Ripple remains editable geometry, not a falsely checked manufacturing handoff',{skip:!bin},async()=>{
+ const dir=await workspace('legacy',new URL('fixtures/empty/',import.meta.url));
+ await cp(new URL('fixtures/ripple.scad',import.meta.url),join(dir,'model.scad'));
+ const report=await build(dir,{bin});
+ assert.equal(report.checked,false);assert.equal(report.watertight,true);
+ const verdict=await readJSON(join(dir,'.harness/verdict.json'));assert.equal(verdict.ready,false);assert.equal(verdict.artifact,'part.stl');
+});
diff --git a/store/agents/openscad/test/toolchain.test.mjs b/store/agents/openscad/test/toolchain.test.mjs
index 43370cc27..8a6efb2b3 100644
--- a/store/agents/openscad/test/toolchain.test.mjs
+++ b/store/agents/openscad/test/toolchain.test.mjs
@@ -9,6 +9,7 @@ import { tmpdir } from 'node:os'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { after, test } from 'node:test'
+import { compiler } from './fixture.mjs'
const here = fileURLToPath(new URL('..', import.meta.url))
const manifest = JSON.parse(readFileSync(join(here, 'harness.json'), 'utf8'))
@@ -23,6 +24,8 @@ function tempDir() {
function run(script, { cwd = here, env = {} } = {}) {
const merged = { ...process.env }
+ delete merged.OPENSCAD_BIN
+ delete merged.OPENSCAD_TOOLCHAIN
for (const [key, value] of Object.entries(env)) if (value === null) delete merged[key]; else merged[key] = value
const result = spawnSync(join(here, script), { cwd, env: merged, encoding: 'utf8' })
return { code: result.status, stdout: result.stdout, stderr: result.stderr }
@@ -35,7 +38,7 @@ function fakeOpenscad() {
const faces = [[[0,0,0],[0,1,0],[1,0,0]],[[0,0,0],[1,0,0],[0,0,1]],[[0,0,0],[0,0,1],[0,1,0]],[[1,0,0],[0,1,0],[0,0,1]]]
const mesh = 'solid tetra\n' + faces.map(face => 'facet normal 0 0 0\nouter loop\n' + face.map(v => 'vertex '+v.join(' ')).join('\n') + '\nendloop\nendfacet').join('\n') + '\nendsolid tetra\n'
writeFileSync(join(dir,'fixture.stl'), mesh)
- writeFileSync(bin, '#!/bin/sh\n[ "$1" = "-o" ] || exit 0\ncp "'+join(dir,'fixture.stl')+'" "$2"\n')
+ writeFileSync(bin, compiler(join(dir,'fixture.stl')).replace('import {copyFileSync,writeFileSync} from "node:fs";', 'const {copyFileSync,writeFileSync}=require("node:fs");'))
chmodSync(bin, 0o755)
return { dir, bin }
}
@@ -48,7 +51,9 @@ test('every script the manifest names is in the folder and executable', () => {
test('setup finds an openscad CLI on PATH and says ok', () => {
const { dir, bin } = fakeOpenscad()
- const { code, stdout } = run(manifest.toolchain.setup, { env: { PATH: `${dir}:/usr/bin:/bin` } })
+ const install = tempDir()
+ mkdirSync(join(install, 'toolchain'))
+ const { code, stdout } = run(manifest.toolchain.setup, { env: { PATH: `${dir}:/usr/bin:/bin`, HARNESS_DSH_DIR: install } })
assert.equal(code, 0)
assert.match(stdout, /ok openscad/)
})
@@ -76,7 +81,7 @@ test('init seeds the first verdict and the initialized marker', () => {
assert.match(readFileSync(join(workspace, '.harness-initialized'), 'utf8'), new RegExp(manifest.id.replace('/', '/')))
})
-test('render-part.sh renders an artifact and flips the verdict, exactly as SKILL.md writes it', () => {
+test('render-part.sh exports a legacy preview without claiming checked readiness', () => {
const skill = readFileSync(join(here, 'skills/openscad/SKILL.md'), 'utf8')
const command = 'sh "$OPENSCAD_SKILLS/openscad/scripts/render-part.sh"'
assert.ok(skill.includes(command), 'SKILL.md should document the one-stop render command')
@@ -88,12 +93,12 @@ test('render-part.sh renders an artifact and flips the verdict, exactly as SKILL
writeFileSync(join(workspace, 'model.scad'), 'cube(10);\n')
const result = spawnSync('/bin/sh', ['-c', command], {
cwd: workspace,
- env: { ...process.env, OPENSCAD_SKILLS: join(here, 'skills'), PATH: `${dir}:${dirname(process.execPath)}:/usr/bin:/bin`, HARNESS_WORKSPACE: workspace },
+ env: { ...process.env, OPENSCAD_BIN: bin, OPENSCAD_SKILLS: join(here, 'skills'), PATH: `${dir}:${dirname(process.execPath)}:/usr/bin:/bin`, HARNESS_WORKSPACE: workspace },
encoding: 'utf8',
})
assert.equal(result.status, 0, result.stderr)
assert.equal(existsSync(join(workspace, 'part.stl')), true)
const verdict = JSON.parse(readFileSync(join(workspace, '.harness/verdict.json'), 'utf8'))
- assert.equal(verdict.ready, true)
+ assert.equal(verdict.ready, false)
assert.equal(verdict.artifact, 'part.stl')
})
diff --git a/store/showcase/openscad/bottles.jpg b/store/showcase/openscad/bottles.jpg
new file mode 100644
index 000000000..837349c6a
Binary files /dev/null and b/store/showcase/openscad/bottles.jpg differ
diff --git a/store/showcase/openscad/drawer.jpg b/store/showcase/openscad/drawer.jpg
new file mode 100644
index 000000000..8f6b29cef
Binary files /dev/null and b/store/showcase/openscad/drawer.jpg differ
diff --git a/store/showcase/openscad/handoff.jpg b/store/showcase/openscad/handoff.jpg
new file mode 100644
index 000000000..ef9d54be9
Binary files /dev/null and b/store/showcase/openscad/handoff.jpg differ
diff --git a/store/tools/REAL-WORKFLOWS.md b/store/tools/REAL-WORKFLOWS.md
index 23345d3a6..4a194f005 100644
--- a/store/tools/REAL-WORKFLOWS.md
+++ b/store/tools/REAL-WORKFLOWS.md
@@ -19,7 +19,7 @@ catalog workflow and verify the live catalog after each accepted release.
| --- | --- | --- | --- |
| 1 | freecad | Measurements and fit requirements → checked assembly, individual parts, editable native/source project and handoff | Implemented and validated; relisted in this change. See [acceptance evidence](../agents/freecad/test/ACCEPTANCE.md). |
| 2 | score | Musical brief and player constraints → revised score, audible mix, individual parts and practice exports | Implemented and validated; relisted in this change. See [acceptance evidence](../agents/score/test/ACCEPTANCE.md). |
-| 3 | openscad | Dimensions and fabrication constraints → parametric parts, verified variants and usable exports | Not started; unlisted |
+| 3 | openscad | Dimensions and fabrication constraints → parametric parts, verified variants and usable exports | Implemented and validated; relisted in this change. See [acceptance evidence](../agents/openscad/test/ACCEPTANCE.md). |
| 4 | orca-slicer | User mesh and explicit machine/material profiles → compared slicing options and reviewed toolpath handoff | Not started; unlisted |
| 5 | data-studio | User data and a question → saved analysis, source-linked results and repeatable report | Not started; unlisted |
| 6 | gis | User geographic data and a decision → reproducible spatial analysis and exported results | Not started; unlisted |