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 FreeCAD for measured design jobs and relist it (#127)
Dee28f4165e8852
diff --git a/.github/workflows/experience-checks.yml b/.github/workflows/experience-checks.ymlindex 9941c1c53..233f3ae1c 100644--- a/.github/workflows/experience-checks.yml+++ b/.github/workflows/experience-checks.yml@@ -31,3 +31,5 @@ jobs:store/viewers/web-viewer/test/*.test.mjs- name: Validate Store catalogrun: node store/tools/catalog.mjs+ - name: Check FreeCAD contracts and delivery (native suite is opt-in)+ run: node --test store/agents/freecad/test/*.test.mjsdiff --git a/store/agents/freecad/AGENTS.md b/store/agents/freecad/AGENTS.mdindex 89bc14391..8e0173173 100644--- a/store/agents/freecad/AGENTS.md+++ b/store/agents/freecad/AGENTS.md@@ -1,15 +1,21 @@# FreeCAD-Read the `freecad` skill. The saved design is `part.FCMacro`, a Python macro executed by FreeCADCmd.-Keep design inputs at the top and rebuild after changes. The shared CAD Viewer follows `part.step`.+Read the `freecad` skill. Help someone who does not know CAD turn measurements, a sketch or an+existing part into an editable design they can actually use. The enclosure is an example, not+the product boundary: create the user's bracket, adapter, housing or other suitable solid model.-The Pocket starter exports a two-piece electronics enclosure, a vented lid, an STL mesh and a-FreeCAD document. Geometry is generated by the macro; the exported parameter object records inputs,-not a fully constrained Sketcher feature history.+Capture the brief, measured dimensions, fit/fastener needs and unresolved assumptions in+`design.json` before modeling. Use user-derived acceptance values, not values copied back from+your generated geometry. Missing measurements must stay visible; ask when they determine fit+or safety. Do not shrink a reference envelope or loosen a requirement to make a check pass.-Use the one-stop build. The macro must export into `HARNESS_BUILD_DIR` (falling back to the current-directory only for manual use). The build reimports and checks the newly written STEP in FreeCAD.-An old export is never proof of a successful new build.+`part.FCMacro` and its named inputs are the parametric source. The macro saves `part.FCStd` into+`HARNESS_BUILD_DIR`; the build runner reopens it, checks declared objects and requirements, then+exports the assembly and individual parts. Use the one-stop build after each substantive edit.+Inspect the real STEP and projected drawings too: a valid hole can still be inaccessible to a tool.-State manufacturing assumptions and inspect the real assembly. Closed, valid solids do not prove-wall thickness, strength, fit or suitability for a particular machine.+Finish with the measured results, remaining physical checks and the handoff page/project ZIP.+Offer the loopback download page so the user need not locate files manually. A failed build must+not be presented as success; the previous handoff is retained and explicitly belongs to the prior+successful revision. Keep source editable, but do not promise Sketcher history that was not built.+Geometry checks are not strength, process, electrical-safety or physical-fit certification.diff --git a/store/agents/freecad/PROVENANCE.md b/store/agents/freecad/PROVENANCE.mdindex 441be6692..c0e723dd3 100644--- a/store/agents/freecad/PROVENANCE.md+++ b/store/agents/freecad/PROVENANCE.md@@ -1,7 +1,10 @@# Provenance-The Pocket enclosure macro, native validation/export runner and instructions are-original MIT-licensed OpenHarness work. [FreeCAD](https://freecad.org) is a+The measured enclosure and bench-bracket fixtures, contract validator, native+validation/export runner, projected drawings, handoff page, portable build tools,+loopback download server and instructions are original MIT-licensed OpenHarness+work. The fixtures use synthetic dimensions, not proprietary product data.+[FreeCAD](https://freecad.org) is aseparately installed LGPL-2.1-or-later CAD application; no FreeCAD binary or sourceis redistributed. Native QA used FreeCAD 1.1.3. The CAD pane is the separateautonomous/cad-viewer package, which carries its own upstream notices.diff --git a/store/agents/freecad/README.md b/store/agents/freecad/README.mdindex 05c418b45..1fb3d5f8a 100644--- a/store/agents/freecad/README.md+++ b/store/agents/freecad/README.md@@ -1,25 +1,70 @@# FreeCAD-Turn a design brief into real CAD geometry and a STEP assembly. The **Pocket** starter includes-a rounded electronics enclosure, screw bosses, a cable opening and a vented locating lid.-Change named dimensions in the macro, rebuild, then inspect and measure the parts in the CAD Viewer.+Turn measurements into a custom bracket, adapter, enclosure or other solid part—even if you do+not know CAD. Describe what it must fit and how it attaches. The agent captures the requirements,+builds an editable FreeCAD model, measures the result and delivers separate parts you can take+to a slicer, another CAD tool or a fabricator for review.-Try: “Resize the enclosure for my board, keep 3 mm clearance, and move the cable opening.”+Try: “Make a bench bracket with a 60 mm mounting pattern. Keep room for the sensor and screwdriver,+then give me the individual part files and a project I can keep editing.”-The build produces STEP, STL and a native FreeCAD document. It reimports the fresh STEP and verifies-closed, valid, positive-volume solids; a failed build cannot reuse an old export as success.-The macro is the parametric source. The native file records the generated shapes and design inputs,-not a complete Sketcher constraint history. Manufacturing fit and strength still need review.+Or: “My board is 65 × 40 mm, with 12 mm-high components. Design a removable-lid enclosure. Ask me+for the connector measurements you need, and check the actual clearances before handing it over.”-Requires FreeCADCmd, Node 20+ and the shared CAD Viewer. Use `FREECAD_BIN` for a custom binary.+## What you get++- An editable macro, named inputs and a native FreeCAD document—not just a render.+- A saved brief and measurable requirements: size, position, holes, clearance, interference,+ containment and modeled tool-access space.+- Assembly STEP plus **individual STEP and closed STL parts**, reimported for validation.+- Three-view reference SVGs, actual measurements and explicit manufacturing assumptions.+- A portable project ZIP with sources and standalone rebuild tools. Extract it elsewhere and run+ `node tools/build.mjs` with Node and FreeCAD installed; no Harness installation is required.++The build checks the reopened native solids against the saved requirements. A wrong hole pattern,+obstructed tool envelope or insufficient gap fails even when the CAD solid itself is valid. Failed+builds keep the previous successful exports intact and identify the failing candidate. Source+fingerprints prevent an in-flight edit from being passed off as the built revision.++The included enclosure demonstrates the workflow; new jobs are not restricted to that design.+For a successful build, open `handoff/index.html` or ask the agent for its local download link.+The page includes the ZIP, per-part files, drawings, checks and assembly notes. It describes the+last successful build, not later edits to the source.++## Run locally++Requires FreeCADCmd with Part, MeshPart and TechDraw, Node 20+ and the shared CAD Viewer. Native+acceptance tests use FreeCAD 1.1.3. Set `FREECAD_BIN` for a custom installation. Installation does+not bundle FreeCAD; the toolchain reports how to install it if it is missing.```shharness dsh install "$PWD/store/agents/freecad" --linkharness dsh doctor autonomous/freecad```-Upstream: [FreeCAD](https://freecad.org). This package adds the workspace, skill, example design and-fresh-export verification.+Inside a project, the agent builds with:++```sh+sh "$FREECAD_SKILLS/freecad/scripts/build-part.sh"+node "$FREECAD_SKILLS/freecad/scripts/serve-handoff.mjs" "$HARNESS_WORKSPACE"+```++The second command prints a clickable loopback download URL. It serves only generated handoff+files, not arbitrary workspace contents. Stop it with Ctrl-C when finished.++## What remains your responsibility++Passing checks means the **specified geometric requirements** passed—not that strength, material,+electrical safety, weather sealing or as-printed fit is certified. Review process allowances,+hardware, support/orientation and physical fit. The SVGs show overall dimensions, not complete+production tolerances. STL orientation is unchanged; the assembly mesh is not a prepared print bed.+Generated native solids do not promise a constrained Sketcher feature history. Run only trusted macros.++See [the contract](skills/freecad/references/design-contract.md) for supported checks and+[acceptance evidence](test/ACCEPTANCE.md) for tests, versions and limitations.++Upstream: [FreeCAD](https://freecad.org). This package adds the measured-job workflow, workspace,+skill, native export checks and portable handoff.## Credit and stewardshipdiff --git a/store/agents/freecad/harness.json b/store/agents/freecad/harness.jsonindex a95841bc9..13050285a 100644--- a/store/agents/freecad/harness.json+++ b/store/agents/freecad/harness.json@@ -4,7 +4,7 @@"name": "FreeCAD","category": "CAD","author": "OpenHarness contributors",- "description": "Build parametric FreeCAD macros, inspect real STEP assemblies, and verify freshly reimported solids. Includes an editable enclosure and vented lid.",+ "description": "Turn measurements into custom parts with checked holes, clearances and tool access. Keep an editable FreeCAD project, individual STEP/STL exports, reference drawings and a portable handoff.","engine": "claude","workspace": {"template": "template",diff --git a/store/agents/freecad/skills/freecad/SKILL.md b/store/agents/freecad/skills/freecad/SKILL.mdindex 7cdbdf488..483aed564 100644--- a/store/agents/freecad/skills/freecad/SKILL.md+++ b/store/agents/freecad/skills/freecad/SKILL.md@@ -1,36 +1,88 @@---name: freecad-description: Build parametric FreeCAD macros, export STEP assemblies and verify fresh geometry in the shared CAD Viewer.+description: Turn measured design briefs or existing parts into editable FreeCAD projects with checked dimensions, bores, clearances, interference and fastener access; deliver separate STEP/STL parts, reference drawings and a portable project handoff.---# FreeCAD-`part.FCMacro` is Python executed by FreeCADCmd, not system Python. Import `FreeCAD as App` and-`Part`; use named dimensions and reusable construction functions. The Pocket starter produces-a base and vented lid laid out side by side, with screw bosses, clearance and a cable opening.+## From brief to useful part++Establish what the part must fit, how it attaches, which dimensions are measured, the units and+the intended process/material. Explain a needed measurement in everyday terms. A sketch or photo+can guide shape, but does not establish scale or hidden dimensions. Record assumptions separately+from requirements. For load-bearing, electrical, medical or other consequential uses, identify+the necessary professional/physical validation; do not certify suitability from a CAD preview.++Create `design.json` with the brief, named parts/reference envelopes and measurable checks. Read+[the design contract](references/design-contract.md) when creating or changing this file. Cover+the requirements that matter to the user's job: outside dimensions alone do not establish fit.+Use reference shapes for boards, connectors, movement or fastener/tool access, and check those+references' dimensions/positions so an accidentally moved or undersized keep-out cannot pass.++Build the appropriate model, not automatically an enclosure. `part.FCMacro` is Python executed by+FreeCADCmd, not system Python. Use `FreeCAD as App`, `Part`, named inputs and reusable construction+functions. Import an existing STEP as a reference when useful; include only user-approved input+files in the explicit `sourceFiles` list. Never bundle an entire workspace or hidden credentials.++The macro reads inputs from `HARNESS_WORKSPACE`, creates the named document objects and saves+`part.FCStd` in the unique `HARNESS_BUILD_DIR`. Close the document after saving. The runner handles+exports, measurements, drawings and the portable bundle. The example's `dimensions.json` is an+editable starting point, not a restriction on new designs. Preserve a user's existing work.++## Build and inspect```shsh "$FREECAD_SKILLS/freecad/scripts/build-part.sh"```-Requires Node 20+ and the headless FreeCAD binary. Resolve `FREECAD_BIN`, the toolchain link,+Requires Node 20+ and headless FreeCAD with Part, MeshPart and TechDraw (tested with 1.1.3).+The wrapper resolves `FREECAD_BIN`, the toolchain link,`freecadcmd`/`FreeCADCmd` or the installed macOS app. Recent macOS packages put the CLI at`FreeCAD.app/Contents/Resources/bin/freecadcmd`, not necessarily `Contents/MacOS/FreeCADCmd`.-## Export contract+The runner reopens the native document and validates its individual solids. Each manufactured part+must be one solid; declare disconnected pieces separately. It checks the saved requirements and+reimports individual STEP and STL exports. STEP volume, size and position must survive export;+STL must be a closed mesh with matching dimensions. Assembly contacts are allowed, but unwanted+overlap must be covered by interference/clearance checks. Reference objects are not exported.++Read `.harness/geometry.json`, inspect the actual assembly in the shared CAD Viewer and review+each projected drawing. Inspect access, orientation and assembly sequence as well as dimensions.+For revisions, retain unchanged requirements; update requirements only when the brief changes.+Rebuild, inspect the changed geometry and report what changed. Never treat a previous render as+evidence of a successful new build.-The build runs `runner.py` in FreeCAD with `HARNESS_WORKSPACE` and a unique `HARNESS_BUILD_DIR`.-Your macro reads its source inputs from the workspace and writes `part.step` to that build directory.-Optional `part.stl` and `part.FCStd` exports are copied alongside it only after verification.-Use `MeshPart.meshFromShape` for controlled mesh tessellation, and `doc.saveAs` for the native file.+On failure, inspect `.harness/build.log` or `.harness/failed-design.json`. A failed measured candidate+is shown as `candidate.step`; the last successful `part.step` and `handoff/` stay unchanged. Fix the+model or resolve the brief conflict, not the test threshold. `.harness/history/` retains replaced+successful artifacts. Do not delete history or a build lock merely to hide an error. A stale lock+may be removed only after confirming its owning build is no longer running.++Legacy macros without `design.json` may still export `part.step`, but remain `ready:false`: geometry+validity alone is not a checked job. Add requirements before claiming a complete handoff.++## Deliver and keep editing++After a successful build, explain the measured results and unresolved manufacturing assumptions.+Deliver `handoff/project.zip` plus the human-readable `handoff/index.html`, not just a screenshot.+To give the user a clickable local download page, run this in a managed long-lived process and+share the printed loopback URL (keep it running while the user needs it; Ctrl-C stops it):++```sh+node "$FREECAD_SKILLS/freecad/scripts/serve-handoff.mjs" "$HARNESS_WORKSPACE"+```-The runner reimports the new STEP, calls `shape.check(True)`, and requires positive-volume,-closed, valid solids. `shape.check` does not return a success boolean; exceptions indicate errors.-It writes a fresh geometry receipt. The Node wrapper rejects missing output or receipt even if-FreeCAD reports exit zero after a Python exception. See `.harness/build.log` and `geometry.json`.+The server serves only generated handoff artifacts, never directory listings or arbitrary inputs.+The page is a receipt of the last successful build, not a live claim about later edits.-Do not equate STEP validity with printability or machining suitability. Review wall thickness,-clearance, supports, tool access, strength and intended materials separately. Parametric macro-inputs are not a promise of a fully constrained Sketcher history in the exported document.+The ZIP contains the explicitly selected sources, native document, assembly, separate parts,+dimensioned reference SVGs, measurement receipt and standalone tools. With Node and FreeCAD+installed, extract it elsewhere and run `node tools/build.mjs`; no Harness installation is needed.+Verify this path for a materially new workflow before presenting it as independently reproducible.-Inspect both parts in the actual viewer; verify dimensions or section cuts relevant to the request.+STEP files keep assembly coordinates. Each part STL is translated to nonnegative coordinates,+without choosing a print orientation. Quantity is a bill-of-parts count, not repeated geometry.+The assembly STL is not a prepared print layout. The SVGs show overall projected dimensions;+they are not fully toleranced production drawings. Review material, wall thickness, tool access,+supports and physical fit separately. The macro is executable Python; run only trusted sources.+Native files may contain generated Part features, not a fully constrained Sketcher history.diff --git a/store/agents/freecad/skills/freecad/references/design-contract.md b/store/agents/freecad/skills/freecad/references/design-contract.mdnew file mode 100644index 000000000..39a62c85a--- /dev/null+++ b/store/agents/freecad/skills/freecad/references/design-contract.md@@ -0,0 +1,85 @@+# Saved design contract (spec 1)++Keep the user's requirements separate from construction code. Check values should come from+the brief or measurements, not from reading back the solid or automatically copying construction+parameters. An unmeasured requirement is still unresolved even when every listed check passes.++## Minimal complete job++```json+{+ "spec": 1,+ "title": "Equipment adapter",+ "brief": "A 60 by 30 by 4 mm prototype plate with a centred 6.4 mm through bore.",+ "units": "mm",+ "sourceFiles": ["part.FCMacro", "design.json", "dimensions.json"],+ "parts": [{"id": "adapter", "object": "Adapter", "label": "Adapter plate", "material": "Prototype plastic; process not yet selected", "quantity": 1}],+ "references": [],+ "checks": [+ {"id": "outside", "type": "bounds", "part": "Adapter", "size": [60, 30, 4], "origin": [-30, -15, 0], "reason": "Fit the measured mounting space."},+ {"id": "bore", "type": "bore", "part": "Adapter", "origin": [0, 0, 0], "axis": [0, 0, 1], "diameter": 6.4, "length": 4, "wall": 2, "reason": "Match the required fastener clearance and location."}+ ],+ "assumptions": ["Nominal geometry only; choose material and verify printed fit before use."],+ "assembly": ["Test the prototype against the measured equipment before installation."],+ "hardware": ["Select fastener length and load rating against the actual joint."]+}+```++Create a document object named `Adapter` (the internal **Name**, not the displayed Label). Save+the document to `os.path.join(os.environ["HARNESS_BUILD_DIR"], "part.FCStd")`. There is no need+to export files manually. Imported references must also be named solid objects in this document.++## Fields and checks++All distances/coordinates are in millimetres; volume tolerances are mm³. Bounds use world axes.+Part IDs become filenames and must be unique ASCII identifiers; internal object names must be+unique. Up to 32 individual manufactured parts, 64 references and 256 checks are supported.+Optional `notes` on each part explain handling, orientation or other caveats.++| Type | Required fields beyond `id`, `type`, `reason` | What the native kernel checks |+| --- | --- | --- |+| `bounds` | `part`, `size: [x,y,z]` | Bounding-box size; optional `origin: [xmin,ymin,zmin]` also checks position. |+| `clearance` | `parts: [A,B]`, `minimum` | Closest surface distance **and no intersecting volume**. Optional `maximum` limits excess gap. |+| `no-overlap` | `parts: [A,B]` | Common volume. Touching surfaces are allowed. |+| `contains` | `part: Container`, `other: Payload` | Volume of Payload outside Container. Use a solid available-space reference, not a hollow shell. |+| `bore` | `part`, `origin`, `axis`, `diameter`, `length`, `wall` | The axial cylinder is empty and an annulus of surrounding material exists. Empty space alone cannot pass as a hole. |++`bounds`, `clearance` and `bore` accept `tolerance` (default 0.02 mm).+`contains` and `no-overlap` accept `toleranceVolume` (default 0.00001 mm³).+These are numeric measurement allowances, **not** a specification of manufacturing tolerances.+Do not loosen them to conceal a faulty design. Bore tolerance must be smaller than the radius,+half-depth and required surrounding wall. Axis is a nonzero vector and is normalized by the runner.++For a through bore, place `origin` on its entry surface and point `axis` through the material.+`length` spans the material; `wall` is the surrounding annulus required along that span. This+check does not establish countersinks, threads, retention or tool access. Model the necessary+access volumes separately and use bounds plus no-overlap checks. A stepped bore needs separate+appropriate probes, not one cylinder through air or counterbore space.++Reference shapes let you check clearance around an actual PCB, connector, moving part or tool.+Check their dimensions and locations independently. A passing check against a shrunken reference+proves nothing about the real object. Include motion extremes or swept volumes when needed.+Model physical inserts/supports intentionally: `no-overlap` alone does not prove retention.++## Sources, receipts and portability++`sourceFiles` is an explicit allowlist of at most 128 regular files (64 MiB each, 128 MiB total).+It must include `part.FCMacro` and `design.json`; include every additional input/helper the macro+needs. Visible nested paths such as `inputs/board.step` are allowed. Hidden files, symlinks,+absolute/parent paths, generated outputs, `tools/` and `handoff/` are rejected. Imported third-party+input must be permitted to redistribute in the user-directed project bundle; keep its notices.++The builder hashes included sources before/after native execution and again before publishing.+The receipt records those SHA-256 values, actual measurements and FreeCAD version. A source edit+during a build invalidates that result. A macro depending on undeclared external files is not+portable: test the extracted ZIP in a new folder to expose missing inputs.++Each manufactured object must be one closed, valid positive-volume solid. Quantity does not create+instances: name actual assembled instances separately when placement/interference matters. The+builder exports only declared manufactured objects, not the reference solids.++Unknown fields/types, duplicate IDs, non-finite numbers and undeclared object names fail validation.+Read `.harness/build.log` for schema/native errors, `.harness/failed-design.json` for failed measured+checks, and `.harness/verdict.json` for the current result. A failed candidate does not replace the+last successful handoff. A success means **the specified checks passed**, not that every aspect of+the user's intended use has been certified.diff --git a/store/agents/freecad/skills/freecad/scripts/LICENSE b/store/agents/freecad/skills/freecad/scripts/LICENSEnew file mode 100644index 000000000..d3eab18ed--- /dev/null+++ b/store/agents/freecad/skills/freecad/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/freecad/skills/freecad/scripts/build.mjs b/store/agents/freecad/skills/freecad/scripts/build.mjsindex 2f7fa7bd0..d8a215010 100644--- a/store/agents/freecad/skills/freecad/scripts/build.mjs+++ b/store/agents/freecad/skills/freecad/scripts/build.mjs@@ -1,7 +1,8 @@-import { access, readFile, writeFile, mkdir, mkdtemp, rename, rm } from 'node:fs/promises';+import { access, readFile, writeFile, mkdir, mkdtemp, rename, rm, lstat, realpath } from 'node:fs/promises';import { constants } from 'node:fs';import { spawnSync } from 'node:child_process';-import { delimiter, join, resolve } from 'node:path';+import { createHash } from 'node:crypto';+import { basename, delimiter, join, resolve, sep } from 'node:path';import { fileURLToPath } from 'node:url';export async function findExecutable(){const candidates=[process.env.FREECAD_BIN,process.env.FREECAD_TOOLCHAIN&&join(process.env.FREECAD_TOOLCHAIN,'freecad-cli'),'freecadcmd','FreeCADCmd','/Applications/FreeCAD.app/Contents/Resources/bin/freecadcmd','/Applications/FreeCAD.app/Contents/MacOS/FreeCADCmd'];@@ -10,36 +11,95 @@ export async function findExecutable(){}throw new Error('FreeCADCmd not found. Set FREECAD_BIN or run harness dsh doctor autonomous/freecad.');}+async function exists(path) {+ try { await lstat(path); return true; } catch (error) { if (error.code === 'ENOENT') return false; throw error; }+}++async function publish(workspace, state, stage, names) {+ const history = join(state, 'history', basename(stage));+ await mkdir(history, {recursive:true});+ const saved = [], installed = [];+ try {+ if (await exists(join(state, 'geometry.json'))) await writeFile(join(history, 'geometry.json'), await readFile(join(state, 'geometry.json')));+ for (const name of names) {+ const destination = join(workspace, name);+ if (await exists(destination)) { await rename(destination, join(history, name)); saved.push(name); }+ await rename(join(stage, name), destination); 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 (failure) { failures.push(failure.message); }+ }+ for (const name of saved.reverse()) {+ try { await rename(join(history, name), join(workspace, name)); } catch (failure) { failures.push(failure.message); }+ }+ if (failures.length) throw new Error(`Publication failed; previous files are retained in ${history}. Restore errors: ${failures.join('; ')}`);+ throw error;+ }+}+export async function build(workspace,{bin}={}){+ workspace = resolve(workspace);const state=join(workspace,'.harness');await mkdir(state,{recursive:true});+ const lock = join(state, 'freecad-build.lock');+ try { await mkdir(lock); }+ catch (error) {+ if (error.code === 'EEXIST') throw new Error('Another FreeCAD build owns .harness/freecad-build.lock. If a build crashed, confirm it has stopped before removing that lock directory.');+ throw error;+ }const atomic=async(path,value)=>{const temporary=path+'.'+process.pid+'.tmp';await writeFile(temporary,value);await rename(temporary,path);};const verdict=value=>atomic(join(state,'verdict.json'),JSON.stringify({spec:1,...value,updatedAt:new Date().toISOString()},null,2)+'\n');- let temporary;+ let temporary, candidate = false, failedChecks = [];try{- await verdict({ready:false,summary:'Building and reimporting the STEP assembly',findings:[],artifact:null});+ await writeFile(join(lock, 'owner.json'), JSON.stringify({pid:process.pid, startedAt:new Date().toISOString()}));+ await verdict({ready:false,summary:'Building the native project, measuring requirements and preparing the handoff',findings:[],artifact:null});const executable=bin||await findExecutable();await access(join(workspace,'part.FCMacro'));temporary=await mkdtemp(join(state,'freecad-'));const runner=fileURLToPath(new URL('runner.py',import.meta.url));- const result=spawnSync(executable,[runner],{cwd:workspace,env:{...process.env,HARNESS_WORKSPACE:workspace,HARNESS_BUILD_DIR:temporary},encoding:'utf8',timeout:180000,maxBuffer:10*1024*1024});+ const result=spawnSync(executable,['--user-cfg',join(temporary,'user.cfg'),'--system-cfg',join(temporary,'system.cfg'),runner],{cwd:workspace,env:{...process.env,HARNESS_WORKSPACE:workspace,HARNESS_BUILD_DIR:temporary},encoding:'utf8',timeout:300000,maxBuffer:20*1024*1024});await atomic(join(state,'build.log'),(result.stdout||'')+(result.stderr||''));if(result.error||result.status!==0)throw new Error('FreeCAD failed: '+(result.error?.message||'exit '+result.status)+'. See .harness/build.log.');- const report=JSON.parse(await readFile(join(temporary,'geometry.json'),'utf8'));+ let report;+ try { report=JSON.parse(await readFile(join(temporary,'geometry.json'),'utf8')); }+ catch { throw new Error('FreeCAD did not produce a fresh geometry receipt. See .harness/build.log for the source or requirement error.'); }const step=await readFile(join(temporary,'part.step'));if(!report.valid||!report.closed||report.solids<1||report.volumeMM3<=0||!step.toString('utf8').startsWith('ISO-10303-21;'))throw new Error('Fresh STEP verification failed.');- const files=new Map([['part.step',step]]);+ const files=['part.step'];for(const name of ['part.stl','part.FCStd']){- try{const bytes=await readFile(join(temporary,name));if(!bytes.length)throw new Error(name+' is empty');files.set(name,bytes);}+ try{const bytes=await readFile(join(temporary,name));if(!bytes.length)throw new Error(name+' is empty');files.push(name);}catch(error){if(error.code!=='ENOENT')throw error;}}- for(const[name,bytes]of files)await atomic(join(workspace,name),bytes);+ if (report.designChecked === true) {+ if (!report.sources || !Array.isArray(report.checks) || !report.checks.length || !Array.isArray(report.parts) || !report.parts.length) throw new Error('The design receipt is incomplete.');+ const root = await realpath(workspace);+ for (const [name, digest] of Object.entries(report.sources)) {+ const path = await realpath(resolve(workspace, name));+ if (!path.startsWith(root + sep) || createHash('sha256').update(await readFile(path)).digest('hex') !== digest) throw new Error('Source changed during the build; rebuild the current saved project: ' + name);+ }+ failedChecks = report.checks.filter(check => check.passed !== true);+ if (report.requirementsPassed !== true || failedChecks.length) {+ await atomic(join(state,'failed-design.json'),JSON.stringify(report,null,2)+'\n');+ await atomic(join(workspace,'candidate.step'),step); candidate = true;+ throw new Error(`${failedChecks.length} design requirement(s) failed. Inspect candidate.step and .harness/failed-design.json; the last successful handoff is unchanged.`);+ }+ for (const name of ['part.FCStd','part.stl','handoff/project.zip','handoff/index.html','handoff/checks.json']) {+ if (!(await readFile(join(temporary,name))).length) throw new Error('The handoff is missing '+name);+ }+ files.push('handoff');+ }+ const previous = await publish(workspace, state, temporary, files);+ report.previousArtifacts = previous;await atomic(join(state,'geometry.json'),JSON.stringify(report,null,2)+'\n');- await verdict({ready:true,summary:report.solids+' closed solids · STEP reimport verified',findings:[{severity:'info',kind:'manufacturing',message:'Geometry checks do not certify wall thickness, tolerances or strength. Review the design for its intended manufacturing process.'}],artifact:'part.step'});+ const ready = report.designChecked === true && report.requirementsPassed === true;+ await verdict({ready,summary:ready?`${report.parts.length} parts · ${report.checks.length} design checks passed · portable handoff ready`:'Geometry exported; add design.json to check the job requirements and prepare a portable handoff',findings:[{severity:ready?'info':'warning',kind:ready?'manufacturing':'requirements',message:ready?'Open handoff/index.html for parts, measured requirements and the editable project ZIP. Geometry checks do not certify strength, process suitability or physical fit.':'Legacy geometry-only build. Keep the preview, then capture the actual brief and measurable requirements in design.json.'}],artifact:'part.step'});return report;- }catch(error){await verdict({ready:false,summary:'FreeCAD build failed',findings:[{severity:'error',kind:'build',message:error.message}],artifact:null});throw error;}- finally{if(temporary)await rm(temporary,{recursive:true,force:true});}+ }catch(error){await verdict({ready:false,summary:failedChecks.length?'Design requirements failed':'FreeCAD build failed',findings:[{severity:'error',kind:'build',message:error.message},...failedChecks.map(check=>({severity:'error',kind:'requirement',message:check.id+': '+check.reason}))],artifact:candidate?'candidate.step':null});throw error;}+ finally{if(temporary)await rm(temporary,{recursive:true,force:true});await rm(lock,{recursive:true,force:true});}}if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){- try{console.log(await build(resolve(process.env.HARNESS_WORKSPACE||process.cwd())));}+ try{const report=await build(resolve(process.argv[2]||process.env.HARNESS_WORKSPACE||process.cwd()));console.log(report.designChecked?`${report.parts.length} parts · ${report.checks.length} measured requirements · handoff/index.html`:'Geometry rendered; design.json is needed to verify the user’s requirements.');}catch(error){console.error(error.message);process.exitCode=1;}}diff --git a/store/agents/freecad/skills/freecad/scripts/design.py b/store/agents/freecad/skills/freecad/scripts/design.pynew file mode 100644index 000000000..f95b8f48e--- /dev/null+++ b/store/agents/freecad/skills/freecad/scripts/design.py@@ -0,0 +1,155 @@+"""The saved job contract. Standard-library only so validation needs no CAD runtime."""+import math+import os+import re+++def fail(message):+ raise ValueError("design.json: " + message)+++def text(value, name, limit=2000):+ if not isinstance(value, str) or not value.strip() or len(value) > limit:+ fail(name + " must be nonempty text (at most %d characters)" % limit)+ return value+++def number(value, name, minimum=None, maximum=1000000):+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):+ fail(name + " must be a finite number")+ if minimum is not None and value < minimum or maximum is not None and value > maximum:+ fail(name + " is outside the supported range")+ return value+++def vector(value, name, positive=False):+ if not isinstance(value, list) or len(value) != 3:+ fail(name + " must contain three millimetre coordinates")+ for component in value:+ number(component, name, 0.000001 if positive else -1000000)+ return value+++def keys(value, required, optional, name):+ if not isinstance(value, dict):+ fail(name + " must be an object")+ missing = set(required) - set(value)+ unknown = set(value) - set(required) - set(optional)+ if missing:+ fail(name + " is missing " + ", ".join(sorted(missing)))+ if unknown:+ fail(name + " has unknown fields: " + ", ".join(sorted(unknown)))+++def source_path(value):+ text(value, "sourceFiles entry", 240)+ components = value.split("/")+ if (os.path.isabs(value) or "\\" in value or ":" in value or+ any(not c or c.startswith(".") for c in components) or+ any(ord(c) < 32 for c in value)):+ fail("sourceFiles must be visible, relative paths inside the project")+ if components[0].lower() in {"handoff", "tools", "node_modules", "part.step", "part.stl", "part.fcstd", "candidate.step", "rebuild.txt"}:+ fail("sourceFiles cannot include generated outputs or tools: " + value)+ return value+++def validate(value):+ keys(value, ["spec", "title", "brief", "units", "parts", "checks"],+ ["references", "sourceFiles", "assumptions", "assembly", "hardware"], "project")+ if value["spec"] != 1 or isinstance(value["spec"], bool):+ fail("spec must be 1")+ if value["units"] != "mm":+ fail("units must be mm; convert the user's measurements explicitly")+ text(value["title"], "title", 160)+ text(value["brief"], "brief", 6000)+ parts = value["parts"]+ if not isinstance(parts, list) or not 1 <= len(parts) <= 32:+ fail("parts must contain 1–32 manufactured parts")+ objects, ids = set(), set()+ for part in parts:+ keys(part, ["id", "object", "label", "material"], ["quantity", "notes"], "part")+ for field in ["id", "object"]:+ if not isinstance(part[field], str) or not re.fullmatch(r"[A-Za-z][A-Za-z0-9_-]{0,63}", part[field]):+ fail("part " + field + " must be a short ASCII identifier")+ if part["id"].lower() in ids or part["object"] in objects:+ fail("part IDs (case-insensitive) and FreeCAD object names must be unique")+ ids.add(part["id"].lower())+ objects.add(part["object"])+ text(part["label"], "part label", 160)+ text(part["material"], "part material", 240)+ quantity = part.get("quantity", 1)+ if type(quantity) is not int or not 1 <= quantity <= 1000:+ fail("part quantity must be an integer from 1 to 1000")+ if "notes" in part:+ text(part["notes"], "part notes")+ references = value.get("references", [])+ if not isinstance(references, list) or len(references) > 64:+ fail("references must be a list of up to 64 FreeCAD object names")+ for name in references:+ if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z][A-Za-z0-9_-]{0,63}", name) or name in objects:+ fail("reference object names must be unique, distinct from manufactured parts")+ objects.add(name)+ sources = value.get("sourceFiles", ["part.FCMacro", "design.json"])+ if not isinstance(sources, list) or not 1 <= len(sources) <= 128:+ fail("sourceFiles must contain 1–128 explicitly selected source files")+ for path in sources:+ source_path(path)+ if len(set(path.lower() for path in sources)) != len(sources):+ fail("sourceFiles cannot contain duplicate names")+ if not {"part.FCMacro", "design.json"}.issubset(sources):+ fail("sourceFiles must include part.FCMacro and design.json")+ for field in ["assumptions", "assembly", "hardware"]:+ if field in value:+ if not isinstance(value[field], list) or len(value[field]) > 100:+ fail(field + " must contain at most 100 text entries")+ for entry in value[field]:+ text(entry, field + " entry")+ checks = value["checks"]+ if not isinstance(checks, list) or not 1 <= len(checks) <= 256:+ fail("checks must contain 1–256 measurable requirements")+ check_ids = set()+ for check in checks:+ if not isinstance(check, dict):+ fail("each check must be an object")+ kind = check.get("type")+ schemas = {+ "bounds": (["part", "size"], ["origin", "tolerance"]),+ "clearance": (["parts", "minimum"], ["maximum", "tolerance"]),+ "no-overlap": (["parts"], ["toleranceVolume"]),+ "contains": (["part", "other"], ["toleranceVolume"]),+ "bore": (["part", "origin", "axis", "diameter", "length", "wall"], ["tolerance"]),+ }+ if not isinstance(kind, str) or kind not in schemas:+ fail("unsupported check type: " + str(kind))+ required, optional = schemas[kind]+ keys(check, ["id", "type", "reason"] + required, optional, "check")+ text(check["id"], "check id", 100)+ text(check["reason"], "check reason", 1000)+ if check["id"] in check_ids:+ fail("check IDs must be unique")+ check_ids.add(check["id"])+ names = [check[field] for field in ["part", "other"] if field in check]+ if "parts" in check:+ if not isinstance(check["parts"], list) or len(check["parts"]) != 2:+ fail("check parts must name exactly two different objects")+ names += check["parts"]+ if any(not isinstance(name, str) or name not in objects for name in names) or len(set(names)) != len(names):+ fail("checks must name distinct objects declared in parts or references")+ for field in ["origin", "axis", "size"]:+ if field in check:+ vector(check[field], field, field == "size")+ for field in ["minimum", "maximum", "tolerance", "toleranceVolume"]:+ if field in check:+ number(check[field], field, 0)+ for field in ["diameter", "length", "wall"]:+ if field in check:+ number(check[field], field, 0.000001)+ if kind == "clearance" and check.get("maximum", float("inf")) < check["minimum"]:+ fail("clearance maximum cannot be less than minimum")+ if kind == "bore":+ if sum(component ** 2 for component in check["axis"]) < 1e-12:+ fail("bore axis cannot be zero")+ tolerance = check.get("tolerance", 0.02)+ if tolerance >= min(check["diameter"] / 2, check["length"] / 2, check["wall"]):+ fail("bore tolerance must be smaller than its radius, half-depth and wall")+ return valuediff --git a/store/agents/freecad/skills/freecad/scripts/geometry.py b/store/agents/freecad/skills/freecad/scripts/geometry.pynew file mode 100644index 000000000..a3b17b5fc--- /dev/null+++ b/store/agents/freecad/skills/freecad/scripts/geometry.py@@ -0,0 +1,216 @@+"""Real OpenCascade measurements, fresh per-part exports and projected drawings."""+import html+import math+import os+import re++import FreeCAD as App+import Part+import Mesh+import MeshPart+import TechDraw+++def metrics(shape):+ box = shape.BoundBox+ values = [box.XLength, box.YLength, box.ZLength, shape.Volume, shape.Area]+ if not all(math.isfinite(value) for value in values):+ raise ValueError("Geometry contains non-finite measurements")+ return {"boundsMM": values[:3], "originMM": [box.XMin, box.YMin, box.ZMin],+ "volumeMM3": shape.Volume, "areaMM2": shape.Area,+ "solids": len(shape.Solids)}+++def solid(shape, name):+ # Separate assembly bodies may intentionally touch. A compound-wide BOP check+ # calls those shared boundaries self-intersections; validate each body deeply.+ try:+ shape.check(False)+ for body in shape.Solids:+ body.check(True)+ except Exception as error:+ raise ValueError(name + " failed native shape validation: " + str(error)) from error+ if shape.isNull() or not shape.isValid() or not shape.isClosed() or not shape.Solids or shape.Volume <= 0:+ raise ValueError(name + " is not a closed, valid, positive-volume solid")+ return metrics(shape)+++def recompute_document(document):+ document.recompute()+ # Failed FreeCAD features can retain a perfectly valid *previous* Shape.+ # Geometry validity cannot substitute for a successful dependency recompute.+ failures = [obj.Name + ": " + obj.getStatusString() for obj in document.Objects+ if not obj.isValid() or "Touched" in obj.State]+ if failures:+ raise ValueError("Native document has failed or uncomputed features: " + "; ".join(failures))+++def measure(check, shapes):+ kind = check["type"]+ tolerance = check.get("tolerance", 0.02)+ if kind == "bounds":+ data = metrics(shapes[check["part"]])+ passed = all(abs(a - b) <= tolerance for a, b in zip(data["boundsMM"], check["size"]))+ if "origin" in check:+ passed = passed and all(abs(a - b) <= tolerance for a, b in zip(data["originMM"], check["origin"]))+ actual = {"sizeMM": data["boundsMM"], "originMM": data["originMM"], "toleranceMM": tolerance}+ elif kind in {"clearance", "no-overlap"}:+ left, right = [shapes[name] for name in check["parts"]]+ overlap = max(0, left.common(right).Volume)+ if kind == "no-overlap":+ limit = check.get("toleranceVolume", 0.00001)+ passed = overlap <= limit+ actual = {"overlapMM3": overlap, "toleranceMM3": limit}+ else:+ gap = left.distToShape(right)[0]+ # A contained solid can have nonzero surface distance despite overlapping volume.+ passed = (overlap <= 0.00001 and gap + tolerance >= check["minimum"] and+ gap - tolerance <= check.get("maximum", float("inf")))+ actual = {"minimumDistanceMM": gap, "overlapMM3": overlap, "toleranceMM": tolerance}+ elif kind == "contains":+ outside = max(0, shapes[check["other"]].cut(shapes[check["part"]]).Volume)+ limit = check.get("toleranceVolume", 0.00001)+ passed = outside <= limit+ actual = {"outsideMM3": outside, "toleranceMM3": limit}+ elif kind == "bore":+ shape = shapes[check["part"]]+ axis = App.Vector(*check["axis"])+ axis.normalize()+ start = App.Vector(*check["origin"]) + axis * tolerance+ depth = check["length"] - 2 * tolerance+ radius = check["diameter"] / 2+ empty = Part.makeCylinder(radius - tolerance, depth, start, axis)+ ring = Part.makeCylinder(radius + check["wall"], depth, start, axis).cut(+ Part.makeCylinder(radius + tolerance, depth, start, axis))+ blocked = max(0, shape.common(empty).Volume)+ missing = max(0, ring.cut(shape).Volume)+ # A probe in empty space is not a hole: require surrounding material too.+ limit = min(0.00001, min(empty.Volume, ring.Volume) * 0.000001)+ if limit <= 0:+ raise ValueError("Bore probe is below the kernel's supported geometric scale")+ passed = blocked <= limit and missing <= limit+ actual = {"blockedBoreMM3": blocked, "missingSurroundMM3": missing,+ "requiredDiameterMM": check["diameter"], "requiredSurroundMM": check["wall"],+ "toleranceMM": tolerance, "volumeToleranceMM3": limit}+ else:+ raise ValueError("Unknown geometric check " + kind)+ if not all(math.isfinite(value) for value in actual.values() if isinstance(value, (float, int))):+ raise ValueError("Non-finite result for " + check["id"])+ return {"id": check["id"], "type": kind, "reason": check["reason"],+ "passed": bool(passed), "requirement": check, "measured": actual}+++def drawing(shape, part, title, destination):+ box = shape.BoundBox+ centered = shape.copy()+ centered.translate(-box.Center)+ x, y, z = box.XLength, box.YLength, box.ZLength+ scale = min(1.0, 64 / max(x, y, z), 51 / max(y, z))+ escape = html.escape+ content = [+ '<svg xmlns="http://www.w3.org/2000/svg" width="297mm" height="210mm" viewBox="0 0 297 210">',+ '<rect width="297" height="210" fill="white"/>',+ '<style>text{font-family:Arial,sans-serif;fill:#18342d}.small{font-size:3px}.dim{stroke:#53756a;stroke-width:.22;fill:none}</style>',+ '<rect x="10" y="10" width="277" height="190" fill="none" stroke="#53756a" stroke-width=".3"/>',+ '<text x="18" y="23" font-size="5">' + escape(part["label"][:75]) + '</text>',+ '<text x="18" y="30" class="small">' + escape(title[:120]) + '</text>',+ ]+ # Project along a fixed Z direction after explicit model rotations. Allowing+ # TechDraw to choose its own in-plane basis can rotate front/side views 90°,+ # making otherwise correct dimension labels point at the wrong edges.+ views = [("TOP · X/Y", App.Vector(1, 0, 0), 0, x, y),+ ("FRONT · X/Z", App.Vector(1, 0, 0), -90, x, z),+ ("RIGHT · Y/Z", App.Vector(1, 1, 1), -120, y, z)]+ for i, (label, axis, angle, width, height) in enumerate(views):+ cx, cy = 56 + i * 92, 80+ projected = centered.copy()+ projected.rotate(App.Vector(0, 0, 0), axis, angle)+ fragment = TechDraw.projectToSVG(projected, App.Vector(0, 0, 1))+ fragment = re.sub(r'\s+id\s*=\s*"[^"]*"', '', fragment)+ fragment = re.sub(r'stroke-width="[^"]*"', 'stroke-width="%g"' % (0.28 / scale), fragment)+ content.append('<text x="%g" y="42" text-anchor="middle" class="small">%s</text>' % (cx, label))+ content.append('<g class="projection" data-width="%g" data-height="%g" transform="translate(%g,%g) scale(%g)">%s</g>' % (width, height, cx, cy, scale, fragment))+ left, right = cx - width * scale / 2, cx + width * scale / 2+ top, bottom = cy - height * scale / 2, cy + height * scale / 2+ dy, dx = bottom + 7, right + 6+ content.append('<path class="dim" d="M %g %g V %g M %g %g V %g M %g %g H %g"/>' %+ (left, bottom+1, dy+2, right, bottom+1, dy+2, left, dy, right))+ content.append('<path class="dim" d="M %g %g H %g M %g %g H %g M %g %g V %g"/>' %+ (right+1, top, dx+2, right+1, bottom, dx+2, dx, top, bottom))+ content.append('<text x="%g" y="%g" text-anchor="middle" class="small">%.3f mm</text>' % (cx, dy+5, width))+ content.append('<text x="%g" y="%g" transform="rotate(-90 %g %g)" text-anchor="middle" class="small">%.3f mm</text>' %+ (dx+4, cy, dx+4, cy, height))+ notes = ["DIMENSIONED REFERENCE · all dimensions in mm · use written dimensions, not screen/print scale",+ "Generated from the reopened native solid using FreeCAD TechDraw projections.",+ "Overall dimensions only. Hole/fit requirements and measured checks are in the handoff report.",+ "Not a toleranced production drawing. Manufacturing process, strength and physical fit require review.",+ "Material (project assumption): " + part["material"][:130],+ "Quantity: %s · object: %s · source units: mm" % (part.get("quantity", 1), part["object"])]+ for i, note in enumerate(notes):+ content.append('<text x="18" y="%g" class="small">%s</text>' % (148 + i * 7, escape(note)))+ content.append('</svg>')+ with open(destination, "w", encoding="utf8") as handle:+ handle.write("\n".join(content))+++def export_project(project, native, output):+ document = App.openDocument(native)+ try:+ recompute_document(document)+ document.save()+ shapes, objects = {}, {}+ names = [part["object"] for part in project["parts"]] + project.get("references", [])+ for name in names:+ obj = document.getObject(name)+ if obj is None or not hasattr(obj, "Shape"):+ raise ValueError("Native document is missing shape object " + name)+ solid(obj.Shape, name)+ shapes[name], objects[name] = obj.Shape.copy(), obj+ parts_dir = os.path.join(output, "handoff", "parts")+ os.makedirs(parts_dir, exist_ok=True)+ reports = []+ for part in project["parts"]:+ shape = shapes[part["object"]]+ data = solid(shape, part["label"])+ if data["solids"] != 1:+ raise ValueError(part["label"] + " must be one solid; declare disconnected pieces separately")+ prefix = os.path.join(parts_dir, part["id"])+ shape.exportStep(prefix + ".step")+ reopened = Part.Shape()+ reopened.read(prefix + ".step")+ exported = solid(reopened, part["label"] + " STEP reimport")+ if (abs(exported["volumeMM3"] - data["volumeMM3"]) > max(0.00001, data["volumeMM3"] * 1e-6) or+ any(abs(a - b) > 0.001 for field in ["boundsMM", "originMM"]+ for a, b in zip(exported[field], data[field]))):+ raise ValueError(part["label"] + " changed dimensions or volume during STEP export")+ local = shape.copy()+ translation = [-coordinate for coordinate in data["originMM"]]+ local.translate(App.Vector(*translation))+ mesh = MeshPart.meshFromShape(Shape=local, LinearDeflection=0.05, AngularDeflection=0.1, Relative=False)+ mesh.write(prefix + ".stl")+ reopened_mesh = Mesh.Mesh(prefix + ".stl")+ if reopened_mesh.CountFacets == 0 or not reopened_mesh.isSolid():+ raise ValueError(part["label"] + " STL reimport is not a closed mesh")+ mesh_box = reopened_mesh.BoundBox+ if any(abs(a - b) > 0.11 for a, b in zip(+ [mesh_box.XLength, mesh_box.YLength, mesh_box.ZLength], data["boundsMM"])):+ raise ValueError(part["label"] + " STL changed dimensions during tessellation")+ drawing(shape, part, project["title"], prefix + ".svg")+ reports.append({**part, **data, "stepReimported": True, "stlReimported": True,+ "stlTranslationMM": translation, "meshTriangles": mesh.CountFacets,+ "files": {kind: "parts/" + part["id"] + "." + kind for kind in ["step", "stl", "svg"]}})+ result = [measure(check, shapes) for check in project["checks"]]+ Part.export([objects[part["object"]] for part in project["parts"]], os.path.join(output, "part.step"))+ assembly = Part.Shape()+ assembly.read(os.path.join(output, "part.step"))+ data = solid(assembly, "Assembly STEP reimport")+ if data["solids"] != len(project["parts"]):+ raise ValueError("STEP assembly does not contain the declared manufactured parts")+ MeshPart.meshFromShape(Shape=assembly, LinearDeflection=0.05, AngularDeflection=0.1, Relative=False).write(+ os.path.join(output, "part.stl"))+ return {**data, "valid": True, "closed": True, "designChecked": True,+ "requirementsPassed": all(check["passed"] for check in result),+ "checks": result, "parts": reports,+ "freecadVersion": ".".join(App.Version()[:3])}+ finally:+ App.closeDocument(document.Name)diff --git a/store/agents/freecad/skills/freecad/scripts/handoff.py b/store/agents/freecad/skills/freecad/scripts/handoff.pynew file mode 100644index 000000000..69bd0956d--- /dev/null+++ b/store/agents/freecad/skills/freecad/scripts/handoff.py@@ -0,0 +1,135 @@+"""Portable, allowlisted source bundle and a report of actual CAD measurements."""+import hashlib+import html+import json+import os+import stat+import zipfile+++def read_sources(project, workspace):+ sources = {}+ total = 0+ for name in project.get("sourceFiles", ["part.FCMacro", "design.json"]):+ path = workspace+ for component in name.split("/"):+ path = os.path.join(path, component)+ if stat.S_ISLNK(os.lstat(path).st_mode):+ raise ValueError("Bundle source cannot be a symlink: " + name)+ info = os.stat(path)+ if not stat.S_ISREG(info.st_mode) or info.st_size > 64 * 1024 * 1024:+ raise ValueError("Bundle source must be a regular file under 64 MiB: " + name)+ with open(path, "rb") as handle:+ data = handle.read(64 * 1024 * 1024 + 1)+ total += len(data)+ if len(data) > 64 * 1024 * 1024 or total > 128 * 1024 * 1024:+ raise ValueError("Source bundle exceeds its 128 MiB limit")+ sources[name] = data+ return sources+++def fingerprints(sources):+ return {name: hashlib.sha256(data).hexdigest() for name, data in sorted(sources.items())}+++def source_revision(sources):+ return hashlib.sha256(json.dumps(fingerprints(sources), sort_keys=True).encode("utf8")).hexdigest()+++def render_report(project, report):+ esc = html.escape+ passed = sum(check["passed"] for check in report["checks"])+ total = len(report["checks"])+ rows = []+ for check in report["checks"]:+ detail = json.dumps(check["measured"], indent=2, ensure_ascii=False)+ expected = json.dumps(check["requirement"], indent=2, ensure_ascii=False)+ rows.append('<tr><td><span class="%s">%s</span></td><td><strong>%s</strong><p>%s</p>'+ '<details><summary>Requirement and measurement</summary><h4>Required</h4><pre>%s</pre>'+ '<h4>Measured</h4><pre>%s</pre></details></td></tr>' %+ ("pass" if check["passed"] else "fail", "PASS" if check["passed"] else "FAIL",+ esc(check["id"]), esc(check["reason"]), esc(expected), esc(detail)))+ cards = []+ for part in report["parts"]:+ links = ' '.join('<a href="%s" download>%s ↓</a>' % (esc(path), kind.upper()) for kind, path in part["files"].items())+ cards.append('<article class="part"><div><h3>%s</h3><p>%s · quantity %s</p></div>'+ '<a href="%s"><img src="%s" alt="Projected reference drawing of %s"></a>'+ '<p class="dimensions">%s mm</p><p>%.2f cm³ · %s mesh triangles · STEP and STL reimports checked</p>'+ '<p class="downloads">%s</p><p>%s</p></article>' %+ (esc(part["label"]), esc(part["material"]), part.get("quantity", 1),+ esc(part["files"]["svg"]), esc(part["files"]["svg"]), esc(part["label"]),+ ' × '.join('%.3f' % d for d in part["boundsMM"]), part["volumeMM3"] / 1000,+ part["meshTriangles"], links, esc(part.get("notes", ""))))+ def items(field, fallback):+ return '<ul>' + ''.join('<li>%s</li>' % esc(value) for value in project.get(field, [fallback])) + '</ul>'+ source_rows = ''.join('<tr><td>%s</td><td><code>%s</code></td></tr>' % (esc(name), digest)+ for name, digest in report["sources"].items())+ bundle = '<a class="primary" href="project.zip" download>Download editable project + deliverables ↓</a>' if report["requirementsPassed"] else '<p class="fail">Some requirements failed. No release bundle was created.</p>'+ return '''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">+<title>''' + esc(project["title"]) + ''' · FreeCAD handoff</title>+<style>+:root{color-scheme:light;--ink:#182e3c;--muted:#596e78;--line:#d5e0e4;--blue:#185bb1;--paper:#f3f6f7}+*{box-sizing:border-box}body{margin:0;color:var(--ink);background:var(--paper);font:16px/1.6 system-ui,sans-serif}+main{max-width:1140px;margin:auto;padding:44px 32px 70px}.eyebrow{font:12px ui-monospace,monospace;letter-spacing:.15em;color:var(--blue)}+h1{font-size:clamp(30px,5vw,56px);line-height:1.1;letter-spacing:-.04em;max-width:900px;margin:16px 0 24px}h2{font-size:25px;margin:0 0 18px}h3{margin:0;font-size:20px}+p{margin:8px 0;color:var(--muted)}.brief{max-width:800px;white-space:pre-wrap}.primary{display:inline-block;background:var(--blue);color:#fff;padding:14px 20px;border-radius:8px;margin:22px 0;text-decoration:none;font-weight:600}+.summary{display:flex;gap:28px;flex-wrap:wrap;padding:22px 0;margin-bottom:24px;border-bottom:1px solid var(--line)}.summary strong{font-size:24px;display:block}.summary span{font-size:13px;color:var(--muted)}+section{margin-top:30px;background:white;border:1px solid var(--line);border-radius:12px;padding:28px}.parts{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,390px),1fr));gap:20px}+.part{border:1px solid var(--line);border-radius:10px;overflow:hidden;padding:22px}.part img{width:100%;display:block;margin:12px 0}.part p{font-size:13px}.part .dimensions{font:600 19px ui-monospace,monospace;color:var(--ink)}+a{color:var(--blue)}.downloads{display:flex;flex-wrap:wrap;gap:20px}table{border-collapse:collapse;width:100%}td{vertical-align:top;border-bottom:1px solid var(--line);padding:17px 8px}td:first-child{width:90px}+.pass,.fail{font:600 12px ui-monospace,monospace;white-space:nowrap}.pass{color:#176c44}.fail{color:#b3261e}details{font-size:13px}summary{cursor:pointer;color:var(--blue)}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:var(--paper);padding:12px;border-radius:6px}+.caution{border-left:4px solid #d89938;background:#fffaf0;padding:18px 22px;margin:24px 0}.caution p{color:#77501d}code{font:12px ui-monospace,monospace;overflow-wrap:anywhere}.hashes{table-layout:fixed;font-size:12px}.hashes td:first-child{width:35%;overflow-wrap:anywhere}+@media(max-width:600px){main{padding:26px 16px}section{padding:18px}.part{padding:14px}.summary{gap:18px}td{padding:12px 5px}.primary{font-size:14px}section h2{font-size:22px}}+@media print{body{background:white}main{padding:0}section,.part{break-inside:avoid}.primary{display:none}details{display:block}}+</style><main><div class="eyebrow">FREECAD / MEASURED BUILD</div><h1>''' + esc(project["title"]) + '''</h1>+<p class="brief">''' + esc(project["brief"]) + '''</p>''' + bundle + '''+<div class="summary"><div><strong>''' + str(passed) + ' / ' + str(total) + '''</strong><span>specified checks passed</span></div>+<div><strong>''' + str(len(report["parts"])) + '''</strong><span>individually exported parts</span></div>+<div><strong>mm</strong><span>design units</span></div><div><strong>''' + esc(report["freecadVersion"]) + '''</strong><span>FreeCAD runtime</span></div></div>+<div class="caution"><strong>Checked geometry, not a physical test</strong><p>These checks verify only the requirements below. They do not certify strength, wall thickness everywhere, process suitability or real-world fit. Review material, tolerances, orientation, supports and hardware before manufacturing.</p></div>+<section><h2>Your parts</h2><p>STEP keeps assembly coordinates. Each STL is translated to the positive octant; its orientation is unchanged. Review orientation in your slicer.</p><div class="parts">''' + ''.join(cards) + '''</div>+<p class="downloads"><a href="../part.step" download>Assembly STEP ↓</a><a href="../part.FCStd" download>Native FreeCAD document ↓</a><a href="../part.stl" download>Assembly mesh ↓</a></p></section>+<section><h2>Requirements, measured</h2><p>Measurements are made on the reopened native solids. Individual STEP files are reimported and checked for valid solids, volume, position and dimensions. STL files are reimported and checked for closed meshes and dimensions.</p><table>''' + ''.join(rows) + '''</table><p><a href="checks.json" download>Download measurement receipt ↓</a></p></section>+<section><h2>Assembly and hardware</h2>''' + items("assembly", "Assembly steps have not been supplied; obtain them before making the design.") + items("hardware", "No hardware has been specified.") + '''</section>+<section><h2>Assumptions to review</h2>''' + items("assumptions", "Manufacturing assumptions have not been supplied.") + '''</section>+<section><h2>Keep editing it</h2><p>The ZIP contains the named source files, native document, exports and standalone build tools. Extract it to a new folder. With Node 20+ and FreeCAD installed, run <code>node tools/build.mjs</code> from that folder. Set <code>FREECAD_BIN</code> for a nonstandard FreeCAD installation.</p>+<p>Open this saved report directly, or run <code>node tools/serve-handoff.mjs</code> for a local download page. This report describes the saved build, not subsequent edits.</p><p>The macro and its inputs are the parametric source. The native file may contain generated solids rather than a fully constrained Sketcher feature history. Only run macros you trust.</p><p>Source revision <code>''' + report["sourceRevision"] + '''</code></p>+<details><summary>Included source files and SHA-256 fingerprints</summary><table class="hashes">''' + source_rows + '''</table></details></section></main></html>'''+++def write_handoff(project, report, sources, output, tools):+ directory = os.path.join(output, "handoff")+ os.makedirs(directory, exist_ok=True)+ report["sources"] = fingerprints(sources)+ report["sourceRevision"] = source_revision(sources)+ with open(os.path.join(directory, "checks.json"), "w", encoding="utf8") as handle:+ json.dump(report, handle, indent=2, allow_nan=False)+ with open(os.path.join(directory, "index.html"), "w", encoding="utf8") as handle:+ handle.write(render_report(project, report))+ if not report["requirementsPassed"]:+ return+ with zipfile.ZipFile(os.path.join(directory, "project.zip"), "w", compression=zipfile.ZIP_DEFLATED) as archive:+ for name, data in sorted(sources.items()):+ archive.writestr(name, data)+ for name in ["build.mjs", "runner.py", "design.py", "geometry.py", "handoff.py", "serve-handoff.mjs", "LICENSE"]:+ archive.write(os.path.join(tools, name), "tools/" + name)+ for name in ["part.step", "part.stl", "part.FCStd"]:+ archive.write(os.path.join(output, name), name)+ for root, dirs, files in os.walk(directory, followlinks=False):+ for name in files:+ if name == "project.zip":+ continue+ path = os.path.join(root, name)+ if os.path.islink(path):+ raise ValueError("Generated bundle cannot contain symlinks")+ archive.write(path, os.path.relpath(path, output))+ archive.writestr("REBUILD.txt", "Extract this project. Install Node 20+ and FreeCAD.\n"+ "From the extracted folder run: node tools/build.mjs\n"+ "Set FREECAD_BIN to your FreeCADCmd binary if it is not detected.\n"+ "Edit part.FCMacro and the named source inputs, not the generated exports.\n"+ "Review design.json against your measurements; never weaken a requirement merely to pass.\n"+ "The saved project contains executable Python. Run only trusted source.\n"+ "Open handoff/index.html for the measurements, part files and assumptions.\n")+ bad = archive.testzip()+ if bad is not None:+ raise ValueError("Project archive failed CRC verification: " + bad)diff --git a/store/agents/freecad/skills/freecad/scripts/runner.py b/store/agents/freecad/skills/freecad/scripts/runner.pyindex cb1cc6595..72d6a25ee 100644--- a/store/agents/freecad/skills/freecad/scripts/runner.py+++ b/store/agents/freecad/skills/freecad/scripts/runner.py@@ -2,22 +2,40 @@import osimport jsonimport runpy+import sysimport FreeCAD as Appimport Part+tools = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, tools)+from design import validate+from geometry import export_project, solid+from handoff import read_sources, fingerprints, write_handoff+workspace = os.environ["HARNESS_WORKSPACE"]output = os.environ["HARNESS_BUILD_DIR"]+sys.path.insert(1, workspace)+project = None+contract = os.path.join(workspace, "design.json")+if os.path.exists(contract):+ if os.path.getsize(contract) > 1024 * 1024:+ raise ValueError("design.json exceeds 1 MiB")+ with open(contract, encoding="utf8") as handle:+ project = validate(json.load(handle))+ sources = read_sources(project, workspace)runpy.run_path(os.path.join(workspace, "part.FCMacro"), run_name="__main__")-shape = Part.Shape()-shape.read(os.path.join(output, "part.step"))-shape.check(True)-if not shape.isValid() or not shape.isClosed() or not shape.Solids or shape.Volume <= 0:- raise RuntimeError("Reimported STEP does not contain closed, valid solids")-bounds = shape.BoundBox-report = {"valid": True, "closed": True, "solids": len(shape.Solids),- "volumeMM3": shape.Volume, "areaMM2": shape.Area,- "boundsMM": [bounds.XLength, bounds.YLength, bounds.ZLength],- "freecadVersion": ".".join(App.Version()[:3])}+if project:+ report = export_project(project, os.path.join(output, "part.FCStd"), output)+ if fingerprints(read_sources(project, workspace)) != fingerprints(sources):+ raise ValueError("Source changed during the build; rebuild from the current saved inputs")+ write_handoff(project, report, sources, output, tools)+else:+ # Legacy projects still render, but have no claim of checked design requirements.+ shape = Part.Shape()+ shape.read(os.path.join(output, "part.step"))+ report = {**solid(shape, "Reimported STEP"), "valid": True, "closed": True,+ "designChecked": False, "requirementsPassed": False,+ "checks": [], "parts": [], "freecadVersion": ".".join(App.Version()[:3])}with open(os.path.join(output, "geometry.json"), "w", encoding="utf8") as handle:- json.dump(report, handle, indent=2)+ json.dump(report, handle, indent=2, allow_nan=False)print("HARNESS_GEOMETRY_VERIFIED")diff --git a/store/agents/freecad/skills/freecad/scripts/serve-handoff.mjs b/store/agents/freecad/skills/freecad/scripts/serve-handoff.mjsnew file mode 100644index 000000000..b9c02ab2d--- /dev/null+++ b/store/agents/freecad/skills/freecad/scripts/serve-handoff.mjs@@ -0,0 +1,57 @@+// A loopback-only download page. Never serves a workspace directory listing or+// arbitrary source files; the user-selected source bundle is an explicit export.+import {createServer} from 'node:http';+import {lstat, readFile, realpath} from 'node:fs/promises';+import {join, resolve, sep, extname} from 'node:path';+import {fileURLToPath} from 'node:url';++const allowed = /^(?:part\.(?:step|stl|FCStd)|handoff\/(?:index\.html|checks\.json|project\.zip|parts\/[A-Za-z][A-Za-z0-9_-]{0,63}\.(?:step|stl|svg)))$/;+const types = {'.html':'text/html; charset=utf-8', '.json':'application/json; charset=utf-8', '.svg':'image/svg+xml', '.zip':'application/zip', '.step':'model/step', '.stl':'model/stl', '.FCStd':'application/octet-stream'};++export async function serve(workspace, port=0) {+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('Port must be an integer from 0 to 65535');+ const root = await realpath(resolve(workspace));+ const server = createServer(async (request, response) => {+ const actualPort = server.address().port;+ if (![`127.0.0.1:${actualPort}`, `localhost:${actualPort}`].includes(request.headers.host)) {+ response.writeHead(403).end('Loopback host required'); return;+ }+ if (!['GET','HEAD'].includes(request.method)) { response.writeHead(405, {Allow:'GET, HEAD'}).end(); return; }+ try {+ const path = decodeURIComponent(new URL(request.url, `http://127.0.0.1:${actualPort}`).pathname);+ if (path === '/') { response.writeHead(302, {Location:'/handoff/index.html'}).end(); return; }+ const name = path.slice(1);+ if (!allowed.test(name)) { response.writeHead(404).end('Not a handoff artifact'); return; }+ let target = root;+ for (const component of name.split('/')) {+ target = join(target, component);+ if ((await lstat(target)).isSymbolicLink()) throw new Error('Symlink artifacts are not served');+ }+ if (!(await realpath(target)).startsWith(root + sep)) throw new Error('Artifact is outside the workspace');+ const bytes = await readFile(target);+ const extension = extname(name);+ const headers = {+ 'Content-Type':types[extension], 'Content-Length':bytes.length, 'Cache-Control':'no-store',+ 'X-Content-Type-Options':'nosniff', 'Cross-Origin-Resource-Policy':'same-origin',+ 'Content-Security-Policy':"default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",+ };+ if (!['.html','.svg'].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 FreeCAD handoff: http://127.0.0.1:${server.address().port}/handoff/index.html`);+ console.log('This page describes the last successful build. Rebuild after edits. Ctrl-C stops this local server.');+ const close = () => server.close(() => process.exit(0));+ process.on('SIGINT', close); process.on('SIGTERM', close);+ } catch (error) { console.error(error.message); process.exitCode = 1; }+}diff --git a/store/agents/freecad/store.json b/store/agents/freecad/store.jsonindex 793c1465e..e83019efc 100644--- a/store/agents/freecad/store.json+++ b/store/agents/freecad/store.json@@ -1,17 +1,17 @@{- "listed": false,"homepage": "https://freecad.org","upstream": "https://github.com/FreeCAD/FreeCAD","license": "MIT",- "tagline": "Parametric 3D modeling with verified STEP exports",+ "tagline": "From your measurements to checked, editable custom parts","screenshots": [- "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/freecad/starter.jpg"+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/freecad/bracket.jpg",+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/freecad/handoff.jpg"],"examples": [{- "prompt": "Build the Pocket enclosure with its vented lid and export validated STEP solids.",- "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/freecad/starter.jpg",- "caption": "Pocket · editable enclosure and two closed STEP solids"+ "prompt": "Build a bench bracket with a 60 mm mounting pattern. Check the hole positions and screwdriver access, then give me the part files and an editable project.",+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/freecad/bracket.jpg",+ "caption": "Bench bracket · measured holes and tool access, individual exports and portable source"}]}diff --git a/store/agents/freecad/template/design.json b/store/agents/freecad/template/design.jsonnew file mode 100644index 000000000..346de2dbf--- /dev/null+++ b/store/agents/freecad/template/design.json@@ -0,0 +1,37 @@+{+ "spec": 1,+ "title": "Desk sensor enclosure",+ "brief": "A desktop enclosure for a 65 × 40 × 1.6 mm PCB with a 12 mm component envelope. Support the board on rails, leave at least 2 mm above the components, provide a cable opening and an easily removable lift-off lid. These are example measurements, not a discovered board.",+ "units": "mm",+ "sourceFiles": ["part.FCMacro", "dimensions.json", "design.json"],+ "parts": [+ {"id": "base", "object": "Base", "label": "Enclosure base", "material": "Prototype plastic; select material before fabrication", "quantity": 1, "notes": "The rails support the PCB but do not positively fasten it. Review the board's underside and the chosen print process."},+ {"id": "lid", "object": "Lid", "label": "Lift-off lid", "material": "Prototype plastic; select material before fabrication", "quantity": 1, "notes": "A locating lid, not a latch or a seal. Review print orientation and fit compensation in the slicer."}+ ],+ "references": ["Board", "Components", "Cable"],+ "assumptions": [+ "All measurements are millimetres. Example dimensions must be replaced with the user's measured part or board data.",+ "The model is a dry, indoor prototype. No ingress, thermal, electrical or structural performance has been tested.",+ "Nominal 0.3 mm locating-lip gap and 0.4 mm cable clearance are design inputs, not guaranteed as-printed fit.",+ "The board has an unobstructed underside where it rests on the two rails. Check the actual component layout.",+ "The reference drawing shows projected geometry and overall dimensions, not complete production tolerances."+ ],+ "assembly": [+ "Inspect the base and lid; remove process residue and review the mating surfaces before fitting anything.",+ "Place the PCB on the two rails, align the cable with its opening, then lower the locating lid.",+ "Do not force the board or lid. Measure a fit coupon or revise the saved clearances if the fabrication process requires it."+ ],+ "hardware": ["No fasteners or locking hardware are included; this is a lift-off desktop enclosure."],+ "checks": [+ {"id": "base-envelope", "type": "bounds", "part": "Base", "size": [72.8, 47.8, 23.4], "origin": [-36.4, -23.9, 0], "tolerance": 0.02, "reason": "Meet the specified outer envelope and assembly origin."},+ {"id": "lid-envelope", "type": "bounds", "part": "Lid", "size": [72.8, 47.8, 4.2], "origin": [-36.4, -23.9, 21.4], "tolerance": 0.03, "reason": "Keep the lid in its assembled position, including its locating lip."},+ {"id": "measured-board", "type": "bounds", "part": "Board", "size": [65, 40, 1.6], "origin": [-32.5, -20, 5.8], "reason": "Use the supplied board dimensions and its rail-supported location."},+ {"id": "component-envelope", "type": "bounds", "part": "Components", "size": [65, 40, 12], "origin": [-32.5, -20, 7.4], "reason": "Retain the required component keep-out, rather than shrinking it to make a fit check pass."},+ {"id": "board-does-not-intersect-base", "type": "no-overlap", "parts": ["Base", "Board"], "reason": "The board may rest on the rails but must not penetrate the enclosure."},+ {"id": "components-clear-base", "type": "clearance", "parts": ["Base", "Components"], "minimum": 1, "reason": "Keep at least 1 mm around the nominal component envelope."},+ {"id": "components-clear-lid", "type": "clearance", "parts": ["Lid", "Components"], "minimum": 2, "reason": "Leave at least 2 mm above the component envelope, including near the lid lip."},+ {"id": "assembled-parts-do-not-intersect", "type": "no-overlap", "parts": ["Base", "Lid"], "reason": "The lid must seat without intersecting the base in the nominal model."},+ {"id": "cable-location", "type": "bounds", "part": "Cable", "size": [10, 10.4, 5], "origin": [6, -27.9, 7.5], "reason": "Keep the requested cable envelope at the measured connector position."},+ {"id": "cable-clearance", "type": "clearance", "parts": ["Base", "Cable"], "minimum": 0.4, "reason": "The actual opening must clear the specified cable envelope on every side."}+ ]+}diff --git a/store/agents/freecad/template/dimensions.json b/store/agents/freecad/template/dimensions.jsonnew file mode 100644index 000000000..ddcdbd709--- /dev/null+++ b/store/agents/freecad/template/dimensions.json@@ -0,0 +1,21 @@+{+ "board_length": 65,+ "board_width": 40,+ "board_thickness": 1.6,+ "wall": 2.4,+ "floor": 2.8,+ "side_clearance": 1.5,+ "support_height": 3,+ "component_height": 12,+ "roof_clearance": 2,+ "lid_thickness": 2.2,+ "lip_height": 2,+ "lip_wall": 1.2,+ "lid_gap": 0.3,+ "corner_radius": 4.5,+ "port_width": 10,+ "port_height": 5,+ "port_clearance": 0.4,+ "port_x": 11,+ "port_z": 10+}diff --git a/store/agents/freecad/template/part.FCMacro b/store/agents/freecad/template/part.FCMacroindex 6c0f9c299..f34f4bffc 100644--- a/store/agents/freecad/template/part.FCMacro+++ b/store/agents/freecad/template/part.FCMacro@@ -1,80 +1,85 @@-# Pocket / a parametric two-piece electronics enclosure, millimetres.-# Build with build-part.sh; exports a real STEP assembly, mesh and FreeCAD document.-# Edit dimensions here, then rebuild. Clearances are design inputs, not certified fit.+# A measured enclosure with a lift-off lid. Millimetres; edit dimensions.json.+# The build runner reopens this native document and exports only declared parts.+import json+import mathimport osimport FreeCAD as Appimport Part-import MeshPart-length, width, height = 92.0, 60.0, 26.0-wall, floor, corner_radius = 2.4, 2.8, 6.0-lid_thickness, lip_height, clearance = 2.4, 2.0, 0.3-screw_diameter, boss_radius, boss_inset = 3.4, 4.4, 9.0-vent_count, vent_width, vent_length = 7, 2.2, 22.0+workspace = os.environ.get("HARNESS_WORKSPACE", os.getcwd())+outdir = os.environ.get("HARNESS_BUILD_DIR", workspace)+with open(os.path.join(workspace, "dimensions.json"), encoding="utf8") as handle:+ p = json.load(handle)+for key, value in p.items():+ if isinstance(value, bool) or not isinstance(value, (float, int)) or not math.isfinite(value):+ raise ValueError("Dimension " + key + " must be a finite number in millimetres")+board_l, board_w, board_t = p["board_length"], p["board_width"], p["board_thickness"]+wall, floor = p["wall"], p["floor"]+side, support = p["side_clearance"], p["support_height"]+component_h, roof = p["component_height"], p["roof_clearance"]+lid_t, lip_h, lip_wall, lip_gap = p["lid_thickness"], p["lip_height"], p["lip_wall"], p["lid_gap"]+inner_l, inner_w = board_l + 2 * side, board_w + 2 * side+length, width = inner_l + 2 * wall, inner_w + 2 * wall+height = floor + support + board_t + component_h + roof + lip_h+radius = p["corner_radius"]+assert min(board_l, board_w) >= 20 and min(board_t, support, component_h, roof, lid_t, lip_h, lip_wall, lip_gap) > 0+assert min(wall, floor) >= 1.2 and side >= 0.5 and radius > wall + lip_gap + lip_wall+assert radius < min(length, width) / 4 and lip_gap < side and lip_wall < wall+assert p["port_width"] > 0 and p["port_height"] > 0 and p["port_clearance"] > 0+assert abs(p["port_x"]) + p["port_width"] / 2 + p["port_clearance"] < inner_l / 2 - radius+assert p["port_z"] - p["port_height"] / 2 - p["port_clearance"] > floor+assert p["port_z"] + p["port_height"] / 2 + p["port_clearance"] < height - lip_h-assert min(length, width) > 2 * (boss_inset + boss_radius)-assert height > floor + 6 and 1.2 <= wall < corner_radius < min(length, width) / 2-assert min(floor, lid_thickness) >= 1.2 and 0 < clearance < wall-assert screw_diameter / 2 < boss_radius and vent_count >= 1-outdir = os.environ.get("HARNESS_BUILD_DIR", os.getcwd())-doc = App.newDocument("Pocket")+doc = App.newDocument("MeasuredEnclosure")-def rounded_box(l, w, h, radius):- shape = Part.makeBox(l, w, h, App.Vector(-l/2, -w/2, 0))- vertical = [edge for edge in shape.Edges if edge.BoundBox.ZLength > h - 1e-7- and edge.BoundBox.XLength < 1e-7 and edge.BoundBox.YLength < 1e-7]- return shape.makeFillet(radius, vertical)-shell = rounded_box(length, width, height, corner_radius)-cavity = rounded_box(length-2*wall, width-2*wall, height, corner_radius-wall)+def rounded_box(l, w, h, r):+ shape = Part.makeBox(l, w, h, App.Vector(-l / 2, -w / 2, 0))+ edges = [edge for edge in shape.Edges if edge.BoundBox.ZLength > h - 1e-7+ and edge.BoundBox.XLength < 1e-7 and edge.BoundBox.YLength < 1e-7]+ return shape.makeFillet(r, edges)+++base = rounded_box(length, width, height, radius)+cavity = rounded_box(inner_l, inner_w, height, radius - wall)cavity.translate(App.Vector(0, 0, floor))-shell = shell.cut(cavity)-positions = [(x, y) for x in [-length/2+boss_inset, length/2-boss_inset]- for y in [-width/2+boss_inset, width/2-boss_inset]]-for x, y in positions:- boss = Part.makeCylinder(boss_radius, height-floor-3, App.Vector(x, y, floor-0.01))- hole = Part.makeCylinder(screw_diameter/2, height, App.Vector(x, y, floor))- shell = shell.fuse(boss).cut(hole)-# A cable opening in the near wall, intentionally open to the cavity.-shell = shell.cut(Part.makeBox(12, wall+0.2, 7, App.Vector(-6, -width/2-0.1, floor+3)))-shell = shell.removeSplitter()+base = base.cut(cavity)+# Two rails support the PCB from below. No promise of screw fastening or latching.+for y in [-board_w / 2, board_w / 2 - 2]:+ base = base.fuse(Part.makeBox(board_l, 2, support + 0.02, App.Vector(-board_l / 2, y, floor - 0.02)))+opening_w = p["port_width"] + 2 * p["port_clearance"]+opening_h = p["port_height"] + 2 * p["port_clearance"]+opening = Part.makeBox(opening_w, wall + 0.2, opening_h,+ App.Vector(p["port_x"] - opening_w / 2, -width / 2 - 0.1, p["port_z"] - opening_h / 2))+base = base.cut(opening).removeSplitter()-lid = rounded_box(length, width, lid_thickness, corner_radius)-lip_outer = rounded_box(length-2*(wall+clearance), width-2*(wall+clearance), lip_height,- corner_radius-wall-clearance)-lip_inner = rounded_box(length-2*(2*wall+clearance), width-2*(2*wall+clearance), lip_height+0.2,- max(0.5, corner_radius-2*wall-clearance))+lid = rounded_box(length, width, lid_t, radius)+lid.translate(App.Vector(0, 0, height))+lip_outer = rounded_box(inner_l - 2 * lip_gap, inner_w - 2 * lip_gap, lip_h + 0.02, radius - wall - lip_gap)+lip_inner = rounded_box(inner_l - 2 * (lip_gap + lip_wall), inner_w - 2 * (lip_gap + lip_wall),+ lip_h + 0.2, radius - wall - lip_gap - lip_wall)lip_inner.translate(App.Vector(0, 0, -0.1))lip = lip_outer.cut(lip_inner)-lip.translate(App.Vector(0, 0, lid_thickness-0.01))-lid = lid.fuse(lip)-for x, y in positions:- lid = lid.cut(Part.makeCylinder(screw_diameter/2, lid_thickness+lip_height+2, App.Vector(x, y, -1)))-for i in range(int(vent_count)):- x = (i-(vent_count-1)/2)*5.5- lid = lid.cut(Part.makeBox(vent_width, vent_length, lid_thickness+2,- App.Vector(x-vent_width/2, -vent_length/2, -1)))-lid = lid.removeSplitter()-lid.translate(App.Vector(length+14, 0, 0)) # laid out beside the base for inspection+lip.translate(App.Vector(0, 0, height - lip_h))+lid = lid.fuse(lip).removeSplitter()-features = []-for name, shape in [("Base", shell), ("Lid", lid)]:- if not shape.isValid() or not shape.isClosed() or len(shape.Solids) != 1:- raise RuntimeError(name + " is not one closed, valid solid")- shape.check(True) # raises on BRep errors; it does not return a boolean+board_z = floor + support+board = Part.makeBox(board_l, board_w, board_t, App.Vector(-board_l / 2, -board_w / 2, board_z))+payload = Part.makeBox(board_l, board_w, component_h,+ App.Vector(-board_l / 2, -board_w / 2, board_z + board_t))+plug = Part.makeBox(p["port_width"], wall + 8, p["port_height"],+ App.Vector(p["port_x"] - p["port_width"] / 2, -width / 2 - 4, p["port_z"] - p["port_height"] / 2))+for name, label, shape in [("Base", "Enclosure base", base), ("Lid", "Lift-off lid", lid),+ ("Board", "REFERENCE: measured PCB", board),+ ("Components", "REFERENCE: component envelope", payload),+ ("Cable", "REFERENCE: cable envelope", plug)]:feature = doc.addObject("Part::Feature", name)- feature.Label = name- feature.Shape = shape- features.append(feature)-parameters = doc.addObject("App::FeaturePython", "DesignInputs")-for name, value in [("Length",length),("Width",width),("Height",height),("Wall",wall),("Clearance",clearance)]:- parameters.addProperty("App::PropertyLength", name, "Dimensions", "Source parameter; edit the macro and rebuild")- setattr(parameters, name, value)+ feature.Label, feature.Shape = label, shape+inputs = doc.addObject("App::FeaturePython", "DesignInputs")+for name, value in p.items():+ prop = "".join(word.title() for word in name.split("_"))+ inputs.addProperty("App::PropertyLength", prop, "Source dimensions", "Edit dimensions.json and rebuild to regenerate geometry")+ setattr(inputs, prop, value)doc.recompute()doc.saveAs(os.path.join(outdir, "part.FCStd"))-Part.export(features, os.path.join(outdir, "part.step"))-mesh = MeshPart.meshFromShape(Shape=Part.makeCompound([shell,lid]),- LinearDeflection=0.1, AngularDeflection=0.15, Relative=False)-mesh.write(os.path.join(outdir, "part.stl"))App.closeDocument(doc.Name)-print("Exported Pocket: base + vented lid")diff --git a/store/agents/freecad/test/ACCEPTANCE.md b/store/agents/freecad/test/ACCEPTANCE.mdnew file mode 100644index 000000000..8d5743504--- /dev/null+++ b/store/agents/freecad/test/ACCEPTANCE.md@@ -0,0 +1,93 @@+# FreeCAD acceptance evidence++Rebuild reviewed on 2026-09-20 with **FreeCAD 1.1.3**, managed **Node 22.23.2**,+Python 3.9 for standard-library tests, and the actual shared CAD Viewer 0.5.1.+Native QA ran on macOS. This is functional and visual acceptance, not a physical+manufacturing test or a study with novice users.++## Native jobs, not just the starter++| Job | Verified outcome |+| --- | --- |+| Two-face bracket from an independent brief | One manufactured solid; 17 measurements cover dimensions, two orthogonal hole patterns, fixed references, sensor clearance, work envelope and four tool-access volumes. |+| Wrong spacing | Changing the model from 50 to 54 mm while preserving the 50 mm requirement fails all four bore checks. The previous STEP and ZIP remain byte-identical. |+| Substantive revision | Change the mounting pattern to 60 mm, overall height to 52 mm and back-hole height to 37 mm. Revise the corresponding brief/acceptance values, retain unrelated requirements and rebuild. |+| Obstructed access | Moving gussets inward causes tool-access checks to fail even when the new holes are correctly positioned. Moving the gussets clear produces a passing revision. |+| Independent project | Extract the generated ZIP into a new folder. Run its bundled `tools/build.mjs` with only Node and FreeCAD; match the source revision, measured volume and requirements. Unselected private notes and `.harness` history are absent. |+| Enclosure | Two individually exported solids and 10 checks cover PCB/component dimensions, actual clearances, cable position and assembled interference. Reference volumes do not enter the exported assembly. |+| In-flight source change | A macro that alters an included input during native execution cannot publish a handoff. |++Each STEP part is reimported and checked for valid closed solids, volume, size+and position. Each STL part is reimported and checked for a closed mesh and+dimensions. Assembly contacts do not cause false failures of valid individual+bodies; specified interference checks still reject intersecting volume.++The native kernel cases additionally test misplaced, undersized, oversized,+overlong and empty-space bore probes; contained solids mistaken for clearance;+minimum/maximum gaps; misplaced bounding boxes; touching assemblies; open+or empty shapes; and failed native features retaining a valid previous shape.+The bore check requires surrounding material as well as air. A failed or still+touched document feature prevents export, even if its old Shape remains valid.++## Delivery, safety and visual checks++The full package suite has **14 passing Node test cases**, including a runner+for **9 standard-library Python cases** and **7 real-kernel Python cases**.+Native checks are explicitly skipped without `FREECAD_BIN`; a skipped native+suite is not release proof. The ordinary package checks run in Experience CI.++Tests cover strict contract validation, source path/symlink restrictions,+explicit source selection, SHA-256 fingerprints, HTML escaping, portable-tool+license notices, archive integrity, stale native output and an active build lock.+The loopback download server tests allowed downloads, denied workspace files,+symlinks, unsupported methods and a hostile Host header.++Real browser checks at 1440 px and 390 px verify loaded drawings, no horizontal+overflow, every download link and no page errors. All three SVG projections'+actual bounds must match their labeled axes/dimensions. The STEP is loaded in+the real CAD Viewer; zoom/reset and captured output are checked. Screenshots+are then visually reviewed—the browser assertions alone are not visual QA.++This process caught and corrected a rotated front projection, obstructed tool+access after widening the mounting pattern, and enclosure corners with only+0.54 mm clearance where 1 mm was required. The requirement was retained and+the geometry was corrected.++## Reproduce++From the repository root:++```sh+node --test store/agents/freecad/test/*.test.mjs+FREECAD_BIN=/path/to/freecadcmd node --test store/agents/freecad/test/*.test.mjs+```++Set `FREECAD_QA_DIR` to an existing or new scratch directory to retain native+job outputs; otherwise tests clean up their own temporary directories. Keep+these tests away from a user's real project. Native jobs have bounded timeouts.+Run network-binding tests outside sandboxes that prohibit even loopback ports.++For browser QA, run the shared CAD Viewer against a retained job, then:++```sh+HARNESS_WORKSPACE=/path/to/retained-job \+CAD_VIEWER_URL='http://127.0.0.1:PORT/?file=part.step' \+PLAYWRIGHT_MODULE=/absolute/path/to/playwright/index.mjs \+node store/agents/freecad/test/visual.mjs+```++The helper starts its own restricted handoff server, captures desktop/mobile+pages, drawings and the actual STEP viewer, then closes its browser and server.+Visually inspect the resulting `.harness/visual/` images. Playwright is optional+developer tooling, not a runtime dependency of the harness.++## Limits and remaining validation++No printed/machined part, physical load, temperature, electrical safety, real+fastener joint or actual commercial sensor was tested. Fixtures use synthetic+acceptance briefs. Manufacturing allowances and appropriate professional+review remain necessary. The workflow supports arbitrary macros and named+solid references; these tests are not a claim that every possible model works.+The saved native file may use generated Part features rather than Sketcher+history. Reference SVGs are not complete toleranced fabrication drawings.+Browser QA is not a full desktop-agent or novice-user end-to-end study.diff --git a/store/agents/freecad/test/build.test.mjs b/store/agents/freecad/test/build.test.mjsindex 342abb326..ef2cb6478 100644--- a/store/agents/freecad/test/build.test.mjs+++ b/store/agents/freecad/test/build.test.mjs@@ -1,6 +1,6 @@import assert from 'node:assert/strict';import { test } from 'node:test';-import { mkdtemp, writeFile, readFile, rm } from 'node:fs/promises';+import { mkdtemp, writeFile, readFile, rm, mkdir } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';import { build } from '../skills/freecad/scripts/build.mjs';@@ -21,3 +21,14 @@ test('a successful CLI exit with no fresh STEP receipt cannot reuse an old artif}}finally{await rm(workspace,{recursive:true,force:true});}});++test('a second build cannot steal the active lock or replace its verdict', async () => {+ const workspace = await mkdtemp(join(tmpdir(), 'freecad-lock-test-'));+ try {+ await mkdir(join(workspace, '.harness/freecad-build.lock'), {recursive:true});+ const marker = '{"ready":false,"summary":"Active build owns this verdict"}\n';+ await writeFile(join(workspace, '.harness/verdict.json'), marker);+ await assert.rejects(() => build(workspace), /Another FreeCAD build/);+ assert.equal(await readFile(join(workspace, '.harness/verdict.json'), 'utf8'), marker);+ } finally { await rm(workspace, {recursive:true, force:true}); }+});diff --git a/store/agents/freecad/test/contract.test.mjs b/store/agents/freecad/test/contract.test.mjsnew file mode 100644index 000000000..60b9ed2ed--- /dev/null+++ b/store/agents/freecad/test/contract.test.mjs@@ -0,0 +1,10 @@+import assert from 'node:assert/strict';+import {test} from 'node:test';+import {spawnSync} from 'node:child_process';+import {fileURLToPath} from 'node:url';++test('saved design schema, explicit source allowlist and portable report', () => {+ const result = spawnSync('python3', [fileURLToPath(new URL('contract_test.py', import.meta.url))], {encoding:'utf8'});+ assert.equal(result.status, 0, result.error?.message || result.stderr);+ assert.match(result.stderr, /Ran 9 tests/);+});diff --git a/store/agents/freecad/test/contract_test.py b/store/agents/freecad/test/contract_test.pynew file mode 100644index 000000000..584c2f283--- /dev/null+++ b/store/agents/freecad/test/contract_test.py@@ -0,0 +1,124 @@+"""Fast schema, source-selection and handoff tests; no native CAD dependencies."""+import json+from pathlib import Path+import sys+import tempfile+import unittest+import zipfile++HERE = Path(__file__).resolve().parent+TOOLS = HERE.parent / "skills" / "freecad" / "scripts"+sys.path.insert(0, str(TOOLS))+from design import validate+from handoff import read_sources, fingerprints, source_revision, write_handoff+++def project():+ return json.loads((HERE / "fixtures" / "bench-bracket" / "design.json").read_text())+++class ContractTests(unittest.TestCase):+ def test_saved_jobs_validate(self):+ validate(project())+ validate(json.loads((HERE.parent / "template" / "design.json").read_text()))++ def test_rejects_unknown_fields_and_unmeasured_jobs(self):+ for change in [{"checks": []}, {"units": "inch"}, {"spec": True}, {"approved": True}, {"parts": []}]:+ with self.subTest(change=change), self.assertRaises(ValueError):+ validate({**project(), **change})++ def test_rejects_unsafe_or_generated_source_paths(self):+ for name in ["../secrets", "/tmp/file", ".env", "a/.env", "a/../b", "a//b", "a\\b", "C:/x", "a\nfile",+ "handoff/checks.json", "tools/design.py", "PART.STEP", "part.FCStd", "REBUILD.txt"]:+ data = project()+ data["sourceFiles"].append(name)+ with self.subTest(name=name), self.assertRaises(ValueError):+ validate(data)++ def test_requires_unique_names_and_sources(self):+ for mutate in [lambda p: p["parts"].append({**p["parts"][0], "id": "BRACKET", "object": "Other"}),+ lambda p: p["references"].append("Bracket"),+ lambda p: p["sourceFiles"].append("DESIGN.json"),+ lambda p: p["checks"].append(p["checks"][0]),+ lambda p: p["sourceFiles"].remove("design.json")]:+ data = project()+ mutate(data)+ with self.assertRaises(ValueError):+ validate(data)++ def test_checks_reject_invalid_numbers_names_and_types(self):+ for fields in [{"type": []}, {"part": "Missing"}, {"size": [True, 20, 30]}, {"size": [1, 2, float("nan")]},+ {"size": [1, 0, 3]}, {"size": [1, 2]}, {"tolerance": -1}, {"tolerence": .1}]:+ data = project()+ data["checks"][0].update(fields)+ with self.subTest(fields=fields), self.assertRaises(ValueError):+ validate(data)++ def test_bore_and_clearance_constraints(self):+ for fields in [{"axis": [0, 0, 0]}, {"length": .01}, {"diameter": 0}, {"wall": .01}, {"tolerance": 4}]:+ data = project()+ data["checks"][1].update(fields)+ with self.subTest(fields=fields), self.assertRaises(ValueError):+ validate(data)+ data = project()+ data["checks"][6]["maximum"] = 4+ with self.assertRaises(ValueError):+ validate(data)++ def test_source_allowlist_and_fingerprints(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ data = project()+ for name in data["sourceFiles"]:+ (root / name).write_text(name)+ (root / "private-notes.txt").write_text("Do not bundle")+ sources = read_sources(data, directory)+ self.assertEqual(set(sources), set(data["sourceFiles"]))+ self.assertEqual(source_revision(sources), source_revision(dict(reversed(list(sources.items())))))+ changed = {**sources, "dimensions.json": b"new dimensions"}+ self.assertNotEqual(source_revision(sources), source_revision(changed))+ self.assertNotEqual(fingerprints(sources)["dimensions.json"], fingerprints(changed)["dimensions.json"])++ def test_symlink_source_or_parent_is_rejected(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ (root / "real").mkdir()+ (root / "real" / "data.json").write_text("{}"); (root / "linked").symlink_to(root / "real", target_is_directory=True)+ (root / "direct.json").symlink_to(root / "real" / "data.json")+ for path in ["direct.json", "linked/data.json"]:+ with self.subTest(path=path), self.assertRaisesRegex(ValueError, "symlink"):+ read_sources({"sourceFiles": [path]}, directory)++ def test_handoff_is_escaped_and_bundle_is_portable_allowlist(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ data = project()+ data["title"] = '<script>alert("unsafe")</script>'+ part = {**data["parts"][0], "boundsMM": [80, 40, 45], "volumeMM3": 1234,+ "meshTriangles": 200, "files": {"svg": "parts/bracket.svg", "step": "parts/bracket.step", "stl": "parts/bracket.stl"}}+ report = {"parts": [part], "checks": [{"passed": True, "id": "a", "reason": "A < B", "measured": {"actual": 1}, "requirement": {"expected": 1}}],+ "requirementsPassed": True, "freecadVersion": "test-fixture"}+ (root / "handoff" / "parts").mkdir(parents=True)+ for name in ["part.step", "part.stl", "part.FCStd", "handoff/parts/bracket.svg", "handoff/parts/bracket.step", "handoff/parts/bracket.stl"]:+ (root / name).write_text("export fixture")+ (root / "secret.txt").write_text("not selected")+ sources = {"part.FCMacro": b"# source", "design.json": json.dumps(data).encode(), "dimensions.json": b"{}"}+ write_handoff(data, report, sources, directory, str(TOOLS))+ page = (root / "handoff" / "index.html").read_text()+ self.assertNotIn('<script>', page)+ self.assertIn('<script>', page)+ self.assertIn('A < B', page)+ with zipfile.ZipFile(root / "handoff" / "project.zip") as archive:+ names = archive.namelist()+ self.assertEqual(len(names), len(set(names)))+ self.assertNotIn("secret.txt", names)+ self.assertNotIn("handoff/project.zip", names)+ self.assertIn("tools/geometry.py", names)+ self.assertIn("tools/LICENSE", names)+ self.assertIn("REBUILD.txt", names)+ self.assertEqual(archive.read("part.FCMacro"), sources["part.FCMacro"])+ self.assertIsNone(archive.testzip())+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/store/agents/freecad/test/fixtures/bench-bracket/design.json b/store/agents/freecad/test/fixtures/bench-bracket/design.jsonnew file mode 100644index 000000000..02a421073--- /dev/null+++ b/store/agents/freecad/test/fixtures/bench-bracket/design.json@@ -0,0 +1,31 @@+{+ "spec": 1,+ "title": "Two-face bench bracket",+ "brief": "Make a prototype bracket for a small bench sensor: an 80 × 40 mm foot, 45 mm overall height and 5 mm material. Two 6.4 mm vertical bores are 50 mm apart at y=-7; two 4.5 mm horizontal bores use the same spacing, 30 mm above the foot. Leave the specified sensor envelope unobstructed. This is a fit prototype, not a rated structural mount.",+ "units": "mm",+ "sourceFiles": ["part.FCMacro", "dimensions.json", "design.json"],+ "parts": [{"id": "bracket", "object": "Bracket", "label": "Two-face bench bracket", "material": "Prototype plastic; process and grade not selected", "quantity": 1, "notes": "Two gussets connect the faces. Verify fastener/tool access and printed hole fit before installation."}],+ "references": ["Payload", "AvailableSpace", "BaseAccessLeft", "BaseAccessRight", "BackAccessLeft", "BackAccessRight"],+ "checks": [+ {"id": "overall-envelope", "type": "bounds", "part": "Bracket", "size": [80, 40, 45], "origin": [-40, -20, 0], "reason": "The bracket must fit the measured installation envelope."},+ {"id": "base-left-bore", "type": "bore", "part": "Bracket", "origin": [-25, -7, 0], "axis": [0, 0, 1], "diameter": 6.4, "length": 5, "wall": 2, "reason": "The first base mounting hole must match the bench pattern."},+ {"id": "base-right-bore", "type": "bore", "part": "Bracket", "origin": [25, -7, 0], "axis": [0, 0, 1], "diameter": 6.4, "length": 5, "wall": 2, "reason": "The second base hole must be 50 mm from the first."},+ {"id": "back-left-bore", "type": "bore", "part": "Bracket", "origin": [-25, 15, 30], "axis": [0, 1, 0], "diameter": 4.5, "length": 5, "wall": 2, "reason": "The sensor mounting hole must have the specified height and diameter."},+ {"id": "back-right-bore", "type": "bore", "part": "Bracket", "origin": [25, 15, 30], "axis": [0, 1, 0], "diameter": 4.5, "length": 5, "wall": 2, "reason": "The sensor mounting pattern requires 50 mm between centres."},+ {"id": "payload-envelope", "type": "bounds", "part": "Payload", "size": [50, 15, 10], "origin": [-25, -5, 25], "reason": "The clearance reference must represent the specified sensor envelope."},+ {"id": "payload-clearance", "type": "clearance", "parts": ["Bracket", "Payload"], "minimum": 5, "reason": "Keep at least 5 mm clear around the sensor envelope."},+ {"id": "work-envelope", "type": "bounds", "part": "AvailableSpace", "size": [100, 100, 100], "origin": [-50, -50, 0], "reason": "Keep the installation-space reference fixed to the acceptance brief."},+ {"id": "available-space", "type": "contains", "part": "AvailableSpace", "other": "Bracket", "reason": "The finished bracket must stay inside the available 100 mm work envelope."},+ {"id": "base-left-access-envelope", "type": "bounds", "part": "BaseAccessLeft", "size": [10, 10, 20], "origin": [-30, -12, 5], "reason": "Preserve the specified 10 mm diameter fastener/tool access above the left foot hole."},+ {"id": "base-right-access-envelope", "type": "bounds", "part": "BaseAccessRight", "size": [10, 10, 20], "origin": [20, -12, 5], "reason": "Preserve the specified fastener/tool access above the right foot hole."},+ {"id": "back-left-access-envelope", "type": "bounds", "part": "BackAccessLeft", "size": [10, 25, 10], "origin": [-30, -10, 25], "reason": "Preserve the specified 10 mm diameter access in front of the left sensor hole."},+ {"id": "back-right-access-envelope", "type": "bounds", "part": "BackAccessRight", "size": [10, 25, 10], "origin": [20, -10, 25], "reason": "Preserve the specified fastener/tool access in front of the right sensor hole."},+ {"id": "base-left-access", "type": "no-overlap", "parts": ["Bracket", "BaseAccessLeft"], "reason": "The gusset must not obstruct access to the left foot fastener."},+ {"id": "base-right-access", "type": "no-overlap", "parts": ["Bracket", "BaseAccessRight"], "reason": "The gusset must not obstruct access to the right foot fastener."},+ {"id": "back-left-access", "type": "no-overlap", "parts": ["Bracket", "BackAccessLeft"], "reason": "The gusset must not obstruct access to the left sensor fastener."},+ {"id": "back-right-access", "type": "no-overlap", "parts": ["Bracket", "BackAccessRight"], "reason": "The gusset must not obstruct access to the right sensor fastener."}+ ],+ "assumptions": ["Dimensions describe a synthetic acceptance brief, not a measured commercial sensor.", "No load, fatigue, temperature or electrical-safety qualification has been performed.", "Nominal bores must be checked against the selected process and actual fasteners."],+ "assembly": ["Review the STEP and individual drawing against your measurements.", "Make a fit prototype; check hole spacing, tool access and the sensor envelope.", "Use only after choosing appropriate material and verifying the actual loads and mounting surfaces."],+ "hardware": ["Fastener sizes and lengths require selection against the real bench and sensor; bore diameters alone do not define a safe joint."]+}diff --git a/store/agents/freecad/test/fixtures/bench-bracket/dimensions.json b/store/agents/freecad/test/fixtures/bench-bracket/dimensions.jsonnew file mode 100644index 000000000..429940317--- /dev/null+++ b/store/agents/freecad/test/fixtures/bench-bracket/dimensions.json@@ -0,0 +1,10 @@+{+ "width": 80,+ "depth": 40,+ "height": 45,+ "thickness": 5,+ "hole_spacing": 50,+ "base_bore": 6.4,+ "back_bore": 4.5,+ "back_hole_z": 30+}diff --git a/store/agents/freecad/test/fixtures/bench-bracket/part.FCMacro b/store/agents/freecad/test/fixtures/bench-bracket/part.FCMacronew file mode 100644index 000000000..873394401--- /dev/null+++ b/store/agents/freecad/test/fixtures/bench-bracket/part.FCMacro@@ -0,0 +1,35 @@+# New-job fixture: a two-face mounting bracket, not an enclosure derivative.+import json+import os+import FreeCAD as App+import Part++with open(os.path.join(os.environ["HARNESS_WORKSPACE"], "dimensions.json")) as handle:+ p = json.load(handle)+width, depth, height, thickness = p["width"], p["depth"], p["height"], p["thickness"]+doc = App.newDocument("BenchBracket")+foot = Part.makeBox(width, depth, thickness, App.Vector(-width / 2, -depth / 2, 0))+back = Part.makeBox(width, thickness, height, App.Vector(-width / 2, depth / 2 - thickness, 0))+shape = foot.fuse(back)+for x in [-width / 2, width / 2 - 3]:+ wire = Part.makePolygon([App.Vector(x, -5, thickness), App.Vector(x, 15, thickness),+ App.Vector(x, 15, height - 10), App.Vector(x, -5, thickness)])+ shape = shape.fuse(Part.Face(wire).extrude(App.Vector(3, 0, 0)))+for x in [-p["hole_spacing"] / 2, p["hole_spacing"] / 2]:+ shape = shape.cut(Part.makeCylinder(p["base_bore"] / 2, thickness + 2, App.Vector(x, -7, -1)))+ shape = shape.cut(Part.makeCylinder(p["back_bore"] / 2, thickness + 2,+ App.Vector(x, depth / 2 - thickness - 1, p["back_hole_z"]), App.Vector(0, 1, 0)))+part = doc.addObject("Part::Feature", "Bracket")+part.Label, part.Shape = "Two-face bench bracket", shape.removeSplitter()+payload = doc.addObject("Part::Feature", "Payload")+payload.Shape = Part.makeBox(50, 15, 10, App.Vector(-25, -5, 25))+bed = doc.addObject("Part::Feature", "AvailableSpace")+bed.Shape = Part.makeBox(100, 100, 100, App.Vector(-50, -50, 0))+for side, x in [("Left", -p["hole_spacing"] / 2), ("Right", p["hole_spacing"] / 2)]:+ access = doc.addObject("Part::Feature", "BaseAccess" + side)+ access.Shape = Part.makeCylinder(5, 20, App.Vector(x, -7, thickness))+ access = doc.addObject("Part::Feature", "BackAccess" + side)+ access.Shape = Part.makeCylinder(5, 25, App.Vector(x, -10, p["back_hole_z"]), App.Vector(0, 1, 0))+doc.recompute()+doc.saveAs(os.path.join(os.environ["HARNESS_BUILD_DIR"], "part.FCStd"))+App.closeDocument(doc.Name)diff --git a/store/agents/freecad/test/geometry_cases.py b/store/agents/freecad/test/geometry_cases.pynew file mode 100644index 000000000..155f39b6e--- /dev/null+++ b/store/agents/freecad/test/geometry_cases.py@@ -0,0 +1,77 @@+"""Native acceptance tests: executed by FreeCADCmd, never mocked geometry."""+import json+import os+import sys+import unittest++sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "skills", "freecad", "scripts"))+import FreeCAD as App+import Part+from geometry import measure, solid, recompute_document+++class GeometryTests(unittest.TestCase):+ def check_shape(self, kind, shapes, **fields):+ return measure({"id": "probe", "type": kind, "reason": "Independent native test", **fields}, shapes)["passed"]++ def test_bore_requires_opening_and_material(self):+ plate = Part.makeBox(40, 30, 5)+ hole = Part.makeCylinder(3.2, 7, App.Vector(10, 10, -1))+ shapes = {"Plate": plate.cut(hole)}+ spec = dict(part="Plate", origin=[10, 10, 0], axis=[0, 0, 1], diameter=6.4, length=5, wall=2)+ self.assertTrue(self.check_shape("bore", shapes, **spec))+ for change in [{"origin": [12, 10, 0]}, {"diameter": 7}, {"diameter": 5}, {"origin": [60, 10, 0]}, {"length": 8}]:+ with self.subTest(change=change):+ self.assertFalse(self.check_shape("bore", shapes, **{**spec, **change}))++ def test_containment_is_not_clearance(self):+ shapes = {"Outer": Part.makeBox(20, 20, 20), "Inner": Part.makeBox(2, 2, 2, App.Vector(5, 5, 5))}+ self.assertTrue(self.check_shape("contains", shapes, part="Outer", other="Inner"))+ self.assertFalse(self.check_shape("clearance", shapes, parts=["Outer", "Inner"], minimum=1))+ self.assertFalse(self.check_shape("no-overlap", shapes, parts=["Outer", "Inner"]))+ self.assertFalse(self.check_shape("contains", shapes, part="Inner", other="Outer"))++ def test_measured_gap_and_maximum(self):+ shapes = {"Left": Part.makeBox(10, 10, 10), "Right": Part.makeBox(10, 10, 10, App.Vector(12, 0, 0))}+ self.assertTrue(self.check_shape("clearance", shapes, parts=["Left", "Right"], minimum=2, maximum=2))+ self.assertFalse(self.check_shape("clearance", shapes, parts=["Left", "Right"], minimum=3))+ self.assertFalse(self.check_shape("clearance", shapes, parts=["Left", "Right"], minimum=0, maximum=1))++ def test_bounds_include_position(self):+ shapes = {"Box": Part.makeBox(10, 20, 30, App.Vector(-5, 2, 3))}+ self.assertTrue(self.check_shape("bounds", shapes, part="Box", size=[10, 20, 30], origin=[-5, 2, 3]))+ self.assertFalse(self.check_shape("bounds", shapes, part="Box", size=[10, 20, 30], origin=[0, 0, 0]))+ self.assertFalse(self.check_shape("bounds", shapes, part="Box", size=[11, 20, 30]))++ def test_contacting_parts_are_valid_but_not_fused(self):+ left, right = Part.makeBox(10, 10, 10), Part.makeBox(10, 10, 10, App.Vector(10, 0, 0))+ self.assertEqual(solid(Part.makeCompound([left, right]), "Contact assembly")["solids"], 2)+ self.assertTrue(self.check_shape("no-overlap", {"Left": left, "Right": right}, parts=["Left", "Right"]))++ def test_empty_and_open_shapes_fail(self):+ for shape in [Part.Shape(), Part.makePlane(10, 10)]:+ with self.assertRaises(ValueError):+ solid(shape, "Invalid")++ def test_failed_recompute_cannot_reuse_a_valid_previous_shape(self):+ class BrokenFeature:+ def execute(self, obj):+ raise RuntimeError("Intentional failed feature")+ doc = App.newDocument("FailedFeatureTest")+ try:+ obj = doc.addObject("Part::FeaturePython", "Broken")+ obj.Shape = Part.makeBox(10, 10, 10)+ obj.Proxy = BrokenFeature()+ with self.assertRaisesRegex(ValueError, "failed or uncomputed features"):+ recompute_document(doc)+ self.assertTrue(obj.Shape.isValid())+ self.assertFalse(obj.isValid())+ finally:+ App.closeDocument(doc.Name)+++result = unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(GeometryTests))+if not result.wasSuccessful():+ raise RuntimeError("Native geometry tests failed")+with open(os.environ["FREECAD_TEST_RESULT"], "w") as handle:+ json.dump({"passed": result.testsRun, "freecad": App.Version()[:3]}, handle)diff --git a/store/agents/freecad/test/native.test.mjs b/store/agents/freecad/test/native.test.mjsnew file mode 100644index 000000000..e53533fc0--- /dev/null+++ b/store/agents/freecad/test/native.test.mjs@@ -0,0 +1,149 @@+// Opt in with FREECAD_BIN=/path/to/freecadcmd. These checks use real FreeCAD,+// STEP reimports and extracted bundles. A fake CLI cannot satisfy this suite.+import assert from 'node:assert/strict';+import {test} from 'node:test';+import {spawnSync} from 'node:child_process';+import {mkdtemp, cp, readFile, writeFile, mkdir, rm, access} from 'node:fs/promises';+import {tmpdir} from 'node:os';+import {join, resolve} from 'node:path';+import {fileURLToPath} from 'node:url';+import {createHash} from 'node:crypto';+import {build} from '../skills/freecad/scripts/build.mjs';++const here = fileURLToPath(new URL('.', import.meta.url));+const bin = process.env.FREECAD_BIN;+const options = {skip: !bin && 'Set FREECAD_BIN to run real native acceptance tests', timeout: 900_000};+const json = async path => JSON.parse(await readFile(path, 'utf8'));+const save = async (path, data) => writeFile(path, JSON.stringify(data, null, 2) + '\n');+const digest = async path => createHash('sha256').update(await readFile(path)).digest('hex');+async function scratch(prefix) {+ const root = process.env.FREECAD_QA_DIR || tmpdir();+ await mkdir(root, {recursive:true});+ return mkdtemp(join(root, prefix));+}+async function cleanup(path) {+ if (!process.env.FREECAD_QA_DIR) await rm(path, {recursive:true, force:true});+ else console.log('Native QA files retained:', path);+}++test('real kernel detects incorrect holes, interference, containment and dimensions', options, async () => {+ const work = await scratch('freecad-kernel-');+ try {+ const resultFile = join(work, 'result.json');+ const result = spawnSync(bin, ['--user-cfg', join(work, 'user.cfg'), '--system-cfg', join(work, 'system.cfg'), join(here, 'geometry_cases.py')],+ {encoding:'utf8', timeout:300_000, env:{...process.env, FREECAD_TEST_RESULT:resultFile}});+ await writeFile(join(work, 'native.log'), (result.stdout || '') + (result.stderr || ''));+ assert.equal(result.status, 0, result.error?.message || result.stderr);+ const report = await json(resultFile);+ assert.equal(report.passed, 7);+ console.log('Real FreeCAD kernel cases:', report);+ } finally { await cleanup(work); }+});++test('new bracket job: measured handoff, broken revision, substantive revision, standalone rebuild', options, async () => {+ const work = await scratch('freecad-bracket-');+ try {+ await cp(join(here, 'fixtures/bench-bracket'), work, {recursive:true});+ // Unselected workspace files must never leak into the downloadable project.+ await writeFile(join(work, 'private-notes.txt'), 'not a source input');+ const first = await build(work, {bin});+ assert.equal(first.parts.length, 1);+ assert.equal(first.checks.length, 17);+ assert.equal(first.requirementsPassed, true);+ assert.equal((await json(join(work, '.harness/verdict.json'))).ready, true);+ for (const [actual, expected] of first.parts[0].boundsMM.map((n, i) => [n, [80, 40, 45][i]])) assert.ok(Math.abs(actual-expected) < .001);+ assert.ok(first.parts[0].meshTriangles > 100);+ const originalZip = await digest(join(work, 'handoff/project.zip'));+ const originalStep = await digest(join(work, 'part.step'));++ const dims = await json(join(work, 'dimensions.json'));+ dims.hole_spacing = 54; // Intentional mistake: the agreed requirement remains 50.+ await save(join(work, 'dimensions.json'), dims);+ await assert.rejects(() => build(work, {bin}), /design requirement\(s\) failed/);+ assert.equal(await digest(join(work, 'handoff/project.zip')), originalZip);+ assert.equal(await digest(join(work, 'part.step')), originalStep);+ const failed = await json(join(work, '.harness/failed-design.json'));+ const failedIds = failed.checks.filter(c => !c.passed).map(c => c.id);+ for (const id of ['back-left-bore', 'back-right-bore', 'base-left-bore', 'base-right-bore']) assert.ok(failedIds.includes(id));+ const verdict = await json(join(work, '.harness/verdict.json'));+ assert.equal(verdict.ready, false);+ assert.equal(verdict.artifact, 'candidate.step');+ await access(join(work, 'candidate.step'));++ // New brief: 60 mm mounting pattern; raise the sensor holes and overall back.+ dims.hole_spacing = 60; dims.height = 52; dims.back_hole_z = 37;+ const design = await json(join(work, 'design.json'));+ design.brief = 'Revised two-face bench bracket: 80 × 40 mm foot, 52 mm overall height, 5 mm material. Use 60 mm mounting-hole centre spacing on both faces; the back holes are 37 mm above the foot. Preserve the sensor envelope and the 10 mm diameter fastener/tool access volumes. This is a fit prototype, not a rated structural mount.';+ design.checks.find(c => c.id === 'overall-envelope').size[2] = 52;+ for (const check of design.checks.filter(c => c.type === 'bore')) {+ check.origin[0] = check.id.includes('left') ? -30 : 30;+ if (check.id.startsWith('back')) check.origin[2] = 37;+ check.reason = check.reason.replace('50 mm', '60 mm');+ }+ for (const check of design.checks.filter(c => c.id.endsWith('-access-envelope'))) {+ check.origin[0] = check.id.includes('left') ? -35 : 25;+ if (check.id.startsWith('back')) check.origin[2] = 32;+ }+ await save(join(work, 'dimensions.json'), dims);+ await save(join(work, 'design.json'), design);+ // A wider pattern can put otherwise correct bores behind a gusset. Checking+ // bores alone is insufficient: protect the declared fastener/tool volumes.+ const macro = await readFile(join(work, 'part.FCMacro'), 'utf8');+ await writeFile(join(work, 'part.FCMacro'), macro.replace('[-width / 2, width / 2 - 3]', '[-width / 2 + 5, width / 2 - 9]'));+ await assert.rejects(() => build(work, {bin}), /design requirement\(s\) failed/);+ const obstructed = await json(join(work, '.harness/failed-design.json'));+ assert.ok(obstructed.checks.some(c => c.id.endsWith('-access') && !c.passed));+ assert.equal(await digest(join(work, 'handoff/project.zip')), originalZip);+ await writeFile(join(work, 'part.FCMacro'), macro);+ const revised = await build(work, {bin});+ assert.equal(revised.requirementsPassed, true);+ assert.ok(Math.abs(revised.parts[0].boundsMM[2]-52) < .001);+ assert.notEqual(revised.sourceRevision, first.sourceRevision);+ assert.equal(await digest(join(revised.previousArtifacts, 'handoff/project.zip')), originalZip);++ const extracted = join(work, 'independent-copy');+ const unzip = spawnSync('python3', ['-m', 'zipfile', '-e', join(work, 'handoff/project.zip'), extracted], {encoding:'utf8'});+ assert.equal(unzip.status, 0, unzip.stderr);+ await assert.rejects(access(join(extracted, 'private-notes.txt')), {code:'ENOENT'});+ await assert.rejects(access(join(extracted, '.harness')), {code:'ENOENT'});+ const standalone = spawnSync(process.execPath, [join(extracted, 'tools/build.mjs')], {+ cwd:extracted, encoding:'utf8', timeout:300_000,+ env:{PATH:process.env.PATH, FREECAD_BIN:resolve(bin)},+ });+ assert.equal(standalone.status, 0, standalone.stderr);+ const reopened = await json(join(extracted, '.harness/geometry.json'));+ assert.equal(reopened.sourceRevision, revised.sourceRevision);+ assert.equal(reopened.requirementsPassed, true);+ assert.ok(Math.abs(reopened.volumeMM3-revised.volumeMM3) < .00001);+ for (const name of ['part.FCStd', 'handoff/parts/bracket.step', 'handoff/parts/bracket.stl', 'handoff/parts/bracket.svg']) await access(join(extracted, name));+ console.log('Bracket: original + wrong spacing + obstructed access + corrected revision + independent ZIP rebuild verified');+ } finally { await cleanup(work); }+});++test('two-part enclosure validates the actual board, component and cable envelopes', options, async () => {+ const work = await scratch('freecad-enclosure-');+ try {+ await cp(join(here, '../template'), work, {recursive:true});+ const report = await build(work, {bin});+ assert.equal(report.requirementsPassed, true);+ assert.equal(report.parts.length, 2);+ assert.equal(report.solids, 2); // Reference volumes must not be exported.+ assert.equal(report.checks.length, 10);+ assert.ok(report.checks.find(c => c.id === 'components-clear-base').measured.minimumDistanceMM >= 1);+ assert.ok(report.checks.find(c => c.id === 'components-clear-lid').measured.minimumDistanceMM >= 1.999);+ for (const part of report.parts) assert.equal(part.stepReimported, true);+ } finally { await cleanup(work); }+});++test('source mutation during native execution cannot publish a mixed revision', options, async () => {+ const work = await scratch('freecad-mutation-');+ try {+ await cp(join(here, 'fixtures/bench-bracket'), work, {recursive:true});+ const macro = await readFile(join(work, 'part.FCMacro'), 'utf8');+ await writeFile(join(work, 'part.FCMacro'), macro + '\nwith open(os.path.join(os.environ["HARNESS_WORKSPACE"], "dimensions.json"), "a") as changed:\n changed.write("\\n")\n');+ await assert.rejects(() => build(work, {bin}), /fresh geometry receipt/);+ assert.match(await readFile(join(work, '.harness/build.log'), 'utf8'), /Source changed during the build/);+ assert.equal((await json(join(work, '.harness/verdict.json'))).ready, false);+ await assert.rejects(access(join(work, 'handoff/project.zip')), {code:'ENOENT'});+ } finally { await cleanup(work); }+});diff --git a/store/agents/freecad/test/serve.test.mjs b/store/agents/freecad/test/serve.test.mjsnew file mode 100644index 000000000..9ef10e471--- /dev/null+++ b/store/agents/freecad/test/serve.test.mjs@@ -0,0 +1,42 @@+import assert from 'node:assert/strict';+import {test} from 'node:test';+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/freecad/scripts/serve-handoff.mjs';++test('handoff server exposes only generated downloads on loopback', async () => {+ const work = await mkdtemp(join(tmpdir(), 'freecad-downloads-'));+ let server;+ try {+ await mkdir(join(work, 'handoff/parts'), {recursive:true});+ await writeFile(join(work, 'handoff/index.html'), '<h1>Saved handoff</h1>');+ await writeFile(join(work, 'handoff/project.zip'), 'fixture zip');+ await writeFile(join(work, 'design.json'), 'private inputs');+ await symlink(join(work, 'design.json'), join(work, 'handoff/parts/escape.svg'));+ server = await serve(work);+ assert.equal(server.address().address, '127.0.0.1');+ const url = `http://127.0.0.1:${server.address().port}`;+ const page = await fetch(url + '/');+ assert.equal(page.status, 200);+ assert.match(await page.text(), /Saved handoff/);+ assert.match(page.headers.get('content-security-policy'), /default-src 'none'/);+ const zip = await fetch(url + '/handoff/project.zip');+ assert.equal(zip.headers.get('content-disposition'), 'attachment; filename="project.zip"');+ assert.equal(await zip.text(), 'fixture zip');+ for (const path of ['/design.json', '/handoff/../design.json', '/.harness/build.log', '/handoff/parts/escape.svg', '/handoff/parts/', '/%ZZ']) {+ assert.equal((await fetch(url + path)).status,404,path);+ }+ assert.equal((await fetch(url + '/', {method:'POST'})).status,405);+ assert.equal(await (await fetch(url + '/', {method:'HEAD'})).text(),'');+ const status = await new Promise((resolve,reject) => {+ const req = request(url, {headers:{host:'untrusted.example'}}, res => { res.resume(); resolve(res.statusCode); });+ req.on('error',reject); req.end();+ });+ assert.equal(status,403);+ } finally {+ if (server) await new Promise(resolve => server.close(resolve));+ await rm(work, {recursive:true, force:true});+ }+});diff --git a/store/agents/freecad/test/toolchain.test.mjs b/store/agents/freecad/test/toolchain.test.mjsindex a717934af..c8e25f823 100644--- a/store/agents/freecad/test/toolchain.test.mjs+++ b/store/agents/freecad/test/toolchain.test.mjs@@ -23,6 +23,11 @@ function tempDir() {function run(script, { cwd = here, env = {} } = {}) {const merged = { ...process.env }+ delete merged.FREECAD_BIN+ delete merged.FREECAD_TOOLCHAIN+ const isolatedPackage = tempDir()+ mkdirSync(join(isolatedPackage, 'toolchain'))+ merged.HARNESS_DSH_DIR = isolatedPackagefor (const [key, value] of Object.entries(env)) if (value === null) delete merged[key]; else merged[key] = valueconst result = spawnSync(join(here, script), { cwd, env: merged, encoding: 'utf8' })return { code: result.status, stdout: result.stdout, stderr: result.stderr }@@ -74,7 +79,7 @@ test('init seeds the first verdict and the initialized marker', () => {assert.match(readFileSync(join(workspace, '.harness-initialized'), 'utf8'), new RegExp(manifest.id.replace('/', '/')))})-test('build-part.sh exports an artifact and flips the verdict, exactly as SKILL.md writes it', () => {+test('build-part.sh supports legacy geometry without claiming the design is checked', () => {const skill = readFileSync(join(here, 'skills/freecad/SKILL.md'), 'utf8')const command = 'sh "$FREECAD_SKILLS/freecad/scripts/build-part.sh"'assert.ok(skill.includes(command), 'SKILL.md should document the one-stop build command')@@ -86,12 +91,13 @@ test('build-part.sh exports an artifact and flips the verdict, exactly as SKILL.writeFileSync(join(workspace, 'part.FCMacro'), 'import FreeCAD as App\nimport Part\n')const result = spawnSync('/bin/sh', ['-c', command], {cwd: workspace,- env: { ...process.env, FREECAD_SKILLS: join(here, 'skills'), PATH: `${dir}:${dirname(process.execPath)}:/usr/bin:/bin`, HARNESS_WORKSPACE: workspace },+ env: { ...process.env, FREECAD_BIN: bin, FREECAD_SKILLS: join(here, 'skills'), PATH: `${dir}:${dirname(process.execPath)}:/usr/bin:/bin`, HARNESS_WORKSPACE: workspace },encoding: 'utf8',})assert.equal(result.status, 0, result.stderr)assert.equal(existsSync(join(workspace, 'part.step')), true)const verdict = JSON.parse(readFileSync(join(workspace, '.harness/verdict.json'), 'utf8'))- assert.equal(verdict.ready, true)+ assert.equal(verdict.ready, false)+ assert.match(verdict.summary, /design.json/)assert.equal(verdict.artifact, 'part.step')})diff --git a/store/agents/freecad/test/visual.mjs b/store/agents/freecad/test/visual.mjsnew file mode 100644index 000000000..bfba56846--- /dev/null+++ b/store/agents/freecad/test/visual.mjs@@ -0,0 +1,76 @@+// Optional real-browser QA. Point HARNESS_WORKSPACE at a successful native job,+// CAD_VIEWER_URL at its running shared viewer and PLAYWRIGHT_MODULE at Playwright.+import assert from 'node:assert/strict';+import {createHash} from 'node:crypto';+import {mkdir, readFile} from 'node:fs/promises';+import {join, resolve} from 'node:path';+import {serve} from '../skills/freecad/scripts/serve-handoff.mjs';++const {chromium} = await import(process.env.PLAYWRIGHT_MODULE || 'playwright');+assert.ok(process.env.HARNESS_WORKSPACE, 'HARNESS_WORKSPACE is required');+assert.ok(process.env.CAD_VIEWER_URL, 'CAD_VIEWER_URL is required');+const workspace = resolve(process.env.HARNESS_WORKSPACE);+const output = resolve(process.env.FREECAD_VISUAL_DIR || join(workspace, '.harness/visual'));+await mkdir(output, {recursive:true});+const report = JSON.parse(await readFile(join(workspace, 'handoff/checks.json'), 'utf8'));+const server = await serve(workspace);+let browser;+try {+ browser = await chromium.launch({headless:true});+ const base = `http://127.0.0.1:${server.address().port}`;+ for (const [name, width] of [['desktop',1440], ['mobile',390]]) {+ const page = await browser.newPage({viewport:{width,height:1000}});+ const errors = [];+ page.on('pageerror', e => errors.push(e.message));+ await page.goto(base + '/handoff/index.html');+ await page.locator('h1').waitFor();+ await page.locator('img').evaluateAll(images => Promise.all(images.map(image => image.decode())));+ assert.equal(await page.locator('.pass').count(), report.checks.length);+ assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth));+ for (const href of await page.locator('a').evaluateAll(links => links.map(a=>a.href))) {+ assert.equal((await page.request.get(href)).status(),200,href);+ }+ await page.screenshot({path:join(output,`handoff-${name}.png`),fullPage:true});+ await page.screenshot({path:join(output,`handoff-${name}-top.png`)});+ for (const part of report.parts) {+ await page.goto(base + '/handoff/' + part.files.svg);+ const projections = await page.locator('.projection').evaluateAll(groups => groups.map(group => {+ const box = group.getBBox();+ return {actual:[box.width,box.height],expected:[Number(group.dataset.width),Number(group.dataset.height)]};+ }));+ assert.equal(projections.length,3);+ for (const projection of projections) for (let i=0;i<2;i++) {+ assert.ok(Math.abs(projection.actual[i]-projection.expected[i]) < .001, JSON.stringify(projection));+ }+ await page.screenshot({path:join(output,`${part.id}-drawing-${name}.png`)});+ }+ assert.deepEqual(errors,[]);+ await page.close();+ }+ const handoffPage = await browser.newPage({viewport:{width:1600,height:1000}});+ await handoffPage.goto(base + '/handoff/index.html');+ await handoffPage.locator('img').evaluateAll(images => Promise.all(images.map(image => image.decode())));+ await handoffPage.screenshot({path:join(output,'handoff.jpg'),type:'jpeg',quality:88});+ await handoffPage.close();+ const page = await browser.newPage({viewport:{width:1600,height:1000}});+ const errors = [];+ page.on('pageerror', e => errors.push(e.message));+ await page.goto(process.env.CAD_VIEWER_URL);+ await page.locator('canvas').first().waitFor();+ await page.waitForTimeout(7000);+ const before = await page.screenshot();+ await page.getByRole('button',{name:'Zoom in',exact:true}).click();+ await page.waitForTimeout(400);+ const after = await page.screenshot();+ assert.notEqual(createHash('sha256').update(before).digest('hex'),createHash('sha256').update(after).digest('hex'));+ await page.getByRole('button',{name:'Reset view',exact:true}).click();+ await page.waitForTimeout(400);+ await page.screenshot({path:join(output,'cad-viewer.png')});+ await page.screenshot({path:join(output,'cad-viewer.jpg'),type:'jpeg',quality:88});+ assert.deepEqual(errors,[]);+ console.log('PASS: desktop/mobile report, all downloads, geometrically aligned projections and interactive actual CAD viewer.');+ console.log('Visually inspect the captures in',output,'before release.');+} finally {+ if (browser) await browser.close();+ await new Promise(resolve => server.close(resolve));+}diff --git a/store/showcase/freecad/bracket.jpg b/store/showcase/freecad/bracket.jpgnew file mode 100644index 000000000..8cffb3774Binary files /dev/null and b/store/showcase/freecad/bracket.jpg differdiff --git a/store/showcase/freecad/handoff.jpg b/store/showcase/freecad/handoff.jpgnew file mode 100644index 000000000..006743908Binary files /dev/null and b/store/showcase/freecad/handoff.jpg differdiff --git a/store/tools/REAL-WORKFLOWS.md b/store/tools/REAL-WORKFLOWS.mdnew file mode 100644index 000000000..778eb85ed--- /dev/null+++ b/store/tools/REAL-WORKFLOWS.md@@ -0,0 +1,36 @@+# Twelve-harness rebuild++User direction, 2026-09-20: improve all twelve withdrawn packages, **one at a+time**, then list each only when it meets the real-workflow bar. This supersedes+the earlier proposal to park ten permanently. No parallel agents.++## Release gate++For each package, implement a complete path from a new user's brief or files to+an independently usable result. Test a substantive revision, saved-project+reopening, exports and meaningful failure cases. Keep source editable. Record+exact checks, actual tool versions, known limits and any remaining user/hardware+validation. A passing starter or a new screenshot alone is not release evidence.++Do not flip `listed` for uncompleted packages. Publish through the normal PR and+catalog workflow and verify the live catalog after each accepted release.++| Order | Package | Intended complete workflow | Status |+| --- | --- | --- | --- |+| 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, individual parts and practice exports | Not started; unlisted |+| 3 | openscad | Dimensions and fabrication constraints → parametric parts, verified variants and usable exports | Not started; unlisted |+| 4 | orca-slicer | User mesh and explicit machine/material profiles → compared slicing options and reviewed toolpath handoff | Not started; unlisted |+| 5 | data-studio | User data and a question → saved analysis, source-linked results and repeatable report | Not started; unlisted |+| 6 | gis | User geographic data and a decision → reproducible spatial analysis and exported results | Not started; unlisted |+| 7 | web-studio | User application brief → useful app with durable data and a runnable handoff | Not started; unlisted |+| 8 | sheet-docs | User document/data requirements → editable, recalculated and reconciled deliverables | Not started; unlisted |+| 9 | godot-studio | Original game brief → revised gameplay, verified playable build and distributable project | Not started; unlisted |+| 10 | quantum-studio | User circuit/experiment question → reproducible experiment, quantitative checks and portable program | Not started; unlisted |+| 11 | firmware-studio | Target device and behavior → tested logic, compiled firmware and explicit hardware-test handoff | Not started; unlisted |+| 12 | home-assistant | Actual entities and desired behavior → engine-validated automation and approved installation workflow | Not started; unlisted |++The final two require special care: a simulated device is not tested hardware,+and local YAML parsing is not a real Home Assistant run. Obtain authorization+before accessing a user's physical device or live installation. Missing access+must be reported rather than converted into a passing release claim.diff --git a/store/viewers/isolated-web-viewer/README.md b/store/viewers/isolated-web-viewer/README.mdindex bc83794b3..99ce9c2b0 100644--- a/store/viewers/isolated-web-viewer/README.md+++ b/store/viewers/isolated-web-viewer/README.md@@ -48,5 +48,9 @@ node --test --test-concurrency=1 store/viewers/isolated-web-viewer/test/*.test.mnode --test --test-concurrency=1 store/tools/browser/*.test.mjs```+## Credit and stewardship+Built for OpenHarness by its contributors, MIT. No third-party packages are required to serve a-preview; Playwright is separate optional verification tooling.+preview; Playwright is separate optional verification tooling. See [LICENSE](LICENSE)+for the wrapper's terms. Wrapper issues belong in OpenHarness; upstream maintainers+are welcome to discuss stewardship. No upstream endorsement is implied.