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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Rebuild OrcaSlicer for native slicing plans and portable projects (#138)
Dee77a106786ef8
diff --git a/.github/workflows/experience-checks.yml b/.github/workflows/experience-checks.ymlindex 6b902f0c3..3554fb713 100644--- a/.github/workflows/experience-checks.yml+++ b/.github/workflows/experience-checks.yml@@ -37,6 +37,8 @@ jobs: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+ - name: Check OrcaSlicer briefs, G-code and delivery (native suite is opt-in)+ run: node --test store/agents/orca-slicer/test/*.test.mjsauthoring-browser:runs-on: ubuntu-latestdiff --git a/store/agents/orca-slicer/AGENTS.md b/store/agents/orca-slicer/AGENTS.mdindex a21fa30eb..29258b1b2 100644--- a/store/agents/orca-slicer/AGENTS.md+++ b/store/agents/orca-slicer/AGENTS.md@@ -1,18 +1,27 @@-# Orca Slicer harness+# Orca Slicer · Strata-Read the `orcaslicer` skill. Use `slice-config.json` as the executable profile-contract and `model.stl` as the input mesh. Build with:+Read the `orcaslicer` skill. Deliver a revised, usable slicing project: actual+G-code, editable native 3MF, effective profiles, checked evidence and portable+source—not just a toolpath animation.++Ask for the user's STL, millimetre dimensions, printer/nozzle/firmware, plate,+filament and goal (time, finish or material). Without hardware details, keep+`machine.context: "example"` and the conspicuous example warning. Never infer a+real printer from a bundled profile.++Save independent requirements in `slice-config.json` before slicing. Run:```shsh "$ORCA_SKILLS/orcaslicer/scripts/slice-part.sh"```-Show the actual toolpath in `preview.html`. Inspect the first layer, layer stack,-travel/custom moves, speed coloring, slicer estimates and recorded profile inputs.-The default Prusa profile is a labeled demo, never a claim about the user's printer.-Ask for the actual machine and material before preparing a hardware-specific file.+Inspect `.harness/verdict.json`, `slice.log` and `handoff/report.json`; then use+`preview.html` to compare all plans, first layers, full motion and heater commands.+Make a substantive requested revision and rebuild. Download and reopen a 3MF;+the builder also independently reopens every native project with Orca.-`ready` means freshly sliced and parsed, not watertight, collision-free, printable,-or print-tested. Never fake a successful receipt, select an old G-code by mtime,-or substitute PrusaSlicer for OrcaSlicer's different CLI. Preserve old artifacts on-failure but write a new failed verdict. Do not print, upload, or run post-processors.+`ready` means this saved brief passed the documented software checks. It never+means physically print-tested, collision-free, strong, food-safe or safe to print.+A failed candidate preserves the last successful files but clears readiness.+Do not relabel old files as a new successful slice. Do not upload, connect to,+heat or start a printer, run post-processors, or substitute another slicer.diff --git a/store/agents/orca-slicer/PROVENANCE.md b/store/agents/orca-slicer/PROVENANCE.mdindex 6abef00b6..847029759 100644--- a/store/agents/orca-slicer/PROVENANCE.md+++ b/store/agents/orca-slicer/PROVENANCE.md@@ -1,13 +1,30 @@# Provenance-The wrapper, linear G-code parser, Strata inspector and fluted-vessel SCAD/STL-starter are original OpenHarness work, licensed under the included MIT license.+The wrapper, strict brief/mesh/G-code inspection, Strata comparison viewer,+archive/server helpers, Bottle Bench rack and spacer test fixture are original+OpenHarness work under the included MIT license. Mesh/archive/transaction helpers+are adapted from the original OpenHarness OpenSCAD and Score harnesses; each+package carries its own standalone copy and license.-[OrcaSlicer](https://github.com/OrcaSlicer/OrcaSlicer) is a separately installed-AGPL-3.0 project derived from PrusaSlicer. No slicer binaries, source code or-printer/material profiles are redistributed in this package. Demo builds load-the named profiles from the user's OrcaSlicer installation and record the resolved-settings in the workspace. Tested with version 2.4.2.+The rack STL was regenerated from `template/model.scad` with OpenSCAD 2021.01.+Its geometry matches the Everyday six-bottle rack in the OpenSCAD harness's+acceptance workflow. The spacer STL was generated from its adjacent original+test SCAD. They are dimensional examples, not physically fit- or load-tested+products. Screenshots show actual native slices in the working viewer.-The STL was generated from the included original model.scad using OpenSCAD-2021.01. It is a demonstration model, not a certified manufacturable product.+[OrcaSlicer](https://github.com/OrcaSlicer/OrcaSlicer) is separately installed,+AGPL-3.0 software derived from PrusaSlicer. No Orca binaries, source code or+bundled printer/filament profiles are committed to this package. Tested with+OrcaSlicer 2.4.2, using its own CLI and native 3MF exporter/importer.++At runtime, the chosen installed or user-exported JSON presets are resolved.+Generated portable projects contain flattened copies of those selected settings+and a PROFILE-NOTICES file linking to upstream source/license. That profile data+is not relicensed as OpenHarness MIT code. Printer connection fields and+credentials are rejected/removed; post-processors are never executed.++Primary upstream CLI documentation:+[CLI mode](https://github.com/OrcaSlicer/OrcaSlicer/wiki/cli_mode),+[CLI actions](https://github.com/OrcaSlicer/OrcaSlicer/wiki/cli_actions).+This implementation was also checked against the installed 2.4.2 `--help`.+No upstream endorsement or stewardship is implied.diff --git a/store/agents/orca-slicer/README.md b/store/agents/orca-slicer/README.mdindex 9c787af02..78580bb82 100644--- a/store/agents/orca-slicer/README.md+++ b/store/agents/orca-slicer/README.md@@ -1,61 +1,88 @@# Orca Slicer · Strata-Turn a mesh into a toolpath you can actually inspect. Strata shows the real linear-moves from OrcaSlicer: scrub 240 layers of the included fluted vessel, orbit the-stack, isolate a layer, show travel and purge paths, or color by speed.+Turn “I have this STL—how should I print it?” into a project you can inspect,+change and take to OrcaSlicer. Compare real slicing plans for time, material and+layer tradeoffs; inspect actual toolpaths and heater commands; keep the editable+native 3MF, G-code, profiles and source together.-## First run+No printer is required to use the software workflow. The starter is a six-bottle+craft rack, sliced three ways against an explicitly labelled example machine.+It is not a recommendation for an unknown printer.-Install `autonomous/orca-slicer` from the Harness Store. Install-[OrcaSlicer 2.4.2](https://github.com/OrcaSlicer/OrcaSlicer/releases) separately,-then run the harness doctor. Set `ORCA_BIN` for a nonstandard binary.-The included model and **demo** profiles make a local toolpath study:+## Try it++Install `autonomous/orca-slicer` from the Harness Store and install+[OrcaSlicer 2.4.2](https://github.com/OrcaSlicer/OrcaSlicer/releases) separately.+The harness uses its managed Node runtime. For a nonstandard installation set+`ORCA_BIN`; for profiles outside the usual app resources set `ORCA_PROFILES_DIR`.++Ask: “Compare faster and finer plans for this rack. Keep the printer as a+software-only example. Show the actual tradeoff and give me projects I can edit.”```shsh "$ORCA_SKILLS/orcaslicer/scripts/slice-part.sh"```-The build produces `part.gcode`, `preview.html`, and a fresh verdict. The default-Prusa MK3S / 0.4 mm / PLA profile is **not your printer**. Do not send this G-code-to hardware until you have reviewed the exact machine, filament, temperatures,-bed origin, first layer and all machine-specific commands in OrcaSlicer.+The viewer compares plans, verifies each G-code hash before display, scrubs or+isolates layers, colors by feature/speed, and shows every commanded linear move+in **Full motion**, including purge, Z hops and parking. Review notes and view+state can be downloaded and restored for that exact source/toolpath revision.++## Use your own part++Supply an STL and its millimetre dimensions, intended use, printer/nozzle,+firmware, plate and filament. Save requirements in `slice-config.json` before+slicing. Use installed profiles or explicit workspace JSON exports and their+sibling inheritance files. Profile credentials and post-processors are rejected.++Compare 1–4 plans; choose heights, wall counts, infill, top/bottom layers,+supports and brim, with saved time/material estimate budgets and a bed inset.+Orientation and scale are explicit; no silent auto-orient. The current checked+scope is one closed STL, one extruder, Marlin/Marlin 2, and a zero-origin+rectangular bed without exclusion zones. Unsupported workflows fail clearly.-## Make it yours+Revise the brief or mesh, then rebuild. CAD source is included for editing, but+this slicer uses the STL; it does not automatically compile SCAD changes.-Ask: “Adapt this dry-use vessel to 70 mm tall, compare two layer heights, and-explain the time/filament tradeoff. Do not print it.”+## Own the result-Edit `slice-config.json`, not the descriptive `print-config.md`. Demo profile-paths resolve against the installed Orca profiles directory; on Linux or a-nonstandard install set `ORCA_PROFILES_DIR`. Custom mode takes three exported JSON-profiles, relative to the workspace or absolute. Put inherited parent JSON files-beside their children; the builder resolves the explicit chain and records the-flattened settings in `.harness/*-resolved.json`. Missing parents fail rather-than silently substituting defaults. The model must be an STL inside the workspace.+- `part.gcode` / `part.3mf`: the selected plan.+- `handoff/plans/<id>/`: every actual G-code, editable native 3MF, effective+ settings and inspection receipt.+- `handoff/report.json`: source hashes, requirements, comparisons and evidence.+- `handoff/project.zip`: declared source, flattened profiles, results and+ standalone rebuild/preview tools. No binary or unrelated workspace files.+- `.harness/verdict.json`: current build status. Failed candidates preserve the+ last good handoff and clear readiness; earlier outputs are in local history.++Extract the ZIP elsewhere, install Node 22+ and OrcaSlicer, then:++```sh+ORCA_BIN=/path/to/OrcaSlicer node rebuild/build.mjs+node rebuild/serve-preview.mjs .+```-The original `model.scad` is included alongside its generated STL. Edit it with-OpenSCAD, re-export the mesh, then re-slice. This harness does not run a CAD build-automatically.+Open the printed loopback URL. Native 3MF/G-code work independently of the viewer.-## What is verified+## Evidence, not a print certificate-A new OrcaSlicer process must succeed and produce exactly one fresh, nonempty-G-code plate with linear extrusion paths. Failed builds clear readiness and-preserve the previous preview. Logs and receipts live in `.harness/`.-The starter was sliced with OrcaSlicer 2.4.2 and inspected in a real browser.-Unit tests additionally cover parsing, profile inheritance and failed builds.+Every plan is freshly sliced. The builder checks independent saved dimensions,+closed positive-volume mesh shells, profile/setting agreement, actual heater+commands, model/support centerlines, layers and estimate budgets. It verifies+the exact G-code inside the 3MF, then reopens the project in Orca and compares+geometry and effective settings. See [acceptance evidence](test/ACCEPTANCE.md).-The inspector supports single-tool linear G0/G1 paths, coordinate/extrusion-modes, resets and units. Arc fitting and post-processing are disabled for this-workflow. Curved/multitool paths fail explicitly. Travel-only Z-hop heights are-omitted from the layer list. Custom/purge moves are hidden in model focus by-default; enable them to inspect the full extent. Estimates come from the slicer,-not a timed print. No mesh-manifold, collision, thermal, firmware or structural-safety certification is implied. Nothing is uploaded, printed or connected.+`ready` means those software checks passed—not that a physical print was tested.+No strength, fit, support adequacy, collision, firmware, thermal or food-safety+claim is made. Purge/parking can extend beyond the model inset and must be+reviewed. The inspector is bounded to 32 MiB G-code / one million linear moves.+Review the actual printer, profiles, plate, material, custom commands and first+layer in OrcaSlicer before any hardware use. Nothing is uploaded or printed.## 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.+Original OpenHarness wrapper/UI/models are MIT. OrcaSlicer and selected upstream+profiles retain their separate terms; see [PROVENANCE.md](PROVENANCE.md).+No upstream ownership or endorsement is implied.+Wrapper issues belong in OpenHarness; upstream maintainers are welcome to take+stewardship of the package.diff --git a/store/agents/orca-slicer/harness.json b/store/agents/orca-slicer/harness.jsonindex 59561665d..4127891ef 100644--- a/store/agents/orca-slicer/harness.json+++ b/store/agents/orca-slicer/harness.json@@ -4,7 +4,7 @@"name": "Orca Slicer","category": "Fabrication","author": "OpenHarness contributors",- "description": "Describe a part to print; get G-code \u2014 a printable mesh sliced to your printer's profile, with a print summary (time, filament, layers) live in the pane.",+ "description": "Turn your STL and printer brief into compared slicing plans, checked G-code, editable native Orca projects and a portable handoff. Inspect actual paths and revise time/material tradeoffs without connecting a printer.","engine": "claude","workspace": {"template": "template",diff --git a/store/agents/orca-slicer/skills/orcaslicer/SKILL.md b/store/agents/orca-slicer/skills/orcaslicer/SKILL.mdindex 5fa9310b8..e751d4cbc 100644--- a/store/agents/orca-slicer/skills/orcaslicer/SKILL.md+++ b/store/agents/orca-slicer/skills/orcaslicer/SKILL.md@@ -1,44 +1,105 @@---name: orcaslicer-description: Slice an STL with explicit OrcaSlicer JSON profiles and inspect actual G-code layers, travel, features and speeds. Use for Orca Slicer harness work.+description: Turn a user's STL and explicit machine/material requirements into compared OrcaSlicer plans, editable 3MF projects, checked G-code and a portable handoff. Use for Orca Slicer harness work.----# Strata workflow--1. Inspect the mesh dimensions and intended use. The included fluted vessel is an- original dry-use demo, not a food-safe or pressure-rated design.-2. Set `slice-config.json`: mode `demo` loads the specified installed Orca- profiles; `custom` loads explicit workspace-relative or absolute JSON files.- Required keys: `model`, `printer`, `process`, `filament`. Parent profiles- must be sibling JSON files. Notes in `print-config.md` do not change settings.-3. Run the real build:-- ```sh- sh "$ORCA_SKILLS/orcaslicer/scripts/slice-part.sh"- ```--4. Inspect `.harness/slice.log`, `slice.json` and the three resolved profile- files. Open `preview.html`: scrub layers, isolate one, inspect first-layer- travel and enable custom/purge moves (hidden by default for model focus).-5. Review the exact G-code and profiles in OrcaSlicer before any proposed print.- Report slicer estimates as estimates and unsupported preview behavior plainly.--## Runtime and limits--Tested with OrcaSlicer 2.4.2. Set `ORCA_BIN` and, if needed,-`ORCA_PROFILES_DIR`. PrusaSlicer is not a compatible fallback. The builder uses-a fresh temporary output directory, explicit flattened profiles, disables arc-fitting and post-processing, and requires one fresh plate. No machine connection-is made. Builds fail closed; an old preview is not a new successful build.--The linear single-tool inspector handles G0/G1, G20/G21, G90/G91, M82/M83 and G92.-Curves and multiple tools are rejected. Firmware retraction, leveling, offsets,-collisions and material behavior are not simulated. Travel-only heights are not-extrusion layers. Maximum preview: 32 MiB text and 250,000 linear moves.--## Verification language--Ready means “sliced and parsed,” not “safe to print.” The helper does not establish-watertightness, support adequacy or printer compatibility. Do not assert those-properties without independent evidence. Do not upload or print without explicit-user authorization. Preserve the editable mesh source and exact profile inputs.+# Strata: mesh to an owned slicing project++## Establish the brief++Ask for a mesh, its intended millimetre dimensions and use, and the actual+printer model, nozzle, firmware, plate and filament. Ask which tradeoff matters.+If those details are unavailable, a clearly labelled software-only example is+useful; keep `machine.context: "example"`. No hardware is needed to compare,+inspect, revise or export it. Do not treat the example as the user's printer.++Start from the schema in `template/slice-config.json` in this package. Save the+brief before running the slicer:++- `sourceFiles` is the explicit portable-source allowlist. Include the config,+ STL, supporting CAD/notes and all workspace-profile inheritance files.+ Never add unrelated workspace files or credentials.+- `model.expectedSizeMM` is the requirement, not a value copied back from a+ failed output. STL has no unit metadata. `rotationDegrees` rotates X, then Y,+ then Z; `scale` is explicit. Orca cannot silently reorient this workflow.+- `profiles.source` is `installed` or `workspace`. Installed paths are relative+ to `ORCA_PROFILES_DIR` or Orca's bundled profiles directory. Workspace paths+ are safe relative paths, with inherited JSON parents beside the child.+ Remove connection credentials and post-processors from exported profiles.+- `machine` records independent model/nozzle/bed/plate/firmware/material and+ temperature envelopes. These bounds apply to all nonzero heater commands,+ including startup targets; they are not measured temperatures.+- Save 1–4 `plans`, a `selectedPlan`, estimate budgets and a bed inset. Each plan+ states layer/first-layer heights, walls, infill, top/bottom layers, supports+ and brim. Changing a prose note does not change a slicing setting.++The current checked scope is one closed STL, one extruder, Marlin or Marlin 2,+and a zero-origin rectangular bed without exclusion zones. Unknown fields,+unsupported motion/macros and missing profiles fail explicitly. Do not broaden+a passing claim to Klipper macros, multi-material, belt/nonrectangular machines+or firmware retraction. Unsupported machines need a separately implemented+and verified workflow, not an arbitrary flag change.++## Build, inspect, revise++```sh+sh "$ORCA_SKILLS/orcaslicer/scripts/slice-part.sh"+```++Node 22+ and OrcaSlicer 2.4.2 are tested. Set `ORCA_BIN` and, where needed,+`ORCA_PROFILES_DIR`. This helper does not use PrusaSlicer's different CLI.+It creates an isolated Orca data directory and fresh output per plan; no printer+connection is made. Arc fitting, post-processing, spiral mode and infill+combination are disabled. Top/bottom thickness minima are zero so the saved+layer counts are not silently overridden by inherited minimum-thickness values.++Open `preview.html` in the harness. Compare estimates, inspect the first layer,+isolate layers, show travel and use **Full motion** to include purge, Z hops and+final parking. The normal layer list includes extrusion heights, not every+travel height. Custom purge may legitimately lie outside the model inset;+review its separately reported full-motion bounds and exact commands.++Use `handoff/report.json` for the saved source revision, profile names, effective+settings, checks, temperatures and native-reopen evidence. The live verdict is+`.harness/verdict.json`; a retained preview after a failure is an older success.+`.harness/slice.log` contains native diagnostics. Never hand-edit checks or+readiness to suppress a failure.++Make revisions in the saved inputs, then rebuild. Check that the requested+change appears in effective settings and actual paths/estimates. Discuss the+tradeoff without promising strength, finish or physical fit from wall counts.+The included `model.scad` is provenance, not an automatically compiled input:+after CAD changes, re-export its STL before slicing.++## Deliver a reusable result++Each `handoff/plans/<id>/` contains actual G-code, native editable `project.3mf`,+effective JSON and an inspection receipt. `part.gcode` and `part.3mf` are the+selected plan. The complete-project ZIP includes declared source, flattened+profiles, all native results and standalone Node helpers. It excludes unrelated+files and the Orca binary. Respect upstream profile notices.++Reopen the chosen 3MF in OrcaSlicer. For a handoff verification, extract the ZIP+into a separate directory and run `node rebuild/build.mjs` with `ORCA_BIN` set.+Use `node rebuild/serve-preview.mjs .` for its loopback viewer; file:// cannot+fetch toolpaths. Downloaded review JSON saves plan/view/notes and restores only+against the matching source and G-code hashes. It is not print authorization.++## What the checks establish++The helper measures mesh closure/orientation, dimensions and bed envelope;+checks effective settings against emitted G-code settings and saved constraints;+inspects linear model/support centerlines, layer heights, estimate budgets and+actual heater target commands; requires both heaters off after final extrusion;+and verifies exact embedded G-code plus native 3MF geometry/settings reopening.+The only reopen normalization is absent versus empty `upward_compatible_machine`+preset metadata. No slicing value is ignored.++Limits: 32 MiB per source/G-code/download, 64 MiB total declared sources,+1,000,000 linear moves, 1,000,000 STL triangles, 4 plans, 128 MiB expanded ZIP.+Mesh checks weld at 1e-5 mm; they do not prove no self-intersections. The parser+models retraction debt, units and coordinate/extrusion modes, but not actual+firmware motion, offsets, leveling, pressure/flow overrides, collisions, thermal+behavior, support adequacy or material mechanics. Estimates are not timed prints.+No physical print or safety certification is implied. Never upload or print+without a separate explicit request and the appropriate machine-specific review.diff --git a/store/agents/orca-slicer/skills/orcaslicer/scripts/LICENSE b/store/agents/orca-slicer/skills/orcaslicer/scripts/LICENSEnew file mode 100644index 000000000..d3eab18ed--- /dev/null+++ b/store/agents/orca-slicer/skills/orcaslicer/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/orca-slicer/skills/orcaslicer/scripts/archive.mjs b/store/agents/orca-slicer/skills/orcaslicer/scripts/archive.mjsnew file mode 100644index 000000000..99c23c105--- /dev/null+++ b/store/agents/orca-slicer/skills/orcaslicer/scripts/archive.mjs@@ -0,0 +1,61 @@+// Small, bounded, deterministic ZIP writer. No global npm or Python dependency.+import {deflateRawSync,inflateRawSync} 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>128*1024*1024) throw new Error('Portable project exceeds 128 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;+}++// Read ZIP members in memory, never extract paths. Orca's 3MF is a ZIP container.+export function unzip(input) {+ const data=Buffer.from(input);if(data.length>32*1024*1024)throw new Error('ZIP exceeds 32 MiB.');+ let end=-1;for(let p=data.length-22;p>=Math.max(0,data.length-65557);p--)if(data.readUInt32LE(p)===0x06054b50&&p+22+data.readUInt16LE(p+20)===data.length){end=p;break;}+ if(end<0)throw new Error('Missing ZIP directory.');+ const count=data.readUInt16LE(end+10),size=data.readUInt32LE(end+12),start=data.readUInt32LE(end+16);+ if(data.readUInt16LE(end+4)||data.readUInt16LE(end+6)||count!==data.readUInt16LE(end+8)||!count||count>256||start+size!==end)throw new Error('Unsupported ZIP directory.');+ const result=new Map(),seen=new Set(),ranges=[];let cursor=start,total=0;+ for(let i=0;i<count;i++){+ if(cursor+46>end||data.readUInt32LE(cursor)!==0x02014b50)throw new Error('Invalid ZIP entry.');+ const flags=data.readUInt16LE(cursor+8),method=data.readUInt16LE(cursor+10),crc=data.readUInt32LE(cursor+16),compressed=data.readUInt32LE(cursor+20),length=data.readUInt32LE(cursor+24),n=data.readUInt16LE(cursor+28),extra=data.readUInt16LE(cursor+30),comment=data.readUInt16LE(cursor+32),offset=data.readUInt32LE(cursor+42);+ if(flags&1||![0,8].includes(method)||compressed===0xffffffff||length===0xffffffff||offset===0xffffffff||data.readUInt16LE(cursor+34))throw new Error('Encrypted, split or ZIP64 files are unsupported.');+ if(cursor+46+n+extra+comment>end)throw new Error('Truncated ZIP entry.');+ const name=data.subarray(cursor+46,cursor+46+n).toString('utf8'),key=name.toLowerCase();+ if(!name||name.includes('\\')||name.includes('\0')||name.startsWith('/')||name.includes(':')||name.split('/').some(v=>v==='.'||v==='..'||!v)||seen.has(key))throw new Error('Unsafe or duplicate ZIP path.');+ if((data.readUInt32LE(cursor+38)>>>16&0xf000)===0xa000)throw new Error('ZIP symlinks are unsupported.');+ seen.add(key);total+=length;if(total>128*1024*1024)throw new Error('Expanded ZIP exceeds 128 MiB.');+ if(offset+30>start||data.readUInt32LE(offset)!==0x04034b50||data.readUInt16LE(offset+6)!==flags||data.readUInt16LE(offset+8)!==method)throw new Error('ZIP local header mismatch.');+ const ln=data.readUInt16LE(offset+26),le=data.readUInt16LE(offset+28),body=offset+30+ln+le,finish=body+compressed;+ if(finish>start||!data.subarray(offset+30,offset+30+ln).equals(Buffer.from(name)))throw new Error('ZIP member bounds/name mismatch.');+ if(ranges.some(([a,b])=>offset<b&&finish>a))throw new Error('Overlapping ZIP members.');ranges.push([offset,finish]);+ const bytes=method===0?data.subarray(body,finish):inflateRawSync(data.subarray(body,finish),{maxOutputLength:Math.max(1,length)});+ if(bytes.length!==length||crc32(bytes)!==crc)throw new Error('ZIP member checksum mismatch.');result.set(name,bytes);cursor+=46+n+extra+comment;+ }+ if(cursor!==end)throw new Error('Unexpected ZIP directory data.');return result;+}diff --git a/store/agents/orca-slicer/skills/orcaslicer/scripts/build.mjs b/store/agents/orca-slicer/skills/orcaslicer/scripts/build.mjsindex e0278ccbc..dd5a46845 100644--- a/store/agents/orca-slicer/skills/orcaslicer/scripts/build.mjs+++ b/store/agents/orca-slicer/skills/orcaslicer/scripts/build.mjs@@ -1,41 +1,97 @@-import {access,readFile,writeFile,mkdir,mkdtemp,readdir,rename,copyFile,rm,stat} from 'node:fs/promises';-import {constants} from 'node:fs';import {spawnSync} from 'node:child_process';import {resolve,join,dirname,isAbsolute,relative} from 'node:path';+import {readFile,mkdir,realpath} from 'node:fs/promises';+import {resolve,join,relative,sep} from 'node:path';+import {fileURLToPath} from 'node:url';+import {isDeepStrictEqual} from 'node:util';+import {createHash} from 'node:crypto';import {parseGcode} from './gcode.mjs';-import {resolveProfile} from './profiles.mjs';-const ws=resolve(process.env.HARNESS_WORKSPACE||process.cwd()),meta=join(ws,'.harness');await mkdir(meta,{recursive:true});-const verdict=async(ready,summary,findings=[])=>writeFile(join(meta,'verdict.json'),JSON.stringify({spec:1,ready,summary,findings,artifact:ready?'preview.html':null,updatedAt:new Date().toISOString()},null,2)+'\n');-await verdict(false,'Loading explicit slicer profiles…');let stage,log='';-try{- const config=JSON.parse(await readFile(join(ws,'slice-config.json'),'utf8'));- if(!['demo','custom'].includes(config.mode))throw new Error('slice-config.json mode must be demo or custom.');- let bin=process.env.ORCA_BIN;if(!bin){bin=spawnSync('/bin/sh',['-c','command -v orca-slicer || command -v orcaslicer'],{encoding:'utf8'}).stdout.trim()||'/Applications/OrcaSlicer.app/Contents/MacOS/OrcaSlicer';}- await access(bin,constants.X_OK).catch(()=>{throw new Error('OrcaSlicer not found. Install OrcaSlicer 2.4.2 or set ORCA_BIN. PrusaSlicer is not a CLI substitute.');});- const profiles=process.env.ORCA_PROFILES_DIR||resolve(dirname(bin),'../Resources/profiles');- stage=await mkdtemp(join(meta,'slice-'));- const settings=[],resolvedProfiles={};- for(const key of ['printer','process','filament']){- if(typeof config[key]!=='string'||!config[key]||config[key].includes(';'))throw new Error('Provide one '+key+' JSON profile in slice-config.json.');- const path=resolve(config.mode==='demo'?profiles:ws,config[key]);- const profile=await resolveProfile(path);- const flat=join(stage,key+'.json');await writeFile(flat,JSON.stringify(profile,null,2));settings.push(flat);resolvedProfiles[key]=profile;- }- if(typeof config.model!=='string'||!config.model.toLowerCase().endsWith('.stl'))throw new Error('This workflow slices one STL mesh; specify model in slice-config.json.');- const model=resolve(ws,config.model),rel=relative(ws,model);if(isAbsolute(rel)||rel.startsWith('..'))throw new Error('The mesh must be inside this workspace.');await access(model);- const output=join(stage,'out');await mkdir(output);- const args=['--slice','0','--arrange','1','--ensure-on-bed','--load-settings',settings.slice(0,2).join(';'),'--load-filaments',settings[2],'--outputdir',output,'--enable-arc-fitting=0','--post-process','',model];- const result=spawnSync(bin,args,{cwd:stage,encoding:'utf8',timeout:240000,maxBuffer:16*1024*1024});log=(result.stdout||'')+(result.stderr||'');- if(result.error||result.status!==0)throw new Error(result.error?.message||'OrcaSlicer failed; inspect .harness/slice.log.');- const files=(await readdir(output)).filter(name=>name.endsWith('.gcode'));- if(files.length!==1)throw new Error('Expected exactly one freshly sliced G-code plate; got '+files.length+'.');- const gcode=await readFile(join(output,files[0]),'utf8'),parsed=parseGcode(gcode);- const data={...parsed,config,at:new Date().toISOString(),bytes:Buffer.byteLength(gcode)};- const template=await readFile(new URL('preview.html',import.meta.url),'utf8'),app=await readFile(new URL('preview.js',import.meta.url),'utf8');- const safe=JSON.stringify(data).replace(/</g,'\\u003c').replace(/\u2028/g,'\\u2028').replace(/\u2029/g,'\\u2029');- await writeFile(join(stage,'preview.html'),template.replace('__CONFIG__',()=>safe).replace('/*APP*/',()=>app));- await copyFile(join(output,files[0]),join(stage,'part.gcode'));await rename(join(stage,'part.gcode'),join(ws,'part.gcode'));await rename(join(stage,'preview.html'),join(ws,'preview.html'));- await writeFile(join(meta,'slice.json'),JSON.stringify({config,stats:parsed.stats,layers:parsed.layers.length,moves:parsed.moves,warnings:parsed.warnings},null,2)+'\n');- for(const [key,profile]of Object.entries(resolvedProfiles))await writeFile(join(meta,key+'-resolved.json'),JSON.stringify(profile,null,2)+'\n');- await verdict(true,parsed.layers.length+' extrusion heights inspected · not print-tested',[{severity:'warning',kind:'safety',message:config.mode==='demo'?'Demo Prusa profile, not your printer. Do not print this file until printer, material, temperatures and geometry are reviewed.':'A sliced file is not a safety or printability certificate. Review machine-specific G-code in OrcaSlicer before printing.'},...parsed.warnings.map(message=>({severity:'info',kind:'preview',message}))]);- console.log('ok '+parsed.layers.length+' extrusion heights → part.gcode + preview.html');-}catch(error){await verdict(false,'Slice failed',[{severity:'error',kind:'slice',message:error.message}]);console.error(error.message);process.exitCode=1;}-finally{await writeFile(join(meta,'slice.log'),log);if(stage)await rm(stage,{recursive:true,force:true});}+import {profileWithSources,unchangedProfiles} from './profiles.mjs';+import {validateConfig,assertProfiles,prepareModel,inspectPlan,planSettings,assertMesh,canonicalReopenSettings} from './contract.mjs';+import {inspectSTL} from './mesh.mjs';+import {zip,unzip} from './archive.mjs';+import {engine,runNative,oneFile} from './native.mjs';+import {source,snapshot,unchanged,save,atomic,publish,transaction,sha,json} from './files.mjs';+const local=name=>new URL(name,import.meta.url);+const toolkit=['build.mjs','native.mjs','profiles.mjs','contract.mjs','mesh.mjs','archive.mjs','files.mjs','gcode.mjs','preview.html','preview.js','preview.css','serve-preview.mjs','LICENSE'];+const limits='Software checks only. No physical print, strength, fit, support adequacy, collision, firmware behavior, offsets, bed leveling or thermal safety is certified. Estimates are from the slicer, not measured print times. Custom purge/parking moves may be outside the model bed inset; review all commands in OrcaSlicer. Never send these files to an unverified printer.';+export async function build(workspace=process.env.HARNESS_WORKSPACE||process.cwd()){+ const ws=await realpath(resolve(workspace));+ return transaction(ws,async({state,stage,verdict})=>{+ let log='';try{+ const c=validateConfig(JSON.parse(await source(ws,'slice-config.json'))),files=await snapshot(ws,c.sourceFiles);+ const native=await engine(),resolved={},origins=[];+ for(const key of ['printer','process','filament']){+ const path=resolve(c.profiles.source==='installed'?native.profiles:ws,c.profiles[key]);+ if(c.profiles.source==='workspace')await source(ws,c.profiles[key]);+ const result=await profileWithSources(path);resolved[key]=result.profile;origins.push(result);+ if(c.profiles.source==='workspace')for(const entry of result.sources){+ const name=relative(ws,entry.path).split(sep).join('/');+ if(!c.sourceFiles.includes(name))throw new Error('Declare inherited workspace profile in sourceFiles: '+name);+ await source(ws,name);+ }+ }+ assertProfiles(resolved,c);+ const input=files.find(f=>f.name===c.model.path),model=prepareModel(input.bytes,c);+ const profilePaths=new Set(origins.flatMap(p=>p.sources.map(s=>relative(ws,s.path).split(sep).join('/'))));+ const semanticFiles=files.filter(f=>f.name!=='slice-config.json'&&!profilePaths.has(f.name)).map(f=>({name:f.name,sha256:sha(f.bytes)}));+ const revision=sha(json({brief:{...c,sourceFiles:undefined,profiles:undefined},sources:semanticFiles,profiles:resolved}));+ const report={spec:1,revision,title:c.title,brief:c.brief,assumptions:c.assumptions,machine:c.machine,model:{source:model.input,oriented:model.mesh,rotationDegrees:c.model.rotationDegrees,scale:c.model.scale},selectedPlan:c.selectedPlan,limits:c.limits,sourceFiles:files.map(f=>({name:f.name,sha256:sha(f.bytes)})),profileNames:Object.fromEntries(Object.entries(resolved).map(([k,p])=>[k,p.name])),plans:[],limitations:limits};+ const handoff=join(stage,'handoff');await mkdir(handoff);+ const bundle=[];+ const output=async(name,bytes)=>{await save(join(stage,name),bytes);bundle.push({name,bytes});};+ await save(join(stage,'oriented.stl'),model.bytes);+ for(const plan of c.plans){+ const job=join(stage,'job-'+plan.id),out=join(job,'out'),reopened=join(job,'reopened');await mkdir(out,{recursive:true});await mkdir(reopened);+ const printer=join(job,'printer.json'),process=join(job,'process.json'),filament=join(job,'filament.json');+ await save(printer,json(resolved.printer));await save(process,json({...resolved.process,...planSettings(plan)}));await save(filament,json(resolved.filament));+ const args=['--datadir',join(job,'appdata'),'--debug','2','--slice','0','--arrange','1','--orient','0','--allow-rotations=0','--ensure-on-bed','--load-settings',printer+';'+process,'--load-filaments',filament,'--outputdir',out,'--export-3mf','project.3mf','--export-settings',join(job,'effective.json'),'--curr-bed-type='+c.machine.bedType,'--enable-arc-fitting=0','--post-process','',join(stage,'oriented.stl')];+ log+='\nPLAN '+plan.id+'\n'+runNative(native.bin,args,job);+ const raw=await oneFile(out,'.gcode'),project=await oneFile(out,'.3mf'),effective=JSON.parse(await readFile(join(job,'effective.json'))),parsed=parseGcode(raw.bytes.toString('utf8'));+ const checks=inspectPlan(parsed,effective,c,plan,model.mesh),members=unzip(project.bytes);+ const embedded=members.get('Metadata/plate_1.gcode'),digest=members.get('Metadata/plate_1.gcode.md5');+ if(!embedded?.equals(raw.bytes)||digest?.toString('utf8').trim().toLowerCase()!==createHash('md5').update(raw.bytes).digest('hex'))throw new Error(plan.id+': Native 3MF does not contain the exact checked G-code.');+ const projectSettings=JSON.parse(members.get('Metadata/project_settings.config')||'null');+ const withoutVersion=object=>Object.fromEntries(Object.entries(object||{}).filter(([key])=>key!=='version'));+ if(!isDeepStrictEqual(withoutVersion(projectSettings),withoutVersion(effective)))throw new Error(plan.id+': Embedded project settings disagree with the effective slice.');+ checks.push({name:'Native 3MF payload',pass:true,detail:'Embedded G-code equals checked file byte-for-byte; MD5 agrees; all settings agree except native project schema version.'});+ log+='\nREOPEN '+plan.id+'\n'+runNative(native.bin,['--datadir',join(job,'reopen-appdata'),'--debug','2','--info','--arrange','0','--orient','0','--export-stl','--export-settings',join(reopened,'effective.json'),'--outputdir',reopened,'--enable-arc-fitting=0','--post-process','',join(out,project.name)],job);+ const reopenSettings=JSON.parse(await readFile(join(reopened,'effective.json'))),reopenSTL=await oneFile(join(reopened,'stl'),'.stl'),reopenMesh=inspectSTL(reopenSTL.bytes);+ assertMesh(reopenMesh,'Native reopened 3MF mesh');+ if(!isDeepStrictEqual(canonicalReopenSettings(reopenSettings),canonicalReopenSettings(effective))){+ const changes=[...new Set([...Object.keys(effective),...Object.keys(reopenSettings)])].filter(key=>!isDeepStrictEqual(effective[key],reopenSettings[key])).map(key=>({key,before:effective[key],after:reopenSettings[key]}));+ log+='\nREOPEN SETTINGS DIFFERENCES\n'+json(changes);throw new Error(plan.id+': Native reopened 3MF settings changed: '+changes.map(c=>c.key).join(', '));+ }+ if(reopenMesh.bounds.size.some((n,i)=>Math.abs(n-model.mesh.bounds.size[i])>.03)||Math.abs(reopenMesh.volumeMM3-model.mesh.volumeMM3)>Math.max(.05,model.mesh.volumeMM3*.00001)||reopenMesh.triangles!==model.mesh.triangles||reopenMesh.shells.length!==model.mesh.shells.length)throw new Error(plan.id+': Native reopened project geometry changed.');+ checks.push({name:'Native 3MF reopen',pass:true,detail:'Orca reopened project: all settings agree (absent/empty upward_compatible_machine metadata normalized); dimensions ±0.03 mm, volume 1e-5 relative, triangles and closed shell count agree.'});+ const base='handoff/plans/'+plan.id;+ const summary={...plan,stats:parsed.stats,layers:parsed.modelLayers,moves:parsed.moves,bounds:parsed.modelBounds,fullMotionBounds:parsed.motionBounds,warnings:parsed.warnings,temperatures:parsed.temperatures,commands:parsed.commands,checks,effective,sha256:{gcode:sha(raw.bytes),project:sha(project.bytes)},gcode:base+'/part.gcode',project:base+'/project.3mf',settings:base+'/effective.json',reopenedMesh:reopenMesh};+ report.plans.push(summary);+ await output(summary.gcode,raw.bytes);await output(summary.project,project.bytes);await output(summary.settings,json(effective));+ await output(base+'/inspection.json',json({...summary,effective:undefined}));+ if(plan.id===c.selectedPlan){await save(join(stage,'part.gcode'),raw.bytes);await save(join(stage,'part.3mf'),project.bytes);}+ }+ const portableProfiles={source:'workspace',printer:'profiles/printer.json',process:'profiles/process.json',filament:'profiles/filament.json'};+ const sourceFiles=files.filter(f=>f.name!=='slice-config.json'&&!profilePaths.has(f.name));+ const portable={...c,profiles:portableProfiles,sourceFiles:['slice-config.json',...sourceFiles.map(f=>f.name),...['printer','process','filament'].map(k=>portableProfiles[k])]};+ bundle.push(...sourceFiles,{name:'slice-config.json',bytes:json(portable)});+ for(const [key,value]of Object.entries(resolved))bundle.push({name:portableProfiles[key],bytes:json(value)});+ const notices='OpenHarness wrapper and generated inspection UI: MIT (rebuild/LICENSE).\nOrcaSlicer 2.4.2 is separately installed, not included. OrcaSlicer and its bundled profiles are upstream software/data, not relicensed as OpenHarness MIT code. Flattened profile exports derive from the selected Orca/user presets; retain their original notices and terms.\nUpstream: https://github.com/OrcaSlicer/OrcaSlicer\nOrcaSlicer license: https://github.com/OrcaSlicer/OrcaSlicer/blob/main/LICENSE\nProfile source directory: https://github.com/OrcaSlicer/OrcaSlicer/tree/main/resources/profiles\nNo binary, printer connection or credentials are included.\n';+ bundle.push({name:'PROFILE-NOTICES.txt',bytes:notices});+ for(const name of toolkit)bundle.push({name:'rebuild/'+name,bytes:await readFile(local(name))});+ report.engine={name:'OrcaSlicer',version:report.plans[0].effective.version};+ await output('handoff/report.json',json(report));+ const template=await readFile(local('preview.html'),'utf8'),safe=JSON.stringify(report).replaceAll('<','\\u003c');+ await output('preview.html',template.replace('__REPORT__',()=>safe));+ for(const name of ['preview.js','preview.css','gcode.mjs'])await output('handoff/'+name,await readFile(local(name)));+ const readme='# '+c.title+'\n\n'+c.brief+'\n\n'+c.assumptions+'\n\n'+limits+'\n\nEach handoff/plans/<id>/ folder contains the actual G-code, native editable project.3mf, effective settings and inspection receipt. Open the 3MF in OrcaSlicer and inspect the correct machine, plate, filament, orientation, custom start/end code, first layer and supports before any physical use.\n\nNode 22+, OrcaSlicer 2.4.2 separately installed:\n\n ORCA_BIN=/path/to/OrcaSlicer node rebuild/build.mjs\n node rebuild/serve-preview.mjs .\n\nOpen the loopback URL printed by the preview server. Double-clicking preview.html cannot fetch toolpaths from file://. Exported 3MF and G-code do not need this server.\n\nEdit slice-config.json to save requirements/plan revisions before rebuilding. The machine context is '+c.machine.context+'. Do not change it to user without confirming your actual printer/material. Rebuilds never connect to or start a printer. Output failure preserves the last successful handoff; .harness/verdict.json distinguishes it from current inputs. A downloaded review JSON is notes/view state, not printing authorization.\n';+ bundle.push({name:'README.md',bytes:readme});await output('handoff/README.txt',readme);+ await save(join(handoff,'project.zip'),zip(bundle));+ await unchanged(ws,files);await unchangedProfiles(origins);+ const history=await publish(ws,state,stage,['handoff','part.gcode','part.3mf','preview.html']);+ await atomic(join(state,'slice.json'),json({...report,history:relative(ws,history)}));+ await verdict({ready:true,artifact:'preview.html',summary:report.plans.length+' native slicing plans checked and reopened · '+(c.machine.context==='example'?'example printer only':'printer brief supplied')+' · not print-tested',findings:[{severity:'warning',kind:'physical-review',message:limits}]});+ console.log('ok '+report.plans.length+' plans · '+report.plans.reduce((n,p)=>n+p.checks.length,0)+' checks · G-code + native 3MF + portable project');+ return report;+ }catch(error){log+='\n'+(error.nativeLog||'');throw error;}finally{await atomic(join(state,'slice.log'),log);}+ });+}+if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url))build().catch(error=>{console.error(error.message);process.exitCode=1;});diff --git a/store/agents/orca-slicer/skills/orcaslicer/scripts/contract.mjs b/store/agents/orca-slicer/skills/orcaslicer/scripts/contract.mjsnew file mode 100644index 000000000..4928c0362--- /dev/null+++ b/store/agents/orca-slicer/skills/orcaslicer/scripts/contract.mjs@@ -0,0 +1,117 @@+import {inspectSTL,parseSTL,binarySTL} from './mesh.mjs';+import {isDeepStrictEqual} from 'node:util';+const fail=message=>{throw new Error(message);};+function obj(value,label,keys){if(!value||Array.isArray(value)||typeof value!=='object')fail(label+' must be an object.');for(const key of Object.keys(value))if(!keys.includes(key))fail('Unknown '+label+' field: '+key);}+function str(value,label){if(typeof value!=='string'||!value.trim()||value.length>2000)fail(label+' must be nonempty text under 2000 characters.');}+function num(value,label,min,max){if(typeof value!=='number'||!Number.isFinite(value)||value<min||value>max)fail(label+' must be between '+min+' and '+max+'.');}+function array(value,label,n){if(!Array.isArray(value)||value.length!==n)fail(label+' needs '+n+' values.');}+export function pathName(value){if(typeof value!=='string'||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(value)||value.split('/').some(p=>!p||p==='.'||p==='..'))fail('Use a safe workspace-relative path: '+value);return value;}+export function validateConfig(c){+ if(c?.spec!==1)fail('Save a spec: 1 slicing brief. Legacy demo/custom configs are not checked projects; see the current template.');+ obj(c,'brief',['spec','title','brief','assumptions','sourceFiles','profiles','machine','model','plans','selectedPlan','limits']);+ for(const k of ['title','brief','assumptions'])str(c[k],k);+ if(!Array.isArray(c.sourceFiles)||!c.sourceFiles.length||c.sourceFiles.length>32)fail('Declare 1–32 sourceFiles.');+ c.sourceFiles.forEach(pathName);if(new Set(c.sourceFiles.map(v=>v.toLowerCase())).size!==c.sourceFiles.length)fail('Duplicate source files.');+ if(!c.sourceFiles.includes('slice-config.json'))fail('sourceFiles must include slice-config.json.');+ if(c.sourceFiles.some(n=>/^(?:plans|handoff|rebuild|\.harness)\//.test(n)||/^(?:preview\.html|part\.(?:gcode|3mf))$/.test(n)))fail('Source files cannot be generated output paths.');+ obj(c.profiles,'profiles',['source','printer','process','filament']);if(!['installed','workspace'].includes(c.profiles.source))fail('profiles.source must be installed or workspace.');+ for(const k of ['printer','process','filament']){+ const path=c.profiles[k];+ if(c.profiles.source==='installed'){if(typeof path!=='string'||!path||/[;:\\\x00-\x1f]/.test(path)||path.split('/').some(p=>!p||p==='.'||p==='..'))fail('Installed profiles must be relative paths inside the Orca profiles directory.');}+ else {pathName(path);if(!c.sourceFiles.includes(path))fail('Declare each workspace profile in sourceFiles.');}+ }+ obj(c.machine,'machine',['context','label','printerModel','nozzleMM','bedMM','bedType','firmware','material','nozzleTemperatureRange','bedTemperatureRange']);+ const m=c.machine;if(!['example','user'].includes(m.context))fail('machine.context must explicitly be example or user.');+ for(const k of ['label','printerModel','material'])str(m[k],'machine.'+k);+ if(!['marlin','marlin2'].includes(m.firmware))fail('This checked workflow currently supports single-tool Marlin / Marlin 2 only, without named macros.');+ if(!['High Temp Plate','Textured PEI Plate','Cool Plate','Engineering Plate'].includes(m.bedType))fail('Declare a supported explicit bedType.');+ num(m.nozzleMM,'nozzleMM',.1,2);array(m.bedMM,'bedMM',3);m.bedMM.forEach(v=>num(v,'bedMM',10,2000));+ for(const [key,max] of [['nozzleTemperatureRange',400],['bedTemperatureRange',150]]){array(m[key],key,2);m[key].forEach(v=>num(v,key,1,max));if(m[key][0]>m[key][1])fail('Temperature ranges must be ordered.');}+ obj(c.model,'model',['path','expectedSizeMM','toleranceMM','rotationDegrees','scale']);pathName(c.model.path);+ if(!c.model.path.endsWith('.stl')||!c.sourceFiles.includes(c.model.path))fail('Declare one source STL in sourceFiles.');+ array(c.model.expectedSizeMM,'expectedSizeMM',3);c.model.expectedSizeMM.forEach(v=>num(v,'expectedSizeMM',.01,2000));+ num(c.model.toleranceMM,'toleranceMM',.0001,1);num(c.model.scale,'scale',.001,100);+ array(c.model.rotationDegrees,'rotationDegrees',3);c.model.rotationDegrees.forEach(v=>num(v,'rotationDegrees',-360,360));+ obj(c.limits,'limits',['maxTimeSeconds','maxFilamentGrams','bedMarginMM']);num(c.limits.maxTimeSeconds,'maxTimeSeconds',1,604800);num(c.limits.maxFilamentGrams,'maxFilamentGrams',.01,20000);num(c.limits.bedMarginMM,'bedMarginMM',0,50);+ if(!Array.isArray(c.plans)||c.plans.length<1||c.plans.length>4)fail('Compare 1–4 plans.');const ids=new Set();+ for(const p of c.plans){+ obj(p,'plan',['id','label','description','layerHeightMM','firstLayerMM','wallLoops','infillPercent','infillPattern','topLayers','bottomLayers','supports','brimMM']);+ if(!/^[a-z][a-z0-9-]{0,31}$/.test(p.id)||ids.has(p.id))fail('Use unique lowercase plan ids.');ids.add(p.id);str(p.label,'plan label');str(p.description,'plan description');+ for(const k of ['layerHeightMM','firstLayerMM'])num(p[k],k,.03,m.nozzleMM*.8);+ for(const k of ['wallLoops','topLayers','bottomLayers']){num(p[k],k,1,30);if(!Number.isInteger(p[k]))fail(k+' must be an integer.');}+ num(p.infillPercent,'infillPercent',0,100);num(p.brimMM,'brimMM',0,30);+ if(!['gyroid','rectilinear','grid','crosshatch'].includes(p.infillPattern))fail('Unsupported infill pattern.');+ if(typeof p.supports!=='boolean')fail('supports must be true or false.');+ }+ if(!ids.has(c.selectedPlan))fail('selectedPlan must name a saved plan.');return c;+}+export function planSettings(p){return {+ layer_height:String(p.layerHeightMM),initial_layer_print_height:String(p.firstLayerMM),wall_loops:String(p.wallLoops),+ sparse_infill_density:p.infillPercent+'%',sparse_infill_pattern:p.infillPattern,top_shell_layers:String(p.topLayers),bottom_shell_layers:String(p.bottomLayers),+ top_shell_thickness:'0',bottom_shell_thickness:'0',enable_support:p.supports?'1':'0',brim_width:String(p.brimMM),brim_type:p.brimMM?'outer_only':'no_brim',+ enable_arc_fitting:'0',post_process:[],spiral_mode:'0',infill_combination:'0',enable_prime_tower:'0',print_sequence:'by layer'+};}+// Orca 2.4.2 sometimes materializes this absent preset-catalog metadata as [].+// No numerical, G-code, geometry or slicing setting is ignored.+export function canonicalReopenSettings(settings){return {...settings,upward_compatible_machine:settings.upward_compatible_machine??[]};}+export function assertMesh(mesh,label){if(!mesh.watertight||mesh.orientedVolumeMM3<=0||mesh.shells.some(s=>s.orientedVolumeMM3<=0))fail(label+' must have closed, consistently oriented positive-volume shells. Repair the mesh first.');}+export function prepareModel(bytes,c){+ const input=inspectSTL(bytes);assertMesh(input,'Source STL');+ input.bounds.size.forEach((n,i)=>{if(Math.abs(n-c.model.expectedSizeMM[i])>c.model.toleranceMM)fail('Source size disagrees with the saved millimetre brief on axis '+i+': '+n);});+ const radians=c.model.rotationDegrees.map(v=>v*Math.PI/180);+ const triangles=parseSTL(bytes).map(face=>face.map(original=>{+ let p=original.map(v=>v*c.model.scale);+ for(let axis=0;axis<3;axis++){const a=(axis+1)%3,b=(axis+2)%3,x=p[a],y=p[b];p[a]=x*Math.cos(radians[axis])-y*Math.sin(radians[axis]);p[b]=x*Math.sin(radians[axis])+y*Math.cos(radians[axis]);}+ return p;+ }));+ const first=inspectSTL(binarySTL(triangles)),oriented=binarySTL(triangles,first.bounds.min.map(v=>-v)),mesh=inspectSTL(oriented);assertMesh(mesh,'Oriented STL');+ for(let i=0;i<3;i++)if(mesh.bounds.size[i]+(i<2?2*(c.limits.bedMarginMM+Math.max(...c.plans.map(p=>p.brimMM))):0)>c.machine.bedMM[i])fail('Oriented model plus requested brim/margin exceeds the declared bed.');+ return {input,mesh,bytes:oriented};+}+export function assertProfiles(profiles,c){+ for(const [kind,type] of [['printer','machine'],['process','process'],['filament','filament']]){+ const p=profiles[kind];if(p.type!==type)fail(kind+' profile has the wrong type.');+ if(p.post_process?.length)fail('Remove post_process commands from profiles. This workflow never runs post-processors.');+ }+ const p=profiles.printer,m=c.machine;+ if(p.printer_model!==m.printerModel||p.gcode_flavor!==m.firmware)fail('Printer model/firmware does not match the saved brief.');+ if(!Array.isArray(p.nozzle_diameter)||p.nozzle_diameter.length!==1||Number(p.nozzle_diameter[0])!==m.nozzleMM)fail('Exactly one nozzle matching the saved diameter is required.');+ const points=(p.printable_area||[]).map(v=>v.split('x').map(Number));+ const expected=[[0,0],[m.bedMM[0],0],[m.bedMM[0],m.bedMM[1]],[0,m.bedMM[1]]];+ if(points.length!==4||points.some(v=>!expected.some(e=>isDeepStrictEqual(v,e)))||new Set(points.map(v=>v.join(','))).size!==4||Number(p.printable_height)!==m.bedMM[2])fail('Printer bed must match the declared zero-origin rectangular build volume.');+ if(p.bed_exclude_area?.some(v=>v!=='0x0'))fail('Nonempty bed exclusion zones are not supported by this checked workflow.');+ if(profiles.filament.filament_type?.length!==1||profiles.filament.filament_type[0]!==m.material)fail('Filament type must match the brief.');+ for(const plan of c.plans)for(const value of [plan.layerHeightMM,plan.firstLayerMM])if(value<Number(p.min_layer_height?.[0]||.03)||value>Number(p.max_layer_height?.[0]||m.nozzleMM*.8))fail('Layer height is outside this printer profile’s range.');+}+export function inspectPlan(parsed,effective,c,plan,mesh){+ const checks=[];const check=(name,pass,detail)=>{checks.push({name,pass,detail});if(!pass)fail(plan.id+': '+name+' — '+detail);};+ const scalar=v=>Array.isArray(v)?v.join(';'):String(v??'');+ check('One complete emitted settings block',parsed.configBlocks===1,'CONFIG_BLOCK_START / END');+ const required={...planSettings(plan),curr_bed_type:c.machine.bedType,printer_model:c.machine.printerModel,gcode_flavor:c.machine.firmware,nozzle_diameter:[String(c.machine.nozzleMM)],printable_height:String(c.machine.bedMM[2]),filament_type:[c.machine.material]};+ for(const [key,value] of Object.entries(required)){+ check('Effective '+key,scalar(effective[key])===scalar(value),'expected '+scalar(value)+', got '+scalar(effective[key]));+ check('Emitted '+key,scalar(parsed.settings[key])===scalar(value),'G-code setting agrees with saved brief');+ }+ const area=['0x0',c.machine.bedMM[0]+'x0',c.machine.bedMM[0]+'x'+c.machine.bedMM[1],'0x'+c.machine.bedMM[1]];+ check('Effective bed polygon',isDeepStrictEqual(effective.printable_area,area),'zero-origin rectangular area agrees with the saved brief');+ check('Emitted bed polygon',parsed.settings.printable_area===area.join(','),'G-code agrees with the saved bed');+ const excluded=effective.bed_exclude_area||[];+ check('No effective bed exclusions',Array.isArray(excluded)&&excluded.every(v=>v==='0x0')&&['','0x0'].includes(parsed.settings.bed_exclude_area??''),'no unsupported exclusion zone was applied');+ const bedKeys={'High Temp Plate':'hot_plate_temp','Textured PEI Plate':'textured_plate_temp','Cool Plate':'cool_plate_temp','Engineering Plate':'eng_plate_temp'};+ for(const [heater,keys,range] of [['nozzle',['nozzle_temperature','nozzle_temperature_initial_layer'],c.machine.nozzleTemperatureRange],['bed',[bedKeys[c.machine.bedType],bedKeys[c.machine.bedType]+'_initial_layer'],c.machine.bedTemperatureRange]]){+ for(const key of keys){const values=effective[key];check('Profile '+key,Array.isArray(values)&&values.length===1&&Number(values[0])>=range[0]&&Number(values[0])<=range[1],scalar(values));check('Emitted '+key,scalar(parsed.settings[key])===scalar(values),'matches effective profile');}+ const commands=parsed.temperatures.filter(t=>t.heater===heater),active=commands.filter(t=>t.target>0);+ check(heater+' heater commands within saved range',active.length>0&&active.every(t=>t.target>=range[0]&&t.target<=range[1]),JSON.stringify(commands));+ check(heater+' targets at extrusion',parsed.extrusionTemperatures.length>0&&parsed.extrusionTemperatures.every(t=>t[heater]>=range[0]&&t[heater]<=range[1]),'commanded targets only, not measured temperatures');+ check(heater+' heater off after final extrusion',parsed.thermal[heater]===0&&commands.at(-1)?.line>parsed.lastExtrusionLine,'last command must be zero after all extrusion');+ }+ check('Positive feeds',parsed.motions.filter(s=>s[8]).every(s=>s[6]>0),'every deposition move has a positive commanded speed');+ check('Reported model layers agree',parsed.stats.sourceLayers===parsed.modelLayers,parsed.modelLayers+' measured model heights; '+parsed.stats.sourceLayers+' reported');+ check('Top height agrees with mesh',Math.abs(parsed.modelBounds.max[2]-mesh.bounds.size[2])<=Math.max(plan.layerHeightMM,plan.firstLayerMM)+.02,parsed.modelBounds.max[2]+' mm');+ check('First layer agrees',Math.abs(parsed.layers.filter(l=>l.modelExtrusionMm>0)[0].z-plan.firstLayerMM)<.001,plan.firstLayerMM+' mm');+ const b=parsed.modelBounds,margin=c.limits.bedMarginMM;+ check('Model/support centerlines inside bed inset',[0,1].every(i=>b.min[i]>=margin&&b.max[i]<=c.machine.bedMM[i]-margin)&&b.min[2]>=0&&b.max[2]<=c.machine.bedMM[2],JSON.stringify(b));+ check('Time budget',Number.isFinite(parsed.stats.timeSeconds)&&parsed.stats.timeSeconds>0&&parsed.stats.timeSeconds<=c.limits.maxTimeSeconds,parsed.stats.time+' (slicer estimate)');+ check('Material budget',Number.isFinite(parsed.stats.filamentGrams)&&parsed.stats.filamentGrams>0&&parsed.stats.filamentGrams<=c.limits.maxFilamentGrams,parsed.stats.filamentGrams+' g (slicer estimate)');+ return checks;+}diff --git a/store/agents/orca-slicer/skills/orcaslicer/scripts/files.mjs b/store/agents/orca-slicer/skills/orcaslicer/scripts/files.mjsnew file mode 100644index 000000000..9e470af78--- /dev/null+++ b/store/agents/orca-slicer/skills/orcaslicer/scripts/files.mjs@@ -0,0 +1,73 @@+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>32*1024*1024)throw new Error('Source must be a regular file no larger than 32 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>64*1024*1024)throw new Error('Sources exceed 64 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) {+ if(await exists(join(state,'history'))&&(await lstat(join(state,'history'))).isSymbolicLink())throw new Error('History must not be a symlink.');+ const history=join(state,'history',basename(stage));await mkdir(history,{recursive:true});+ const saved=[],installed=[];+ try {+ if(await exists(join(state,'slice.json')))await copyFile(join(state,'slice.json'),join(history,'slice.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,'orca-build.lock');+ try{await mkdir(lock);}catch(error){if(error.code==='EEXIST')throw new Error('Another build owns .harness/orca-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 slicing plans and checking saved requirements'});+ stage=await mkdtemp(join(state,'orca-'));+ return await run({state,stage,verdict});+ }catch(error){+ await verdict({summary:'OrcaSlicer 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/orca-slicer/skills/orcaslicer/scripts/gcode.mjs b/store/agents/orca-slicer/skills/orcaslicer/scripts/gcode.mjsindex bd97d6417..2f1fa3ce7 100644--- a/store/agents/orca-slicer/skills/orcaslicer/scripts/gcode.mjs+++ b/store/agents/orca-slicer/skills/orcaslicer/scripts/gcode.mjs@@ -1,46 +1,135 @@-// Linear FDM toolpaths, in millimetres. Rendering is inspection, not printer validation.+// Inspect commanded single-tool linear FDM motion. This is not firmware simulation.+export function durationSeconds(value){+ if(typeof value!=='string'||!value.trim())throw new Error('Missing slicer time estimate.');+ let total=0,position=0;+ for(const match of value.matchAll(/(\d+(?:\.\d+)?)\s*([dhms])/g)){+ if(value.slice(position,match.index).trim())throw new Error('Unrecognized slicer time estimate.');+ total+=Number(match[1])*({d:86400,h:3600,m:60,s:1}[match[2]]);position=match.index+match[0].length;+ }+ if(value.slice(position).trim()||!position||!Number.isFinite(total))throw new Error('Unrecognized slicer time estimate.');+ return total;+}+function words(text,line,{motion=false}={}){+ const result=Object.create(null);let end=0;+ for(const match of text.matchAll(/([A-Z])\s*([-+]?(?:\d+(?:\.\d*)?|\.\d+))/g)){+ if(motion&&text.slice(end,match.index).trim())throw new Error('Unsupported motion syntax at line '+line);+ const key=match[1],value=Number(match[2]);+ if(motion&&(!'XYZEF'.includes(key)||Object.hasOwn(result,key)))throw new Error('Unsupported or duplicate motion word at line '+line);+ if(!Number.isFinite(value)||Math.abs(value)>1e7)throw new Error('Invalid coordinate at line '+line);+ result[key]=value;end=match.index+match[0].length;+ }+ if(motion&&text.slice(end).trim())throw new Error('Unsupported motion syntax at line '+line);+ return result;+}+const extent=()=>({min:[Infinity,Infinity,Infinity],max:[-Infinity,-Infinity,-Infinity]});+const include=(bounds,point)=>point.forEach((v,i)=>{bounds.min[i]=Math.min(bounds.min[i],v);bounds.max[i]=Math.max(bounds.max[i],v);});export function parseGcode(source){- if(typeof source!=='string'||source.length>32*1024*1024)throw new Error('G-code must be text under 32 MiB.');- const layers=[],map=new Map(),features=[],warnings=new Set();- let pos=[0,0,0],offset=[0,0,0],e=0,absolute=true,absoluteE=true,unit=1,feed=0,feature='Custom',lineNumber=0,moves=0;- const stats={time:null,filamentMm:null,filamentGrams:null,sourceLayers:null};- const bounds={min:[Infinity,Infinity,Infinity],max:[-Infinity,-Infinity,-Infinity]};- const modelBounds={min:[Infinity,Infinity,Infinity],max:[-Infinity,-Infinity,-Infinity]};- const layerAt=z=>{const key=Math.round(z*10000)/10000;if(!map.has(key)){const layer={z:key,segments:[],extrusionMm:0};map.set(key,layer);layers.push(layer);}return map.get(key);};+ if(typeof source!=='string'||new TextEncoder().encode(source).length>32*1024*1024)throw new Error('G-code must be text under 32 MiB.');+ const layers=[],map=new Map(),features=[],warnings=new Set(),motions=[],temperatures=[],settings=Object.create(null),commands=Object.create(null);+ let pos=[0,0,0],offset=[0,0,0],e=0,debt=0,absolute=true,absoluteE=true,unit=1,feed=0,feature='Custom',lineNumber=0;+ let modelExtrusionMm=0,commandedExtrusionMm=0,travelMM=0,depositionMM=0,config=false,configBlocks=0,configEnds=0,lastDepositionLine=0;+ const thermal={nozzle:null,bed:null};let lastExtrusionLine=0;const extrusionTemperatures=[];+ const stats={time:null,timeSeconds:null,filamentMm:null,filamentGrams:null,filamentCm3:null,sourceLayers:null};+ const bounds=extent(),modelBounds=extent(),motionBounds=extent();+ const layerAt=z=>{+ const key=Math.round(z*10000)/10000;+ if(!map.has(key)){const layer={z:key,segments:[],indices:[],extrusionMm:0,modelExtrusionMm:0};map.set(key,layer);layers.push(layer);}+ return map.get(key);+ };for(const raw of source.split(/\r?\n/)){lineNumber++;+ if(/^;\s*CONFIG_BLOCK_START\s*$/.test(raw)){if(config)throw new Error('Nested settings block.');config=true;configBlocks++;continue;}+ if(/^;\s*CONFIG_BLOCK_END\s*$/.test(raw)){if(!config)throw new Error('Settings block ended without a start.');config=false;configEnds++;continue;}+ if(config){+ const match=raw.match(/^;\s*([a-zA-Z0-9_]+)\s*=\s?(.*)$/);+ if(match){+ const key=match[1],value=match[2].trim(),prior=settings[key],numeric=/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)$/;+ // Orca 2.4.2 repeats wipe-tower coordinates as e.g. 15.000 and 15.+ // Equivalent duplicates are harmless; contradictory settings are not.+ if(Object.hasOwn(settings,key)&&prior!==value&&!(numeric.test(prior)&&numeric.test(value)&&Number(prior)===Number(value)))throw new Error('Conflicting duplicate emitted setting: '+key);+ settings[key]=value;+ }+ else if(raw.trim()&&!raw.trim().startsWith(';'))throw new Error('Executable code inside settings block.');+ continue;+ }let match=raw.match(/^;\s*(?:TYPE|FEATURE):\s*(.+)/i);if(match)feature=match[1].trim();- match=raw.match(/^;\s*estimated printing time \(normal mode\)\s*=\s*(.+)/i);if(match)stats.time=match[1].trim();- match=raw.match(/^;\s*total layer number:\s*(\d+)/i);if(match)stats.sourceLayers=Number(match[1]);- match=raw.match(/^;\s*total filament used \[mm\]\s*=\s*([\d.]+)/i);if(match)stats.filamentMm=Number(match[1]);- match=raw.match(/^;\s*total filament used \[g\]\s*=\s*([\d.]+)/i);if(match)stats.filamentGrams=Number(match[1]);- const code=raw.split(';')[0].replace(/\([^)]*\)/g,'').trim().toUpperCase();if(!code)continue;- const command=code.match(/^(?:N\d+\s*)?([GMT]\d+(?:\.\d+)?)/)?.[1];if(!command)continue;- const params=Object.fromEntries([...code.matchAll(/([XYZEF])\s*([-+]?(?:\d*\.)?\d+)/g)].map(m=>[m[1],Number(m[2])]));+ match=raw.match(/^;\s*estimated printing time \(normal mode\)\s*=\s*(.+)/i);if(match){stats.time=match[1].trim();stats.timeSeconds=durationSeconds(stats.time);}+ match=raw.match(/^;\s*(?:total layer number:|total layers count\s*=)\s*(\d+)/i);if(match)stats.sourceLayers=Number(match[1]);+ for(const [unitName,key] of [['mm','filamentMm'],['g','filamentGrams'],['cm3','filamentCm3']]){+ const found=raw.match(new RegExp('^;\\s*(?:total )?filament used \\['+unitName+'\\]\\s*=\\s*([\\d.]+)\\s*$','i'));+ if(found){const value=Number(found[1]);if(!Number.isFinite(value)||value<0)throw new Error('Invalid filament estimate.');stats[key]=value;}+ }+ let code=raw.split(';')[0].replace(/\([^)]*\)/g,'').trim().toUpperCase();if(!code)continue;+ if(code.includes('*'))throw new Error('Serial checksums are not supported; export plain G-code.');+ code=code.replace(/^N\d+\s*/,'');+ const token=code.match(/^([GMT])(\d+(?:\.\d+)?)(?=\s|[A-Z+-]|$)/);+ if(!token)throw new Error('Unmodeled macro/command at line '+lineNumber+': '+code.split(/\s/)[0]);+ const command=token[1]+Number(token[2]),tail=code.slice(token[0].length);+ if(!commands[command])commands[command]={count:0,firstLine:lineNumber};+ commands[command].count++;if(command==='G20'){unit=25.4;continue;}if(command==='G21'){unit=1;continue;}if(command==='G90'){absolute=true;absoluteE=true;continue;}if(command==='G91'){absolute=false;absoluteE=false;continue;}if(command==='M82'){absoluteE=true;continue;}if(command==='M83'){absoluteE=false;continue;}- if(command==='G92'){for(const [i,axis]of ['X','Y','Z'].entries())if(params[axis]!==undefined)offset[i]=pos[i]-params[axis]*unit;if(params.E!==undefined)e=params.E*unit;continue;}- if(['G2','G02','G3','G03','G5'].includes(command))throw new Error('Curved moves at line '+lineNumber+' are not modeled. Disable arc fitting and re-slice.');- if(command==='G28'){warnings.add('Homing assumed to establish the machine origin; firmware offsets and bed leveling are not modeled.');continue;}- if(/^T\d/.test(command)&&command!=='T0')throw new Error('Multiple tools are not modeled. Use a single-tool G-code file.');- if(!['G0','G00','G1','G01'].includes(command))continue;- if(params.F!==undefined)feed=params.F*unit;+ if(['G2','G3','G5'].includes(command))throw new Error('Curved moves at line '+lineNumber+' are not modeled. Disable arc fitting and re-slice.');+ if(['G10','G11','G53','G54','G55','G56','G57','G58','G59','G68','G69','G92.1','M206','M218','M32','M98','M125','M600','M601','M605','M701','M702'].includes(command))throw new Error(command+' changes unmodeled motion, extrusion or control flow at line '+lineNumber+'. Use explicit linear, single-origin G-code.');+ if(command.startsWith('G')&&!['G0','G1','G4','G17','G18','G19','G20','G21','G28','G29','G80','G90','G91','G92'].includes(command))throw new Error('Unsupported motion command '+command+' at line '+lineNumber);+ if(command.startsWith('T')&&command!=='T0')throw new Error('Multiple tools are not modeled. Use a single-tool G-code file.');+ if(command==='G28'){+ // The preview assumes homed axes have machine coordinate zero. Real home+ // offsets and leveling are firmware properties, not proven by this parser.+ const axes=['X','Y','Z'],requested=axes.filter(axis=>tail.includes(axis));+ for(const axis of requested.length?requested:axes){const index=axes.indexOf(axis);pos[index]=0;offset[index]=0;}+ warnings.add('Homing is drawn at zero; firmware home offsets and bed leveling are not modeled.');continue;+ }+ if(['G29','G80','M290','M220','M221','M900'].includes(command))warnings.add('Firmware leveling, flow/speed overrides and pressure advance are not simulated.');+ const linear=['G0','G1','G92'].includes(command);+ const params=words(tail,lineNumber,{motion:linear});+ if(command==='M200'&¶ms.D!==undefined&¶ms.D!==0)throw new Error('Volumetric E coordinates are not supported.');+ if(['M104','M109','M140','M190'].includes(command)){+ if(params.T!==undefined&¶ms.T!==0)throw new Error('Multiple heater tools are not supported.');+ const target=params.S??params.R;+ if(target!==undefined){+ const heater=['M104','M109'].includes(command)?'nozzle':'bed';+ if(target<0||target>1000)throw new Error('Invalid heater target at line '+lineNumber);+ thermal[heater]=target;temperatures.push({line:lineNumber,command,heater,target,wait:['M109','M190'].includes(command)});+ }+ }+ if(command==='G92'){+ for(const [i,axis] of ['X','Y','Z'].entries())if(params[axis]!==undefined)offset[i]=pos[i]-params[axis]*unit;+ if(params.E!==undefined)e=params.E*unit;continue;+ }+ if(!['G0','G1'].includes(command))continue;+ if(params.F!==undefined){feed=params.F*unit;if(feed<0)throw new Error('Negative feed at line '+lineNumber);}const next=pos.map((value,i)=>params[['X','Y','Z'][i]]===undefined?value:absolute?params[['X','Y','Z'][i]]*unit+offset[i]:value+params[['X','Y','Z'][i]]*unit);const nextE=params.E===undefined?e:absoluteE?params.E*unit:e+params.E*unit,deltaE=nextE-e;if([...next,nextE,feed].some(v=>!Number.isFinite(v)||Math.abs(v)>1e7))throw new Error('Invalid coordinate at line '+lineNumber);- if(Math.hypot(...next.map((v,i)=>v-pos[i]))>0.00001){- if(++moves>250000)throw new Error('Preview supports at most 250,000 linear moves.');- const extrude=deltaE>0.00001;+ let deposited=0;+ if(deltaE<0)debt-=deltaE;+ if(deltaE>0){const recovery=Math.min(debt,deltaE);debt-=recovery;deposited=deltaE-recovery;commandedExtrusionMm+=deposited;}+ if(deposited>.00001){lastExtrusionLine=lineNumber;if(!extrusionTemperatures.some(item=>item.nozzle===thermal.nozzle&&item.bed===thermal.bed))extrusionTemperatures.push({...thermal,line:lineNumber});}+ const distance=Math.hypot(...next.map((v,i)=>v-pos[i]));+ if(distance>.00001){+ if(motions.length>=1000000)throw new Error('Inspection supports at most 1,000,000 linear moves.');+ const extrude=deposited>.00001;if(!features.includes(feature))features.push(feature);- const layer=layerAt(next[2]);- layer.segments.push([...pos,...next,feed/60,features.indexOf(feature),extrude?1:0,lineNumber]);- if(extrude){layer.extrusionMm+=deltaE;for(const point of [pos,next])for(let i=0;i<3;i++){bounds.min[i]=Math.min(bounds.min[i],point[i]);bounds.max[i]=Math.max(bounds.max[i],point[i]);if(feature!=='Custom'){modelBounds.min[i]=Math.min(modelBounds.min[i],point[i]);modelBounds.max[i]=Math.max(modelBounds.max[i],point[i]);}}}+ // Layout retained for the renderer: XYZ start/end, mm/s, feature, deposition, source line.+ const segment=[...pos,...next,feed/60,features.indexOf(feature),extrude?1:0,lineNumber,deposited];+ const layer=layerAt(next[2]);layer.indices.push(motions.length);layer.segments.push(segment);motions.push(segment);+ include(motionBounds,pos);include(motionBounds,next);+ if(extrude){+ lastDepositionLine=lineNumber;depositionMM+=distance;layer.extrusionMm+=deposited;+ include(bounds,pos);include(bounds,next);+ if(feature!=='Custom'){modelExtrusionMm+=deposited;layer.modelExtrusionMm+=deposited;include(modelBounds,pos);include(modelBounds,next);}+ if(feed===0)warnings.add('A deposition move has no known positive feed.');+ }else travelMM+=distance;}pos=next;e=nextE;}+ if(config||configBlocks!==configEnds||configBlocks>1)throw new Error('Incomplete or repeated emitted settings block.');const printed=layers.filter(layer=>layer.extrusionMm>0).sort((a,b)=>a.z-b.z);if(!printed.length)throw new Error('No linear extrusion paths found.');- if(layers.some(layer=>layer.extrusionMm===0))warnings.add('Travel-only heights are omitted from the layer list (including Z hops and final parking).');- return {layers:printed,features,bounds,modelBounds:Number.isFinite(modelBounds.min[0])?modelBounds:bounds,stats,moves,warnings:[...warnings],lines:lineNumber};+ if(layers.some(layer=>layer.extrusionMm===0))warnings.add('Travel-only heights are outside the print-layer list; use the full-motion view to include Z hops and final parking.');+ return {layers:printed,features,bounds,modelBounds:Number.isFinite(modelBounds.min[0])?modelBounds:bounds,motionBounds,motions,+ stats,moves:motions.length,warnings:[...warnings],lines:lineNumber,settings,configBlocks,commands,temperatures,thermal,lastDepositionLine,lastExtrusionLine,extrusionTemperatures,+ modelLayers:printed.filter(layer=>layer.modelExtrusionMm>0).length,modelExtrusionMm,commandedExtrusionMm,travelMM,depositionMM};}diff --git a/store/agents/orca-slicer/skills/orcaslicer/scripts/mesh.mjs b/store/agents/orca-slicer/skills/orcaslicer/scripts/mesh.mjsnew file mode 100644index 000000000..87d4dbdec--- /dev/null+++ b/store/agents/orca-slicer/skills/orcaslicer/scripts/mesh.mjs@@ -0,0 +1,63 @@+// 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=[];+ 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 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),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,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;+ 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/orca-slicer/skills/orcaslicer/scripts/native.mjs b/store/agents/orca-slicer/skills/orcaslicer/scripts/native.mjsnew file mode 100644index 000000000..c25f4e447--- /dev/null+++ b/store/agents/orca-slicer/skills/orcaslicer/scripts/native.mjs@@ -0,0 +1,21 @@+import {access,readFile,readdir,realpath} from 'node:fs/promises';+import {constants} from 'node:fs';+import {spawnSync} from 'node:child_process';+import {dirname,resolve,join} from 'node:path';+export async function engine(){+ let bin=process.env.ORCA_BIN;+ if(!bin)bin=spawnSync('/bin/sh',['-c','command -v orca-slicer || command -v orcaslicer'],{encoding:'utf8'}).stdout?.trim()||'/Applications/OrcaSlicer.app/Contents/MacOS/OrcaSlicer';+ await access(bin,constants.X_OK).catch(()=>{throw new Error('Install OrcaSlicer 2.4.2 or set ORCA_BIN. No slicing outputs were replaced.');});+ bin=await realpath(bin);return {bin,profiles:process.env.ORCA_PROFILES_DIR||resolve(dirname(bin),'../Resources/profiles')};+}+export function runNative(bin,args,cwd){+ const result=spawnSync(bin,args,{cwd,encoding:'utf8',timeout:240000,maxBuffer:16*1024*1024,env:{...process.env}});+ const log=(result.stdout||'')+(result.stderr||'');+ if(result.error||result.status!==0){const error=new Error('OrcaSlicer failed ('+(result.error?.message||result.signal||result.status)+'). Inspect .harness/slice.log.');error.nativeLog=log;throw error;}+ return log;+}+export async function oneFile(dir,extension){+ const names=(await readdir(dir)).filter(n=>n.toLowerCase().endsWith(extension));+ if(names.length!==1)throw new Error('Expected exactly one fresh '+extension+' output, got '+names.length+'.');+ return {name:names[0],bytes:await readFile(join(dir,names[0]))};+}diff --git a/store/agents/orca-slicer/skills/orcaslicer/scripts/preview.css b/store/agents/orca-slicer/skills/orcaslicer/scripts/preview.cssnew file mode 100644index 000000000..c37ff7591--- /dev/null+++ b/store/agents/orca-slicer/skills/orcaslicer/scripts/preview.css@@ -0,0 +1 @@+*{box-sizing:border-box}body{margin:0;background:#131c22;color:#e7eeeb;font:14px/1.6 system-ui,sans-serif}header{padding:22px 38px;border-bottom:1px solid #37444a;display:flex;justify-content:space-between;align-items:center;gap:20px}.brand{font:30px Georgia,serif}.brand span{color:#efb887}.brand small{font:9px monospace;letter-spacing:2px;color:#8da3ac;margin-left:15px}.eyebrow{font:10px/1.6 monospace;letter-spacing:1.6px;color:#a5babe;margin:0}main{max-width:1550px;margin:auto;padding:32px 38px}.intro{display:flex;align-items:center;justify-content:space-between;gap:34px;margin:6px 0 24px}.intro>div{max-width:820px}h1{font:44px/1.12 Georgia,serif;letter-spacing:-1.5px;margin:14px 0}h2{font:25px/1.2 Georgia,serif;margin:10px 0 14px}p{color:#a9babf;margin:8px 0 15px}a,button,.file-button{font:12px/1.5 system-ui,sans-serif;border:1px solid #59676a;border-radius:6px;background:#202e36;color:#e5eeea;text-decoration:none;padding:10px 13px;cursor:pointer;display:inline-block}a:hover,button:hover,.file-button:hover{border-color:#e5b585}a.primary{background:#eabd94;border-color:#eabd94;color:#192229;white-space:nowrap}button[aria-pressed=true]{border-color:#eeb98b;color:#f5cda9;background:#333731}button:disabled{opacity:.4;cursor:default}:focus-visible{outline:2px solid #f3c396;outline-offset:3px}.notice{border-left:3px solid #d9a976;background:#292a26;color:#d9c6b1;padding:13px 18px;font-size:12px;margin-bottom:22px}.plans{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px;margin-bottom:22px}.plan{text-align:left;padding:17px 20px;background:#1b282f;border-color:#384c53}.plan[aria-pressed=true]{box-shadow:inset 0 3px #e9b17e}.plan .name{display:block;font-size:14px;margin-bottom:12px}.plan .numbers{font:27px Georgia,serif;display:flex;gap:20px}.plan .numbers small{font:10px monospace;color:#9cb4bd;margin-left:4px}.plan .settings{font:10px/1.8 monospace;color:#a8b9bb;display:block;margin-top:10px}.plan .delta{display:block;color:#cdb49a;font-size:11px;margin-top:8px}.layout{display:grid;grid-template-columns:minmax(0,1fr) 295px;gap:22px}.view{position:relative;min-width:0;background:radial-gradient(ellipse at 50% 40%,#243b43,#101b23 75%);border:1px solid #3a515a;border-radius:12px;overflow:hidden}.view-head{position:absolute;inset:17px 18px auto;display:flex;justify-content:space-between;align-items:center;gap:8px}.group{display:flex;gap:7px;flex-wrap:wrap}canvas{display:block;width:100%;height:590px;touch-action:none}.view-foot{display:flex;justify-content:space-between;gap:10px;padding:12px 17px;border-top:1px solid #334950;font:10px/1.6 monospace;color:#b8c9c9;min-height:41px}aside{padding:12px 8px}aside p{font-size:12px}.layer{font:37px Georgia,serif;margin:20px 0 0}.layer small{font-size:17px;color:#88a3ad;margin-left:6px}input[type=range]{width:100%;accent-color:#e6af81;margin:14px 0}input[type=checkbox]{accent-color:#e6af81}.controls{display:flex;justify-content:space-between;gap:6px}.options{display:grid;gap:8px;margin:19px 0}label{font-size:12px;color:#b7c8cb}select{padding:6px;background:#23343d;color:#d5e3e2;border:1px solid #526970;border-radius:4px}.legend{display:flex;flex-wrap:wrap;gap:7px 12px;font:9px/1.5 monospace;color:#a4bdc1;margin:15px 0}.legend span{display:flex;align-items:center;gap:5px}.dot{width:7px;height:7px;border-radius:50%;display:inline-block}.downloads{display:grid;gap:8px;margin-top:20px}.downloads a:first-child{color:#f2cda5;border-color:#b58e66}.evidence{display:grid;grid-template-columns:1.2fr 1fr;gap:40px;margin-top:34px;padding-top:30px;border-top:1px solid #3d5055}.evidence p{font-size:12px}.evidence details{font-size:12px;margin:15px 0}.evidence summary{cursor:pointer;color:#d5deda}.evidence li{padding:3px;overflow-wrap:anywhere}pre{white-space:pre-wrap;overflow-wrap:anywhere;color:#a9c1c7;font:11px/1.7 monospace}.review{padding:24px;border:1px solid #3b535a;background:#1a2931;border-radius:10px}textarea{display:block;width:100%;margin:8px 0 13px;padding:12px;border:1px solid #4f6870;border-radius:6px;resize:vertical;background:#122029;color:#dbe7e3;font:12px/1.6 system-ui}.file-button input{display:none}footer{display:flex;justify-content:space-between;gap:15px;margin-top:30px;padding-top:18px;border-top:1px solid #33474d;font:9px/1.5 monospace;color:#8ba3a9;overflow-wrap:anywhere}@media(max-width:900px){main,header{padding:22px}.intro{align-items:start;flex-direction:column}.layout{grid-template-columns:minmax(0,1fr) 245px}canvas{height:500px}.evidence{gap:22px}}@media(max-width:650px){header{align-items:start}.brand small{display:block;margin:7px 0 0}header>.eyebrow{max-width:125px;text-align:right;font-size:8px}main{padding:20px}h1{font-size:34px}.plans{grid-template-columns:1fr}.plan{padding:14px 17px}.layout,.evidence{grid-template-columns:1fr}canvas{height:390px}.view-head{inset:12px 10px auto}.view-head button{padding:7px 9px}.view-head .eyebrow{font-size:8px}.view-foot{flex-direction:column;gap:3px}.review{padding:19px}footer{font-size:8px}.primary{white-space:normal!important}}diff --git a/store/agents/orca-slicer/skills/orcaslicer/scripts/preview.html b/store/agents/orca-slicer/skills/orcaslicer/scripts/preview.htmlindex 00c1191af..97ee000d5 100644--- a/store/agents/orca-slicer/skills/orcaslicer/scripts/preview.html+++ b/store/agents/orca-slicer/skills/orcaslicer/scripts/preview.html@@ -1,5 +1,16 @@-<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Strata · Toolpath inspector</title><link rel="icon" href="data:,">-<style>-*{box-sizing:border-box}body{margin:0;background:#151a20;color:#e2e9e8;font-family:Arial,sans-serif}header{display:flex;justify-content:space-between;align-items:center;padding:23px 32px;border-bottom:1px solid #354047}.brand{font:28px Georgia,serif;letter-spacing:-.8px}.brand span{color:#efa275;margin-right:12px}.mono{font:10px monospace;letter-spacing:1.6px;color:#9daeb1}main{max-width:1550px;margin:auto;padding:30px 32px}.intro{display:flex;align-items:end;justify-content:space-between;margin-bottom:28px;gap:20px}h1{font:normal 38px Georgia,serif;letter-spacing:-1px;margin:10px 0}p{font-size:12px;line-height:1.65;color:#91a3a9;margin:0}a{color:#ffd0a2;font-size:12px;text-decoration:none;padding:11px 16px;border:1px solid #745b4e;border-radius:7px;white-space:nowrap}.layout{display:grid;grid-template-columns:minmax(0,1fr) 270px;gap:24px}.view{position:relative;min-width:0;background:radial-gradient(ellipse at 50% 40%,#21313a,#10171e 70%);border:1px solid #34444d;border-radius:14px;overflow:hidden}.view-head{display:flex;justify-content:space-between;align-items:center;padding:18px 20px;position:absolute;inset:0 0 auto;z-index:1}.group{display:flex;gap:5px}button,select,input{font:inherit}button,select{background:#1c2b32;color:#bdd0d1;border:1px solid #42545a;border-radius:6px;padding:8px 11px;font-size:11px;cursor:pointer}button[aria-pressed=true]{color:#f4be8b;border-color:#b68b66;background:#35352f}button:focus-visible,select:focus-visible,input:focus-visible,a:focus-visible{outline:2px solid #f4be8b;outline-offset:3px}canvas{display:block;width:100%;height:590px;touch-action:none}.hint{position:absolute;bottom:18px;left:20px;font:9px monospace;letter-spacing:1px;color:#6f8e99}.metrics{display:grid;grid-template-columns:1fr 1fr;gap:10px}.metric{border:1px solid #35434b;border-radius:9px;padding:17px 14px;background:#1a232a}.metric b{font:23px Georgia,serif;display:block;margin-top:10px}.metric span{font:9px monospace;color:#8ea2a9}.metric.wide{grid-column:1/-1}.panel{margin-top:21px;border-top:1px solid #35434b;padding-top:20px}.panel h2{font-size:12px;font-weight:400;margin:0 0 16px;color:#b7c7c8}.layer{font:37px Georgia,serif;color:#f0bf91}.layer small{font-size:18px;color:#738a93}input[type=range]{width:100%;accent-color:#e6ac79;margin:18px 0 10px}label{font:10px monospace;color:#93a8af}.controls{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:13px}.controls select{width:125px}.legend{display:grid;gap:8px;margin-top:18px;font:10px monospace;color:#8fa5ac}.legend span{display:flex;gap:8px;align-items:center}.dot{width:7px;height:7px;border-radius:50%;display:inline-block}.notice{margin-top:22px;background:#2a2623;border:1px solid #5c483c;border-radius:9px;padding:16px 18px;color:#cdb093;font:11px/1.6 Arial,sans-serif}details{margin-top:17px;font:11px/1.7 monospace;color:#819ba7}summary{cursor:pointer}pre{white-space:pre-wrap;overflow-wrap:anywhere}footer{display:flex;justify-content:space-between;font:10px monospace;color:#77909b;padding-top:20px;gap:20px}@media(max-width:1000px){.layout{grid-template-columns:1fr 235px}canvas{height:520px}}@media(max-width:650px){header,main{padding:20px}.layout{grid-template-columns:1fr}h1{font-size:31px}.intro{align-items:start;flex-direction:column}canvas{height:370px}.metrics{grid-template-columns:repeat(3,1fr)}.metric.wide{grid-column:auto}.metric{padding:12px 9px}.metric b{font-size:20px}.panel{margin-top:16px}.view-head{padding:13px 10px}.mono{font-size:8px}footer{font-size:9px}}-</style>-<header><div class="brand"><span>≋</span>Strata</div><div class="mono">ORCA SLICER / TOOLPATH INSPECTOR</div></header><main><div class="intro"><div><div class="mono">FROM A SOLID TO A SEQUENCE</div><h1>See what your printer will do.</h1><p>Actual linear moves from the sliced G-code. Explore one layer, or the stack beneath it.</p></div><a href="part.gcode" download>Download G-code ↓</a></div><div class="layout"><section class="view"><div class="view-head"><div class="group"><button id="iso" aria-pressed="true">Isometric</button><button id="top" aria-pressed="false">Top</button><button id="reset">Fit</button></div><span class="mono" id="z-label"></span></div><canvas id="path" tabindex="0" role="img" aria-label="Interactive G-code toolpath. Drag to orbit; scroll to zoom."></canvas><span class="hint">MODEL FOCUS · CUSTOM MOVES HIDDEN UNLESS ENABLED</span></section><aside><div class="metrics"><div class="metric"><span>EXTRUSION HEIGHTS</span><b id="layers"></b></div><div class="metric"><span>SLICER ESTIMATE</span><b id="time"></b></div><div class="metric wide"><span>FILAMENT ESTIMATE</span><b id="filament"></b></div></div><section class="panel"><h2>Layer by layer</h2><div class="layer"><span id="layer-label"></span> <small id="total-label"></small></div><input id="layer" type="range" min="1" value="1" aria-label="Layer"><div class="controls"><button id="previous" aria-label="Previous layer">←</button><button id="play" aria-pressed="false">Play layers</button><button id="next" aria-label="Next layer">→</button></div><div class="controls"><label><input id="stack" type="checkbox" checked> Show stack</label><label><input id="travel" type="checkbox"> Travel</label></div><div class="controls"><label><input id="custom" type="checkbox"> Include custom / purge moves</label></div><div class="controls"><label for="color">Color by</label><select id="color"><option value="feature">Feature</option><option value="speed">Speed</option></select></div><div class="legend" id="legend"></div></section></aside></div><div class="notice" id="notice"></div><details><summary>Profile inputs and preview limits</summary><pre id="config-view"></pre><ul id="warnings"></ul></details><footer><span id="moves"></span><span>LOCAL SLICE · NO PRINTER CONNECTED</span></footer></main><script type="application/json" id="config">__CONFIG__</script><script>/*APP*/</script></html>+<!doctype html>+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Strata · From mesh to machine plan</title><link rel="icon" href="data:,"><link rel="stylesheet" href="handoff/preview.css"></head>+<body><header><div class="brand"><span>≋</span> Strata <small>ORCA SLICER</small></div><span class="eyebrow">LOCAL FILES · NO PRINTER CONNECTED</span></header>+<main><section class="intro"><div><p class="eyebrow">01 MESH → 02 COMPARE → 03 INSPECT → 04 TAKE IT WITH YOU</p><h1 id="title"></h1><p id="brief"></p></div><a class="primary" href="handoff/project.zip" download>Download complete project ↗</a></section>+<div id="notice" class="notice"></div>+<section aria-label="Compare slicing plans" class="plans" id="plans"></section>+<section class="layout"><div class="view"><div class="view-head"><div class="group"><button id="iso" aria-pressed="true">Orbit</button><button id="top" aria-pressed="false">Top</button><button id="reset">Fit</button></div><span id="z-label" class="eyebrow"></span></div><canvas id="path" tabindex="0" role="img" aria-label="Actual G-code paths. Drag to orbit, scroll to zoom, arrow keys change layers."></canvas><div class="view-foot"><span id="status" role="status">Loading actual G-code…</span><span id="moves"></span></div></div>+<aside><p class="eyebrow">INSPECT THE ACTUAL OUTPUT</p><h2 id="plan-title"></h2><p id="plan-description"></p><div class="layer"><span id="layer-label">—</span><small id="total-label"></small></div><input id="layer" type="range" min="1" value="1" aria-label="Layer">+<div class="controls"><button id="previous" aria-label="Previous layer">←</button><button id="play" aria-pressed="false">Play layers</button><button id="next" aria-label="Next layer">→</button></div>+<div class="options"><label><input id="stack" type="checkbox" checked> Stack through this layer</label><label><input id="travel" type="checkbox"> Include travel</label><label><input id="custom" type="checkbox"> Include custom / purge paths</label><label><input id="full" type="checkbox"> Full motion: hops, purge & final park</label></div>+<label for="color">Color by</label> <select id="color"><option value="feature">Feature</option><option value="speed">Speed</option></select><div id="legend" class="legend"></div>+<div class="downloads"><a id="project" download>Open editable 3MF ↗</a><a id="gcode" download>Download G-code ↓</a><a id="settings" download>Effective settings ↓</a></div></aside></section>+<section class="evidence"><div><p class="eyebrow">CHECKED AGAINST YOUR SAVED BRIEF</p><h2 id="check-count"></h2><p id="machine"></p><p id="assumptions"></p><details><summary>Heater targets and full-motion bounds</summary><pre id="thermal"></pre></details><details><summary>Native output and reopen evidence</summary><ul id="checks"></ul></details><details><summary>Limits and parser notices</summary><p id="limits"></p><ul id="warnings"></ul></details><a href="handoff/report.json" download>Download inspection receipt ↓</a></div>+<div class="review"><p class="eyebrow">KEEP YOUR REVIEW WITH THE PROJECT</p><h2>A decision, not a guess.</h2><p>Record what you want to change. Export your selected plan, view and notes; restore them against this exact source revision. These notes do not approve a print.</p><label for="notes">Review notes</label><textarea id="notes" rows="5" maxlength="12000" placeholder="First layer, support needs, tolerances, machine-specific questions…"></textarea><div class="group"><button id="save-review">Save review ↓</button><button id="restore-button">Restore review</button><input id="restore-review" type="file" accept=".json,application/json" hidden></div><p id="review-status" role="status"></p></div></section>+<footer><span id="revision"></span><span>SLICE. COMPARE. REVISE. REOPEN.</span></footer></main>+<script type="application/json" id="report">__REPORT__</script><script type="module" src="handoff/preview.js"></script></body></html>diff --git a/store/agents/orca-slicer/skills/orcaslicer/scripts/preview.js b/store/agents/orca-slicer/skills/orcaslicer/scripts/preview.jsindex bf8fd439e..899dbc08c 100644--- a/store/agents/orca-slicer/skills/orcaslicer/scripts/preview.js+++ b/store/agents/orca-slicer/skills/orcaslicer/scripts/preview.js@@ -1,31 +1,94 @@-const $=id=>document.getElementById(id),data=JSON.parse($('config').textContent),canvas=$('path'),g=canvas.getContext('2d');+import {parseGcode} from './gcode.mjs';+const $=id=>document.getElementById(id),report=JSON.parse($('report').textContent),canvas=$('path'),g=canvas.getContext('2d');const palette=['#edb783','#b5d6c1','#73b8bd','#d4cf94','#d68b8e','#8aa9d8','#b49acc'];-let layer=Math.max(1,Math.round(data.layers.length*.7)),yaw=.6,pitch=.65,zoom=1,topView=false,timer=null,drag;-$('layers').textContent=data.layers.length;$('time').textContent=data.stats.time||'Not reported';$('filament').textContent=data.stats.filamentGrams!==null?data.stats.filamentGrams.toFixed(1)+' g':data.stats.filamentMm!==null?(data.stats.filamentMm/1000).toFixed(2)+' m':'Not reported';$('layer').max=data.layers.length;$('layer').value=layer;$('total-label').textContent='/ '+data.layers.length;$('config-view').textContent=JSON.stringify(data.config,null,2);$('moves').textContent=data.moves.toLocaleString()+' LINEAR MOVES PARSED';-$('notice').textContent=data.config.mode==='demo'?'DEMO PROFILE — Prusa MK3S, not your printer. This is a toolpath study, not a print-ready recommendation. Review the exact machine, material, temperatures, origin and first layer before printing.':'Sliced, not print-tested. Review machine-specific G-code, temperatures, bed boundaries and the first layer in OrcaSlicer before printing.';-for(const text of [...data.warnings,'Geometry preview does not model heater behavior, firmware limits, offsets, bed leveling, collisions, supports adequacy or mechanical printability.']){const li=document.createElement('li');li.textContent=text;$('warnings').append(li);}+let data=null,selected=null,layer=1,yaw=.6,pitch=.65,zoom=1,topView=false,timer=null,drag,request=0;+const artifactRevision=report.plans.map(p=>p.sha256.gcode).join(':');+$('title').textContent=report.title;$('brief').textContent=report.brief;$('assumptions').textContent=report.assumptions;+$('notice').textContent=(report.machine.context==='example'?'EXAMPLE MACHINE — NOT YOUR PRINTER. ':'USER-SUPPLIED MACHINE BRIEF — NOT PHYSICALLY VERIFIED. ')+'Native slices have been checked and reopened. Review the actual printer, plate, material, custom code and first layer in OrcaSlicer before printing.';+$('machine').textContent=report.machine.label+' · '+report.machine.nozzleMM+' mm nozzle · '+report.machine.material+' · '+report.machine.bedType+' · '+report.machine.bedMM.join(' × ')+' mm';+$('limits').textContent=report.limitations;$('revision').textContent='SAVED SOURCE '+report.revision.slice(0,16)+' · ORCA '+report.engine.version;+function time(seconds){const minutes=Math.round(seconds/60);return Math.floor(minutes/60)+'h '+minutes%60+'m';}+for(const plan of report.plans){+ const button=document.createElement('button');button.className='plan';button.dataset.plan=plan.id;button.setAttribute('aria-pressed','false');+ const name=document.createElement('span');name.className='name';name.textContent=plan.label;+ const metrics=document.createElement('span');metrics.className='numbers';+ for(const [value,unit] of [[time(plan.stats.timeSeconds),'EST.'],[plan.stats.filamentGrams.toFixed(1),'g']]){const span=document.createElement('span'),small=document.createElement('small');span.textContent=value;small.textContent=unit;span.append(small);metrics.append(span);}+ const settings=document.createElement('span');settings.className='settings';settings.textContent=plan.layerHeightMM+' mm · '+plan.wallLoops+' walls · '+plan.infillPercent+'% '+plan.infillPattern+' · '+plan.layers+' layers';+ const delta=document.createElement('span');delta.className='delta';const base=report.plans[0],dt=plan.stats.timeSeconds-base.stats.timeSeconds,dg=plan.stats.filamentGrams-base.stats.filamentGrams;+ delta.textContent=plan===base?'Comparison baseline · estimates, not measurements':(dt>=0?'+':'')+Math.round(dt/60)+' min / '+(dg>=0?'+':'')+dg.toFixed(1)+' g vs '+base.label;+ button.append(name,metrics,settings,delta);button.onclick=()=>select(plan.id);$('plans').append(button);+}+function list(id,items){$(id).replaceChildren(...items.map(text=>{const li=document.createElement('li');li.textContent=text;return li;}));}+function stop(){clearInterval(timer);timer=null;$('play').textContent='Play layers';$('play').setAttribute('aria-pressed','false');}function legend(){- $('legend').replaceChildren();for(const [i,name]of ($('color').value==='speed'?['≤20 mm/s','100 mm/s','≥180 mm/s']:data.features).entries()){const row=document.createElement('span'),dot=document.createElement('i');dot.className='dot';dot.style.background=$('color').value==='speed'?['#8ac5df','#bdd495','#e69a6c'][i]:palette[i%palette.length];row.append(dot,document.createTextNode(name));$('legend').append(row);}+ $('legend').replaceChildren();if(!data)return;+ for(const [i,name]of ($('color').value==='speed'?['≤20 mm/s','100 mm/s','≥180 mm/s']:data.features).entries()){const row=document.createElement('span'),dot=document.createElement('i');dot.className='dot';dot.style.background=$('color').value==='speed'?['#8ac5df','#bdd495','#e69a6c'][i]:palette[i%palette.length];row.append(dot,document.createTextNode(name));$('legend').append(row);}+}+async function select(id){+ const turn=++request;stop();data=null;selected=report.plans.find(p=>p.id===id);if(!selected)throw new Error('Unknown saved plan.');+ for(const button of $('plans').children)button.setAttribute('aria-pressed',String(button.dataset.plan===id));+ $('plan-title').textContent=selected.label;$('plan-description').textContent=selected.description;+ for(const key of ['gcode','project','settings'])$(key).href=selected[key];+ $('check-count').textContent=selected.checks.length+' checks. Native project reopened.';+ $('thermal').textContent=selected.temperatures.map(t=>'Line '+t.line+' · '+t.command+' '+t.heater+' target '+t.target+' °C'+(t.wait?' · wait command':'')).join('\n')+'\n\nModel/support centerline bounds (mm):\n'+JSON.stringify(selected.bounds)+'\n\nAll commanded motion, including purge and parking (mm):\n'+JSON.stringify(selected.fullMotionBounds)+'\n\nThese are commands, not measured temperatures or firmware simulation.';+ list('checks',selected.checks.map(c=>'✓ '+c.name+' — '+c.detail));list('warnings',selected.warnings);+ $('status').textContent='Loading and verifying '+selected.label+' G-code…';canvas.dataset.ready='false';draw();+ try{+ const expected=selected,response=await fetch(expected.gcode);if(!response.ok)throw new Error('Could not load G-code; serve this project over its loopback URL.');+ const buffer=await response.arrayBuffer();if(buffer.byteLength>32*1024*1024)throw new Error('Toolpath exceeds the 32 MiB inspection limit.');+ if(!crypto.subtle)throw new Error('Integrity checks require a localhost or HTTPS browser context.');+ const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',buffer)),n=>n.toString(16).padStart(2,'0')).join('');+ if(hash!==expected.sha256.gcode)throw new Error('G-code changed since its checked receipt. Rebuild the project.');+ await new Promise(resolve=>requestAnimationFrame(resolve));if(turn!==request)return;+ const parsed=parseGcode(new TextDecoder().decode(buffer));if(turn!==request)return;+ data=parsed;layer=Math.max(1,Math.round(data.layers.length*.72));$('layer').max=data.layers.length;$('layer').value=layer;$('total-label').textContent='/ '+data.layers.length;+ $('moves').textContent=data.moves.toLocaleString()+' ACTUAL MOVES';$('status').textContent='SHA-256 verified · drag to orbit · scroll to zoom';canvas.dataset.ready='true';canvas.dataset.plan=id;legend();draw();+ }catch(error){if(turn!==request)return;$('status').textContent=error.message;canvas.dataset.error=error.message;draw();}}function draw(){- const width=canvas.clientWidth,height=canvas.clientHeight,ratio=Math.min(devicePixelRatio||1,2);canvas.width=width*ratio;canvas.height=height*ratio;g.scale(ratio,ratio);g.clearRect(0,0,width,height);- const bounds=$('custom').checked?data.bounds:(data.modelBounds||data.bounds),center=bounds.min.map((v,i)=>(v+bounds.max[i])/2),span=Math.max(1,...bounds.max.map((v,i)=>v-bounds.min[i]));const scale=Math.min(width-80,height-110)/span*.85*zoom;- const project=p=>{const x=p[0]-center[0],y=p[1]-center[1],z=p[2]-center[2];if(topView)return [width/2+x*scale,height/2-y*scale];const xx=x*Math.cos(yaw)-y*Math.sin(yaw),yy=x*Math.sin(yaw)+y*Math.cos(yaw);return [width/2+xx*scale,height/2+(yy*Math.sin(pitch)-z*Math.cos(pitch))*scale];};- const segment=(a,b)=>{const p=project(a),q=project(b);g.moveTo(...p);g.lineTo(...q);};- g.lineWidth=.7;g.strokeStyle='#46636a35';g.beginPath();for(let i=-5;i<=5;i++){const v=i*span/10;segment([center[0]-span/2,center[1]+v,0],[center[0]+span/2,center[1]+v,0]);segment([center[0]+v,center[1]-span/2,0],[center[0]+v,center[1]+span/2,0]);}g.stroke();- let displayed=0;const start=$('stack').checked?0:layer-1;- for(let l=start;l<layer;l++){- const active=l===layer-1,groups=new Map();- for(const s of data.layers[l].segments){if((!s[8]&&!$('travel').checked)||(!$('custom').checked&&data.features[s[7]]==='Custom'))continue;const color=!s[8]?'#677d8744':!active?'#86abb033':$('color').value==='speed'?'hsl('+Math.max(20,205-s[6]*1.05)+',48%,66%)':palette[s[7]%palette.length];if(!groups.has(color))groups.set(color,[]);groups.get(color).push(s);displayed++;}- for(const [color,segments]of groups){g.strokeStyle=color;g.lineWidth=active?1.35:.6;g.beginPath();for(const s of segments)segment(s.slice(0,3),s.slice(3,6));g.stroke();}+ const width=canvas.clientWidth,height=canvas.clientHeight,ratio=Math.min(devicePixelRatio||1,2);canvas.width=width*ratio;canvas.height=height*ratio;g.scale(ratio,ratio);g.clearRect(0,0,width,height);if(!data)return;+ const full=$('full').checked,bounds=full?data.motionBounds:$('custom').checked?data.bounds:data.modelBounds,center=bounds.min.map((v,i)=>(v+bounds.max[i])/2),span=Math.max(1,...bounds.max.map((v,i)=>v-bounds.min[i]));+ const scale=Math.max(1,Math.min(width-70,height-100))/span*.88*zoom;+ const project=p=>{const x=p[0]-center[0],y=p[1]-center[1],z=p[2]-center[2];if(topView)return [width/2+x*scale,height/2-y*scale];const xx=x*Math.cos(yaw)-y*Math.sin(yaw),yy=x*Math.sin(yaw)+y*Math.cos(yaw);return [width/2+xx*scale,height/2+(yy*Math.sin(pitch)-z*Math.cos(pitch))*scale];};+ const segment=(a,b)=>{const p=project(a),q=project(b);g.moveTo(...p);g.lineTo(...q);};+ g.lineWidth=.7;g.strokeStyle='#50778040';g.beginPath();for(let i=-5;i<=5;i++){const v=i*span/10;segment([center[0]-span/2,center[1]+v,0],[center[0]+span/2,center[1]+v,0]);segment([center[0]+v,center[1]-span/2,0],[center[0]+v,center[1]+span/2,0]);}g.stroke();+ let displayed=0;const rows=full?[{segments:data.motions}]:data.layers.slice($('stack').checked?0:layer-1,layer);+ for(const [index,row] of rows.entries()){+ const active=full||index===rows.length-1,groups=new Map();+ for(const s of row.segments){+ if(!full&&((!s[8]&&!$('travel').checked)||(!$('custom').checked&&data.features[s[7]]==='Custom')))continue;+ const color=!s[8]?'#9fb7c14a':!active?'#94bdc138':$('color').value==='speed'?'hsl('+Math.max(20,Math.round((205-s[6]*1.05)/10)*10)+',48%,66%)':palette[s[7]%palette.length];+ if(!groups.has(color))groups.set(color,[]);groups.get(color).push(s);displayed++;}- $('layer-label').textContent=layer;$('z-label').textContent='Z '+data.layers[layer-1].z.toFixed(2)+' MM';canvas.dataset.layer=String(layer);canvas.dataset.segments=String(displayed);canvas.dataset.projection=topView?'top':'isometric';$('previous').disabled=layer===1;$('next').disabled=layer===data.layers.length;+ for(const [color,segments]of groups){g.strokeStyle=color;g.lineWidth=active?1.2:.65;g.beginPath();for(const s of segments)segment(s.slice(0,3),s.slice(3,6));g.stroke();}+ }+ $('layer-label').textContent=full?'All':layer;$('z-label').textContent=full?'PURGE → MODEL → PARK':'Z '+data.layers[layer-1].z.toFixed(2)+' MM';+ canvas.dataset.layer=String(layer);canvas.dataset.segments=String(displayed);canvas.dataset.projection=topView?'top':'isometric';canvas.dataset.full=String(full);+ $('layer').disabled=full;$('previous').disabled=full||layer===1;$('next').disabled=full||layer===data.layers.length;$('play').disabled=full;}-function setLayer(value){layer=Math.max(1,Math.min(data.layers.length,Number(value)));$('layer').value=layer;draw();}+function setLayer(value){if(!data)return;layer=Math.max(1,Math.min(data.layers.length,Number(value)));$('layer').value=layer;draw();}$('layer').oninput=()=>setLayer($('layer').value);$('previous').onclick=()=>setLayer(layer-1);$('next').onclick=()=>setLayer(layer+1);-function stop(){clearInterval(timer);timer=null;$('play').textContent='Play layers';$('play').setAttribute('aria-pressed','false');}-$('play').onclick=()=>{if(timer){stop();return;}$('play').textContent='Pause';$('play').setAttribute('aria-pressed','true');timer=setInterval(()=>{if(layer===data.layers.length){stop();return;}setLayer(layer+1);},120);};+$('play').onclick=()=>{if(timer){stop();return;}if(!data)return;$('play').textContent='Pause';$('play').setAttribute('aria-pressed','true');timer=setInterval(()=>{if(layer===data.layers.length){stop();return;}setLayer(layer+1);},180);};for(const id of ['iso','top'])$(id).onclick=()=>{topView=id==='top';$('iso').setAttribute('aria-pressed',String(!topView));$('top').setAttribute('aria-pressed',String(topView));draw();};-$('reset').onclick=()=>{yaw=.6;pitch=.65;zoom=1;draw();};for(const id of ['stack','travel','color','custom'])$(id).onchange=()=>{legend();draw();};-canvas.onpointerdown=e=>{canvas.setPointerCapture(e.pointerId);drag={x:e.clientX,y:e.clientY};};canvas.onpointermove=e=>{if(!drag)return;yaw+=(e.clientX-drag.x)*.009;pitch=Math.max(.1,Math.min(1.5,pitch+(e.clientY-drag.y)*.007));drag={x:e.clientX,y:e.clientY};draw();};canvas.onpointerup=canvas.onpointercancel=()=>{drag=null;};canvas.addEventListener('wheel',e=>{e.preventDefault();zoom=Math.max(.3,Math.min(6,zoom*Math.exp(-e.deltaY*.001)));draw();},{passive:false});canvas.onkeydown=e=>{if(e.key==='ArrowRight'||e.key==='ArrowLeft'){e.preventDefault();setLayer(layer+(e.key==='ArrowRight'?1:-1));}};-new ResizeObserver(draw).observe(canvas);document.addEventListener('visibilitychange',()=>{if(document.hidden)stop();});legend();draw();+$('reset').onclick=()=>{yaw=.6;pitch=.65;zoom=1;draw();};for(const id of ['stack','travel','color','custom','full'])$(id).onchange=()=>{stop();legend();draw();};+canvas.onpointerdown=e=>{canvas.setPointerCapture(e.pointerId);drag={x:e.clientX,y:e.clientY};};canvas.onpointermove=e=>{if(!drag)return;yaw+=(e.clientX-drag.x)*.009;pitch=Math.max(.1,Math.min(1.5,pitch+(e.clientY-drag.y)*.007));drag={x:e.clientX,y:e.clientY};draw();};canvas.onpointerup=canvas.onpointercancel=()=>{drag=null;};+canvas.addEventListener('wheel',e=>{e.preventDefault();zoom=Math.max(.3,Math.min(6,zoom*Math.exp(-e.deltaY*.001)));draw();},{passive:false});+canvas.onkeydown=e=>{if(e.key==='ArrowRight'||e.key==='ArrowLeft'){e.preventDefault();setLayer(layer+(e.key==='ArrowRight'?1:-1));}};+$('save-review').onclick=()=>{+ if(!data){$('review-status').textContent='Wait for a verified toolpath before saving.';return;}+ const state={spec:1,revision:report.revision,artifactRevision,plan:selected.id,notes:$('notes').value,layer,yaw,pitch,zoom,topView,options:Object.fromEntries(['stack','travel','custom','full'].map(k=>[k,$(k).checked])),color:$('color').value};+ const link=document.createElement('a'),url=URL.createObjectURL(new Blob([JSON.stringify(state,null,2)+'\n'],{type:'application/json'}));link.href=url;link.download='strata-review.json';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);$('review-status').textContent='Review exported for this exact source and toolpath revision.';+};+$('restore-button').onclick=()=>$('restore-review').click();+$('restore-review').onchange=async()=>{+ const file=$('restore-review').files[0];try{+ if(!file||file.size>65536)throw new Error('Choose a review JSON under 64 KiB.');const state=JSON.parse(await file.text());+ if(state.spec!==1||state.revision!==report.revision||state.artifactRevision!==artifactRevision)throw new Error('Review belongs to a different source or toolpath revision.');+ if(!report.plans.some(p=>p.id===state.plan)||typeof state.notes!=='string'||state.notes.length>12000||!Number.isInteger(state.layer)||state.layer<1||typeof state.topView!=='boolean'||!['feature','speed'].includes(state.color)||!state.options||['stack','travel','custom','full'].some(k=>typeof state.options[k]!=='boolean'))throw new Error('Invalid review values.');+ for(const [key,min,max]of [['yaw',-100000,100000],['pitch',.1,1.5],['zoom',.3,6]])if(!Number.isFinite(state[key])||state[key]<min||state[key]>max)throw new Error('Invalid view values.');+ await select(state.plan);if(!data||selected.id!==state.plan)throw new Error('Review plan did not load or selection changed.');if(state.layer>data.layers.length)throw new Error('Review layer exceeds this toolpath.');+ $('notes').value=state.notes;yaw=state.yaw;pitch=state.pitch;zoom=state.zoom;topView=state.topView;for(const key of ['stack','travel','custom','full'])$(key).checked=state.options[key];$('color').value=state.color;+ $('iso').setAttribute('aria-pressed',String(!topView));$('top').setAttribute('aria-pressed',String(topView));setLayer(state.layer);legend();$('review-status').textContent='Review restored. No print has been approved or started.';+ }catch(error){$('review-status').textContent=error.message;}finally{$('restore-review').value='';}+};+new ResizeObserver(draw).observe(canvas);document.addEventListener('visibilitychange',()=>{if(document.hidden)stop();});select(report.selectedPlan);diff --git a/store/agents/orca-slicer/skills/orcaslicer/scripts/profiles.mjs b/store/agents/orca-slicer/skills/orcaslicer/scripts/profiles.mjsindex 2c0f1777c..107fb26bf 100644--- a/store/agents/orca-slicer/skills/orcaslicer/scripts/profiles.mjs+++ b/store/agents/orca-slicer/skills/orcaslicer/scripts/profiles.mjs@@ -1,15 +1,45 @@-import {readFile} from 'node:fs/promises';import {resolve,dirname,basename} from 'node:path';-// Orca's CLI does not reliably flatten shipped profile inheritance. Resolve the-// explicit sibling chain ourselves; never silently substitute unrelated defaults.-export async function resolveProfile(file,chain=[]){- const path=resolve(file);if(chain.includes(path)||chain.length>=20)throw new Error('Cyclic or overly deep profile inheritance.');- const value=JSON.parse(await readFile(path,'utf8'));- if(!value||Array.isArray(value)||typeof value!=='object'||typeof value.name!=='string')throw new Error('Invalid profile: '+basename(path));- let parent={};+import {readFile,lstat,realpath} from 'node:fs/promises';+import {resolve,dirname,basename,join,parse} from 'node:path';+import {createHash} from 'node:crypto';+const networkFields=['print_host','print_host_webui','printhost_apikey','printhost_port','printhost_cafile','printhost_user','printhost_password','printhost_authorization_type','flashforge_serial_number'];+const credentialFields=networkFields.filter(key=>!['printhost_port','printhost_authorization_type'].includes(key));+function nonempty(value){return Array.isArray(value)?value.some(nonempty):value!==undefined&&value!==null&&value!==''&&value!==false&&value!==0;}+async function regular(file){+ const path=resolve(file);let current=parse(path).root;+ for(const component of path.slice(current.length).split(/[\\/]/).filter(Boolean)){+ current=join(current,component);+ // /tmp may itself be an OS alias; callers supply real workspace/profile+ // roots. Resolve these roots before calling this function.+ if((await lstat(current)).isSymbolicLink())throw new Error('Profile paths must not contain symlinks: '+basename(path));+ }+ const info=await lstat(path);+ if(!info.isFile()||info.size>1024*1024)throw new Error('Profile must be a regular JSON file under 1 MiB: '+basename(path));+ return readFile(path);+}+export async function profileWithSources(file,chain=[]){+ // Canonicalize the selected directory (including macOS /tmp and /var+ // aliases), but never follow a selected file symlink. Workspace callers+ // separately validate every component against their source allowlist.+ const path=join(await realpath(dirname(resolve(file))),basename(file));+ if(chain.includes(path)||chain.length>=20)throw new Error('Cyclic or overly deep profile inheritance.');+ const bytes=await regular(path),value=JSON.parse(bytes);+ if(!value||Array.isArray(value)||typeof value!=='object'||typeof value.name!=='string'||!value.name.trim())throw new Error('Invalid profile: '+basename(path));+ for(const key of credentialFields)if(nonempty(value[key]))throw new Error('Remove printer connection/credential field '+key+' from the exported slicing profile before bundling it. No connection is needed.');+ let parent={profile:{},sources:[]};if(value.inherits){- if(typeof value.inherits!=='string'||basename(value.inherits)!==value.inherits||value.inherits.includes('\\'))throw new Error('Profile parent must be a sibling profile name.');+ if(typeof value.inherits!=='string'||basename(value.inherits)!==value.inherits||value.inherits.includes('\\')||value.inherits.startsWith('.'))throw new Error('Profile parent must be a sibling profile name.');const parentFile=resolve(dirname(path),value.inherits+'.json');- try{parent=await resolveProfile(parentFile,[...chain,path]);}catch(error){throw new Error('Cannot resolve '+value.name+' parent '+value.inherits+': '+error.message);}+ try{parent=await profileWithSources(parentFile,[...chain,path]);}catch(error){throw new Error('Cannot resolve '+value.name+' parent '+value.inherits+': '+error.message);}+ }+ const merged={...parent.profile,...value,instantiation:'true'};delete merged.inherits;+ for(const key of networkFields)delete merged[key];+ return {profile:merged,sources:[...parent.sources,{path,bytes,sha256:createHash('sha256').update(bytes).digest('hex')}]};+}+export async function resolveProfile(file,chain=[]){return (await profileWithSources(file,chain)).profile;}+export async function unchangedProfiles(profiles){+ const seen=new Set();+ for(const item of profiles.flatMap(profile=>profile.sources)){+ if(seen.has(item.path))continue;seen.add(item.path);+ if(createHash('sha256').update(await regular(item.path)).digest('hex')!==item.sha256)throw new Error('A profile changed during slicing; rebuild: '+basename(item.path));}- const merged={...parent,...value,instantiation:'true'};delete merged.inherits;return merged;}diff --git a/store/agents/orca-slicer/skills/orcaslicer/scripts/serve-preview.mjs b/store/agents/orca-slicer/skills/orcaslicer/scripts/serve-preview.mjsnew file mode 100644index 000000000..7ae8ecde1--- /dev/null+++ b/store/agents/orca-slicer/skills/orcaslicer/scripts/serve-preview.mjs@@ -0,0 +1,58 @@+// 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 = /^(?:preview\.html|part\.(?:gcode|3mf)|handoff\/(?:preview\.(?:js|css)|gcode\.mjs|report\.json|README\.txt|project\.zip|plans\/[a-z0-9-]+\/(?:part\.gcode|project\.3mf|effective\.json|inspection\.json)))$/;+const types = {'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8','.json':'application/json; charset=utf-8','.txt':'text/plain; charset=utf-8','.zip':'application/zip','.gcode':'text/plain; charset=utf-8','.3mf':'model/3mf'};++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:'/preview.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');+ if ((await lstat(target)).size > 32*1024*1024) throw new Error('Artifact exceeds download limit');+ 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 'self'; script-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",+ };+ if (!['.html','.js','.mjs','.css'].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 OrcaSlicer project: http://127.0.0.1:${server.address().port}/preview.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/orca-slicer/store.json b/store/agents/orca-slicer/store.jsonindex 4bd0285db..338b4ba2c 100644--- a/store/agents/orca-slicer/store.json+++ b/store/agents/orca-slicer/store.json@@ -1,17 +1,29 @@{- "listed": false,+ "listed": true,"homepage": "https://orca-slicer.pages.dev",- "upstream": "https://github.com/SoftFever/OrcaSlicer",+ "upstream": "https://github.com/OrcaSlicer/OrcaSlicer","license": "MIT",- "tagline": "An open-source slicer for FFF 3D printers",+ "tagline": "Your mesh. Compared plans. Editable native projects.","screenshots": [- "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/orca-slicer/starter.jpg"+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/orca-slicer/starter.jpg",+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/orca-slicer/review.jpg",+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/orca-slicer/spacer.jpg"],"examples": [{- "prompt": "Slice the included vessel with the labeled demo profile and inspect its layers. Do not print it.",+ "prompt": "Compare faster and finer slicing plans for my rack using a clearly labelled example printer. Give me checked G-code, editable 3MF projects and the full source handoff; do not print.","image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/orca-slicer/starter.jpg",- "caption": "Strata · real Orca G-code, 240 extrusion heights"+ "caption": "Three actual native plans · 225 software checks · editable 3MF + G-code"+ },+ {+ "prompt": "Show the exact heater commands and full motion, including purge and parking. Help me record what must be reviewed before using a real printer.",+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/orca-slicer/review.jpg",+ "caption": "Actual command evidence and revision-bound review notes · no printer connected"+ },+ {+ "prompt": "Prepare this 24 mm spacer with my exported profiles, then revise the Everyday plan to four walls at 0.16 mm. Reopen the native export and show the time/material change.",+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/orca-slicer/spacer.jpg",+ "caption": "Independent mesh and explicit profiles · revised from 30 to 37 layers"}]}diff --git a/store/agents/orca-slicer/template/model.scad b/store/agents/orca-slicer/template/model.scadindex d86e80685..f327c0422 100644--- a/store/agents/orca-slicer/template/model.scad+++ b/store/agents/orca-slicer/template/model.scad@@ -1,7 +1,18 @@-// Original small fluted vessel, for slicer exploration. Millimetres, dry use only.-height=48; diameter=55; wall=2; base=2.4; ribs=18; twist=22; resolution=72;-difference(){- linear_extrude(height=height,twist=twist,slices=24,convexity=10)- polygon([for(i=[0:resolution-1])let(a=i*360/resolution,r=diameter/2+1.5*(1+cos(ribs*a))/2)[r*cos(a),r*sin(a)]]);- translate([0,0,base])cylinder(h=height+0.1,r=diameter/2-wall,$fn=resolution);+// Original Bottle Bench rack, millimetres. Dry indoor craft storage only.+// Regenerate model.stl with OpenSCAD after edits; the slicer does not compile this.+// This geometry matches the Everyday rack in the OpenSCAD harness acceptance case.+bottle_diameter=26;+radial_clearance=0.3;+wall=2;+floor=2.4;+height=18;+columns=3;+rows=2;+bore=bottle_diameter+2*radial_clearance;+$fn=128;+difference() {+ cube([columns*bore+(columns+1)*wall,rows*bore+(rows+1)*wall,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);}diff --git a/store/agents/orca-slicer/template/model.stl b/store/agents/orca-slicer/template/model.stlindex 0e6081e8e..5feb1e2d2 100644Binary files a/store/agents/orca-slicer/template/model.stl and b/store/agents/orca-slicer/template/model.stl differdiff --git a/store/agents/orca-slicer/template/print-config.md b/store/agents/orca-slicer/template/print-config.mdindex 0df3a1204..18f722670 100644--- a/store/agents/orca-slicer/template/print-config.md+++ b/store/agents/orca-slicer/template/print-config.md@@ -1,11 +1,21 @@-# Print intent+# Saved slicing brief-The included fluted vessel and slice-config.json are a **demo for toolpath exploration**, not a recommendation for your printer. No printer is connected.+slice-config.json is executable; these notes explain the example.-The executable settings are the printer, process and filament JSON profiles named in slice-config.json. This Markdown file is notes only; changing it does not change the slice.+- Goal: compare the same six-pocket rack across three actual native slicing plans.+- Requirements: source mesh 87.8 × 59.2 × 18 mm, explicitly millimetres.+- Machine/material: example Prusa MK3S / one 0.4 mm nozzle / PLA / High Temp Plate.+ This is not a claim about the user's printer. No printer is connected.+- Each plan must stay within the saved 8-hour / 80 g estimate budgets and the+ 5 mm model/support-centerline bed inset. Custom purge and parking are reported+ separately and must be reviewed; they are not guaranteed to stay in that inset.+- Source pocket size 26.6 mm is not a measured printed fit. Ask for actual bottle,+ printer and filament details before preparing a hardware-specific job.+- Revisions change the JSON before slicing. Export G-code + editable 3MF + all+ source/profile files, not just a screenshot. Open the 3MF in OrcaSlicer.+- These tests do not establish structural strength, material compatibility,+ support adequacy, food safety, thermal safety or successful physical printing.-For a real project, set mode to "custom", provide your OrcaSlicer-exported profile paths (relative to the workspace or absolute), and confirm printer model, nozzle, bed dimensions, firmware flavor, material temperatures, cooling, layer height, walls and supports. Inherited profiles must resolve in your installed OrcaSlicer. Do not copy the demo profile onto an unrelated printer.--Run: `sh "$ORCA_SKILLS/orcaslicer/scripts/slice-part.sh"`--The helper loads all three profiles explicitly, arranges one mesh onto the bed, disables arc fitting for the linear inspector, disables post-processing commands, and never uploads or prints. Review machine-specific start/end G-code and geometry in OrcaSlicer before printing.+model.scad is editable CAD provenance. Re-export its STL with OpenSCAD after a+CAD edit; this harness does not claim that the SCAD and STL are automatically in+sync. The STL is the actual slicing input.diff --git a/store/agents/orca-slicer/template/slice-config.json b/store/agents/orca-slicer/template/slice-config.jsonindex f217f9162..7071ff298 100644--- a/store/agents/orca-slicer/template/slice-config.json+++ b/store/agents/orca-slicer/template/slice-config.json@@ -1,7 +1,105 @@{- "mode": "demo",- "model": "model.stl",- "printer": "Prusa/machine/Prusa MK3S 0.4 nozzle.json",- "process": "Prusa/process/0.20mm Standard @MK3S 0.4.json",- "filament": "Prusa/filament/Prusa Generic PLA.json"+ "spec": 1,+ "title": "Bottle Bench · Choose the print plan",+ "brief": "Turn a six-bottle craft rack into an editable, inspectable slicing project. Compare draft, everyday and fine layers using the same mesh, printer, material and orientation.",+ "assumptions": "Software-only example: Prusa MK3S, one 0.4 mm nozzle, PLA, High Temp Plate. These are not facts about your printer. The 26.6 mm bottle pockets and 2.4 mm floor have not been physically fit-tested; dry indoor craft storage only.",+ "sourceFiles": [+ "slice-config.json",+ "model.stl",+ "model.scad",+ "print-config.md"+ ],+ "profiles": {+ "source": "installed",+ "printer": "Prusa/machine/Prusa MK3S 0.4 nozzle.json",+ "process": "Prusa/process/0.20mm Standard @MK3S 0.4.json",+ "filament": "Prusa/filament/Prusa Generic PLA.json"+ },+ "machine": {+ "context": "example",+ "label": "Prusa MK3S · example only",+ "printerModel": "Prusa MK3S",+ "nozzleMM": 0.4,+ "bedMM": [+ 250,+ 210,+ 210+ ],+ "bedType": "High Temp Plate",+ "firmware": "marlin",+ "material": "PLA",+ "nozzleTemperatureRange": [+ 190,+ 230+ ],+ "bedTemperatureRange": [+ 50,+ 70+ ]+ },+ "model": {+ "path": "model.stl",+ "expectedSizeMM": [+ 87.8,+ 59.2,+ 18+ ],+ "toleranceMM": 0.03,+ "rotationDegrees": [+ 0,+ 0,+ 0+ ],+ "scale": 1+ },+ "plans": [+ {+ "id": "draft",+ "label": "Draft",+ "description": "Coarser layers and two walls. Compare a faster dimensional trial; this is not a strength recommendation.",+ "layerHeightMM": 0.28,+ "firstLayerMM": 0.2,+ "wallLoops": 2,+ "infillPercent": 10,+ "infillPattern": "gyroid",+ "topLayers": 4,+ "bottomLayers": 3,+ "supports": false,+ "brimMM": 0+ },+ {+ "id": "everyday",+ "label": "Everyday",+ "description": "A middle comparison with three walls and 0.20 mm layers. Inspect the first layer and pocket paths.",+ "layerHeightMM": 0.2,+ "firstLayerMM": 0.2,+ "wallLoops": 3,+ "infillPercent": 15,+ "infillPattern": "gyroid",+ "topLayers": 4,+ "bottomLayers": 3,+ "supports": false,+ "brimMM": 0+ },+ {+ "id": "fine",+ "label": "Fine layers",+ "description": "0.16 mm layers, same walls and infill as Everyday. Compare surface resolution against time and material—not a guaranteed finish.",+ "layerHeightMM": 0.16,+ "firstLayerMM": 0.2,+ "wallLoops": 3,+ "infillPercent": 15,+ "infillPattern": "gyroid",+ "topLayers": 5,+ "bottomLayers": 4,+ "supports": false,+ "brimMM": 0+ }+ ],+ "selectedPlan": "everyday",+ "limits": {+ "maxTimeSeconds": 28800,+ "maxFilamentGrams": 80,+ "bedMarginMM": 5+ }}diff --git a/store/agents/orca-slicer/test/ACCEPTANCE.md b/store/agents/orca-slicer/test/ACCEPTANCE.mdnew file mode 100644index 000000000..3888e8068--- /dev/null+++ b/store/agents/orca-slicer/test/ACCEPTANCE.md@@ -0,0 +1,145 @@+# OrcaSlicer real-workflow acceptance++Validated 2026-09-20 with actual OrcaSlicer 2.4.2 on macOS, Node 22.23.2,+OpenSCAD 2021.01 for original STL generation, and Chromium for browser checks.+No physical printer was connected, heated, uploaded to or tested.++## Repeatable checks++```sh+node --test store/agents/orca-slicer/test/*.test.mjs+ORCA_BIN=/path/to/OrcaSlicer node --test store/agents/orca-slicer/test/*.test.mjs+```++The first command runs 18 unit/transport/server tests and explicitly skips the+three native cases when ORCA_BIN is absent. The native run passed **21/21**.+Use ORCA_PROFILES_DIR if Orca's bundled profiles are not beside its app binary;+ORCA_EVIDENCE_DIR preserves generated native workspaces at a chosen location.+The standard slice-part.sh entrypoint was also exercised successfully.++## 1. Six-bottle rack: compare and independently reopen++A closed 87.8 × 59.2 × 18 mm STL, six 26.6 mm pockets, 2.4 mm floor.+The saved brief states example Prusa MK3S, one 0.4 mm nozzle, Marlin, PLA,+High Temp Plate, 250 × 210 × 210 mm bed, 5 mm model/support-centerline inset,+190–230 °C nozzle and 50–70 °C bed target envelopes, 8-hour / 80 g budgets.++| Plan | Layers | Slicer time estimate | Filament estimate |+| --- | ---: | ---: | ---: |+| Draft · 0.28 mm / 2 walls / 10% gyroid | 65 | 1h 34m 34s | 27.85 g |+| Everyday · 0.20 mm / 3 walls / 15% gyroid | 90 | 2h 45m 12s | 32.12 g |+| Fine · 0.16 mm / 3 walls / 15% gyroid | 112 | 3h 20m 26s | 33.15 g |++75 checks per plan, 225 total: effective and emitted settings, bed geometry,+actual heater targets/shutdown, positive feeds, first/top heights, layer counts,+centerline bounds and budgets, exact native 3MF embedded-G-code bytes/MD5, and+native project reopening with STL/settings re-export. The normal plans contain+145,786 / 311,427 / 386,144 moving linear segments respectively; these are not+the previous 250,000-move-limited demo.++A default implicit plate was observed to produce 35 °C bed commands during+development. The checked workflow now selects High Temp Plate explicitly and+requires the effective profile, emitted settings and actual M140/M190 targets+to agree with the saved temperature envelope (60 °C in this example).++The ZIP was extracted into a separate directory and rebuilt using only its+standalone helper, source and flattened profiles plus installed Node/Orca.+It preserved the semantic source revision and checked geometry/layers; an+undeclared private note was absent. No repository-relative runtime dependency.++An exported Everyday 3MF was independently re-sliced in Orca with a new data+directory. All effective settings agreed (see normalization below), model+centerline bounds agreed within 0.03 mm, layers stayed 90 and material stayed+32.12 g. The new time estimate was 2h 44m 50s, 22 seconds lower (0.22%).+The test permits at most 1% estimate variation. This is not a claim of+byte-identical regenerated paths; the original G-code embedded in each native+3MF is separately verified byte-for-byte.++## 2. New spacer, exported profiles and a meaningful revision++A different original STL: 24 mm outside diameter, 8.4 mm bore, 6 mm high,+centered around negative and positive source XY. Explicit X rotation 180°+and bed translation are applied before slicing. Printer/process/filament+profiles are workspace JSON exports, not installed-path lookups.++Two native plans pass 150 checks. The Everyday plan is revised from three walls+at 0.20 mm to four walls at 0.16 mm with five top layers:++- Before: 30 layers, 8m 33s, 1.73 g.+- After: 37 layers, 10m 53s, 1.93 g.+- Unchanged Draft: 22 layers, 6m 5s, 1.58 g.++The revised native project's effective settings agree and reopen successfully.+The spacer has its own brief, assumptions and notes; no inherited rack claims.++Wrong nozzle, wrong dimensions, smaller declared bed, a contradictory temperature+envelope and an impossible time budget all fail. After each failure, readiness+is false and the prior preview/project ZIP bytes are unchanged. Rebuilding the+valid revision succeeds again. A separate real-native wrapper changes a declared+source note during slicing; the source hash gate prevents publication.++## Browser and transport evidence++Both cases were tested inside the actual shared isolated-web-viewer:+an opaque-origin iframe with scripts/downloads enabled, not same-origin storage.++- All five plans switch and verify G-code SHA-256 before rendering.+- First layer, isolated/stacked layers, travel/custom paths, top/orbit projection+ and speed colors work. Full motion displays exactly every parsed moving+ segment, including travel-only Z hops and final parking.+- Five G-code and five native 3MF downloads match their checked hashes.+ Two complete-project ZIPs and two review JSONs were downloaded.+- Review restore reproduces selected plan/view/notes; a mismatched revision is+ rejected. Review is not printer authorization.+- 1600 px desktop and 390 × 844 mobile checks: no JS errors or horizontal+ overflow. Actual screenshots were visually inspected.+- Portable loopback server serves only named generated artifacts, denies+ undeclared source/hidden files/symlinks and non-loopback Host headers, rejects+ POST, and bounds downloads to 32 MiB.+- The extracted ZIP's own preview server was also tested in Chromium under its+ real content-security policy: all three plans, hashes, downloads, review+ save/restore and mobile layout passed without console errors.++Unit/transport checks additionally cover units and extrusion modes, G92,+unretraction debt, full-motion retention, malformed/unsupported commands,+conflicting settings, wrong heater commands despite valid profile metadata,+missing shutdown, strict schema/bounds, profile inheritance/cycles/credentials,+source changes/symlinks, ZIP CRC/path checks, build locks, a missing native engine,+an empty “successful” CLI output, and refusal to call legacy demo configs ready.++## Known boundaries++Ready means documented software checks passed, not “safe to print.”+One closed STL / one extruder / rectangular zero-origin bed / Marlin or Marlin 2.+No exclusion zones, named firmware macros, arcs, multiple tools, firmware+retraction, arbitrary post-processing or automatic printer connection.++Native geometry reopening compares closure, positive volume, shell/triangle+counts, dimensions (0.03 mm) and volume (1e-5 relative, minimum 0.05 mm³).+It is not a general mesh-equivalence or self-intersection proof.+All effective settings must agree; only absent versus [] for the non-slicing+upward_compatible_machine preset-catalog metadata is normalized. The 3MF's+project-schema version is distinct from the exported engine version.++Centerlines are not bead-footprint, collision or machine-envelope simulation.+Custom purge can be outside the model inset and is displayed separately. Homing+is drawn at zero; real offsets, leveling, firmware flow/speed/pressure behavior,+thermal response, support adequacy, strength and physical fit remain unverified.+The SCAD source is editable provenance; the build slices the saved STL and does+not claim automatic SCAD/STL synchronization.++## Local evidence retained for release review++QA root: `/private/tmp/harness-orca-workflows.5ILEon`.++- `release-native/orca-rack-9f5xBX`: final rack, acceptance receipt.+- `release-native/orca-portable-u4TLWL`: standalone rebuilt ZIP.+- `release-native/orca-project-reslice-r26UHz`: independent 3MF re-slice/log.+- `release-native/orca-race-ZsjEpN`: rejected concurrent source edit.+- `final-spacer/orca-spacer-7OA3TQ`: revised independent spacer and five negatives.+- `release-browser-rack` / `release-browser-spacer`: actual downloads,+ screenshots and machine-readable browser receipts.++These temporary directories are local evidence, not package dependencies.+Registry/catalog/publisher checks passed 433/433; package conformance, skill+validation, generated artifacts/branding and whitespace checks passed.diff --git a/store/agents/orca-slicer/test/contract.test.mjs b/store/agents/orca-slicer/test/contract.test.mjsnew file mode 100644index 000000000..9c93f9728--- /dev/null+++ b/store/agents/orca-slicer/test/contract.test.mjs@@ -0,0 +1,82 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {readFile,mkdtemp,writeFile,rm,symlink,cp,mkdir} from 'node:fs/promises';+import {tmpdir} from 'node:os';+import {join} from 'node:path';+import {fileURLToPath} from 'node:url';+import {validateConfig,prepareModel,inspectPlan,planSettings,canonicalReopenSettings} from '../skills/orcaslicer/scripts/contract.mjs';+import {parseGcode} from '../skills/orcaslicer/scripts/gcode.mjs';+import {profileWithSources,unchangedProfiles} from '../skills/orcaslicer/scripts/profiles.mjs';+import {zip,unzip} from '../skills/orcaslicer/scripts/archive.mjs';+import {build} from '../skills/orcaslicer/scripts/build.mjs';+import {transaction} from '../skills/orcaslicer/scripts/files.mjs';+const root=fileURLToPath(new URL('..',import.meta.url));+const config=()=>readFile(join(root,'template/slice-config.json'),'utf8').then(JSON.parse);+test('saved requirements are strict, bounded and independent of the STL',async()=>{+ const c=await config();validateConfig(c);+ for(const mutate of [+ c=>c.unrecognized=true,c=>c.machine.context='guessed',c=>c.sourceFiles.push('../secret'),+ c=>c.sourceFiles.push('model.stl'),c=>c.model.expectedSizeMM=[1,1],c=>c.model.scale=0,+ c=>c.machine.firmware='klipper',c=>c.plans[0].layerHeightMM=1,c=>c.plans[0].wallLoops=2.2,+ c=>c.selectedPlan='absent',c=>c.profiles.printer='../outside.json'+ ]){const broken=structuredClone(c);mutate(broken);assert.throws(()=>validateConfig(broken));}+ const bytes=await readFile(join(root,'template/model.stl')),model=prepareModel(bytes,c);assert.equal(model.mesh.watertight,true);+ assert.equal(model.mesh.shells.length,1);assert.ok(Math.abs(model.mesh.bounds.size[0]-87.8)<.01);+ c.model.expectedSizeMM[0]+=1;assert.throws(()=>prepareModel(bytes,c),/saved millimetre brief/);c.model.expectedSizeMM[0]-=1;+ c.machine.bedMM=[20,20,20];assert.throws(()=>prepareModel(bytes,c),/exceeds the declared bed/);+});+test('explicit rotation and scale are measured on the mesh passed to Orca',async()=>{+ const c=await config();c.model.rotationDegrees=[90,0,0];c.model.scale=.5;+ const {mesh}=prepareModel(await readFile(join(root,'template/model.stl')),c);+ for(const [i,want]of [43.9,9,29.6].entries())assert.ok(Math.abs(mesh.bounds.size[i]-want)<.01);+ assert.ok(mesh.bounds.min.every(v=>Math.abs(v)<.0001));+});+test('ZIP roundtrip is bounded and CRC checked; unsafe and duplicate entries fail',()=>{+ const bytes=zip([{name:'README.md',bytes:'Hello'},{name:'nested/model.stl',bytes:Buffer.from([1,2,3])}]);+ assert.equal(unzip(bytes).get('README.md').toString(),'Hello');+ const broken=Buffer.from(bytes);broken[40]^=1;assert.throws(()=>unzip(broken));+ assert.throws(()=>zip([{name:'../secret',bytes:''}]),/Unsafe/);+ assert.throws(()=>zip([{name:'a',bytes:''},{name:'A',bytes:''}]),/duplicate/);+ assert.throws(()=>unzip(bytes.subarray(0,-1)),/directory/);+});+test('profile credentials, leaf symlinks and edits during slicing fail without exposing secrets',async()=>{+ const dir=await mkdtemp(join(tmpdir(),'orca-profile-guards-'));try{+ const file=join(dir,'profile.json');await writeFile(file,JSON.stringify({name:'my profile',type:'machine'}));+ const snapshot=await profileWithSources(file);await unchangedProfiles([snapshot]);+ await writeFile(file,JSON.stringify({name:'revised'}));await assert.rejects(unchangedProfiles([snapshot]),/changed/);+ await writeFile(file,JSON.stringify({name:'secret profile',printhost_apikey:'DO_NOT_SHOW'}));+ await assert.rejects(profileWithSources(file),error=>error.message.includes('credential')&&!error.message.includes('DO_NOT_SHOW'));+ await symlink(file,join(dir,'link.json'));await assert.rejects(profileWithSources(join(dir,'link.json')),/symlink/);+ }finally{await rm(dir,{recursive:true,force:true});}+});+test('effective settings alone cannot mask wrong heater commands or a missing shutdown',async()=>{+ const c=await config(),p=c.plans[1],effective={...planSettings(p),curr_bed_type:c.machine.bedType,printer_model:c.machine.printerModel,gcode_flavor:c.machine.firmware,nozzle_diameter:['0.4'],printable_height:'210',filament_type:['PLA'],nozzle_temperature:['220'],nozzle_temperature_initial_layer:['220'],hot_plate_temp:['60'],hot_plate_temp_initial_layer:['60']};+ effective.printable_area=['0x0','250x0','250x210','0x210'];effective.bed_exclude_area=['0x0'];+ const configuration=Object.entries(effective).map(([k,v])=>'; '+k+' = '+(Array.isArray(v)?v.join(','):v)).join('\n');+ const fixture='G90\nM83\nM104 S220\nM140 S60\nG0 X10 Y10 Z.2 F6000\n;TYPE:Outer wall\nG1 X20 E1 F1200\nM104 S0\nM140 S0\n; total layer number: 1\n; estimated printing time (normal mode) = 1m 0s\n; total filament used [g] = 2\n; CONFIG_BLOCK_START\n'+configuration+'\n; CONFIG_BLOCK_END\n';+ const inspect=text=>inspectPlan(parseGcode(text),effective,c,p,{bounds:{size:[10,10,.2]}});+ assert.ok(inspect(fixture).every(c=>c.pass));+ assert.throws(()=>inspect(fixture.replace('M140 S60','M140 S35')),/heater commands/);+ assert.throws(()=>inspect(fixture.replace('M104 S0\n','')),/off after final/);+ assert.throws(()=>inspect(fixture.replace('M140 S0\n','M140 S0\nG1 E1\n')),/targets at extrusion|off after final/);+ assert.throws(()=>inspect(fixture.replace('G1 X20','G1 X300')),/inside bed/);+ const altered={...effective,layer_height:'0.28'};+ assert.throws(()=>inspectPlan(parseGcode(fixture),altered,c,p,{bounds:{size:[10,10,.2]}}),/Effective layer_height/);+});+test('native reopen normalization never ignores changed slicing or compatibility values',()=>{+ assert.deepEqual(canonicalReopenSettings({layer_height:'0.2'}),canonicalReopenSettings({layer_height:'0.2',upward_compatible_machine:[]}));+ assert.notDeepEqual(canonicalReopenSettings({layer_height:'0.2'}),canonicalReopenSettings({layer_height:'0.3'}));+ assert.notDeepEqual(canonicalReopenSettings({}),canonicalReopenSettings({upward_compatible_machine:['different printer']}));+});+test('bad briefs and locks do not replace the last successful handoff',async()=>{+ const dir=await mkdtemp(join(tmpdir(),'orca-failed-'));try{+ await cp(join(root,'template'),dir,{recursive:true});await writeFile(join(dir,'preview.html'),'previous successful artifact');+ const c=await config();c.model.path='../outside.stl';await writeFile(join(dir,'slice-config.json'),JSON.stringify(c));+ await assert.rejects(build(dir),/safe workspace-relative/);+ assert.equal(await readFile(join(dir,'preview.html'),'utf8'),'previous successful artifact');+ assert.equal(JSON.parse(await readFile(join(dir,'.harness/verdict.json'))).ready,false);+ await mkdir(join(dir,'.harness/orca-build.lock'));+ await assert.rejects(transaction(dir,()=>assert.fail('must not enter')),/Another build owns/);+ assert.equal(await readFile(join(dir,'preview.html'),'utf8'),'previous successful artifact');+ }finally{await rm(dir,{recursive:true,force:true});}+});diff --git a/store/agents/orca-slicer/test/fixtures/spacer.scad b/store/agents/orca-slicer/test/fixtures/spacer.scadnew file mode 100644index 000000000..c1659335c--- /dev/null+++ b/store/agents/orca-slicer/test/fixtures/spacer.scad@@ -0,0 +1,7 @@+// Original dimensional trial for a 24 mm OD, 8.4 mm bore, 6 mm spacer.+// No load rating, material or physical fit claim. Millimetres.+$fn=96;+difference() {+ cylinder(d=24,h=6);+ translate([0,0,-0.1]) cylinder(d=8.4,h=6.2);+}diff --git a/store/agents/orca-slicer/test/fixtures/spacer.stl b/store/agents/orca-slicer/test/fixtures/spacer.stlnew file mode 100644index 000000000..92cd67bc9Binary files /dev/null and b/store/agents/orca-slicer/test/fixtures/spacer.stl differdiff --git a/store/agents/orca-slicer/test/gcode.test.mjs b/store/agents/orca-slicer/test/gcode.test.mjsindex eb68f2640..bad2b1967 100644--- a/store/agents/orca-slicer/test/gcode.test.mjs+++ b/store/agents/orca-slicer/test/gcode.test.mjs@@ -1,5 +1,28 @@import {test} from 'node:test';import assert from 'node:assert/strict';import {parseGcode} from '../skills/orcaslicer/scripts/gcode.mjs';test('absolute/relative modes, compact words, extrusion resets and speeds',()=>{const p=parseGcode('G21\nG90\nM82\nG0 X10 Y10 Z.2\nG1X20Y10E1F1200\nG92 E0\nM83\nG1 X20 Y20 E.5\nG91\nG1 X-10 E.5\n');assert.equal(p.layers.length,1);assert.equal(p.layers[0].extrusionMm,2);assert.deepEqual(p.layers[0].segments.at(-1).slice(3,6),[10,20,.2]);assert.equal(p.layers[0].segments.at(-1)[6],20);});test('G92 changes coordinate origin without moving geometry; inches convert to mm',()=>{const p=parseGcode('G20\nG90\nM83\nG0 X1 Y0 Z.01\nG92 X0\nG1 X1 E.1 F60\n');assert.equal(p.layers[0].segments.at(-1)[3],50.8);assert.ok(Math.abs(p.layers[0].segments.at(-1)[6]-25.4)<1e-6);});-test('travel-only heights do not become printed layers; retractions do not extrude',()=>{const p=parseGcode('G90\nM83\nG0 Z.2\nG1 X10 E1\nG0 Z.6\nG0 X20\nG0 Z.2\nG1 X30 E-1\nG0 Z.4\nG1 X40 E1\n');assert.deepEqual(p.layers.map(l=>l.z),[.2,.4]);assert.equal(p.layers[0].segments.at(-1)[8],0);assert.match(p.warnings.join(' '),/Travel-only/);});+test('travel-only heights do not become printed layers; retractions do not extrude',()=>{const p=parseGcode('G90\nM83\nG0 Z.2\nG1 X10 E1\nG0 Z.6\nG0 X20\nG0 Z.2\nG1 X30 E-1\nG0 Z.4\nG1 X40 E1\nG1 X50 E.5\n');assert.deepEqual(p.layers.map(l=>l.z),[.2,.4]);assert.equal(p.layers[0].segments.at(-1)[8],0);assert.match(p.warnings.join(' '),/Travel-only/);});test('arc, multitool and empty inputs cannot receive a misleading linear preview',()=>{assert.throws(()=>parseGcode('G2 X3 Y2 E1'),/Curved/);assert.throws(()=>parseGcode('T1\nG1 X10 E1'),/Multiple tools/);assert.throws(()=>parseGcode('G0 X10'),/No linear extrusion/);});++test('unretraction is not deposition; full motion retains Z hops and final parking',()=>{+ const p=parseGcode('G90\nM83\nG0 Z.2\n;TYPE:Outer wall\nG1 X10 E1 F1200\nG1 E-2\nG0 Z.6\nG0 X20\nG0 Z.2\nG1 X21 E1\nG1 X22 E1\nG1 X23 E.5\nG0 Z50\nG0 X0\n');+ assert.equal(p.modelLayers,1);assert.equal(p.modelExtrusionMm,1.5);+ assert.equal(p.motions.find(s=>s[3]===21&&s[5]===.2)[8],0);+ assert.equal(p.motions.find(s=>s[3]===22&&s[5]===.2)[8],0);+ assert.equal(p.motions.at(-1)[5],50);assert.equal(p.motionBounds.max[2],50);+});+test('settings, estimates and actual heater commands are retained for independent requirements',()=>{+ const p=parseGcode('; total layer number: 1\nG90\nM83\nM104 S215\nM140 S60\nM190 S60\nM109 S215\nG0 Z.2\n;TYPE:Outer wall\nG1 X10 E1 F1200\nM104 S0\nM140 S0\n; filament used [mm] = 100.5\n; total filament used [g] = 1.2\n; estimated printing time (normal mode) = 1h 2m 3s\n; CONFIG_BLOCK_START\n; layer_height = 0.2\n; curr_bed_type = High Temp Plate\n; CONFIG_BLOCK_END\n');+ assert.equal(p.stats.timeSeconds,3723);assert.equal(p.stats.filamentMm,100.5);+ assert.equal(p.settings.curr_bed_type,'High Temp Plate');assert.equal(p.configBlocks,1);+ assert.deepEqual(p.thermal,{nozzle:0,bed:0});assert.equal(p.temperatures.filter(t=>t.wait).length,2);+ assert.ok(p.temperatures.at(-1).line>p.lastDepositionLine);+});+test('unsupported coordinate systems, macros, checksum streams and malformed motion fail explicitly',()=>{+ for(const input of ['G53 G1 X10','G54','G92.1','G10','M200 D1.75','G1 Xnan E1','G1 X1 X2 E1','G1 X1 A2 E1','G1 X10 E1*0']){+ assert.throws(()=>parseGcode(input));+ }+ assert.throws(()=>parseGcode('G1 X1 E1\n; CONFIG_BLOCK_START\n; layer_height = .2\n'),/Incomplete/);+ assert.throws(()=>parseGcode('G1 X1 E1\n; CONFIG_BLOCK_START\n; layer_height = .2\n; layer_height = .3\n; CONFIG_BLOCK_END\n'),/duplicate/);+ assert.equal(parseGcode('G1 X1 E1\n; CONFIG_BLOCK_START\n; wipe_tower_x = 15.000\n; wipe_tower_x = 15\n; CONFIG_BLOCK_END\n').settings.wipe_tower_x,'15');+});diff --git a/store/agents/orca-slicer/test/native.test.mjs b/store/agents/orca-slicer/test/native.test.mjsnew file mode 100644index 000000000..509ea3f7d--- /dev/null+++ b/store/agents/orca-slicer/test/native.test.mjs@@ -0,0 +1,85 @@+// Opt-in actual OrcaSlicer tests. Without ORCA_BIN these SKIP, never claim a slice.+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {mkdtemp,readFile,writeFile,mkdir,cp,chmod} from 'node:fs/promises';+import {tmpdir} from 'node:os';+import {join,dirname} from 'node:path';+import {fileURLToPath} from 'node:url';+import {spawnSync} from 'node:child_process';+import {build} from '../skills/orcaslicer/scripts/build.mjs';+import {engine,runNative,oneFile} from '../skills/orcaslicer/scripts/native.mjs';+import {resolveProfile} from '../skills/orcaslicer/scripts/profiles.mjs';+import {parseGcode} from '../skills/orcaslicer/scripts/gcode.mjs';+import {canonicalReopenSettings} from '../skills/orcaslicer/scripts/contract.mjs';+import {unzip} from '../skills/orcaslicer/scripts/archive.mjs';+import {sha} from '../skills/orcaslicer/scripts/files.mjs';+const root=fileURLToPath(new URL('..',import.meta.url)),enabled=Boolean(process.env.ORCA_BIN);+const workspace=async name=>{+ const parent=process.env.ORCA_EVIDENCE_DIR||tmpdir();await mkdir(parent,{recursive:true});return mkdtemp(join(parent,name+'-'));+};+test('native rack: three checked plans, standalone ZIP rebuild and independent project re-slice',{skip:!enabled,timeout:600000},async()=>{+ const dir=await workspace('orca-rack');await cp(join(root,'template'),dir,{recursive:true});+ await writeFile(join(dir,'private-note.txt'),'not declared, never included');+ const report=await build(dir);assert.equal(report.plans.length,3);+ assert.ok(report.plans.every(p=>p.checks.every(c=>c.pass)));+ assert.ok(report.plans[0].stats.timeSeconds<report.plans[1].stats.timeSeconds);+ assert.ok(report.plans[1].stats.timeSeconds<report.plans[2].stats.timeSeconds);+ const members=unzip(await readFile(join(dir,'handoff/project.zip')));assert.ok(!members.has('private-note.txt'));+ const portable=await workspace('orca-portable');+ for(const [name,bytes]of members){await mkdir(dirname(join(portable,name)),{recursive:true});await writeFile(join(portable,name),bytes);}+ const rebuilt=spawnSync(process.execPath,[join(portable,'rebuild/build.mjs')],{cwd:portable,encoding:'utf8',env:{...process.env,HARNESS_WORKSPACE:portable},timeout:300000,maxBuffer:4*1024*1024});+ assert.equal(rebuilt.status,0,rebuilt.stderr);+ const second=JSON.parse(await readFile(join(portable,'handoff/report.json')));assert.equal(second.revision,report.revision);+ for(const [i,p]of report.plans.entries()){assert.equal(second.plans[i].layers,p.layers);assert.ok(Math.abs(second.plans[i].stats.filamentGrams-p.stats.filamentGrams)<.1);}+ const selected=report.plans.find(p=>p.id===report.selectedPlan),native=await engine(),recheck=await workspace('orca-project-reslice');await mkdir(join(recheck,'out'));+ const log=runNative(native.bin,['--datadir',join(recheck,'appdata'),'--debug','2','--slice','0','--arrange','0','--orient','0','--ensure-on-bed','--outputdir',join(recheck,'out'),'--export-settings',join(recheck,'effective.json'),'--enable-arc-fitting=0','--post-process','',join(dir,selected.project)],recheck);+ await writeFile(join(recheck,'native.log'),log);+ const actual=parseGcode((await oneFile(join(recheck,'out'),'.gcode')).bytes.toString());+ assert.deepEqual(canonicalReopenSettings(JSON.parse(await readFile(join(recheck,'effective.json')))),canonicalReopenSettings(selected.effective));+ assert.equal(actual.modelLayers,selected.layers);+ for(const side of ['min','max'])for(let axis=0;axis<3;axis++)assert.ok(Math.abs(actual.modelBounds[side][axis]-selected.bounds[side][axis])<.03);+ assert.ok(Math.abs(actual.stats.filamentGrams-selected.stats.filamentGrams)<Math.max(.1,selected.stats.filamentGrams*.01));+ assert.ok(Math.abs(actual.stats.timeSeconds-selected.stats.timeSeconds)<Math.max(2,selected.stats.timeSeconds*.01));+ await writeFile(join(dir,'acceptance.json'),JSON.stringify({workspace:dir,portable,recheck,sourceRevision:report.revision,plans:report.plans.map(p=>({id:p.id,stats:p.stats,layers:p.layers,checks:p.checks.length})),reslicedStats:actual.stats},null,2));+ console.log('Native rack evidence: '+dir);+});+test('native spacer: user-exported profiles, rotated mesh, substantive revision and failed candidate preservation',{skip:!enabled,timeout:480000},async()=>{+ const dir=await workspace('orca-spacer'),native=await engine();await cp(join(root,'template'),dir,{recursive:true});+ await cp(join(root,'test/fixtures/spacer.stl'),join(dir,'model.stl'));await cp(join(root,'test/fixtures/spacer.scad'),join(dir,'model.scad'));+ const c=JSON.parse(await readFile(join(dir,'slice-config.json')));c.title='Mounting spacer · A dimensional trial';c.brief='Prepare a 24 mm outside / 8.4 mm bore / 6 mm high spacer trial; compare two slicing plans and preserve editable native projects. No load or fit rating.';+ c.assumptions='Software-only example Prusa MK3S / 0.4 mm nozzle / PLA / High Temp Plate, not a known user printer. The 8.4 mm bore is a CAD dimension, not a measured physical fit. No load rating or physical print validation.';+ await writeFile(join(dir,'print-config.md'),'# Spacer trial\n\n24 mm outside diameter, 8.4 mm bore, 6 mm high. Rotate X by 180 degrees, then compare two plans. Software-only example machine; no physical fit or load rating. Revise the Everyday plan to four walls at 0.16 mm and verify the native output changes.\n');+ c.model={path:'model.stl',expectedSizeMM:[24,24,6],toleranceMM:.03,rotationDegrees:[180,0,0],scale:1};+ c.plans=c.plans.slice(0,2);c.selectedPlan='everyday';c.profiles.source='workspace';+ for(const key of ['printer','process','filament']){const p=await resolveProfile(join(native.profiles,c.profiles[key]));c.profiles[key]='profiles/'+key+'.json';c.sourceFiles.push(c.profiles[key]);await mkdir(join(dir,'profiles'),{recursive:true});await writeFile(join(dir,c.profiles[key]),JSON.stringify(p,null,2));}+ await writeFile(join(dir,'slice-config.json'),JSON.stringify(c,null,2));const first=await build(dir);+ c.plans[1].wallLoops=4;c.plans[1].layerHeightMM=.16;c.plans[1].topLayers=5;c.plans[1].description='Four walls at 0.16 mm; compare the measured slicing tradeoff, not assumed strength.';+ await writeFile(join(dir,'slice-config.json'),JSON.stringify(c,null,2));const second=await build(dir);+ assert.notEqual(first.revision,second.revision);assert.equal(second.plans[1].effective.wall_loops,'4');assert.equal(second.plans[1].effective.layer_height,'0.16');+ assert.notEqual(first.plans[1].layers,second.plans[1].layers);+ const zipHash=sha(await readFile(join(dir,'handoff/project.zip'))),html=await readFile(join(dir,'preview.html'),'utf8');+ for(const [name,mutate,pattern]of [+ ['wrong-nozzle',c=>c.machine.nozzleMM=.6,/nozzle/],+ ['wrong-size',c=>c.model.expectedSizeMM[0]=240,/saved millimetre brief/],+ ['too-small-bed',c=>c.machine.bedMM=[10,10,10],/bed/],+ ['wrong-temperature',c=>c.machine.bedTemperatureRange=[20,40],/Profile hot_plate_temp/],+ ['time-budget',c=>c.limits.maxTimeSeconds=1,/Time budget/]+ ]){+ const bad=structuredClone(c);mutate(bad);await writeFile(join(dir,'slice-config.json'),JSON.stringify(bad));+ await assert.rejects(build(dir),pattern);assert.equal(sha(await readFile(join(dir,'handoff/project.zip'))),zipHash,name);assert.equal(await readFile(join(dir,'preview.html'),'utf8'),html,name);+ assert.equal(JSON.parse(await readFile(join(dir,'.harness/verdict.json'))).ready,false,name);+ }+ await writeFile(join(dir,'slice-config.json'),JSON.stringify(c,null,2));await build(dir);+ await writeFile(join(dir,'acceptance.json'),JSON.stringify({workspace:dir,before:first.plans.map(p=>({id:p.id,layers:p.layers,stats:p.stats})),after:second.plans.map(p=>({id:p.id,layers:p.layers,stats:p.stats})),negativeCandidates:5,preservedZipSha256:zipHash},null,2));+ console.log('Native spacer evidence: '+dir);+});+test('native source edit while slicing cannot publish checked artifacts',{skip:!enabled,timeout:240000},async()=>{+ const dir=await workspace('orca-race');await cp(join(root,'template'),dir,{recursive:true});+ const c=JSON.parse(await readFile(join(dir,'slice-config.json')));c.plans=[c.plans[0]];c.selectedPlan='draft';await writeFile(join(dir,'slice-config.json'),JSON.stringify(c));+ const real=process.env.ORCA_BIN,wrapper=join(dir,'orca-fixture.sh');+ await writeFile(wrapper,'#!/bin/sh\n"$REAL_ORCA" "$@"\nresult=$?\nprintf "\\nchanged while slicing\\n" >> "$RACE_NOTE"\nexit "$result"\n');await chmod(wrapper,0o755);+ const result=spawnSync(process.execPath,[join(root,'skills/orcaslicer/scripts/build.mjs')],{cwd:dir,encoding:'utf8',timeout:180000,env:{...process.env,ORCA_BIN:wrapper,REAL_ORCA:real,RACE_NOTE:join(dir,'print-config.md'),ORCA_PROFILES_DIR:(await engine()).profiles,HARNESS_WORKSPACE:dir}});+ assert.equal(result.status,1);assert.match(result.stderr,/Source changed during build/);+ assert.equal(JSON.parse(await readFile(join(dir,'.harness/verdict.json'))).ready,false);+ console.log('Native source-race evidence: '+dir);+});diff --git a/store/agents/orca-slicer/test/server.test.mjs b/store/agents/orca-slicer/test/server.test.mjsnew file mode 100644index 000000000..fc9cfe3ca--- /dev/null+++ b/store/agents/orca-slicer/test/server.test.mjs@@ -0,0 +1,29 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {mkdtemp,mkdir,writeFile,symlink,rm} from 'node:fs/promises';+import {tmpdir} from 'node:os';+import {join} from 'node:path';+import {request} from 'node:http';+import {serve} from '../skills/orcaslicer/scripts/serve-preview.mjs';+test('portable preview serves only bounded artifacts on loopback; no source leaks or writes',async()=>{+ const dir=await mkdtemp(join(tmpdir(),'orca-preview-'));let server;+ try{+ await mkdir(join(dir,'handoff/plans/draft'),{recursive:true});+ await writeFile(join(dir,'preview.html'),'<h1>saved slice</h1>');+ await writeFile(join(dir,'handoff/gcode.mjs'),'export const checked=true;');+ await writeFile(join(dir,'handoff/plans/draft/part.gcode'),'G1 X1');+ await writeFile(join(dir,'private-note.txt'),'never serve this');+ await symlink(join(dir,'private-note.txt'),join(dir,'handoff/report.json'));+ server=await serve(dir);const base='http://127.0.0.1:'+server.address().port;+ const root=await fetch(base+'/',{redirect:'manual'});assert.equal(root.status,302);assert.equal(root.headers.get('location'),'/preview.html');+ const page=await fetch(base+'/preview.html');assert.equal(page.status,200);assert.match(page.headers.get('content-security-policy'),/connect-src 'self'/);+ const module=await fetch(base+'/handoff/gcode.mjs');assert.match(module.headers.get('content-type'),/javascript/);+ const artifact=await fetch(base+'/handoff/plans/draft/part.gcode');assert.equal(await artifact.text(),'G1 X1');assert.match(artifact.headers.get('content-disposition'),/attachment/);+ for(const path of ['/private-note.txt','/slice-config.json','/.harness/verdict.json','/handoff/report.json','/handoff/%2e%2e%2fprivate-note.txt'])assert.equal((await fetch(base+path)).status,404,path);+ assert.equal((await fetch(base+'/preview.html',{method:'POST'})).status,405);+ const badHost=await new Promise((resolve,reject)=>{const req=request(base+'/preview.html',{headers:{host:'example.com'}},res=>{res.resume();resolve(res.statusCode);});req.on('error',reject);req.end();});+ assert.equal(badHost,403);+ await writeFile(join(dir,'handoff/project.zip'),Buffer.alloc(32*1024*1024+1));+ assert.equal((await fetch(base+'/handoff/project.zip')).status,404);+ }finally{if(server)await new Promise(resolve=>server.close(resolve));await rm(dir,{recursive:true,force:true});}+});diff --git a/store/agents/orca-slicer/test/toolchain.test.mjs b/store/agents/orca-slicer/test/toolchain.test.mjsindex 6f1d3d780..32df7ea2c 100644--- a/store/agents/orca-slicer/test/toolchain.test.mjs+++ b/store/agents/orca-slicer/test/toolchain.test.mjs@@ -1,4 +1,5 @@// Transport fixtures test failure handling, not the native slicer's correctness.+// Successful readiness is covered only by the opt-in real native suite.import {test} from 'node:test';import assert from 'node:assert/strict';import {mkdtemp,writeFile,readFile,rm,mkdir,cp,chmod} from 'node:fs/promises';@@ -7,6 +8,23 @@ import {join} from 'node:path';import {spawnSync} from 'node:child_process';import {fileURLToPath} from 'node:url';import {resolveProfile} from '../skills/orcaslicer/scripts/profiles.mjs';+test('missing engine and an empty successful CLI cannot replace prior results',async()=>{+ const dir=await mkdtemp(join(tmpdir(),'orca-transport-'));try{+ await cp(join(root,'template'),dir,{recursive:true});await writeFile(join(dir,'preview.html'),'last good');+ const c=JSON.parse(await readFile(join(dir,'slice-config.json')));+ c.profiles={source:'workspace',printer:'printer.json',process:'process.json',filament:'filament.json'};+ c.sourceFiles.push('printer.json','process.json','filament.json');+ await writeFile(join(dir,'slice-config.json'),JSON.stringify(c));+ await writeFile(join(dir,'printer.json'),JSON.stringify({name:'fixture printer',type:'machine',printer_model:c.machine.printerModel,gcode_flavor:'marlin',nozzle_diameter:['0.4'],printable_area:['0x0','250x0','250x210','0x210'],printable_height:'210'}));+ await writeFile(join(dir,'process.json'),JSON.stringify({name:'fixture process',type:'process'}));+ await writeFile(join(dir,'filament.json'),JSON.stringify({name:'fixture filament',type:'filament',filament_type:['PLA']}));+ const run=bin=>spawnSync(process.execPath,[join(root,'skills/orcaslicer/scripts/build.mjs')],{cwd:dir,encoding:'utf8',env:{...process.env,HARNESS_WORKSPACE:dir,ORCA_BIN:bin}});+ let result=run(join(dir,'not-installed'));assert.equal(result.status,1);assert.match(result.stderr,/Install OrcaSlicer/);+ const stub=join(dir,'fixture.sh');await writeFile(stub,'#!/bin/sh\nexit 0\n');await chmod(stub,0o755);+ result=run(stub);assert.equal(result.status,1);assert.match(result.stderr,/exactly one fresh .gcode/);+ assert.equal(await readFile(join(dir,'preview.html'),'utf8'),'last good');assert.equal(JSON.parse(await readFile(join(dir,'.harness/verdict.json'))).ready,false);+ }finally{await rm(dir,{recursive:true,force:true});}+});const root=fileURLToPath(new URL('..',import.meta.url));test('profiles resolve sibling inheritance; missing and cyclic parents fail',async()=>{const dir=await mkdtemp(join(tmpdir(),'orca-profiles-'));try{@@ -21,15 +39,12 @@ test('profiles resolve sibling inheritance; missing and cyclic parents fail',asyawait assert.rejects(resolveProfile(join(dir,'child.json')),/sibling/);}finally{await rm(dir,{recursive:true,force:true});}});-test('fresh output required; failure clears readiness and preserves previous artifacts',async()=>{- const dir=await mkdtemp(join(tmpdir(),'orca-build-'));try{- await cp(join(root,'template'),dir,{recursive:true});- for(const name of ['printer','process','filament'])await writeFile(join(dir,name+'.json'),JSON.stringify({name}));- await writeFile(join(dir,'slice-config.json'),JSON.stringify({mode:'custom',model:'model.stl',printer:'printer.json',process:'process.json',filament:'filament.json'}));- const binary=join(dir,'fixture');await writeFile(binary,'#!/bin/sh\nwhile [ "$#" -gt 0 ]; do if [ "$1" = "--outputdir" ]; then shift; out="$1"; fi; shift; done\nprintf "G90\\nM83\\nG0 Z.2\\n;TYPE:Outer wall\\nG1 X10 E1 F1200\\n" > "$out/fresh.gcode"\n');await chmod(binary,0o755);- const run=()=>spawnSync(process.execPath,[join(root,'skills/orcaslicer/scripts/build.mjs')],{cwd:dir,env:{...process.env,ORCA_BIN:binary,HARNESS_WORKSPACE:dir},encoding:'utf8'});- let result=run();assert.equal(result.status,0,result.stderr);const previous=await readFile(join(dir,'preview.html'),'utf8');assert.equal(JSON.parse(await readFile(join(dir,'.harness/verdict.json'))).ready,true);- await writeFile(binary,'#!/bin/sh\nexit 0\n');result=run();assert.equal(result.status,1);assert.equal(JSON.parse(await readFile(join(dir,'.harness/verdict.json'))).ready,false);assert.equal(await readFile(join(dir,'preview.html'),'utf8'),previous);- await writeFile(binary,'#!/bin/sh\nprintf \'quoted "failure"\\n\' >&2\nexit 2\n');result=run();assert.equal(result.status,1);assert.equal(JSON.parse(await readFile(join(dir,'.harness/verdict.json'))).artifact,null);+test('legacy demo configs cannot receive new checked readiness',async()=>{+ const dir=await mkdtemp(join(tmpdir(),'orca-legacy-'));try{+ await cp(join(root,'template'),dir,{recursive:true});+ await writeFile(join(dir,'slice-config.json'),JSON.stringify({mode:'demo',model:'model.stl'}));+ const result=spawnSync(process.execPath,[join(root,'skills/orcaslicer/scripts/build.mjs')],{cwd:dir,env:{...process.env,HARNESS_WORKSPACE:dir},encoding:'utf8'});+ assert.equal(result.status,1);assert.match(result.stderr,/spec: 1 slicing brief/);+ assert.equal(JSON.parse(await readFile(join(dir,'.harness/verdict.json'))).ready,false);}finally{await rm(dir,{recursive:true,force:true});}});diff --git a/store/agents/orca-slicer/toolchain/doctor.sh b/store/agents/orca-slicer/toolchain/doctor.shindex 77db2ab4b..7d6c6cc10 100755--- a/store/agents/orca-slicer/toolchain/doctor.sh+++ b/store/agents/orca-slicer/toolchain/doctor.sh@@ -1,4 +1,4 @@#!/bin/shset -uhere="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"-sh "$here/setup.sh"+exec bash "$here/setup.sh"diff --git a/store/agents/orca-slicer/toolchain/init-workspace.sh b/store/agents/orca-slicer/toolchain/init-workspace.shindex cbf78a8cc..55f0c7785 100755--- a/store/agents/orca-slicer/toolchain/init-workspace.sh+++ b/store/agents/orca-slicer/toolchain/init-workspace.sh@@ -3,7 +3,7 @@set -umkdir -p .harnesscat > .harness/verdict.json <<'JSON'-{ "spec": 1, "ready": false, "summary": "Orca Slicer workspace ready — describe a part to print",+{ "spec": 1, "ready": false, "summary": "Save a mesh/printer brief, compare slicing plans and export native projects — no printer connected","findings": [], "artifact": null, "updatedAt": "2026-09-18T00:00:00Z" }JSONprintf 'Orca Slicer workspace initialized by %s\n' "${HARNESS_DSH:-orca-slicer}" > .harness-initializeddiff --git a/store/agents/orca-slicer/toolchain/node.sh b/store/agents/orca-slicer/toolchain/node.shindex a527a9f1d..602936b14 100644--- a/store/agents/orca-slicer/toolchain/node.sh+++ b/store/agents/orca-slicer/toolchain/node.sh@@ -2,5 +2,5 @@set -euo pipefailhere="$(cd "$(dirname "$0")" && pwd)". "$here/runtimes.sh"-harness_node 20 || exit 1+harness_node 22 || exit 1exec node "$@"diff --git a/store/agents/orca-slicer/toolchain/setup.sh b/store/agents/orca-slicer/toolchain/setup.shindex fd78cded9..4631165d8 100755--- a/store/agents/orca-slicer/toolchain/setup.sh+++ b/store/agents/orca-slicer/toolchain/setup.sh@@ -1,5 +1,8 @@-#!/bin/sh+#!/usr/bin/env bashset -u+here="$(cd "$(dirname "$0")" && pwd)"+. "$here/runtimes.sh"+harness_node 22 || exit 1if [ -n "${ORCA_BIN:-}" ] && [ -x "$ORCA_BIN" ]; then echo "ok OrcaSlicer at $ORCA_BIN"; exit 0; fiif command -v orca-slicer >/dev/null 2>&1 || command -v orcaslicer >/dev/null 2>&1 || [ -x /Applications/OrcaSlicer.app/Contents/MacOS/OrcaSlicer ]; then echo "ok OrcaSlicer found"; exit 0; fiecho "miss OrcaSlicer — install 2.4.2 from https://github.com/OrcaSlicer/OrcaSlicer/releases or set ORCA_BIN"diff --git a/store/showcase/orca-slicer/review.jpg b/store/showcase/orca-slicer/review.jpgnew file mode 100644index 000000000..32e20caadBinary files /dev/null and b/store/showcase/orca-slicer/review.jpg differdiff --git a/store/showcase/orca-slicer/spacer.jpg b/store/showcase/orca-slicer/spacer.jpgnew file mode 100644index 000000000..02af96007Binary files /dev/null and b/store/showcase/orca-slicer/spacer.jpg differdiff --git a/store/showcase/orca-slicer/starter.jpg b/store/showcase/orca-slicer/starter.jpgindex 3feaf00d5..c6fd5adbb 100644Binary files a/store/showcase/orca-slicer/starter.jpg and b/store/showcase/orca-slicer/starter.jpg differdiff --git a/store/tools/REAL-WORKFLOWS.md b/store/tools/REAL-WORKFLOWS.mdindex 4a194f005..d72575ba0 100644--- a/store/tools/REAL-WORKFLOWS.md+++ b/store/tools/REAL-WORKFLOWS.md@@ -20,7 +20,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 | 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 |+| 4 | orca-slicer | User mesh and explicit machine/material profiles → compared slicing options and reviewed toolpath handoff | Implemented and validated; relisted in this change. See [acceptance evidence](../agents/orca-slicer/test/ACCEPTANCE.md). || 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 || 7 | web-studio | User application brief → useful app with durable data and a runnable handoff | Not started; unlisted |