Skip to content

You can now generate creatures directly within your project. Drop the open-source into your Agent, and start prompting what you want.

JavaScript

anyCreature 1.3.1

Ariescar44e1abc2c7fe
diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml
new file mode 100644
index 0000000..859a4a9
--- /dev/null
+++ b/.github/workflows/smoke.yml
@@ -0,0 +1,26 @@
+# Fresh-machine smoke test: exactly what a new user runs, on a machine that has
+# nothing. Catches the "works on the author's machine" class — the missing
+# Playwright browser shipped in 1.2.0 because no fresh environment ever ran
+# setup before push.
+name: smoke
+on: [push, pull_request]
+jobs:
+ fresh-install:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@v4
+ - name: sync check (versions agree, promised features present, no leaks)
+ run: python3 harness/synccheck.py
+ - uses: actions/setup-node@v4
+ with: { node-version: 20 }
+ - uses: actions/setup-python@v5
+ with: { python-version: '3.11' }
+ - name: setup.sh (deps + calibration + browser probe)
+ run: bash setup.sh
+ - name: engine builds the example
+ run: node engine/cli.js example/wolf.json /tmp/wolf.glb
+ - name: render tools run (silhouettes)
+ run: node harness/silmetrics.mjs /tmp/wolf.glb /tmp/sil
+ - name: delivery packs (viewer + heroes)
+ run: python3 harness/deliver.py /tmp/wolf.glb /tmp/del wolf --title "CI Wolf"
diff --git a/.gitignore b/.gitignore
index e03878a..1e3c9e2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -23,6 +23,10 @@ gate.json
# the operator's saved signature (personal data — never commit)
.anyCreature.json
+# synccheck's site-specific leak words: the names of whatever else lives on
+# this disk. They belong in the scanner, never in the tree it scans.
+harness/leakwords.local.txt
+
# scratch / editor / OS
*.log
*.bak
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9e5e62b..ae5e5ed 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,115 @@
# CHANGELOG
+## 1.3.1 — reads are scored, the brief is checked, and everything computable is computed
+
+**Publishing hands back two links, and the second one is checked (2026-09-03)**
+
+- The server answers a successful upload with a claim link as well as the one-time
+ takedown code. This build matched exactly one field name, `manage_token`, so the claim
+ link never reached anyone using it. `harness/publish.mjs` now reads a family of names,
+ classifies each value by shape, and keeps the first link AND the first code — neither
+ may shadow the other: the link lists the model under your account (Google sign-in, dies
+ once used), the code removes it (one-time, cannot be re-issued, no sign-in).
+- The claim link is GETted before it is handed over. `claim_link_live` is `true`, `false`
+ or `null` (could not ask — which changes nothing, since the upload just succeeded through
+ the same network). On `false`, `harness/ship.py` gives `claim_fallback_url` instead: the
+ standing claim page, which takes the same key. Nobody is ever sent to a 404.
+- `cards/04_SHIP.md` has a row for `manage_kind: both`, which is the normal case.
+- Behaviour is verified against all four shapes the server can answer with.
+
+**The blind read**
+
+- Gate 1 is SCORED by rank and view count (`harness/identity.py`) instead of demanding one exact word: rank R passes if the noun reached R in at least R views, and the requirement loosens by one view per repair round. 3 of 4 views, the brief's identity view among them.
+- A round builds TWO OPPOSITE POLES of one named axis, not one attempt and not three near-copies. `round.py` measures how far apart they sit on the mass-layout ruler and refuses to spend a reader on one design built twice (floor 0.25).
+- ONE reader does a whole gate — choosing the winner AND confirming 3-of-4 — in a single batch.
+- On an identity FAIL, `identity.py` names the views not yet read and requires them to be tried before a rebuild.
+- The "wider or taller?" binding question is retired; the bump count and the canary remain.
+- Thumbnails are letterboxed, not squashed, so the proportion the reader sees is the proportion the file records.
+
+**Computed instead of read**
+
+- `harness/outline.py` produces silhouettes from the GEOMETRY — no browser in the LOW loop. Same camera, same masks, same measures, plus `iou_vs_prev` and mass-layout thirds.
+- `value_order` sorts every material by OKLab lightness on each build; whatever is brightest owns the eye, and anything within 0.05 L competes.
+- `contrast_adjacent` compares every part against the material of the thing it sits on; under 0.10 OKLab they read as one mass.
+- `thinnest_px48` is information only and no longer blocks.
+- MID spends NO reader: both the isolated part read and the colour read are deleted, replaced by the two checks above.
+
+**The brief**
+
+- `harness/brief.py` checks the brief for PRESENCE, never content, and runs inside `round.py` at r1. Five slots plus the one exaggeration block when blank; the other four are noted.
+- Slots that name parts also name their CHAINS, and the r1 spec must contain them.
+- Material is not judged anywhere: no "what is it made of", no roughness words in the value plan.
+
+**The engine**
+
+- `soft_mass` — a volume that cannot break anywhere renders as a bean, and that is the DEFAULT. Blocked, with the fix in numbers; `"soft": true` opts a mass out.
+- `gait_direction` — a planted foot must sweep BACKWARD; a forward sweep is a walk cycle playing in reverse.
+- `root_drive` — a lunge must be driven on the skeleton ROOT, or the creature is nailed down by the end that did not move.
+- The L1–L8 shading stack moved into the engine (`engine/core/shade.js`) and runs on every build.
+- Every blocking message states the FIX with the number to apply, not just the fault.
+- `<out>.checks.json` is written on refused builds too.
+
+**The harness**
+
+- `harness/fit.py` makes a spec LEGAL before a round is spent on it. A refused build is refused for two different reasons: DESIGN (the shape does not read) and ARITHMETIC (a root ring is not buried, two bones came out the same length, the height is off). The engine already prints the exact correction for the arithmetic ones; `fit.py` reads them back, applies them, rebuilds and repeats. It never touches `balance`, `mesh_integrity`, `touch`, `part_seat` or any style threshold — those need a decision.
+- `root_containment` now names the CHAIN'S OWN root joint instead of the host joint it hangs from. Moving the host drags the chain with it, so the old advice could not converge; applying it repeatedly just walked the pair across the model.
+- One command per round (`harness/round.py`): build, render, measure, pre-check, one report.
+- `harness/gates.json` maps all 35 checks on five axes — enforce, when, by, kind, dept — and `gates.py` prints them. `stage` is a field: LOW/MID/HIGH are levels of refinement, not a fixed department order. `by` is A/B/C: which source produces the verdict.
+- `pwlaunch.mjs` finds a cached browser under `PLAYWRIGHT_BROWSERS_PATH` before any download; a build-number mismatch is not a missing browser.
+- `synccheck.py` guards the version strings, the promised features, the required files, duplicate measure definitions and the public/private boundary. Its site-specific leak words moved OUT of the script into `harness/leakwords.local.txt` (git-ignored, never packed) — a list of names you refuse to publish, written into a public file, publishes them. It also refuses a tree in which any shipped file points at a `docs/` page that stayed home: a dangling filename names the private document and no one can open it. And it refuses a tree that describes a version which is not out yet: saying a file behaves "identically to" an unreleased build announces that build, its feature set, and that it has users.
+- Iron law 3 is counted by `roundcheck.py`, not self-applied; iron law 9 — one creature, one agent, the reader is the only subagent.
+
+## 1.3.0 — the first-users release: joins verified, fresh installs survive
+
+Field reports (first two public days) split into two classes; both are closed here.
+
+Install class — "setup said OK, then everything broke"
+- **`setup.sh` now installs the browser** (`npx playwright install chromium`; skipped when `PW_CHROMIUM_PATH` is set) **and probes a real launch** (`harness/pwprobe.mjs`) before printing "calibrate OK". The npm package alone ships no browser, calibration never needed one, so 1.2.0's setup passed on a fresh machine and the FIRST silhouette died with a Playwright stack trace.
+- **All render tools share one launcher** (`harness/pwlaunch.mjs`): a missing browser now prints one actionable line — `run npx playwright install chromium` — never a stack.
+- **A hero failure no longer kills the delivery**: the GLB and viewer are the deliverable; heroes degrade to a warning with the fix printed.
+- `playwright` pinned (1.62.1); `setup.ps1` for Windows PowerShell; CI smoke workflow runs the whole fresh-user path (setup → build → silhouettes → delivery) on every push.
+- **`harness/synccheck.py` — the ship gatekeeper**: verifies VERSION == CHANGELOG, every promised feature is present in the shipping code, every file the cards point at exists, and no forbidden string leaks. Born from a real leak: two finished features existed in one working copy but not the one that got pushed. Run it before every push; CI runs it first.
+
+Field-report class — the first outside user, verbatim
+- **`hand` part type**: palm + four fingers + an opposable thumb from one `size` number (`curl`, `spread`, `fist: true` with the thumb wrapped across); built in ONE authoritative hand frame — "issues with hands, palms, fingers and especially thumb placement" was the top quality report, and improvised sphere-and-stick hands always shipped mittens. `paw` gains `"toes": 2..5`.
+- **Declared-height gate**: the spec carries `"height"` (metres); the build must land within ±15% or BLOCK, and the CLI now prints the built dimensions — "correct scaling is a skill completely missing".
+- **README gains the copy-paste agent prompt** — "how do u prompt the agent to use it in his VM exactly? thats missing in your readme". Verbatim block + three field-learned rules: don't invent a workflow prompt (it skips every gate), let the agent run setup itself (don't pre-bundle node_modules), image orders become a text brief first.
+- **Multi-leg gait doctrine** in HIGH: diagonal pairs for quadrupeds, alternating tripods/tetrapods for 6-8 legs, adjacent legs never in sync.
+- **The output contract is ENFORCED, not documented**: every GLB is checked against it the moment the engine writes it (a violating file is deleted, never left on disk), `deliver.py` re-checks the stamped bytes, and `publish.mjs` refuses to upload a file that fails — no card instruction, no human step. The contract: two chunks, zero trailing bytes, one embedded buffer, no URIs, no images at all, no compression extensions, semantic material names, convention bone names, metres/+Z, sane accessors, no paths or markup in any string. Creature names and signatures typed by a person are CLEANED at stamping (control characters, angle brackets, 80/60 caps) rather than failing a delivery. One implementation (`harness/glbcheck.mjs`, zero-dependency `checkGLB(bytes)`, ~1.4 ms) mirrored into the engine as `engine/core/contract.js` by `tools/sync-contract.mjs`; synccheck fails the build if the two drift. Verified against five hostile fixtures — ZIP tail, extra chunk, external URI, path leak, duplicate JSON keys — plus an end-to-end hostile spec whose build is refused. `docs/OUTPUT_CONTRACT.md` writes the same rules down for the community server, which rebuilds submissions independently (`docs/HANDOVER_sanitize.md`).
+- **Every GLB carries its birth certificate**: `asset.extras.source_spec` (the pristine authored spec — a second parse, since the in-memory spec is mutated by resolution) + `extras.parts` manifest (kind/type/name/material/host/join per piece). Extract → edit → recompile round-trips green. `embed_spec: false` opts out. On the CC0 community wall this makes every creature REMIXABLE by design.
+- **`harness/graft.py` — spec-level organ transplant**: takes two GLBs, copies a named part (plus its palette, and for membranes the rib chains, joints, attach/mirror entries and matching animation tracks, rebased onto the new host), rescales by the two declared heights, writes a fused spec. The normal gates judge the transplant — a graft that does not seat is BLOCKED, not shipped. Never touches meshes, so AO and whole-body shading re-bake coherently on the fused creature.
+- example/wolf.json now declares `"height": 1.45` (models best practice; enables graft auto-scaling).
+- **Reader verification — assume every reader is lazy**: every blind read (both LOW gates, every MID part read) now carries three traps — per-image binding questions checked against measured aspect/bump counts, one known-answer canary from `harness/canary/` shuffled into every batch, and shuffled neutral image labels. Any tripped trap voids the whole read. A reader that glances at one image and confabulates the rest can no longer pass.
+
+Colour portability (a creature published to a gallery came back white-and-black)
+- **The hue now lives in the material, not only in the vertices.** Until now every material shipped `baseColorFactor` white with the entire palette in COLOR_0, so any viewer that does not apply vertex colours rendered the creature pure white — reproduced here by stripping COLOR_0 from a build. The engine now splits the baked colour: `baseColorFactor` takes the per-channel MAXIMUM (the unoccluded colour) and COLOR_0 keeps the ratio (≤ 1, the AO and banding multiplier). Where COLOR_0 IS applied the result is identical — a controlled A/B measured a maximum per-channel difference of 5e-08 — and where it is not, the creature keeps its hues and loses only the shading.
+- Found while implementing it: dividing the colours in place corrupted them, because one vertex-colour array can be referenced from several vertices (flat fills, crease splits) and was scaled twice. The pass now builds new arrays; the A/B above is the proof.
+- **The colour ruler was blinded by the split, and is now calibrated.** The judge's albedo pass forced `baseColorFactor` to white whenever `COLOR_0` was present — correct only while the whole palette lived in the vertices. After the split it therefore measured the near-grey shading ratio alone: the wolf read 26.0% saturated before and **0.0% after**, so the standard claims sheet would have failed EVERY creature at HIGH with "the creature reads as a grey mass". Albedo is now `baseColorFactor` x `COLOR_0`, always both. The reason nothing caught it is the deeper fault: `calibrate.py` had never run the judge at all, so five colour norms shipped with no sample proving they separate anything. It now runs the colour ruler in both directions — the shipped example wolf must land inside the 10%-34% band (measured 26.3%), and a desaturated copy of that same file, meshes and vertex colours untouched, must be BLOCKED by `saturation_area`. The colour sample is `example/wolf.json`, not `calibration/wolf_green.json`: wolf_green still carries the pre-1.2.0 beige palette (0.2% saturated) and exists to exercise engine blocks, where palette is irrelevant.
+- **`glbcheck` gains two portability warnings**: `flat_white_base` (a material with a white base carrying vertex colours) and `high_metal` (metalness above 0.3 — with no environment map, which is the default in most galleries and engines, metal renders near-black; this is the second half of the same field failure). Card 03 states the material limits: no textures, hue in the material, metal ≤ 0.2, roughness free.
+
+Bypass
+- **MANUAL.md opens with a stop sign**: you do not need to build a GLB writer, a renderer, a screenshot tool or a modelling script — they are all here, they work, and starting one means you have already left the pipeline. Also corrects the header (1.3.0) and the interview line (exactly ONE question, not two).
+- **Delivery refuses a GLB this engine did not build.** Observed twice in the field (an outside user on Reddit, then a 1.3.0 test run): an agent given the package skips the cards, writes its own GLB generator and its own render pipeline, and arrives at delivery with a file that passed no gate — no blind reads, no `attack_reach`, no `part_seat`, no output contract. `deliver.py` now checks `asset.extras.harness` and stops there: the gates ARE the product, and a file that skipped them cannot carry the stamp. The refusal names the two commands that constitute the real pipeline.
+
+Thin orders
+- **The customer is asked exactly ONE question, and asking it is MANDATORY** (skipping it is as wrong as asking five: picking a direction is what makes the creature theirs — one that simply arrived never gets shown to anyone) (report: a test run stopped to ask which delivery format to use and whether to add the result to a local gallery — both are the harness's decisions, and both read as incompetence to a non-designer). Card 01 branches on the order instead of interrogating: a thin order gets three directions to point at (diverging on mass / weaponised part / broken anatomy — never three colours of one idea, no answer = take the first), a specific order gets "which of the things you named should people notice first?" (that answer becomes the signature part, and with no answer the most unusual one wins). Size, temperament, proportion, palette and animations are decided silently. Card 00 adds the forbidden-question list: never ask about delivery format, file type, triangle count, folders, whether to run a check, whether to list the result anywhere, or whether the expansion is acceptable.
+- **A recoloured example is refused (`example_copy`)**: a thin order tempts the shortest path — open `example/wolf.json`, change the colours, ship it — and the customer who asked for a dragon receives a wolf that reads as a fox. The engine BLOCKs any build whose joints are a shipped reference spec's with the numbers barely moved (≥90% of joints identical in name AND position within 2% of height); building the reference specs themselves is exempt, so calibration is untouched. Templates were deleted from this harness for this exact disease; this stops the example becoming the last template. Card 01 also makes the identity verdict explicit: the blind reader's noun must BE the brief's noun — "a fox" when the order said dragon is a failed gate, not a near miss.
+- **The brief is now derived from the rulers, and expanded without asking.** A thin order ("a dragon") is an UNDECLARED order: every empty slot is one no gate can test, so it drifts to the trope. Card 01 lists the nine slots that downstream machinery actually reads — identity, feel, height, signature part + carrying view, mass hierarchy, the two focals, stance, the attack, the value plan — each traced to the check or claim that consumes it. The session fills them itself, in one pass, and never shows the expansion for approval (a confirmation step is a lost customer, and the gates already catch a wrong guess). Two rules keep the expansion from converging: discard the first three ideas (they are the tropes), and commit to ONE exaggeration that distorts every other slot.
+
+Closing & community (server contract re-checked against gobkit.com/docs)
+- **One command closes the job — `harness/ship.py`**: package, or package AND publish with `--publish`. The old flow was two commands taking the same arguments twice, so the signature drifted between the file and the listing and the upload got skipped when the second command was forgotten. Ask the person once (name / signature / share?), run one command, read one JSON line back. The signature is remembered in `~/.anyCreature.json`.
+- **Uploads survive a flaky network**: the publisher retries twice with a backoff on transport errors and 5xx before declaring the network blocked — a submission lost to one cold start is a creature that never reaches the wall. Verified against a server that fails the first attempt.
+- **`--upload-only`**: publish an already-packaged creature without rebuilding or re-stamping it — for the person who said no and changed their mind, or whose upload failed. Card 04 requires offering it in one line.
+- **The server's one-time `manage_token` is no longer discarded** — it is the only way a person can ever take their own model down, and the API issues it exactly once. `publish.mjs` now saves it to `delivery/manage_token.txt` and returns it; card 04 requires it to be read out in the same message as the share link. Also accepts a bare `slug` (the server no longer always sends `share_url`) and builds the URL from it.
+- **A successful upload is no longer reported as an error.** The server renamed its own success state (`published` → `visible`) and `publish.mjs`, which matched the literal word, printed `{"status":"error"}` on a HTTP 201 and dropped the one-time `manage_token` on the floor — the user was told their upload failed and lost the only takedown key they will ever be issued. Success is no longer a magic word: any 2xx the server acknowledges (`ok !== false`) that carries a `share_url`, `slug` or `url` and does not name a review state IS published; a review state (`/pending|review|queue/i`) is `pending_review`; an acknowledged response with nothing to link to is also treated as uploaded, not refused. `manage_token` is now saved and returned on EVERY branch, refusals included, because a refusal can still carry the token for an earlier upload. Verified against a mock server across six responses (`visible`, `pending_review`, `queued_for_moderation`, a 400 refusal carrying a token, a relative `share_url`, and a bare `{"ok":true}`).
+- **`KHR_materials_anisotropy` on a mesh with no UVs or tangents is a BLOCK** (`anisotropy_without_direction`). Reported from the server side: a brushed-metal attempt came out a flat white smear, and dropping the strength from 0.9 to 0.15 changed nothing — anisotropy stretches the highlight ALONG THE TANGENT, so what was missing is a direction, not an amount. With no `TANGENT` and no `TEXCOORD_0` to derive one from, every renderer invents its own and the model is correct in none. Untunable by definition, therefore refused rather than warned; a primitive that has one of the two gets `anisotropy_derived_tangent` (viewers will disagree on the direction). The fix is to unwrap first (`"keep_uv": true`) or to get the look from geometry and vertex colour.
+- **Role presets removed — every creature is judged at boss standard.** `harness/presets/{minion,npc,boss}.json` collapse into one `harness/claims.json`; a cheaper creature is not a different ruler, it is the same ruler with a smaller `tri_budget`. Interview Q2 changes from "which role?" to "how big is it in the real world?", which feeds the height gate and graft scaling.
+
+Quality class — "parts don't stick to the body"
+- **`part_seat` check + declared joins**: every hosted `curve`/`spike` carries its base ring; the spec declares HOW the part meets the body — `"join":"insert"` (base ring ≥60% buried or BLOCK), `"extrude"` (base centre inside a body or BLOCK), `"snap"` (must ride an anchor or BLOCK), `"place"` (deliberately free). Undeclared roots under 50% buried warn. Kills the exposed-root class: tusks starting in mid-air, beaks hovering off the face, trunks reading as bolted-on objects.
+- Card 02 adds the four join verbs and the colour-continuity rule (flesh parts continue the host colour at the base); card 01's pit-map gains the join line; SYNTAX shows `"join"` on the curve example.
+
+
> **Version renumber (at 1.2.0).** 1.2.0 is the FIRST PUBLIC RELEASE. All
> earlier development versions were renumbered to 0.3.0–0.12.0 in release order
> (old 0.1.0→0.3.0 … old 1.7.0→0.12.0); the full mapping lives in the
@@ -9,7 +119,7 @@
## 1.2.0 — smooth bodies, one shading pass, saturation measured
Stage cards
-- **HIGH gains a fifth colour norm — `saturation_area`, band 10%–34%**: the share of the view whose colour carries HSV saturation ≥ 0.50, measured on the UNLIT baked vertex colour so brightness, AO and lighting cannot skew it. Below the floor the creature reads as a grey mass; above the ceiling saturation stops working as a spotlight. It rules AMOUNT, never LOCATION — the designer picks which surfaces carry the colour. The reshipped wolf measures 26.0%; the previous wolf measured 0.2% and would fail. The accent norm now reads as a cap on the ACCENT alone (<5%), not on total saturated area.
+- **HIGH gains a fifth colour norm — `saturation_area`, band 10%–34%**: the share of the view whose colour carries HSV saturation ≥ 0.50, Verified: the UNLIT baked vertex colour so brightness, AO and lighting cannot skew it. Below the floor the creature reads as a grey mass; above the ceiling saturation stops working as a spotlight. It rules AMOUNT, never LOCATION — the designer picks which surfaces carry the colour. The reshipped wolf measures 26.0%; the previous wolf measured 0.2% and would fail. The accent norm now reads as a cap on the ACCENT alone (<5%), not on total saturated area.
- **MID's fold-and-carve vocabulary no longer offers `faceted` for masses**: concave sections, `sharp` profile rows and a lower per-volume `smooth_angle` instead; parts may still be faceted freely.
- SYNTAX.md gains `shading`, `smooth_angle` and `build`, marks `faceted` parts-only, and drops `colors.gradient`/`colors.noise` from the volume example. 04_SHIP's gate.json example lists `faceted_body` and `saturation_area`.
@@ -30,7 +140,7 @@ Harness & fixes
Stage cards
- **MID = whitelist part blind-reads, identity only**: face (always) + signature part + order-named parts are rendered ALONE (`qa_isolate` builds) and shown 4-view to a context-free reader with one question — "what is this?" A face that reads as "a ball" fails. Edit vocabulary: swap local shapes / fold-carve / bend the pose (elbows are MID); no naked sphere/cube/cone on whitelisted parts. Silhouette share demoted to a budget check.
-- **HIGH = free colour under four norms** (one high-sat main on the signature, one secondary, accent <5%, brightness floor measured on the render) + three animations always (idle/move/attack).
+- **HIGH = free colour under four norms** (one high-sat main on the signature, one secondary, accent <5%, brightness floor Verified: the render) + three animations always (idle/move/attack).
- **04_SHIP (new card)**: gate stamp (real results only) → name + signature questions (ownership first; signature remembered in ~/.anyCreature.json) → scripted delivery → the share ask LAST, CC0 in one sentence → publish only on an explicit yes. Never auto-upload, never background, ask every time.
Engine
@@ -59,7 +169,7 @@ Engine correctness — the "invisible until a human looks" class
- **`mirror_distortion` (new BLOCK + warn): `joints_R` shears the twin instead of
posing it.** The mirrored mesh is grown along the LEFT bone path and then dragged
onto the right joints by weighted TRANSLATION, so a large offset squashes the
- volume. Measured on the wolf: offsets up to 10% of limb length are clean, 16%
+ volume. Verified: the wolf: offsets up to 10% of limb length are clean, 16%
costs 12% of a dimension, 24% costs 19%, 39% costs 31% and blocks. A reported
case had a right thigh 0.152 deep against 0.381 on the left with its width intact
— invisible from the left, invisible in the log. Warn past 12% deviation, BLOCK
@@ -81,7 +191,7 @@ Engine correctness — the "invisible until a human looks" class
instead of letting it surface later as flipped tris during an animation.
- **Anchored parts narrate the world direction they actually face.** `around` is
read in the host section's frame; the documented 0=spine / 90=side / 180=belly is
- the BODY chain's frame. Measured on a leg: 0=inner, 90=FRONT, 180=OUTER, 270=back
+ the BODY chain's frame. On a leg: 0=inner, 90=FRONT, 180=OUTER, 270=back
— so a plate aimed at the outside of a thigh with 90 silently lands on its front.
- **`deliver.py` refuses a self-contradicting gate stamp.** A delivered model was
found carrying `"passed": true` with `mid_face_blindread` failed in the same
@@ -151,7 +261,7 @@ Delivery & publish
## 0.12.0 (was 1.7.0) — clean painter, strict inspector (validated by 7 head-to-head experiments)
-Architecture (from the harness-vs-native duels and the 2x2/gryphon experiments)
+Architecture
- **Creation side stripped to a pit-map**: no design doctrine upfront — free design won or tied every duel where part character mattered; doctrine text taxed boldness. Design knowledge now lives in gates and rulers only.
- **Two gates, four views each, read by context-free agents** (self-grading shipped the worst failure in project history): Gate 1 RECOGNISED — any stick/slab view kills; Gate 2 PUNCHIER — after identity passes, rounds may only exaggerate, judged prev-vs-curr; compliance-only edits forbidden. LOW's deliverable is an exaggerated silhouette.
- **Stop-loss**: same symptom failed twice → concept restart, never a third tweak (verdict-driven micro-repair oscillated: human→bell, trousers→rooster).
diff --git a/MANUAL.md b/MANUAL.md
index cd7ef79..070fdfd 100644
--- a/MANUAL.md
+++ b/MANUAL.md
@@ -1,9 +1,19 @@
-# anyCreature 1.2.0 — text → game-ready 3D creature, one shot
+# anyCreature 1.3.1 — text → game-ready 3D creature, one shot
+
+> **STOP — read this before you write a single line of code.**
+> You do not need to build a GLB writer, a renderer, a screenshot tool, a
+> measuring script or a modelling script. They are all in this folder, they work,
+> and they are the product. If you find yourself starting one, you have already
+> left the pipeline: the quality gates you would be skipping are the entire
+> reason this harness exists, and delivery REFUSES any file this engine did not
+> build. Two field runs were lost to exactly this. The whole interface is:
+> write one JSON spec → `node engine/cli.js spec.json out/creature.glb` → follow
+> the cards in `cards/`. Nothing else needs writing.
Author: **Ariescar**. The engine and the harness scripts are original work. One third-party component IS bundled: `harness/assets/three-bundle.js` is a build of three.js (MIT, © 2010-2025 Three.js Authors) used by the render tools and the delivered showroom — its licence notice travels in the file and in `THIRD-PARTY-NOTICES.md`. Everything else npm installs at setup time. Licence: MIT (`LICENSE`); third-party attributions in `THIRD-PARTY-NOTICES.md`.
-A session receives an order like "make me a menacing mountain giant", asks at most
-2 questions, and delivers a skinned, animated, vertex-coloured, **AO-baked GLB**
+A session receives an order like "make me a menacing mountain giant", asks exactly
+ONE question (card 01), and delivers a skinned, animated, vertex-coloured, **AO-baked GLB**
plus an offline showroom viewer — and, with the user's explicit yes, publishes it
to the Gobkit community under CC0.
@@ -39,7 +49,7 @@ README.md repository front page (humans)
LICENSE MIT
THIRD-PARTY-NOTICES.md bundled + installed dependency licences
SECURITY.md local servers, the public key, untrusted input
-VERSION 1.2.0
+VERSION 1.3.1
setup.sh deps + calibration self-check
cards/ 00_START · 01_LOW · 02_MID · 03_HIGH · 04_SHIP · SYNTAX.md
engine/ cli.js + core/ — the ACS engine v2
@@ -54,7 +64,10 @@ harness/
ALWAYS attempt the upload; the drag-and-drop page is the
fallback for a `blocked` result, never the opening move
gobkit.json endpoint + release key for publish.mjs
- presets/ role QC presets (minion/npc/boss)
+ claims.json the one claims sheet (boss standard for every creature)
+ gates.json/.py the map: every check tagged block-or-advise and
+ allocate-or-verify. `python3 harness/gates.py [STAGE]`
+ roundcheck.py counts repair rounds and refuses the third tweak (iron law 3)
assets/ three-bundle.js for the render tools
calibration/ wolf_green (must build) · wolf_red + red_5050 (must be blocked)
example/ wolf.json + wolf.glb — a bred, approved light quadruped
@@ -83,6 +96,9 @@ example/ wolf.json + wolf.glb — a bred, approved light quadruped
how far a plate conformed. Free QC; read it.
- Shipped GLBs: primitives merged per material, public bone names (`LArm1Sh`
convention), mesh `creature` / skin `creature_rig`, harness stamp in `asset`.
+- Every GLB embeds its authored spec + parts manifest (`extras.source_spec`) —
+ extract, edit, recompile; `harness/graft.py` transplants parts between
+ creatures and the normal gates judge the transplant. `embed_spec: false` opts out.
- `node engine/cli.js spec.json out.glb` — that's the whole interface.
## Scale discipline
@@ -93,7 +109,7 @@ features (four wings) still stagger. Model-level looks are the final judge.
## Delivery & publish
-Card 04 is the whole flow: gate stamp → name + signature questions (once;
+Card 04 is the whole flow, now ONE command (`harness/ship.py`): gate stamp → name + signature questions (once;
`~/.anyCreature.json` remembers the signature) → `deliver.py` (stamped GLB,
offline showroom viewer, hero shots, backup upload pack) → the share ask LAST →
`publish.mjs` only on an explicit yes — and then RUN it, never assume the
@@ -103,5 +119,5 @@ human reviewer. CC0 is stamped at consent time, not before.
## Versioning
Semver; old zips never change; every release adds a CHANGELOG entry and a README
-row. (1.2.0 is the first public release — earlier development history was
+row. (1.2.0 was the first public release — earlier development history was
renumbered 0.3.0–0.12.0; the mapping lives in the version-library README.)
diff --git a/README.md b/README.md
index 9f533be..20f0b7b 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,7 @@ two questions, and delivers a skinned, animated, vertex-coloured, AO-baked GLB p
offline showroom viewer.
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
-[![Version](https://img.shields.io/badge/version-1.2.0-green.svg)](CHANGELOG.md)
+[![Version](https://img.shields.io/badge/version-1.3.1-green.svg)](CHANGELOG.md)
[![Engine](https://img.shields.io/badge/engine-zero%20dependencies-brightgreen.svg)](engine)
[![Output](https://img.shields.io/badge/output-glTF%202.0-000000.svg)](https://www.khronos.org/gltf/)
[![Tooling](https://img.shields.io/badge/tooling-Node%2018%2B%20%C2%B7%20Python%203.9%2B-3776ab.svg)](setup.sh)
@@ -37,9 +37,28 @@ node engine/cli.js example/wolf.json out/wolf.glb
spec that has to pass and two that have to be blocked, so you know the rulers separate
good from bad on your machine.
-To run the full text-to-creature session, point an agent at
-[`MANUAL.md`](MANUAL.md) and let it read `cards/` in order —
-`00_START → 01_LOW → 02_MID → 03_HIGH → 04_SHIP`.
+To run the full text-to-creature session, give your agent (Claude Code,
+Cursor, a VM agent — anything that runs shell commands) EXACTLY this:
+
+> Read MANUAL.md in this folder and follow it exactly — the cards in cards/
+> are the pipeline, do not improvise around them. First run `bash setup.sh`
+> and confirm it prints "calibrate OK". Then make me: **\<describe your
+> creature\>**. Real-world height: **\<e.g. 1.8 m\>**.
+> Ask me exactly one question — card 01's — and nothing else. Not cost, not
+> token budget, not how long, not whether to publish. Decide the rest and
+> tell me what you chose when you deliver.
+
+Three things that make or break the result:
+
+- **Don't invent your own workflow prompt.** "Use this workspace to generate a
+ character" skips every quality gate in the pipeline; twenty iterations of
+ that will not equal one pass through the cards.
+- **Let the agent run `setup.sh` itself, in its own environment.** Don't
+ pre-bundle `node_modules` into a zip — dependencies are per-machine.
+- **Image reference?** The pipeline is text-first. Tell the agent: *"extract a
+ one-paragraph creature brief from this image — masses, signature parts,
+ proportions, real-world size — then proceed with the cards."* The image
+ becomes the brief; the pipeline does the rest.
### Driving it harder
@@ -49,7 +68,8 @@ To run the full text-to-creature session, point an agent at
| `shading` | spec root | Whole-body vertical colour ramp and grain — `{gradient:{top,bottom}, noise:{size,amount}}`. |
| `build: "rigid"` | spec root | The only way to get a fully faceted body past the checker. For robots and crystals, not for animals. |
| `ao` | spec root | Per-vertex ambient occlusion; `false` to skip the bake. |
-| `harness/presets/` | QC | Role presets — `minion.json`, `npc.json`, `boss.json` — different budgets and thresholds per role. |
+| `embed_spec` | spec root | Every GLB embeds its own authored spec (`asset.extras.source_spec`) + a parts manifest — any agent can extract, edit, recompile, or **graft parts between creatures** (`harness/graft.py`). `false` opts out. |
+| `harness/claims.json` | QC | The one claims sheet — signature presence, 6:3:1 hierarchy, focal contrast, saturated area, rig/animations, triangle budget. Everything is judged at boss standard; adjust `tri_budget` for cheap creatures. |
## What is actually in here
@@ -123,14 +143,22 @@ Form beats obedience, everywhere.
- **Isolated-part blind reads misfire on dome-plus-hanging-tube heads.** Elephants and
birds get read as something else when the head is shown alone; put the same head back
on the body and it reads fine. Trust the whole-body read when the two disagree.
-- **Cost is only measured on two bosses**, at roughly 4.4M tokens each. Minions and NPCs
- should be cheaper, but nobody has measured them, so treat the preset budgets in
- `harness/presets/` as estimates rather than data.
+- **Cost scales with the creature.** Treat the triangle budget in
+ `harness/claims.json` as an estimate rather than data.
+- **Splitting the modelling across subagents costs more, not less.** One agent
+ start-to-finish beats a chain of short-lived agents (skeleton → parts → anims →
+ verify) on tokens, wall clock and turns alike. Onboarding is not the cause —
+ every fresh agent reads the same ground truth. The cause is re-derivation: work
+ the previous agent had already done and could not hand over. Iron law 9 in card
+ 00 states the rule.
- **`part_attachment` and `mirror_distortion` are new in 1.2.0.** Specs authored against
an older version may now be blocked. That is usually the checker being right, but it
is a breaking change, not a silent improvement.
- **The example wolf ships two animations, not three.** Card 03 asks for idle, move and
- attack; `example/wolf.json` has idle and move. Copy it for structure, not for
+ attack; `example/wolf.json` has idle and move. It is a SYNTAX reference, never a starting skeleton — the engine
+ refuses a build whose joints are the example's with the numbers barely moved
+ (`example_copy`), because a thin order is not permission to ship a recoloured
+ wolf. Read it for syntax, not for
animation coverage.
- **The engine has zero dependencies; the tooling does not.** Every render and measure
tool drives headless Chromium through playwright. If playwright will not install, you
@@ -152,10 +180,18 @@ Form beats obedience, everywhere.
## Requirements
-Node 18+ and Python 3.9+. `setup.sh` installs `three`, `playwright`, `numpy`, `pillow`
+Node 18+ and Python 3.9+. Windows: run `setup.ps1` in PowerShell (or `setup.sh` in Git Bash/WSL). `setup.sh` installs `three`, `playwright`, `numpy`, `pillow`
and `scipy`, then runs the calibration self-check. The engine alone needs nothing but
Node; the dependencies are for the measuring and render tools.
+## Output contract
+
+Every GLB this harness writes satisfies [`docs/OUTPUT_CONTRACT.md`](docs/OUTPUT_CONTRACT.md)
+— two chunks, no trailing bytes, no external URIs, no textures (colour is baked
+into vertex colours), semantic material names, convention bone names. Verify any
+file with `node harness/glbcheck.mjs <file.glb>`; the same module runs as a
+dependency-free import inside a server or Worker.
+
## Security
Short-lived local servers used by the render tools bind to `127.0.0.1` only, and
diff --git a/VERSION b/VERSION
index 26aaba0..3a3cd8c 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.2.0
+1.3.1
diff --git a/calibration/wolf_green.json b/calibration/wolf_green.json
index a2c5a0c..a872a50 100644
--- a/calibration/wolf_green.json
+++ b/calibration/wolf_green.json
@@ -289,7 +289,8 @@
"color": "#f2ead7"
}
]
- }
+ },
+ "smooth_angle": 17
},
{
"chain": "head",
@@ -356,7 +357,8 @@
"color": "#f2ead7"
}
]
- }
+ },
+ "smooth_angle": 20
},
{
"chain": "tail",
@@ -396,7 +398,8 @@
"color": "#57513f"
}
]
- }
+ },
+ "smooth_angle": 31
},
{
"chain": "LFront",
@@ -428,7 +431,8 @@
"none",
"dome"
],
- "ring_step": 0.055
+ "ring_step": 0.055,
+ "smooth_angle": 35
},
{
"chain": "LBack",
@@ -471,7 +475,8 @@
"none",
"dome"
],
- "ring_step": 0.055
+ "ring_step": 0.055,
+ "smooth_angle": 35
}
],
"parts": [
diff --git a/cards/00_START.md b/cards/00_START.md
index 828f450..3255ebe 100644
--- a/cards/00_START.md
+++ b/cards/00_START.md
@@ -3,19 +3,77 @@
## The pipeline in one line
```
-order → interview (≤2 questions) → silhouette brief → LOW: design FREE + two gates → MID (2 rounds) → HIGH (1 round) → SHIP (scripted delivery + closing dialogue)
+order → ONE required question → silhouette brief → LOW: design FREE + two gates → MID (2 rounds) → HIGH (1 round) → SHIP (scripted delivery + closing dialogue)
```
## Iron laws
1. **Form beats obedience.** Every rule below exists to protect form quality; if following a rule would make the creature tamer, the rule loses. Edits whose only purpose is to make a number match a declaration are forbidden.
-2. **You never grade your own thumbnails.** Every gate is read by a context-free agent you spawn who knows nothing about the order. Its verbatim answer is the verdict.
-3. **Same symptom failed twice = no third tweak.** Restart that view/element from a DIFFERENT concept. If the restart also fails, ship your best version and write one honest DEVLOG line about what didn't land.
+2. **You never grade your own thumbnails — and you never trust a reader either.** Every gate is read by a context-free agent who knows nothing about the order, and every read carries the verification traps of card 01 §4 (binding questions, a canary, shuffled labels): assume every reader is lazy until its answers prove otherwise. Its verified verbatim answer is the verdict.
+ **A reader is the most expensive thing in the run** — a subagent's price is almost entirely the cost of it EXISTING, with no images and a one-line prompt, so ~80% of a read's price is fixed overhead. Three rules follow, and all three are in the cards: batch the images (a five-image read costs barely more than a one-image read), never spend a read the machine could answer (`roundcheck --preflight` refuses those), and never let one round test one idea.
+3. **Same symptom failed twice = no third tweak.** Restart that view/element from a DIFFERENT concept. If the restart also fails, ship your best version and write one honest DEVLOG line about what didn't land. **This one is counted, not trusted** — `harness/roundcheck.py` records each gate verdict and reads `iou_vs_prev` to tell a real restart from a nudge, and refuses the third tweak. Law 2 exists because you cannot grade your own thumbnails; this law had the same problem and now has the same answer. A measured run spent rounds 6–15 moving the same head and ears before restarting at r16: eight rounds, and by then every round cost three times what round 6 did, because the context they ride on keeps growing.
+ **A round tests THREE ideas, not one** (card 01 §4b). A repair builds three versions that differ in KIND and shows all three to one reader — three builds cost four seconds more than one, while three separate reads cost three times a read. Three sizes of the same head is not three ideas; it is one idea with a wobble, and this law counts it as one.
4. **The signature part gets real geometry at LOW.** A giant whose identity is its fists gets fingers, knuckles and a planted pose in the silhouette round — not a placeholder sphere. Budget follows 6:3:1: the 6-level element gets 6-level geometry.
5. **Materials are named per PART** (`skin_torso`, `fur_leg`, `eye`, `tusk`…) — the area rulers identify parts by material name.
6. **Engine floors block builds** — mechanical checks refuse broken geometry and fake attacks (`BLOCK:` lines say exactly what; `warn:` lines are measures for YOUR judgment; `info:` lines narrate what the compiler actually did). Fix and rebuild; a refused build costs no round.
-7. **The customer is a non-designer.** After the interview, never ask them anything until the closing dialogue (card 04).
-8. **Nothing is ever uploaded without the user's explicit yes, this session.** No background uploads, no test uploads, ask for every creature — card 04 has the flow.
+7. **The customer is a non-designer, and gets exactly ONE question — which you MUST ask.** Never skip it, however complete the order looks: choosing a direction is what makes the creature theirs, and a creature that simply arrived is one they will not show anyone. Card 01 asks it (three directions if the order was thin, "which feature is the star?" if it was specific) and that is the last word they hear until the closing dialogue in card 04. In between you decide everything and ask nothing.
+ **ONE means one message, and it is the FIRST thing you send.** Not one question bundled with two others, not "a few quick things before I start". Between the order and that message you run `setup.sh` and nothing else; the very next words the person reads are card 01's question, alone. A second question in that message is a violation even if the question is a good one.
+ **Never ask about:** the delivery format, file type, triangle count, folder layout, whether to run a check, whether your expansion of the order is acceptable — **nor what it will cost, how many tokens or rounds it will take, how long you should spend, nor anything about publishing, sharing, uploading, or where the file should end up.** Those are decided by this harness, not by the customer. Cost and scope are your job: a non-designer has no way to price a round and asking makes them do yours. Publishing is decided in card 04, after the creature exists — nobody can consent to sharing a thing they have not seen, so asking early buys a worthless answer at the price of the one question that mattered. If you truly cannot proceed, choose the option you can defend, state the choice in one line at delivery, and keep moving.
+8. **Nothing is ever uploaded without the user's explicit yes, this session — and that yes is collected in card 04, never before.** No background uploads, no test uploads, ask for every creature. This law says you may not upload unasked; it does not license an early ask, and reading it as one breaks law 7. The share question comes after the creature exists, after they have seen it, in card 04's closing dialogue. Asking it at the start is a violation of both laws at once — it spends the single question they had on a decision they cannot make yet.
+9. **One creature, one agent. The reader is the ONLY subagent.** You build the whole thing yourself — brief, skeleton, parts, anims, repairs — in one session, and you spawn subagents for exactly one purpose: the context-free reads of law 2. Handing the modelling itself to a chain of subagents feels tidy and costs more on every axis — tokens, wall clock and turns alike. Onboarding is not the cause; every fresh agent reads the same ground truth. The cause is RE-DERIVATION: work the previous agent had already done and could not hand over. The reader splits cheaply for the opposite reason — it is one turn, and it MUST NOT inherit anything. The rule that falls out: the cost of a split is how much understanding the next agent has to rebuild.
+10. **Write state down every round; never rely on your own memory of it.** A boss session outlives its own context — the transcript gets compacted and the early rounds are gone. That is a record problem, not a cost problem, and splitting the work does not fix it (see law 9). What fixes it: after every round, the archived `spec.json`, the metrics, and the reader's verbatim verdict are on disk under `out/rN/` and in `log.md` before you move on. Anything not written there did not happen, and after a compaction you resume by reading those files, not by trusting what you think you remember.
+
+## Every check is tagged twice — read the map before arguing with one
+
+`harness/gates.json` lists every check in the system; `python3 harness/gates.py`
+prints it. Two tags on each:
+
+- **block / advise.** Block is for things that are *broken* — geometry that is
+ not geometry, a rig that does not deform, a clip that does not exist, an
+ identity the blind read could not name. Advise is for things that are
+ *debatable*: 6:3:1, focal contrast, saturated area. A number that says the eye
+ will ping-pong is worth reading and is not worth a rebuild. **Advice never
+ stops a build.** If you find yourself rebuilding because of an advisory, you
+ have misread the tag.
+- **allocate / verify.** Allocate = decidable *before* the build, so budget it
+ at generation time and it cannot come out wrong. Verify = only knowable after
+ the thing exists — it ran, it rendered, someone looked at it. `gates.py` prints
+ the ones that are blocking *and* allocatable at the end: each of those can
+ refuse a build over something that should simply have been budgeted, and every
+ such refusal is a round that did not need to happen.
+
+Where the visual load sits: **LOW carries it, MID carries one colour read, HIGH
+carries none.** By HIGH every visual decision is already made, so a gate there
+cannot improve the creature — it can only cost a round. HIGH blocks rig and clip
+only.
+
+## The thing that actually costs money: TURNS
+
+Not tokens, not tools, not compute — **round-trips.** Every command you issue
+re-reads the entire conversation up to that point, and the conversation only
+grows, so an identical command costs several times more at round 20 than at
+early in a run. Split into separate commands, compiles, silhouette renders and
+mask measures are most of a run's round trips. None of those tools is slow: a
+compile is 1.4 seconds, a silhouette view half a second, the whole measure phase
+under ten. The tools are never the bill.
+
+So the harness gives you ONE command per phase, and you use it:
+
+| instead of | run |
+|---|---|
+| build + silhouettes + measures + preflight | `python3 harness/round.py out rN --spec …` |
+| a build + render per whitelisted part | `python3 harness/partreads.py out/qa --spec …` |
+
+Same rule everywhere else: if two commands have no decision between them, they
+are one command. Loop in the shell, not in the conversation.
+
+**LOW no longer needs a browser at all.** Silhouettes come from the geometry:
+`harness/outline.py` projects the triangles under the same camera the renderer
+used and fills them, so the outline is computed rather than photographed and
+then measured. Verified against the rendered masks on all four views at IoU
+0.980–0.989 — the remainder is the renderer's antialiased edge. A round went
+from 9.0s to 1.4s, a three-variant round from 11.0s to 4.4s, and Chromium is now
+only needed for colour (`judge.mjs`), hero shots and the viewer.
## Environment self-check (run verbatim)
diff --git a/cards/01_LOW.md b/cards/01_LOW.md
index 30273b7..a5be98f 100644
--- a/cards/01_LOW.md
+++ b/cards/01_LOW.md
@@ -1,49 +1,531 @@
# 01 LOW — design free, then two gates (the big-form stage)
-## 1. Interview (≤2 questions; skip any already answered)
+## 1. ONE question — REQUIRED. Exactly one, then silence until delivery.
-Q1 Temperament: "What's the first feeling this creature should give?" (cute / solid / scary / free text)
-Q2 Role: minion / NPC / boss → loads `harness/presets/<role>.json` (tri budget + animation list).
+You MUST ask it. Not "if the order is unclear", not "if you need to know" —
+always, even when the order is long and specific and you could proceed without
+it. The question is not there to collect information; it is there to let the
+person put their hand on the creature before it exists. A creature they chose a
+direction for is theirs; one that simply arrived is yours, and they will not
+show it to anyone.
-## 2. Silhouette brief (a few lines, then freeze)
+So: exactly one question, immediately, before any building. Which of the two it
+is depends on what the order already committed to — you decide which branch you
+are in, you never ask which branch.
-Translate the order into the brief the gates will test against — identity ("reads as: tree + giant-proportioned humanoid"), feel ("heavy, crushing"), the ONE signature that must survive shrinking, and which view carries the identity. No method, no numbers you can't check.
+**Send it alone.** The message that carries this question carries nothing else:
+no budget check, no "roughly how long do you want me to spend", no "shall I
+publish it when it's done", no list of options to confirm. Those are law 7's
+forbidden list and they are the common way this goes wrong — the person answers
+three questions, only one of which shaped their creature, and the two that did
+nothing are the ones they remember. If you have already sent something else,
+you have spent the question; do not send a second one to make up for it. Take
+the most defensible reading of the order, build, and say what you chose at
+delivery.
+
+**Thin order** ("a dragon", "a big monster") — offer three directions, one line
+each, and let them point:
+
+> Three ways I could take this — pick one, or say "you choose":
+> 1. <a direction driven by MASS — what is oversized and what is starved>
+> 2. <a direction driven by a WEAPONISED part — what it fights with>
+> 3. <a direction driven by ANATOMY BROKEN ON PURPOSE — what is where it should not be>
+
+The three must diverge on those three different axes, never be three colours of
+the same idea. No answer, or "you choose" → take the first and start. Never ask
+a second time, never ask them to confirm the expansion afterwards.
+
+**Specific order** (it already names species, colour, parts, weapons) — the risk
+is not vagueness, it is that everything they listed competes to be the star. Ask
+which one wins:
+
+> You mentioned <A>, <B> and <C> — which should be the thing people notice first?
+
+That answer becomes the signature part: it takes the geometry budget, the
+highest-saturation colour, and the identity view. No answer → pick the most
+unusual of the ones they named (not the most expected).
+
+**Everything else you decide yourself**, silently — size in metres, temperament,
+proportions, palette, animations. `harness/claims.json` is the one claims sheet
+(every creature is judged at boss standard): fill its `<signature part>` /
+`<primary mass>` placeholders from your brief, and lower `tri_budget` only if
+the creature is meant to be cheap.
+
+## 2. The brief — expand the order yourself, never ask
+
+Orders arrive thin ("a dragon"). A thin order is not a small job, it is an
+UNDECLARED job: every slot the brief leaves empty is a slot no gate can test,
+and an untested slot drifts to whatever the word usually looks like — the same
+black spiky dragon every time. So expand it yourself, in one pass, before you
+build. **Do not show the expansion to the person and do not ask them to
+approve it** (the required question in §1 is a different thing: it comes
+first, before any expansion, and it is the only thing they are asked). They asked for a creature, not for homework; the gates are what
+catch a wrong guess, not a confirmation step.
+
+The slots are not a style; they are the INPUTS every downstream ruler reads.
+Fill all nine, in one short block, then freeze it:
+
+| Slot | What it must say | Who reads it later |
+|---|---|---|
+| identity | "reads as: X" — the noun a stranger should say | Gate 1 (3 of 4 views, identity view mandatory) |
+| feel | one phrase: heavy / fast / sharp / floating | the 24px read |
+| height | real-world metres | `size` gate (±15%, engine BLOCKs) |
+| signature | ONE named part, and which view carries it | `part_exists`, `part_signature`, MID whitelist, HIGH main colour |
+| mass hierarchy | which masses are primary / secondary / detail | `share_hierarchy` (6:3:1) |
+| two focals | the dominant one and the runner-up | `focal_contrast` (≥2× apart) |
+| stance | how the weight is planted; what is asymmetric | `balance`, and the bind pose IS the pose |
+| attack | what strikes, and what lunges forward | `attack_reach` (½ body span or BLOCK) |
+| value plan | dominant COLOUR, secondary, accent <5%, dark or light — **no material words, no roughness numbers; nothing downstream reads them** | `saturation_area`, brightness floor |
+
+Two rules that decide whether the expansion is worth anything:
+
+- **Discard your first three ideas.** The first things that arrive for any
+ creature word are the tropes everyone has seen. Name them to yourself, throw
+ them out, and take the fourth. A brief that could have been written without
+ the order in front of you has failed.
+- **Commit to ONE exaggeration and pay for it everywhere.** Pick a single
+ extreme — a proportion, a weaponised part, a broken symmetry — and let it
+ distort the hierarchy, the stance, the attack and the colour plan. Nine
+ moderate slots make a shapeless creature; eight ordinary slots serving one
+ violent decision make a creature people remember.
+
+These two rules are the highest-value minute in the whole pipeline. Repair
+rounds refine mass; they do not invent objects. Spend the thought here.
+
+**Two slots must also name the CHAINS they mean**, like this:
+
+```
+| signature | the pair of giant pincers — carried by the SIDE view chains: LClaw, RClaw |
+| two focals | dominant = the right pincer · runner-up = the boulder in its net chains: RClaw, net |
+```
+
+You invent the names; nothing checks whether they are good ones. What is checked
+is that the spec you build at r1 actually contains them, so that a part the
+brief ordered cannot go unbuilt until a later stage notices.
+
+**The brief is checked for PRESENCE, never for content.** `harness/brief.py`
+runs automatically inside `round.py` at r1. Declare any height, any identity,
+any palette — all of them pass. What it refuses is a BLANK, and only in the
+slots a later stage actually reads, because a blank does not make the downstream
+ruler lenient, it makes the ruler VANISH:
+
+| blank slot | what silently stops working |
+|---|---|
+| identity | `identity.py` falls back to a placeholder noun, so Gate 1 prints a verdict about nothing |
+| height | `checks.js` guards the size gate with `if (spec.height)` — no declaration, no check, no message |
+| signature | the one customer question in §1 IS this slot, and law 7 forbids asking a second one |
+| value plan | `value_order` has nothing to compare its sorted lightness table against — it can say what IS brightest, not what SHOULD be |
+| feel | the 24px read costs a whole subagent and has nothing to be judged against |
+| the one exaggeration | §4b builds two stagings of it; there is nothing to stage |
+
+Mass hierarchy, two focals, stance and attack are NOTED when blank and never
+blocked — they cost an advisory at most, and blocking them would buy nothing
+while costing design freedom, which is the entire point of this stage.
+
+The order always wins on anything it actually specified. Everything it left
+open is yours to decide — decisively, not cautiously.
## 3. Design FREE
Build the creature with the engine (syntax: `cards/SYNTAX.md`) exactly as you see fit — your own judgment, your own process. Only the pit-map applies (engine-local facts, not design rules):
- Anatomically independent masses get their OWN volumes, overlapping their neighbours (mane, shoulder, chest slab, head). Radius wiggle inside one tube reads as soft sausage, not as blocks.
+- **NO ROUNDED SAUSAGES — and the default IS a sausage.** A volume's wall angle is `360/sides`, and `smooth_angle` (default 50) welds every edge under it: 9 sides is 40°, 16 sides is 22°. Leave the default on and nothing on that mass can break — not the shading, not the outline — and it renders as a glossy bean. The engine BLOCKs it (`soft_mass`) and states the fix in numbers. The ruler is the share of volume edges that can crease, and the floor is 10%. **The lever is `smooth_angle` ON THE VOLUME**, set under its wall angle: it hardens the shading and leaves the silhouette Gate 1 validated untouched. Fewer `sides` works too. A `sharp` row is the SILHOUETTE lever and does nothing unless the radius steps across it. A mass genuinely meant to be a smooth lump declares `"soft": true`.
- Wings spread flat in one plane vanish from the side — give them sweep-back. Every view needs a designed silhouette; a straight-line view is a dead view.
- The bind pose IS the pose. Creatures never stand bolt upright in a T-pose; plant the weight.
- Curved things (tusks, trunks, horns) are `curve`; membranes (wings, frills, sails) are `membrane` — don't fake either with straight spikes or flat plates.
+- **Parts meet the body by a JOIN, not by luck.** A tusk is `insert` (base buried in the jaw), a trunk is `extrude` (grows out of the face), a plate is `snap` (rides an anchor). Decide the relation, declare it, and the engine verifies the root is really seated — card 02 has the four verbs.
- **Bends belong to JOINTS.** An arm that must flex needs its elbow joint placed where the bend lives; radius wiggle inside a straight tube gives you a bent sausage, not an elbow. Place the skeleton for the pose you want.
-Measure every build:
+**Before the first round, make the spec LEGAL:**
+
```bash
-node engine/cli.js spec.json out/creature.glb
-node harness/silmetrics.mjs out/creature.glb out/rN
-python3 harness/maskmetrics.py out/rN out/rN/sil_front.png out/rN/sil_side.png out/rN/sil_top.png out/rN/sil_hero.png
+python3 harness/fit.py pole_a.json -o pole_a.json
```
-The report measures; YOU judge. Flags worth eyes: `sq_fill` (silhouette volume in a 1:1 frame), `mirror_sym` (only the FRONT view may be symmetric; wing pairs stagger even there), `straight_max` (plank-limb detector).
-## 4. Gate 1 — RECOGNISED (all four views)
+A refused build is refused for two different reasons. Some are DESIGN — the
+shape does not read, the poles are one idea twice. Some are ARITHMETIC — a root
+ring is not buried in its host, two neighbouring bones came out the same length,
+the build does not land on its declared height. The engine already computes the
+exact correction for each of the arithmetic ones and prints it inside the BLOCK;
+`fit.py` reads those numbers back, applies them, rebuilds and repeats.
+
+Do this and a build round is spent on the creature. Skip it and the round is
+spent on legality, which is the single largest block of wasted time in a run:
+the arithmetic failures are COUPLED — burying a root ring moves a joint, which
+changes two segment lengths, which trips the proportion band, which moves a
+joint again — so they cannot be cleared in one hand-edit either.
+
+`fit.py` never touches a design decision: not `balance` (which mass moves is a
+choice), not `mesh_integrity`, `touch` or `part_seat` (they say a relationship
+is wrong, not by how much), and no style threshold at all. A clean run does not
+mean the creature is good; it means the next round is about the creature.
+
+A whole round is ONE command:
+```bash
+# r1 — TWO OPPOSITE POLES (§4b), and the brief is checked here:
+python3 harness/round.py out r1 --spec pole_a.json pole_b.json --gate ID
+# a repair round:
+python3 harness/round.py out rN --spec spec.json --prev r<N-1> --gate ID
+```
+
+It builds every spec, renders the four silhouettes, runs the mask measures,
+runs `roundcheck --preflight`, and prints ONE report ending in either "spawn
+the reader" or a BLOCK telling you not to.
+
+**At r1 it also checks the brief** (§2) and, when you give it two specs, whether
+those two are really two designs rather than one design built twice. It finds
+`brief.md` beside the spec, in the out directory or in the working directory;
+`--brief <path>` overrides. Both checks are free — no render, no reader, no
+extra turn — and r1 is the last moment either is cheap to fix.
+
+**Do not run those four tools separately.** A command is a TURN, and a turn
+re-reads the entire conversation so far, which keeps growing — the same command
+issued late in a run costs several times what it cost early. The tools are not
+slow; the round-trips are the bill.
+
+**`--prev` is not optional from round 2 on.** It is what computes
+`iou_vs_prev`, and `iou_vs_prev` is the only mechanical evidence of whether you
+changed the shape or nudged it — without it `roundcheck.py` cannot enforce iron
+law 3, cannot refuse a wasted read, and says so.
+
+The report measures; YOU judge. Flags worth eyes: `sq_fill` (silhouette volume in a 1:1 frame), `mirror_sym` (only the FRONT view may be symmetric; wing pairs stagger even there), `straight_max` (plank-limb detector), and **`thinnest_px48`** — the width of your thinnest feature on the 48px thumbnail the reader actually sees. Under 3 px it is not a thin feature, it is an invisible one, and no amount of repositioning will make the reader see it: thicken it or drop it. This number is available on the FIRST build; a run that discovers it late has spent every round in between moving something nobody could see.
+
+## 3b. Where the reader budget goes — LOW, not later
+
+Blind reads are the most expensive line in the whole run and the only one that
+buys identity. Spend them **here**, on the silhouette, and be stingy afterwards.
+
+**A reader's price is almost entirely the cost of the subagent EXISTING**, not
+the pictures inside it. Everything about how this card spends readers follows
+from that: put images together in one read rather than splitting them across
+reads, never spend a read the machine could have answered (`--preflight`), and
+never let one round test only one idea (§4b builds two opposite poles).
+
+The reason is what a failure costs to undo. A silhouette that reads as a fox
+when the order said dragon is repaired by moving big shapes — cheap, and every
+later stage inherits the fix. The same misread caught at MID or HIGH means
+throwing away the part work, the anims and the shading that were built on top of
+a wrong form. Identity is decided by the big shapes, the big shapes are all
+there is at LOW, so LOW is the only stage where a blind read can still change
+the answer instead of just recording it.
+
+Practical split: both gates here get full reads with all three traps of §4. The
+part reads in card 02 are a spot-check, not a re-litigation of identity — if MID
+is where you first discover the creature is unrecognisable, LOW was under-read,
+not MID.
+
+## 4. Reader verification — ASSUME EVERY READER IS LAZY
+
+A reader that glances at one image and confabulates the rest poisons every
+verdict downstream. Every blind read, at every stage (both gates here, the part
+reads in card 02), carries three traps. **A tripped trap voids the whole read —
+but the repair depends on WHICH trap, because they do not mean the same thing.**
+
+1. **The bump count, and ONLY when it is unambiguous.** For every image the
+ reader first says *"how many things stick out of the outline?"* A gross
+ mismatch (reader says 0, the mask counts 5) voids the read. Looking at image
+ 1 cannot produce image 3's bump count: laziness stays mechanically hard.
+
+ **The "wider or taller?" trap is RETIRED.** Readers cannot reliably make that
+ call at 48px inside roughly 0.55–1.45, and voiding a read on it throws away a
+ whole reader. The trap dates from when aspect could only be read off a
+ picture; `outline.py` computes it exactly from the vertices before anyone is
+ spawned, so asking a reader to confirm it buys a worse copy of a number the
+ machine already has. If you want it as a sanity question, ask it and IGNORE
+ the answer unless the computed W/H is outside 0.55–1.45.
+ The thumbnails `outline.py` writes are letterboxed, not squashed, so the
+ proportion the reader sees is the proportion the file records — check it. (It
+ was not always so: a `resize((px,px))` made every thumbnail square, the trap
+ was unanswerable by construction, and 21 of 52 reads in one three-creature
+ batch were re-runs of a question nobody could have got right. If you ever see
+ every reader answering "square-ish", suspect the thumbnails before the reader.)
+2. **A canary in every batch.** Shuffle ONE image from `harness/canary/` into
+ the set under a neutral name (`answers.json` holds the key). Canary answered
+ wrong = the reader was not looking = discard everything it said.
+3. **Shuffled neutral labels.** Images are IMG-A/B/C in random order (Gate 2:
+ randomize which of previous/current is which) — repeated or swapped answers
+ expose themselves.
+
+Readers are never told which image matters, which is the canary, or why.
+
+### Two speeds of repair, because a trip has two possible causes
+
+The old rule was one speed: any tripped trap, re-run it **one image per
+reader**. On a five-image batch that is five readers where one would do, and
+Gate 1 is where the reader budget goes; everything after it should be stingy.
+The rule assumed every trip means the reader was lazy. It does not.
+
+- **Canary answered wrong → isolate immediately, one image per reader.** There
+ is no second explanation for this one. The canary is a picture with a known
+ answer; getting it wrong means the reader was not looking at anything, and
+ isolation is exactly the right response — hand it a single image and there is
+ nothing left to confabulate from.
+- **Binding question mismatched, canary fine → ONE fresh reader, same batch.**
+ Only if that reader trips too do you isolate. A binding mismatch has a second
+ cause the canary does not: **the image may genuinely be ambiguous.** A view
+ that is a blob at 48px gets inconsistent bump counts from anyone, and five
+ readers each staring at one blob will not do better than one — they will just
+ cost five times as much to fail. (The same class of thing already burned a
+ release: in 1.3.0 the thumbnails were squashed square, so "wider or taller?"
+ was unanswerable by construction and 21 of 52 reads were re-runs of a question
+ nobody could get right.)
+
+If the fresh reader trips on the SAME image, suspect the image before the
+reader: check `thinnest_px48` and the view's own metrics before spending four
+more readers on it.
+
+## 4b. Gate 1 — RECOGNISED (any 3 of the 4 views)
Spawn a context-free reader agent (a fresh subagent given NOTHING but the images) with exactly this task:
> Look at these images one at a time, answering only from what you SEE.
> 1) [thumb24 of the identity view] What FEELING does this shape give — heavy/stable, fast/agile, sharp/menacing, floating? One phrase.
-> 2-5) [thumb48 of front / side / top / hero] What is this? What parts can you make out? Does this view read as a real creature, or as an abstract shape/nothing?
+> 2-5) [thumb48 of front / side / top / hero] **Name your FIVE best guesses for what
+> this is, most likely first.** Then: what parts can you make out, and does this
+> view read as a build or as an abstract shape/nothing?
+
+**The verdict is SCORED, not argued.** Note where the brief's noun landed in each
+view's ranked guesses, then run:
+
+```bash
+python3 harness/identity.py --round N --noun scorpion \
+ --ranks front=none side=2 top=2 hero=1
+```
+
+The rule it applies — **rank R passes if the noun reached R in at least R
+views**:
+
+| | needs |
+|---|---|
+| its FIRST guess in any one view | 1 view |
+| second place | 2 views |
+| third | 3 views |
+| fourth | 4 views |
+
+Fifth and beyond does not count: a noun that never gets above fifth is being
+listed, not recognised. **And the requirement drops by one view per repair
+round** (never below one), because another round costs more than the last while
+buying no more information.
+
+Synonyms count as the noun — buffalo for bison, wyrm for dragon. That judgment
+is yours; it is the only one the tool leaves you.
+
+Why scored rather than exact. A 48px silhouette is a genuinely ambiguous object,
+and a one-word bar measures the reader's confidence as much as the creature's
+clarity. Two shipped logs make the case. One boss's first read came back *"a
+generic bat/moth/gargoyle silhouette"* — the ordered noun is IN that sentence.
+And a creature failed on one view while three readers named it first on the
+others will run round after round and revert to a shape whose read is identical
+to the one that was refused — because a one-word bar cannot express "three
+readers said it first".
+
+Every view answering "abstract / nothing / a stick" scores nothing and fails.
+"A fox" plus four other canines when the order said dragon is still a failed
+gate — the customer asked for a dragon and would receive a fox. Feel mismatch →
+repair. The verdict IS the work order. Budget: 2 repair rounds, then iron law 3
+(concept restart).
+
+Record the rank, not just the pass: `--record rN ID pass "scorpion (rank 3)"`.
+Rank 3 or 4 is a pass that still says something — the creature reads, but not
+loudly — and that belongs in the closing line.
+
+### On a FAIL: look before you rebuild
+
+A pole is read on ONE view. When it fails, **the next thing you spend is three
+more images, not a round.** Show the same shape's other three views to one
+reader before you change a single number. A reader's price is the subagent
+existing, not the pictures inside it, so three more images is a fraction of a
+round — and a rebuild is a whole one that may be throwing away a shape which
+already works from a different angle. `identity.py` prints this on every FAIL
+and names the views you have not tried.
+
+The failure this prevents: a creature fails on its declared view, gets
+rebuilt, fails again, gets its concept restarted — and then reads first-guess
+from a view nobody had tried. The creature was never wrong. **The declared
+identity view was.**
+
+If another view reads, do not celebrate and move on quietly — **change the
+brief's identity view and write down why.** Gate 1's 3-of-4 rule holds you to
+the view the brief names, so the brief has to name the one that works. Some
+forms simply have no good side view: anything wide and sprawling is recognised
+from above, and anything wearing architecture reads as architecture in profile.
+
+### A round builds TWO OPPOSITE POLES, not one attempt and not three near-copies
+
+Do not spend a whole round-trip trying one answer and finding out it was wrong.
+Build **two versions that are opposite ends of ONE named axis**, and put both in
+front of the same reader.
+
+```bash
+python3 harness/round.py out rN --spec pole_a.json pole_b.json --prev r<N-1> --gate ID
+# ... read them, then promote the winner so the iou chain follows it:
+python3 harness/round.py out rN --promote v2
+```
+
+A build and a view are seconds; a reader is the expensive unit and its price is
+almost entirely the subagent existing. Two versions cost seconds more than one.
+Two separate reads cost twice a read. **The expensive unit is the round trip,
+not the work inside it.**
+
+**Name the axis, then push BOTH ends of it.** The brief's one exaggeration stays
+fixed; what changes is how it is STAGED:
+
+| axis | pole A | pole B |
+|---|---|---|
+| coiled / released | energy stored, wound back | mid-strike, thrown forward |
+| reared / flattened | tall, weight on the hind | long and low, weight forward |
+| front-loaded / rear-loaded | mass in the head and chest | mass in the tail and haunches |
+| gathered / sprawled | limbs tucked, one silhouette | limbs thrown wide |
+
+Two poles of one axis beat three vague "different attempts". The trap is that
+`iou_vs_prev` cannot tell you which you have: it counts overlapping pixels, so
+changing proportions moves it a long way while the design stands still. The
+ruler that separates designs is where the mass sits, in thirds of the frame.
+
+`round.py` measures this before the reader is spawned and **refuses to let you
+spend one on two copies of the same idea** (floor 0.25, `harness/brief.py`). It
+also warns when a pole's `fill` — the share of its own bounding box that is
+solid — comes back high: an "opposite pose" that folds the signature part flat
+onto the body has not restaged the creature, it has erased it.
+
+**Poles are judged on the IDENTITY VIEW ONLY — one image each.** Not four views
+each, and not the hero unless the brief named the hero. The batch is two
+identity views plus the canary: three images, not thirteen.
+
+This is what `outline.py` bought. Everything the other three views were being
+shown for — aspect, protrusion count, thinnest feature, how much the shape moved
+— is now computed from the geometry, exactly, for free, before the reader is
+spawned. The only thing left that needs eyes is *what does this look like*, and
+that question is asked of the view the brief declared would carry the creature.
+
+The reason: a reader's price is the subagent existing, not the pictures, and
+three quarters of the pictures were being shown to ask questions a script can
+answer.
+
+**ONE reader does the whole gate — choosing AND confirming, in one batch.**
+This used to be two: one to pick the winner, then a second to confirm 3-of-4 on
+it. Send all of it at once instead — each pole's identity view, plus all four
+views of BOTH poles, plus the canary:
+
+> Images A-J are silhouettes. For each: what is it? (five best guesses, most
+> likely first). Then: taking A and F as two whole creatures, which reads more
+> strongly, and why? One line each.
+
+Then score the winner's four views with `identity.py`. **You already have the
+answers for the loser too; you simply throw them away.**
+
+Why this inverts the old advice. When a read carried thirteen images, images
+were the unit and the rule was "send fewer". Now each read carries one or two,
+Why this inverts the old advice. When a read carried thirteen images, images
+were the unit and the rule was "send fewer". Now each read carries one or two,
+and the balance flips: almost the whole reader bill is the subagent EXISTING,
+so the rule is now the opposite — **as few readers as possible, as many images
+in each as the question needs.** Merging choose+confirm takes a three-round gate
+from six readers to three.
+
+A pole whose noun matches the brief wins outright. If neither matches, two nouns
+from two OPPOSITE stagings is a far better work order than one "no" — the axis
+you named is the thing being tested, so the answer tells you which end of it is
+warmer. Two near-copies cannot tell you that, which is why `round.py` refuses to
+read them.
+
+**Promote the winner** (`--promote v2`) so the winning pole becomes that round's
+output and the next round's `--prev` follows it. Record ONE verdict for the
+round.
+
+This is not a new mechanism: Gate 2 below has always shown one reader two
+silhouettes and asked which is punchier. This applies the same move to Gate 1,
+where changing one variable at a time — claw height, then tail angle, then leg
+thickness — costs a full round to learn one thing.
+
+**Three of the four views must read. The fourth may be a dead view.** This gate
+used to demand all four, and a demand for a view that carries nothing spends
+readers on a repair that cannot work: a low, wide, shelled creature with a
+central mast is a blob from the front at 48px, and no amount of repair changes
+what an outline of that shape looks like head-on. Some forms have
+one axis that carries nothing — that is a property of the form, not a defect in
+the build.
+
+So: **count the views that read. Three or more = pass.** Two or fewer = fail, and
+the repair goes to the biggest shapes, not to the weakest view. One more rule
+comes with the allowance: **the identity view named in the brief is not
+optional** — if the view you declared would carry this creature is the one that
+reads as "a blob", that is a failed gate no matter what the other three say. You
+chose that view; the gate holds you to it.
+
+Write the count into the record so the budget is visible:
+`--record rN ID pass|fail "<noun>"` and put `3/4` or `2/4` at the front of the noun.
+
+**Ask permission BEFORE the reader, record after it — every time:**
+
+```bash
+# round.py already ran --preflight and told you whether to spawn a reader.
+# After the read:
+python3 harness/roundcheck.py out --record rN ID pass|fail "<the reader's noun, verbatim>"
+python3 harness/roundcheck.py out --check ID # BLOCK: = no third tweak, restart
+```
+
+The pre-check exists because the order used to be wrong: the reader was spent
+FIRST and the question "was that round allowed?" came afterwards, so the thing
+that stops waste sat behind the thing that costs money. **A reader is not
+free** — a subagent's price is almost entirely the cost of it EXISTING, not the
+pictures inside it.
+
+`--preflight` refuses a read the machine can already answer: a silhouette more
+than 0.85 similar to the one a reader rejected last round will get the same
+noun back, and a feature under 3px cannot be reported on by anyone. Neither is
+a judgment call — change the shape first, then pay for the read.
+
+Law 3 used to be yours to apply to yourself, and self-applied it does not hold:
+a run will nudge the same feature through many failing rounds before restarting.
+`roundcheck` counts instead, and it counts what the round *produced*: a repair
+that leaves the silhouette more than 0.85 similar to the last one is a nudge
+whatever you call it. Two of those and the third is refused. This is the same
+move as law 2 — the thing you cannot be trusted to judge about your own work is
+taken out of your hands — and it applies to Gate 2 identically (`PUNCH`).
+
+## 5. Gate 2 — PUNCHIER (after Gate 1; the same 3-of-4 must stay readable; reader verification from §4 applies — randomize which of prev/current is IMG-A)
+
+LOW is not done when it's recognisable — it's done when it's EXAGGERATED. A push
+may ONLY make the silhouette bolder: push the extreme proportion further, harden
+breaks, deepen negative space, exaggerate the signature.
+
+**Build THREE different pushes and judge them together against the incumbent —
+in ONE round, not three.** Same command as §4b:
+
+```bash
+python3 harness/round.py out rN --spec push_a.json push_b.json push_c.json \
+ --prev r<N-1> --gate PUNCH
+```
+
+Show the reader the incumbent plus all three pushes, shuffled, labels neutral:
+
+> These are silhouettes of a creature. Which is punchiest — most striking, most
+> tension? Rank them, one sentence why for the winner.
-Judge the verbatim answers against the brief: identity wrong → repair (biggest shapes first). **Any view read as "abstract/nothing/a stick" fails the whole gate.** Feel mismatch → repair. The verdict IS the work order. Budget: 2 repair rounds, then iron law 3 (concept restart).
+Incumbent wins = LOW locks where it is, done. A push wins and three views still
+read (the identity view among them) = promote it, skeleton and main volumes lock.
-## 5. Gate 2 — PUNCHIER (after Gate 1; all four views must stay readable)
+**Why this is one round and not three.** Spending one round per push means each
+push is a full round trip to learn one thing, and the
+answer never moved. Put side by side in one read, the same three pushes cost one
+round-trip and the ranking says WHICH direction was warmest instead of only that
+each was colder than the incumbent.
-LOW is not done when it's recognisable — it's done when it's EXAGGERATED. Up to 2 rounds; each round may ONLY make the silhouette bolder: push the extreme proportion further, harden breaks, deepen negative space, exaggerate the signature. Spawn a fresh reader; show the PREVIOUS round's identity-view silhouette and the CURRENT one:
+**ONE round. If the incumbent wins, this gate is FINISHED — do not run a second.**
-> Two silhouettes of a creature. Which is punchier — more striking, more tension? One sentence why.
+That is not a budget cut, it is what the verdict means. Three pushes built in
+three different directions, judged side by side by a reader who knows nothing,
+and the reader still picked what you already had: the silhouette is punchy
+enough. There is no information left to buy. A second round asks the same
+question with three more guesses and gets the same answer — the
+field build ran that experiment for us, three rounds and four readers, every one
+reverting to r1, three different readers naming the same silhouette.
-Reader picks the old one = the round is reverted; try a different push or stop. Reader picks the new one and all four views still read = LOW passes. Skeleton and main volumes lock.
+A second round is allowed in exactly one case: **a push won on punch but broke
+the 3-of-4 read.** Then you have a direction that works and a legibility problem
+to fix, which is a real work order. Anything else — stop, lock r1, move to MID.
## 6. Outputs
diff --git a/cards/02_MID.md b/cards/02_MID.md
index bd69c31..13e9b36 100644
--- a/cards/02_MID.md
+++ b/cards/02_MID.md
@@ -4,34 +4,66 @@ Output: every part — ears, horns, claws, eyes, fins, shell spikes, paws — ri
bones LOW already placed, or anchored to volume surfaces. No material detail, no
animation. MID's question is: **do the key parts READ as what they are?**
-## The part gate — whitelist blind-reads, identity only
-
-Not every part gets examined. The whitelist:
-
-1. **the face — always** (if the creature has one),
-2. **the signature part** (from the brief),
-3. **any part the order names** ("scissor hands" → the hands).
-
-For each whitelisted part, render it ALONE and blind-read it:
-
-```bash
-# temp spec: copy the real spec, keep only this part (+ its host chain volume
-# if the part is meaningless without it), add "qa_isolate": true
-node engine/cli.js out/qa_face.json out/qa_face.glb
-node harness/silmetrics.mjs out/qa_face.glb out/qa_face
-```
-
-Show the four thumb48s to a context-free reader with EXACTLY this and no more:
-
-> What is this? Answer with the name of the thing or body part you see.
-
-Judge the verbatim answer: the part's name (or an unmistakable synonym) = pass.
-**"a ball", "a blob", "an egg", "nothing" = fail** — a siren's face that reads
-as a sphere has no face. Identity is the only question at MID; feel and beauty
-were LOW's business, colour is HIGH's.
-
-Two repair rounds per failed part, then iron law 3 (different concept for that
-part, not a third tweak).
+## Author the WHOLE part set in one pass. Build once. Fix everything at once.
+
+This is the single most expensive habit in the pipeline, so it gets the top of
+the card. Do not add parts one at a time and rebuild after each. Write every
+part, run one build, read the whole BLOCK list — the engine reports **all**
+failures at once, it does not stop at the first — fix them all in one edit, and
+build again.
+
+The arithmetic: writing the spec is not the cost. Touching the same forty
+elements three times each is, because a turn re-reads the whole conversation and
+the conversation only grows. Two passes is the target: **author everything, then
+repair everything.**
+
+Mirrored structure is not authored twice, either. `"mirror": ["LArm"]` generates
+the right side; hand-writing `RArm` alongside `LArm` doubles the work and the
+chance of the two drifting apart. Use `mirror` for anything symmetric, and
+`joints_R` when the pose (not the shape) differs.
+
+## MID SPENDS NO READER AT ALL
+
+Both reads that used to live here are gone, and neither was replaced by a
+cheaper read — they were replaced by arithmetic that runs at build time.
+
+**The isolated part read is deleted.** It failed every time it was tried: a
+crown reads as "a blob", a face as "a stone", an armoured basket as "a fist" —
+while the whole-body read names all three without being asked twice. A part cut
+away from the body has lost the only context that told the reader what it was,
+so reading it there measures the crop, not the part.
+
+**The colour read is deleted too.** It asked three things, and a machine answers
+all three off the palette in microseconds:
+
+| the question | who answers it now |
+|---|---|
+| what colour is this creature | the palette. You wrote it. |
+| which part draws the eye | `value_order` — every material sorted by OKLab lightness, brightest first, printed on every build. Whatever is at the top owns the eye. |
+| which parts can you make out | `contrast_adjacent` — every part compared against the material of the thing it SITS ON. Under 0.10 OKLab they read as one mass. |
+
+Both answers sit in the palette the whole time. Two masses at the same
+lightness compete and neither owns the eye; a part wearing its host's colour is
+not a part. Rendering a hero and squinting at it is guessing at numbers you
+already have.
+
+Both checks are ADVICE with numbers, not blocks: camouflage and deliberately
+subtle detail are real choices. What is not acceptable is paying a subagent to
+learn them.
+
+**`part_exists` still BLOCKS**, and it costs nobody — it is a machine check on
+the spec. If the brief named a chain and the spec has no such chain, the order
+was not filled, and `harness/brief.py` says so at r1.
+
+**What a reader is still for**, anywhere in this pipeline: *what does this look
+like*, *which of these is punchier*, and *is this form legible*. Those are
+judgments about resemblance and impact, and no amount of coordinate data
+performs them. Colour distance, value order, silhouette aspect, feature
+thickness and animation momentum are all arithmetic — none of them gets a
+reader again.
+
+`harness/partreads.py` stays for a deliberate manual look at one part. No card
+calls it.
## Edit vocabulary (what a MID repair is allowed to be)
@@ -56,6 +88,41 @@ part, not a third tweak).
it BLOCKs. For a genuinely different pose, take that limb OUT of `mirror` and
author it as its own chain.
+## Hands and feet — use the vocabulary, never improvise from spheres
+
+Anything with hands gets `"type":"hand"` — palm, four fingers and an opposable
+thumb, scaled from one `size` number; `curl` for relaxed/gripping, `"fist":
+true` for the folded fist with the thumb wrapped across. Field truth: every
+attempt to improvise a hand from spheres and sticks shipped a mitten. Feet:
+`paw` with `"toes": 3..5` so they stop reading as bread loaves. Both take
+`mirrored: true`, and the blind-read applies — a hand that reads as "a blob"
+fails like any whitelisted part.
+
+## Joins — decide HOW every part meets the body, before placing it
+
+A tusk that starts in mid-air, a beak hovering off the face, a trunk that reads
+as a bolted-on object: all one disease — the part was placed, but its RELATION
+to the body was never decided. For every hosted part, pick the join first:
+
+- **insert** — the part SINKS into the mass (tusks into the jaw, horns into the
+ skull). Declare `"join":"insert"`; the engine BLOCKs unless the base ring is
+ ≥60% buried. Aim the `offset` back INTO the host volume, not at its surface.
+- **extrude** — the part GROWS out of the skin (a trunk from the face, a tail
+ spike from the tail). Declare `"join":"extrude"`; the base centre must sit
+ inside a body. Match the base radius to the local host radius so the skin
+ flows into the part instead of stepping.
+- **snap** — the part LIES ON the surface (plates, scutes, brows). That is what
+ `anchor` + conform already do; declare `"join":"snap"` and the engine insists
+ the anchor exists.
+- **place** — deliberately detached (a floating rune, an orbiting shard). Rare;
+ say why in the spec `_notes`.
+
+Undeclared parts still get measured — a `part_seat` warn means a root may show.
+And the join is also a COLOUR decision: a part that is FLESH of its host (trunk,
+tail, brow) continues the host's material colour at its base; a hard colour
+break at the junction reads as equipment, not anatomy. Check the junction in the
+hero render, not just the part in isolation.
+
## Do (layout)
1. **Signature presence**: silhouette share is a BUDGET check — the signature
diff --git a/cards/03_HIGH.md b/cards/03_HIGH.md
index 627f853..49fdffd 100644
--- a/cards/03_HIGH.md
+++ b/cards/03_HIGH.md
@@ -11,7 +11,7 @@ Pick the palette yourself, from the creature's story. The norms:
— the memory spark. One accent temperature, not two. The 5% caps the ACCENT
alone; it is not a cap on how much of the creature carries saturated colour —
norm 4 sets that, and its floor sits well above 5%.
-4. **Saturated area: 10%–34% — measured, not judged by eye.** The
+4. **Saturated area: 10%–34% — computed, not judged by eye.** The
`saturation_area` claim counts the share of the view carrying HSV saturation
≥ 0.50, read on the UNLIT baked vertex colour, so brightness, AO and lighting
cannot skew it. Below the floor the creature reads as a grey mass; above the
@@ -26,25 +26,84 @@ Pick the palette yourself, from the creature's story. The norms:
floor, lift the mid masses, keep the darks only where a step needs them.
The engine bakes **per-vertex AO at compile** (crevices, pits, undersides
-darken automatically — that's the "solid" look). The floor is measured AFTER
+darken automatically — that's the "solid" look). The floor is computed AFTER
AO; never fight AO by flattening your colours, and never disable it to pass
(`"ao": false` exists only for debug builds).
Vertex colours come from two places. Per volume, `colors.arcs` bands the
section over that material's base colour (0°=spine, 180°=belly) — bands must
follow the form, spine band darkening the top plane, belly band lifting the
-underside. Spec-level, ONE `shading` block ramps value over the WHOLE body's Y
-range and lays one grain, on EVERY mesh — volumes, paws, ears, eyes, horns —
-so the same numbers mean the same thing on an upright leg and a horizontal
-torso, and no part reads as a sticker. Defaults: `gradient {top 0.30, bottom
--0.88}`, `noise {size 0.018, amount 0.26}`; `noise.size` is a fraction of the
-model diagonal, so the grain scales with the creature. `colors.gradient` and
-`colors.noise` are ignored now — the compiler says so in an `info:` line.
+underside. Everything after that is the **L1–L8 stack**, and it is a FORMULA:
+it runs on every build, it takes no decisions, and there is nothing here for
+you to judge. That is the whole reason HIGH has no visual gate.
+
+What it does, in order: smooths the flesh colour across part boundaries so
+junctions cannot show a seam (a colour field that is a function of POSITION
+gives two coincident points the same value, by construction); lays the pattern
+if the spec named one; multiplies a top-to-bottom three-colour ramp over
+everything; brightens **and** saturates the upper region while leaving the
+lower region exactly untouched; bleeds hardware colour into the flesh around
+it; shades hardware and flesh separately; and finally softens the shipped
+NORMAL on flesh toward the bone field, which is the one layer the viewer's own
+lighting reacts to.
+
+**The only field you normally write is `shading.pattern.color`, and you decided
+it at MID.** Everything else is settled — see `cards/SYNTAX.md` for the full
+block for the settled values.
+Two things worth knowing: brighter-and-more-saturated is impossible with any
+blend mode (every mode that brightens moves toward white, and white has chroma
+zero), which is why that layer works in OKLab; and pushing chroma walks back to
+the sRGB boundary by bisection rather than clamping, because clamping per
+channel turns the hue instead of capping the saturation.
+
+The build prints one `info: shade class ...` line naming which pieces are
+flesh, which are hardware and which are features. **Read it.** A trunk is a
+`curve`, so it defaults to hardware and will not take the flesh treatment until
+the spec says `"shade": "flesh"`. `"shading": {"stack": false}` falls back to
+the 1.2.0 ramp-and-grain for a spec that was tuned against it.
UV atlas is opt-in (`"keep_uv": true`) for downstream texture bakes; by default
the shipped file carries colour in vertices and stays lean.
+## Materials — what the format can and cannot carry
+
+- **No textures at all.** Colour is per-vertex; the whole palette ships in the
+ file. Do not plan for a texture, an emissive map or a normal map — there are
+ none, and the contract refuses images.
+- **Every material carries its own hue** in `baseColorFactor`; the engine does
+ this for you by splitting the baked colour (hue into the material, shading
+ into COLOR_0). Never hand-write a pure-white base colour with the colour in
+ vertices only: a viewer that ignores vertex colours then shows a white
+ creature. That happened to a published creature on a public gallery.
+- **Keep `metal` low — 0.2 at most, and only where it earns it.** Metal without
+ an environment map renders NEAR-BLACK, and most galleries, engines and preview
+ tools default to no environment. A brass creature should be a bright warm
+ colour with low metalness, not a metallic material hoping for reflections.
+ The checker warns above 0.3.
+- Roughness is free: use it to separate surfaces (wet, chalky, polished).
+- **No anisotropy, no brushed metal, no hair sheen.** `KHR_materials_anisotropy`
+ stretches the specular highlight ALONG THE TANGENT, and these meshes carry no
+ tangents and (by default) no UVs — so the extension has no direction to work
+ with and every renderer invents its own. The result is a flat white smear, and
+ turning the strength DOWN does not help: what is missing is *which way*, not
+ *how much*. The checker BLOCKS it (`anisotropy_without_direction`). If you
+ want a directional look, get it from GEOMETRY — grooves, plates, aligned
+ spikes, a darker vertex band along the axis — or unwrap first with
+ `"keep_uv": true` and accept that the palette is still vertex colour.
+
## Animation — three, always: `idle`, `move`, `attack`
+**Write all three, then build ONCE.** Not one clip, build, look, next clip. The
+three share a skeleton, a stance and a weight story — the same hips that bob in
+`move` are the hips that wind back in `attack` — so authoring them together is
+easier as well as cheaper, and it is the same rule card 02 applies to parts. The
+engine checks every clip in one pass (`anim_integrity`, `attack_reach`,
+`limb_clearance`) and reports all of their failures at once, so a build per clip
+buys nothing but round-trips at the most expensive point in the run.
+
+Tracks are cheap to write and expensive to iterate: three whole clips are a
+few thousand characters. The characters were never the
+problem. Three builds instead of one were.
+
- The bar for idle/move: skinned, actually moving, no clipping, no explosions.
- **`attack` must COMMIT FORWARD — but it does not have to lunge.** The engine
CPU-skins the clip and BLOCKS (`attack_reach`) only when nothing commits at the
@@ -54,6 +113,13 @@ the shipped file carries colour in vertices and stays lean.
planted on the spot, winding a foreleg, a tail or a weapon BACK and sweeping it
FORWARD, passes. A ±20° twitch does not, and neither does a sideways sweep that
never crosses toward the front. Wind up BACK first, then strike FORWARD.
+- **Gait for many legs.** Two legs: opposite phase (`mirror_phase: 0.5`).
+ Four legs: DIAGONAL pairs — front-left moves with back-right; offset the
+ back pair's keys by half a cycle relative to the front pair, then
+ `mirror_phase: 0.5` staggers left/right. Six or eight (spiders): alternating
+ tripods/tetrapods — two leg groups, one group's keys offset half a cycle;
+ adjacent legs must never move in sync or the creature skates instead of
+ walking.
- Channels stack: several tracks bending one segment = keep total bend modest,
or `anim_integrity` blocks (folds / >3× edge stretch). Reduce bend or add a
joint; don't fight the check.
diff --git a/cards/04_SHIP.md b/cards/04_SHIP.md
index 2896e6c..b511a7e 100644
--- a/cards/04_SHIP.md
+++ b/cards/04_SHIP.md
@@ -15,79 +15,136 @@
## 1. Gate stamp (real results only)
-Serialize the checks you actually ran into `delivery/gate.json`:
+**The engine already wrote most of it. Do not retype it from memory.**
-```json
-{ "passed": true, "checks": [ {"name":"anim_integrity","passed":true},
- {"name":"attack_reach","passed":true}, {"name":"faceted_body","passed":true},
- {"name":"saturation_area","passed":true}, {"name":"gate1_recognised","passed":true},
- {"name":"gate2_punchier","passed":true} ] }
-```
-
-Never invent a line. If a check didn't run, it isn't in the file.
+Every build drops `<out>.checks.json` beside the GLB — every engine check by
+name, whether it passed, whether it merely warned, and the verbatim BLOCK and
+measure lines. It is written by the code that ran the checks, on refused builds
+as well as green ones. Start from that file:
-## 2. Names, then delivery
+```bash
+cp out/creature.checks.json delivery/gate.json # the engine's half
+```
-Ask in the USER'S language, exactly two questions, in this order (they name it
-and sign it BEFORE any talk of sharing — ownership first):
+Then add ONLY the checks the engine cannot know about — the blind-read verdicts,
+which live in `out/rN/round.json` where `roundcheck --record` put them as each
+round happened:
-> Give your monster a name? (Enter = <working name>)
-> Your signature? Asked once — auto-filled from now on. (Enter = anonymous)
+```json
+{ "name": "gate1_recognised", "passed": true, "round": "r1", "reader": "a giant bat" }
+{ "name": "gate2_punchier", "passed": true, "round": "r2", "reader": "incumbent held" }
+{ "name": "mid_colour_read", "passed": false, "round": "r5", "reader": "dried leaves and straw" }
+```
-The signature question is skipped when `~/.anyCreature.json` exists — read
-`{"author": "..."}` from it; on first answer, write it there.
+Never invent a line, and never reconstruct one you could have copied. If a check
+didn't run, it isn't in the file. This is the most expensive moment in the run to
+be remembering things — the conversation is at its longest and a token here costs
+several times what it cost at round 3 — and iron law 10 already says memory is
+not the record. Both halves are on disk. Copy them.
-```bash
-python3 harness/deliver.py out/<name>.glb delivery/ <name> \
- --title "<their name>" --author "<signature>" --gate delivery/gate.json
-```
+## 1b. Conformance is automatic — you do not run anything
-This stamps name + signature + gate INTO the GLB (`asset.copyright`,
-`extras.monster` — they travel with the file forever), then packs: stamped
-`.glb`, offline showroom `_viewer.html`, `hero.png`/`hero.jpg` (auto-framed,
-no label card in shot), and `upload/` (the backup pack). Confirm the viewer
-opens. Echo one line:
+The engine contract-checks every GLB the moment it writes it, `ship.py`/`deliver.py`
+re-check the stamped file, and the publisher refuses to upload a file that fails.
+Names and signatures with markup are cleaned at stamping rather than blocking the
+delivery. A contract failure means a harness bug: report it with the spec, do not
+work around it.
-> "<Name>" by <signature> — written into the model.
+## 2. Ask ONCE, then run ONE command
-## 3. The share ask (LAST, after they've seen their name on it)
+Ask in the USER'S language, in one breath (ownership first — they name it and
+sign it before any talk of sharing):
+> Give your monster a name? (Enter = <working name>)
+> Your signature? Asked once — remembered from now on. (Enter = anonymous)
> Share it to the Gobkit community? Uploading releases it under CC0, permanently —
-> anyone can download, use and remix it. [yes / no]
+> anyone can download, use and remix it. [yes / no]
-That one sentence IS the licence consent — no legal recital. On **no**: reply
-"All files are in delivery/ — say the word if you ever want to share it." and
-STOP. On **yes**:
+The signature question is skipped when `~/.anyCreature.json` already holds one.
```bash
-node harness/publish.mjs delivery/<name>.glb delivery/hero.png \
- --title "<their name>" --creator "<signature>"
+# they said no — package only
+python3 harness/ship.py out/<name>.glb --name "<their name>" --author "<signature>" --gate delivery/gate.json
+
+# they said yes — package AND publish, one command
+python3 harness/ship.py out/<name>.glb --name "<their name>" --author "<signature>" --gate delivery/gate.json --publish
```
-**`hero.png` is not optional.** A submission without an image is not rejected,
-but it will not list automatically — it sits waiting for a human reviewer. That
-is the one common reason a creature stalls after a successful upload. Pass it
-every time.
+`ship.py` stamps the name and signature INTO the GLB (they travel with the file
+forever), packs the viewer, hero shots and the backup upload pack, and — only
+with `--publish` — uploads and prints the result. Never pass `--publish` without
+an explicit yes in this session.
+
+## 3. Read the result back, verbatim
-It re-stamps `extras.license = CC0-1.0` (consent just given) and POSTs to the
-endpoint in `harness/gobkit.json`. One JSON line comes back — answer from it,
-using the SERVER's title/creator (what the wall actually shows):
+`ship.py` prints one JSON line last. Answer from it, in the user's language:
-| result | tell the user (their language, one line) |
+| status | tell them (one line) |
|---|---|
| `published` | ✅ Published: "<title>" by <creator> → <share_url> |
-| `pending_review` | ⚠ Uploaded — a reviewer is checking it; it will appear shortly. (no further explanation) |
-| `blocked` | The upload pack is ready in `delivery/upload/` — open https://gobkit.com/community/upload and drag `creature.glb` in. No account, no key needed. (state it as the next step, NOT as an error — nothing is broken and nothing was lost) |
-| `error` | The server answered and refused — read its message out verbatim, then offer the same backup page. |
+| `pending_review` | ⚠ Uploaded — the server is verifying it; it will appear shortly. (no further explanation) |
+| `blocked` | The upload pack is ready in `delivery/upload/` — open https://gobkit.com/community/upload and drag `creature.glb` in. No account, no key needed. (a next step, NOT an error — nothing is broken, nothing was lost) |
+| `error` | The server refused — read its message out verbatim, then offer the same backup page. |
-**Reading a `blocked` result.** The submit endpoint always answers in JSON, so
-an **HTTP 403 is a filtered network, never a key problem** — 403 is not one of
-the endpoint's own answers. A non-JSON body means a proxy or captive portal
-replied instead of the server. `publish.mjs` already classifies all of these as
-`blocked`; do not re-diagnose them as authentication failures, and never tell
-the user to fetch or change a key.
+**Two different handles come back, and they are NOT interchangeable.** The claim
+link puts the model under their Gobkit account (open it, sign in with Google);
+the takedown code removes it, needs no sign-in, and CANNOT be re-issued. Read
+`manage_kind` from the JSON — it says which of them you actually got:
+
+| `manage_kind` | what to say |
+|---|---|
+| `both` | give BOTH lines below, in this order. This is the normal case. |
+| `url` | the claim link line only |
+| `token` | the takedown code line only |
+
+- 🔑 Claim it: `<manage_url>` — open it and sign in with Google to put this
+ monster under your account. The link stops working once it is used. Saved in
+ `delivery/claim_link.txt`.
+- 🧯 Takedown code (shown ONCE, cannot be re-issued): `<manage_token>` — the
+ only way to remove the model later, no sign-in needed. Do not post it. Saved in
+ `delivery/manage_token.txt`.
+
+Never let one of them stand in for the other, and never drop the code because a
+link was also given — that is exactly the bug this table exists to prevent.
+Give them in the SAME message as the share link, never below the fold.
+`claim_link_file` and `manage_token_file` are the paths they were written to;
+quote those paths, not guessed ones.
+
+**Never hand over a claim link without checking it resolves.** The publisher
+already did: `claim_link_live` is `true` (it answered), `null` (could not ask —
+say nothing, the link is probably fine) or `false` (it answered 404). On `false`
+the claim link is dead; give `claim_fallback_url` instead — the standing claim
+page, where the same takedown code is pasted after signing in. `ship.py` prints
+whichever of the two applies, so quoting its output verbatim is always correct.
+
+**If they said no, or the upload failed, leave them one line:** *"say the word
+and I'll upload it — one command, nothing is rebuilt."* The command is
+`python3 harness/ship.py delivery/<name>.glb --upload-only`. A creature that was
+finished and never reached the wall is the most expensive kind of miss.
+
+**Reading a `blocked` result.** The submit endpoint always answers in JSON, so an
+HTTP 403 is a filtered network, never a key problem. `ship.py` already classifies
+these; do not re-diagnose them as authentication failures, and never tell the
+user to fetch or change a key.
## 4. Closing ledger
-One DEVLOG line (format in card 00) + the delivery checklist: glb, viewer,
-heroes, spec JSON, gate.json, DEVLOG.
+**ONE line. Not a narrative.** Format in card 00:
+
+```
+gates: ID pass@r? PUNCH pass@r? | restarts: none-or-what | unresolved: none-or-what
+```
+
+Plus the delivery checklist: glb, viewer, heroes, spec JSON, gate.json, DEVLOG.
+
+**The round-by-round record is already on disk** — iron law 10 requires the
+archived spec, the metrics and the reader's verbatim verdict under `out/rN/` and
+in `log.md` *as each round happens*. The closing DEVLOG does not repeat any of
+it. It says how the gates landed and what did not get solved, and stops.
+
+This is the most expensive moment in the entire run to write prose: the
+conversation is at its longest, so every token here costs several times what the
+same cost early in the run. A boss build writes a few thousand characters of session
+narrative here — tables, verbatim reader quotes, per-round analysis — all of it
+duplicating `log.md`, all of it at maximum context price. One line was the rule
+the whole time.
diff --git a/cards/SYNTAX.md b/cards/SYNTAX.md
index f702145..5f7bae7 100644
--- a/cards/SYNTAX.md
+++ b/cards/SYNTAX.md
@@ -2,15 +2,33 @@
```jsonc
{
+ "height": 1.85, // real-world metres, ground to crown — the engine verifies ±15%
"palette": { "skin_torso": {"color":"#8a8a80","rough":0.95}, ... }, // one material PER PART
"sections": { "flute": [[1,0],[0.6,0.4],...] }, // named 2D outlines, CONCAVE allowed (bark, crescents)
"smooth_angle": 50, // default: faces meeting at a vertex average when their normals sit within
// this many degrees; the vertex splits only at a REAL crease. Override per
// volume and per part. "faceted":true == smooth_angle 0.
- "shading": { "gradient":{"top":0.30,"bottom":-0.88}, // THE DEFAULTS. ONE value ramp over the
- "noise":{"size":0.018,"amount":0.26} }, // WHOLE body's Y range, on EVERY mesh,
- // parts included; noise.size = FRACTION OF THE MODEL DIAGONAL, not metres.
+ "shading": { // THE L1-L8 STACK. Every field below is optional and every
+ // default is the settled value — you normally write NOTHING
+ // here except `pattern.color`, which is a MID decision.
+ "pattern": {"color":"#ffffff","sharpness":0.45,"amount":1.0,"scale":0.06},
+ // L2. Omit `color` and there is no pattern. Flesh only.
+ "ramp": {"bottom":"#001370","mid":"#cfcfcf","top":"#fffcf0","pm":0.31,"wm":0.08},
+ // L3. Top-to-bottom, multiplied over everything but features.
+ "boost": {"y0":0.00,"y1":0.40,"gamma":0.30,"dL":0.03,"dC":1.50},
+ // L4. Brighter AND more saturated up top, EXACTLY nothing below
+ // y0 (identity, not "almost"). Chroma walks back to the sRGB
+ // edge instead of clamping — clamping turns the hue.
+ "bleed": {"radius":0.025,"sharpness":0.35,"amount":0.45}, // L5 hardware into flesh
+ "hardsh": {"amount":0.54,"gamma":0.70}, // L6 shadow on hardware
+ "bodysh": {"lights":4,"rot":4,"elev":17,"amount":0.20,"gamma":1.95}, // L7 on flesh
+ "normals":{"flesh":0.90}, // L8 — the ONLY layer that leaves COLOR_0 and goes into
+ // the file's NORMAL, so the user's lighting reacts to it.
+ "stack": true }, // false = the 1.2.0 ramp-and-grain instead (gradient/noise below)
+ // legacy, only read when stack:false:
+ // "gradient":{"top":0.30,"bottom":-0.88}, "noise":{"size":0.018,"amount":0.26}
+ // noise.size = FRACTION OF THE MODEL DIAGONAL, not metres.
"build": "rigid", // robots/constructs/golems/vehicles ONLY — lifts the faceted_body BLOCK
"joints": {
@@ -37,8 +55,23 @@
"chain":"torso", "material":"skin_torso", "sides":14, "frame":"up",
"profile":[[0,0.3,0.35], [0.6,0.42,0.5,{"bias":-0.1,"sharp":true}], [1,0.2,0.22]],
// rows [t, half-width, half-height, opts]; exp 2.5-4=boxy slab; bias<0 belly-full;
- // sharp = hard silhouette break; "section":"flute" = use a named outline
- "smooth_angle": 30, // optional per-volume override, crisper creases
+ // sharp = hard SILHOUETTE break, and it only bites when the radius STEPS
+ // across it (>=15%). The flag between two rings of the same radius is a
+ // no-op. It changes nothing.
+ "smooth_angle": 30, // per-volume override, and the SHADING lever. The wall
+ // angle is 360/sides; smooth_angle welds every edge under it, so 9 sides
+ // (40 deg) or 16 sides (22 deg) at the default 50 is welded perfectly
+ // smooth. A volume that can break NOWHERE — no facets, no radius step —
+ // is a bean, and the engine BLOCKs it (soft_mass). Lowering it hardens the
+ // shading and leaves the outline untouched.
+ "soft": true, // OPT-OUT for soft_mass: this mass really is meant to be
+ // a smooth organic lump (a slug, a bladder, a droplet). Deliberate, not default.
+ "shade": "flesh", // OPTIONAL. flesh | hard | fx — which shading
+ // class this piece belongs to. The default is right almost always: volumes, hands and paws
+ // are flesh; spikes, curves, membranes and fins are hard; eyes are fx (no layer, no shadow).
+ // Write it when the default is wrong for THIS creature: a trunk is a `curve` that is flesh;
+ // an armour plate grown as a volume is a volume that is hard. The build prints which pieces
+ // landed in which class ("info: shade class ..."), so check that line rather than guessing.
// "faceted":true on a VOLUME is a BLOCK (faceted_body) — an 800-tri torso becomes 800 shards
// and AO bakes the mess into COLOR_0. Break a body with "sharp" rows or a lower smooth_angle.
"caps":["dome","dome"], "ring_step":0.05,
@@ -48,6 +81,9 @@
"parts": [
{ "type":"curve", "host":"Head", "material":"tusk", "mirrored":true, // CURVED horn/tusk/trunk
+ "join":"insert", // how it meets the body: insert (base buried, verified) /
+ // extrude (grows out of the skin) / snap (rides an anchor) /
+ // place (deliberately free) — undeclared floating roots warn
"offset":[0.06,0,0.1], "dir":[0.3,-0.6,0.7], "sides":8,
"segments":[ {"len":0.1,"r":0.035,"ahead":20}, {"len":0.1,"r":0.028,"rise":35},
{"len":0.08,"r":0.015,"rise":30,"taper":true} ] },
@@ -83,7 +119,13 @@
{ "type":"eye", "host":"Brow", "material":"eye", "size":0.028,
"anchor":{"chain":"head","t":0.4,"around":62} }, // both eyes from one entry; side of head ≈55-70
- { "type":"paw", "host":"LToe", "material":"skin_fist", "size":[0.3,0.25,0.2], "mirrored":true }
+ { "type":"hand", "host":"LWrist", "material":"skin_hand", "mirrored":true, // palm + 4 fingers + OPPOSABLE thumb
+ "size":0.17, // palm length — the whole hand scales from it
+ "dir":[0.1,-0.9,0.35], "up":[0,0,1], // dir = where the knuckles point; up = back of the hand
+ "curl":0.35, "spread":0.5, // relaxed curl / finger fan; "fist":true = folded, thumb wrapped
+ "join":"extrude" },
+
+ { "type":"paw", "toes":3, "host":"LToe", "material":"skin_fist", "size":[0.3,0.25,0.2], "mirrored":true }
],
"animations": {
@@ -99,6 +141,7 @@
},
"style": "heavy", // ONLY if 1:1 segment rhythm is the design (relaxes the 50:50 gate)
"ao": false, // debug only — vertex AO bakes automatically otherwise
+ "embed_spec": false, // opt OUT of the embedded birth certificate (default: the GLB carries its own spec)
"keep_uv": true, // opt-in UV atlas (TEXCOORD_0) for downstream texture bakes
"qa_isolate": true // MID part-isolation builds only: skips whole-body checks
}
diff --git a/docs/HANDOVER_sanitize.md b/docs/HANDOVER_sanitize.md
new file mode 100644
index 0000000..4f28d85
--- /dev/null
+++ b/docs/HANDOVER_sanitize.md
@@ -0,0 +1,198 @@
+# Handover — submission sanitising (harness side → server side)
+
+**To:** whoever builds the gobkit.com/community sanitiser
+**From:** the anyCreature harness side
+**Re:** your discussion sheet of 2026-08-17 (file disinfection for submitted GLBs)
+
+Sanitising itself is yours: it has to sit where files arrive, and it has to
+survive people who edit the harness. This document is what we owe you for it —
+measurements you asked for, the shape of what we send you, and a component you
+can run instead of writing the cheap gate yourself.
+
+---
+
+## 1. Your direction is right, with one correction
+
+Whitelist-rebuild over blacklist-scan: agreed, and the strongest argument for
+it is not in your sheet. It is **duplicate JSON keys**: `{"generator":"clean",
+… ,"generator":"<payload>"}`. A scanner that reads the object sees the first
+value; every loader (and `JSON.parse`) keeps the last. Scanning and loading
+disagree by construction — no blacklist can close that, and rebuilding closes
+it without knowing it existed. Worth putting in your §5 as the load-bearing
+example.
+
+Three more carriers missing from your §4:
+
+- **ZIP polyglot.** Your "tail after the declared length" row, made concrete:
+ a file that is a valid GLB from the front and a valid ZIP from the back (ZIP
+ is parsed from the end). Your gallery becomes the distribution point for the
+ archive. Exact-length rewrite plus tail truncation kills it.
+- **Accessor bombs.** Not smuggling: `count: 2^31`, `NaN` in `min`/`max`, a
+ `bufferView` index that does not exist, an animation channel targeting a
+ missing node. These crash the *downloader's* loader. A rebuild that
+ validates ranges removes the class.
+- **Markup in names.** Node and material names are shown by viewers and
+ galleries. `<img onerror=…>` as a mesh name is an XSS payload aimed at
+ whoever renders your listing, not at the model.
+
+Everything else in your §4 and §5 we agree with as written.
+
+---
+
+## 2. §6.1 — the measurements
+
+Pure JS (`pngjs`), single-threaded, no native libraries — the only path
+available inside a Worker. Node's V8 versus workerd's V8: same order of
+magnitude, so treat these as the shape of the answer, not a promise about your
+account's limits.
+
+| Input | Full sanitise: parse → decode every texture → re-encode → rebuild |
+|---|---|
+| 10 MB GLB, 8 × 1024² pixel-art textures (your realistic case) | **CPU 1.0–1.5 s** |
+| 8 × 1024² pure-noise textures, 23.5 MB (worst case that cannot even be submitted — over your 10 MB ceiling) | **CPU 2.0–2.5 s** |
+| anyCreature file (no textures at all, vertex colours) | **0.2 ms** |
+| Cheap structural gate only (`glbcheck`, any file) | **~1.4 ms** |
+
+Against Cloudflare's limits — please re-verify against current docs, this is
+from our side's knowledge and platform limits move: paid Workers allow ~30 s
+CPU per request (configurable), the free tier ~10 ms. So:
+
+- **Paid tier: full rebuild fits inside the upload request** (1–2.5 s ≪ 30 s).
+ Memory is not a concern either (10 MB file + 8 decoded RGBA buffers ≈ 32 MB
+ against a 128 MB ceiling).
+- **Free tier: only the cheap gate fits.** The rebuild has to go to a queue.
+
+Even on the paid tier we would put the rebuild in a queue, for reasons that
+have nothing to do with CPU: retries come free, texture budgets can grow later
+without re-architecting, and it lines up exactly with your "visible on upload,
+download locked" work order — **the lock lifts when the rebuild finishes.**
+
+---
+
+## 3. Recommended shape
+
+```
+upload → cheap gate (ms) → visible immediately, download LOCKED
+ │ fails: reject now, quote the error code to the submitter
+ ↓ passes
+ queue → whitelist rebuild → download UNLOCKED
+ │ fails: reject, notify, do not keep a zombie
+```
+
+**Do not treat harness-side output as a defence.** You said it yourself in
+§6.7: the harness is open source, so anyone can edit or bypass it. What
+harness-side work *is* good for is making the honest majority trivially cheap
+to process — which is what section 4 is about.
+
+---
+
+## 4. What we send you, and the fast path it enables
+
+`docs/OUTPUT_CONTRACT.md` is the full contract. The short version: an
+anyCreature 1.3.0 file is **two chunks, zero trailing bytes, one embedded
+buffer, no URIs of any kind, no images at all** (colour lives in vertex
+colours with AO baked in — so there is no EXIF/XMP surface to strip), no
+compression extensions, semantic material names, convention bone names,
+lowercase `idle`/`move`/`attack`, metres, +Z forward, 150–800 KB.
+
+Two consequences for you:
+
+- **The expensive half of sanitising does not apply to these files.** Texture
+ decode/re-encode is the entire CPU cost in your budget, and there are no
+ textures. Rebuilding one is pure JSON+buffer work: sub-millisecond.
+- **There is a stronger option than rebuilding for these files.** Every
+ anyCreature GLB embeds its own authored spec (`asset.extras.source_spec`),
+ which is plain JSON data and recompiles byte-identically. The ultimate
+ sanitise is to **recompile from the spec**: the output then contains only
+ bytes our zero-dependency compiler wrote, and nothing from the uploaded file
+ survives except the design intent. The engine is dependency-free JS and can
+ in principle be bundled into a Worker. We are not proposing you do this now
+ — it is the natural phase two once the general rebuild is running.
+
+## 5. `harness/glbcheck.mjs` — take it, it is yours
+
+Zero dependencies, no I/O, one export, never throws:
+
+```js
+import { checkGLB } from './glbcheck.mjs';
+const { ok, errors, warnings, info } = checkGLB(uint8array);
+```
+
+It rejects: extra chunks, trailing bytes, external URIs, mandatory
+compression, duplicate keys, path leaks, markup/control characters in names,
+accessor bombs, malformed containers. It reports `info.anyCreature` so you can
+route conforming submissions to the fast path, plus `info.animations`,
+`info.skinned`, `info.images`, `info.harness_version`. Measured at **~1.4 ms**;
+verified against five hostile fixtures (ZIP tail, extra chunk, external URI,
+path leak, duplicate keys) and clean files.
+
+**Read its own header comment before you rely on it:** it is a validator, not
+a sanitiser. It repairs nothing and must not be your only line. Use it as the
+cheap gate in front of the queue.
+
+---
+
+## 6. The rest of your questions
+
+**§6.2 extensions.** Allow-list: `KHR_texture_transform` (the black dragon
+uses it), `KHR_materials_unlit`, `KHR_materials_emissive_strength`. Outside
+the list but *not* in `extensionsRequired` → drop the extension, keep the
+model, note it on the listing. In `extensionsRequired` and unsupported (Draco,
+Meshopt, quantisation) → **reject the submission**: you cannot rebuild what
+you cannot decode, and `llms.txt` already forbids them.
+
+**§6.2b `KHR_materials_anisotropy` — drop it unless the mesh can carry it.**
+Anisotropy stretches the specular highlight ALONG THE TANGENT. A primitive with
+neither `TANGENT` nor `TEXCOORD_0` gives the renderer no direction, so each one
+invents its own and the model is a flat white smear in some viewers and correct
+in none — and lowering `anisotropyStrength` does not help, because the missing
+information is *which way*, not *how much* (expressed in the field: 0.9 → 0.15,
+no change). On a submission whose primitives lack both, DROP the extension and
+keep the model — the base colour is unaffected and the creature renders
+correctly without it. anyCreature 1.3.0 refuses to emit this case at all
+(`anisotropy_without_direction`), so any file carrying it was hand-edited or
+came from another tool.
+
+**§6.3 texture quality.** Lossless PNG out, always. These are pixel-art and
+flat-colour textures; lossy artefacts are visible at a glance and the
+submitters will notice. JPEG in → PNG out (already lossy once, do not stack a
+second generation). If the source has ≤256 distinct colours, write an indexed
+PNG — usually *smaller* than the original. If the clean file exceeds 10 MB,
+reject with a reason rather than silently degrading.
+
+**§6.4 metadata to write back.** Use the fields the submission API already
+reads, do not invent a second vocabulary: `asset.generator = "gobkit"`,
+`asset.copyright = <creator>`, and under `asset.extras`: `title`, `license:
+"CC0-1.0"`, plus `harness`, `harness_version`, `gate` and `source_spec` when
+present. Keep `source_spec` (re-parse and re-serialise it, cap it at 64 KB) —
+it is what makes wall creatures remixable, which is the point of CC0.
+
+**§6.5 failure handling.** Malformed or unknown structure → reject. Timeout →
+queue retry twice, then reject. **Never "keep but never unlock"** — a
+permanently locked row is storage you pay for and a submitter who is never
+told anything. Reject with a machine-readable code so the agent can quote it:
+`external_uri`, `unsupported_extension`, `broken_image`, `oversize_after_clean`,
+`parse_error`, `timeout`, plus `glbcheck`'s codes (they are listed in the
+output contract, use the same words on both sides).
+
+**§6.6 the existing gallery.** Yes, re-clean it. It is a small set, the slug
+stays, the bytes change — purge the CDN cache after. People who already
+downloaded have the old bytes; under CC0 that is harmless and not worth a
+notification.
+
+**§6.7 where to run it.** Covered in section 3: server-side, both stages;
+harness-side output is a cheapness optimisation, never a boundary.
+
+**§7 headers.** Agreed, do it now, and add two more of the same near-zero
+cost: `Content-Disposition: attachment` and
+`Cross-Origin-Resource-Policy: same-origin`.
+
+---
+
+## 7. What we are NOT doing
+
+We are not building the sanitiser, and we will not pretend the harness output
+is safe by construction just because it is clean today: someone can hand-edit
+a file and still stamp it `anyCreature`. `info.anyCreature` from `glbcheck`
+means "claims to be, and has the right shape" — it is a routing hint for the
+fast path, never an authorisation.
diff --git a/docs/OUTPUT_CONTRACT.md b/docs/OUTPUT_CONTRACT.md
new file mode 100644
index 0000000..1f14ae1
--- /dev/null
+++ b/docs/OUTPUT_CONTRACT.md
@@ -0,0 +1,107 @@
+# anyCreature GLB output contract (1.3.0)
+
+Everything this harness emits satisfies the contract below. It is not a wish
+list: every clause is enforced by `harness/glbcheck.mjs`, which runs on the
+delivered file before it is offered for upload, and can be re-run by anyone
+holding the file — including a server, in a Worker, with no dependencies:
+
+```js
+import { checkGLB } from './glbcheck.mjs';
+const { ok, errors, warnings, info } = checkGLB(bytes); // never throws
+```
+
+A receiving system can treat a file that satisfies this contract as
+**structurally known** — not as trusted. See "What this contract is not".
+
+## Container
+
+| Clause | Value |
+|---|---|
+| Format | glTF 2.0 binary (`glTF` magic, version `2`) |
+| Chunks | **exactly two**, JSON then BIN, in that order |
+| Extra chunks | none — ever |
+| Bytes after the last chunk | **zero**; the header's total length equals the file length exactly |
+| Buffers | exactly one, embedded in the BIN chunk, **no `uri` field** |
+| External references | **none**. No `http(s):`, no relative path, no `data:` URI, anywhere |
+| Compression extensions | none (`extensionsRequired` is absent) |
+| Direction-dependent materials | none. `KHR_materials_anisotropy` is refused on any primitive lacking `TANGENT`/`TEXCOORD_0` — it needs a direction, not a strength |
+| Typical size | 150–800 KB; the 10 MB submission ceiling is never approached |
+
+## Content
+
+| Clause | Value |
+|---|---|
+| Images / textures | **none.** Colour ships in `COLOR_0` vertex colours with AO already baked in. There is no EXIF/XMP surface at all |
+| `TEXCOORD_0` | absent unless the spec opts in with `keep_uv: true` |
+| Mesh | one, named `creature`; primitives merged one per material |
+| Skin | one, named `creature_rig`; every primitive carries `JOINTS_0` + `WEIGHTS_0` |
+| Material names | the spec's part names (`hide_torso`, `tusk`, `beak`) — semantic, never paths |
+| Bone names | limb bones match `^[LR][A-Z][A-Za-z]*\d+[A-Z][a-z]$` (`LArm1Sh`, `RFrontLeg1Kn`); axis bones are plain words (`Hips`, `Chest`, `Skull`) |
+| Animations | lowercase names, always `idle`, `move`, `attack` |
+| Orientation / units | +Z forward, +Y up, metres; `asset.extras.source_spec.height` states the intended real-world height and the build is verified within ±15% |
+| Accessors | counts, `min`/`max` finite and in range; every `bufferView` inside its buffer; every animation channel targets an existing node |
+| Strings | no control characters, no angle brackets, no filesystem paths in any name |
+
+## The `asset` block
+
+```jsonc
+"asset": {
+ "version": "2.0",
+ "generator": "anyCreature v1.3.0",
+ "copyright": "<the creator's signature, or absent>",
+ "extras": {
+ "harness": "anyCreature",
+ "harness_version": "1.3.0",
+ "spec": "<working name of the spec file>",
+ "monster": "<display name the creator typed>",
+ "gate": { "passed": true, "checks": [ { "name": "...", "passed": true } ] },
+ "license": "CC0-1.0", // written ONLY at publish, after consent
+ "source_spec": { /* the pristine authored spec — see below */ },
+ "parts": [ { "kind": "volume|part", "type": "...", "name": "...",
+ "material": "...", "host": "...", "join": "..." } ]
+ }
+}
+```
+
+`source_spec` is the **authored spec, verbatim** — the file the session wrote,
+re-read from disk rather than serialised from memory, so it recompiles
+byte-identically. It is plain JSON data: no URLs, no code, no references to
+anything outside itself, typically 4–12 KB (budget: 64 KB). It exists so the
+creature can be extracted, edited, recompiled, or grafted onto another
+creature (`harness/graft.py`). `embed_spec: false` in the spec opts out.
+
+`parts` is a flat manifest of what the creature is made of, so a receiver can
+list its pieces without parsing the whole spec.
+
+## Error vocabulary
+
+`glbcheck` reports machine-readable codes. A server rejecting a submission
+should quote the same code so an agent can tell the submitter what happened:
+
+| Code | Meaning |
+|---|---|
+| `parse_error` | not a GLB, wrong version, truncated, unparseable JSON |
+| `trailing_bytes` | bytes outside the declared file, or after the last chunk |
+| `extra_chunk` | a chunk that is neither JSON nor BIN |
+| `duplicate_keys` | a repeated key in one JSON object (a scanner and a loader would disagree) |
+| `external_uri` | a buffer or image points outside the file |
+| `unsupported_extension` | `extensionsRequired` names something we cannot read (Draco, Meshopt…) |
+| `path_leak` | a name contains a local filesystem path |
+| `unsafe_string` | a name contains control characters or angle brackets |
+| `accessor_bomb` | counts / ranges / targets that would crash a loader |
+| `anisotropy_without_direction` | a material uses `KHR_materials_anisotropy` on a primitive with neither `TANGENT` nor `TEXCOORD_0`. The extension stretches the highlight along the tangent, so with no direction field every renderer invents its own — a flat white smear that lowering the strength cannot fix |
+
+Warnings (`data_uri`, `unknown_extension`, `large_source_spec`, `chunk_count`,
+`flat_white_base`, `high_metal`, `anisotropy_derived_tangent`)
+are informational: the file is usable, something is merely unusual.
+
+## What this contract is not
+
+**It is not a security boundary.** `glbcheck` verifies shape; it does not
+rebuild, and a hostile file can satisfy every clause here and still carry
+something in a place we have not thought of. A public gallery accepting files
+from anyone should still rebuild each submission from the parsed data — the
+whitelist-rebuild described in `docs/HANDOVER_sanitize.md`. This contract's
+job is different and narrower: it makes anyCreature output *predictable*, so a
+receiver can validate cheaply, fast-path what it recognises, and report
+failures in words a person can act on.
diff --git a/engine/cli.js b/engine/cli.js
index 66c696d..9b78125 100644
--- a/engine/cli.js
+++ b/engine/cli.js
@@ -16,13 +16,85 @@ const [specPath, outPath] = process.argv.slice(2);
if (!specPath || !outPath) { console.error('usage: node cli.js <spec.json> <out.glb>'); process.exit(2); }
const spec = JSON.parse(fs.readFileSync(specPath, 'utf8'));
-require('./core/relative.js').resolveJoints(spec); // relational joints → coordinates
+require('./core/relative.js').resolveJoints(spec);
+
+// ── the shipped example is a SYNTAX REFERENCE, not a starting skeleton ──
+// A thin order ("a dragon") tempts the shortest path: open example/wolf.json,
+// recolour it, ship it. The customer asked for a dragon and gets a wolf that
+// reads as a fox. Templates were removed from this harness for exactly this
+// reason; this check stops the last template from sneaking back in as "the
+// example". Building the reference specs themselves is of course fine.
+{
+ const path_ = require('path');
+ const refs = ['../example/wolf.json', '../calibration/wolf_green.json',
+ '../calibration/wolf_red.json'].map(r => path_.join(__dirname, r));
+ const me = path_.resolve(specPath);
+ if (!refs.some(r => path_.resolve(r) === me)) {
+ const mine = spec.joints || {};
+ const names = Object.keys(mine);
+ for (const r of refs) {
+ let ref;
+ try { ref = JSON.parse(fs.readFileSync(r, 'utf8')); } catch { continue; }
+ require('./core/relative.js').resolveJoints(ref);
+ const rj = ref.joints || {};
+ const shared = names.filter(n => Array.isArray(rj[n]));
+ if (!names.length || shared.length / names.length < 0.9) continue;
+ // same names AND the same places = a copy, not a coincidence
+ const H = Math.max(...Object.values(rj).map(p2 => p2[1])) -
+ Math.min(...Object.values(rj).map(p2 => p2[1])) || 1;
+ const same = shared.filter(n => {
+ const a = mine[n], b = rj[n];
+ return Array.isArray(a) && Math.hypot(a[0]-b[0], a[1]-b[1], a[2]-b[2]) < 0.02 * H;
+ });
+ if (same.length / shared.length >= 0.9) {
+ console.error('='.repeat(68));
+ console.error(`BLOCK: example_copy: this spec is ${path_.basename(r)} with the numbers barely moved `
+ + `(${same.length}/${names.length} joints identical).`);
+ console.error('='.repeat(68));
+ console.error('the example is a SYNTAX reference, not a starting skeleton — a thin order is not');
+ console.error('permission to ship the example in a new colour. Build this creature\'s own skeleton');
+ console.error('from its own brief: the identity gate compares what a stranger SEES against what');
+ console.error('the brief promised, and a recoloured wolf never reads as the creature that was ordered.');
+ process.exit(1);
+ }
+ }
+ }
+} // relational joints → coordinates
const sk = buildSkeleton(spec); // also registers mirrored chains
const meshes = compile(spec);
for (const line of require('./core/compile.js').drainInfo())
console.error('info: ' + line); // the compiler narrates what happened
const { fails, warns } = runChecks(spec, sk, meshes, null);
for (const w of warns) console.error('warn: ' + w); // measures, not laws — you judge
+
+// ── the gate stamp, written by the machine that ran the checks ─────────────
+// card 04 needs a gate.json listing every check and whether it passed. That
+// used to be assembled by hand at the END of a run — the single most expensive
+// moment in the whole build, because the conversation is at its longest and
+// every token costs several times what it did at round 3 — and assembled from
+// memory, which is exactly what iron law 10 says not to trust. The engine ran
+// the checks; the engine writes them down. Roster matches harness/gates.json.
+const ENGINE_CHECKS = ['mesh_integrity', 'root_containment', 'part_attachment',
+ 'touch', 'balance', 'size', 'proportion', 'limb_clearance', 'anim_integrity',
+ 'attack_reach', 'faceted_body', 'mirror_distortion', 'part_overlap', 'part_seat'];
+try {
+ const said = (name, list) => list.some(m => String(m).toLowerCase().includes(name));
+ const stamp = {
+ spec: require('path').basename(specPath),
+ passed: fails.length === 0,
+ checks: ENGINE_CHECKS.map(n => ({
+ name: n,
+ passed: !said(n, fails),
+ ...(said(n, warns) ? { warned: true } : {}),
+ })),
+ blocking: fails.slice(),
+ measures: warns.slice(),
+ };
+ fs.mkdirSync(require('path').dirname(outPath), { recursive: true });
+ fs.writeFileSync(outPath.replace(/\.glb$/i, '') + '.checks.json',
+ JSON.stringify(stamp, null, 1));
+} catch (e) { console.error('warn: could not write the checks stamp: ' + e.message); }
+
if (fails.length) {
console.error('='.repeat(68));
for (const f of fails) console.error('BLOCK: ' + f);
@@ -34,7 +106,20 @@ const anims = compileAnims(spec, sk);
// UV atlas is opt-in ("keep_uv": true): without textures TEXCOORD_0 is dead
// weight in the shipped file, and AO now bakes into vertex colours instead
const uvInfo = spec.keep_uv ? require('./core/uv.js').applyUVs(meshes) : null;
-const aoInfo = require('./core/ao.js').bakeAO(meshes, spec.ao); // vertex AO → COLOR_0 (ao:false skips)
+// The L1-L8 stack takes AO and the vertex normals as INPUTS — its flesh and
+// hardware shading each apply AO with their own amount and gamma — so AO is
+// recorded here and applied by the stack, not multiplied in on the way past.
+const STACK = require('./core/compile.js').useStack(spec);
+const aoCfg = STACK && spec.ao !== false
+ ? Object.assign({}, (typeof spec.ao === 'object' && spec.ao) || {}, { multiply: false })
+ : spec.ao;
+const aoInfo = require('./core/ao.js').bakeAO(meshes, aoCfg); // vertex AO → COLOR_0 (ao:false skips)
+if (STACK) {
+ const { drainInfo } = require('./core/compile.js');
+ const shInfo = [];
+ require('./core/shade.js').shadeStack(spec, meshes, shInfo);
+ for (const line of shInfo) console.log('info: ' + line);
+}
// public identity: harness stamp + convention bone names (internal names stay authoring-side)
let hv = '0.0.0';
for (const vp of ['..', '.']) {
@@ -45,13 +130,60 @@ const asset = {
generator: `anyCreature v${hv}`,
extras: { harness: 'anyCreature', harness_version: hv, spec: specName },
};
+// The GLB carries its own birth certificate: the PRISTINE authored spec (a
+// second parse of the file — the in-memory spec has been mutated by joint
+// resolution and mirror registration and would not recompile cleanly) plus a
+// quick parts manifest. Any agent holding the GLB can extract, edit, and
+// recompile — and graft parts between creatures. "embed_spec": false opts out.
+if (spec.embed_spec !== false) {
+ const pristine = JSON.parse(fs.readFileSync(specPath, 'utf8'));
+ asset.extras.source_spec = pristine;
+ asset.extras.parts = [
+ ...(pristine.volumes || []).map(v => ({ kind: 'volume', chain: v.chain, material: v.material })),
+ ...(pristine.parts || []).map(p => ({ kind: 'part', type: p.type, name: p.name || null,
+ material: p.material, host: p.host || (p.ribs ? 'ribs' : null), join: p.join || null })),
+ ];
+}
const names = require('./core/skeleton.js').exportNames(spec, sk);
+// L8: the only layer that leaves COLOR_0 and goes into the file's NORMAL, so
+// the user's own lighting reacts to it. Flesh only — see the note in glb.js.
+const L8 = STACK
+ ? (((spec.shading || {}).normals || {}).flesh ?? 0.90)
+ : 0;
const bytes = writeGLB({ meshes, skeleton: sk, ibm: inverseBindMatrices(sk), anims }, outPath,
- { asset, names });
+ { asset, names, boneNormals: L8 });
+if (L8) {
+ const moved = require('./core/glb.js').L8_MOVED;
+ const tot = moved.reduce((a, r) => a + r[1], 0), all = moved.reduce((a, r) => a + r[2], 0);
+ if (tot) console.log(`info: shade L8: shipped NORMAL softened toward the bone field on `
+ + `${tot}/${all} flesh vertices at ${(L8 * 100) | 0}% (${moved.map(r => r[0]).join(', ')})`);
+}
+// Contract self-check on the bytes we just wrote (docs/OUTPUT_CONTRACT.md).
+// ~1.4 ms, and it fires on EVERY build: a file that breaks the contract must
+// never reach a delivery folder, a viewer, or a submission — and if one does,
+// that is a harness bug we want to hear about at the moment it is created.
+const { checkGLB } = require('./core/contract.js');
+const conf = checkGLB(fs.readFileSync(outPath));
+if (!conf.ok) {
+ console.error('='.repeat(68));
+ for (const e of conf.errors) console.error(`BLOCK: contract [${e.code}] ${e.msg}`);
+ console.error('='.repeat(68));
+ console.error('the written GLB would break the output contract, so it was NOT kept.');
+ console.error('usually a name in your spec: material / chain / joint names must be plain');
+ console.error('words — no angle brackets, control characters, or filesystem paths. If every');
+ console.error('name in the spec looks fine, this is a harness bug: please report it.');
+ try { fs.unlinkSync(outPath); } catch {}
+ process.exit(1);
+}
+
const tv = meshes.reduce((a, m) => a + m.V.length, 0);
const tf = meshes.reduce((a, m) => a + m.F.length, 0);
+const allV = meshes.flatMap(m => m.V);
+const dims = [0, 1, 2].map(k => +(Math.max(...allV.map(v => v[k])) - Math.min(...allV.map(v => v[k]))).toFixed(3));
console.log(JSON.stringify({ ok: true, out: outPath, bytes,
+ dims: { width: dims[0], height: dims[1], length: dims[2] },
verts: tv, faces: tf, joints: sk.joints.length,
anims: anims.map(a => a.name), checks: 'all green',
uv: uvInfo ? { islands: uvInfo.islands, atlasUtil: +uvInfo.atlasUtil.toFixed(2) } : 'off',
- ao: aoInfo.baked ? { meanOcc: +aoInfo.meanOcc.toFixed(3) } : 'off' }));
+ ao: aoInfo.baked ? { meanOcc: +aoInfo.meanOcc.toFixed(3) } : 'off',
+ contract: 'ok' }));
diff --git a/engine/core/ao.js b/engine/core/ao.js
index ea64890..b8a65ab 100644
--- a/engine/core/ao.js
+++ b/engine/core/ao.js
@@ -25,6 +25,7 @@ function bakeAO(meshes, cfg) {
const opt = typeof cfg === 'object' && cfg ? cfg : {};
const SAMPLES = opt.samples ?? 16;
const STRENGTH = opt.strength ?? 0.59;
+ const MULT = opt.multiply !== false; // false = record it, let the stack apply it
// ── triangle soup + bounds ──
const tris = []; // [a,b,c] as vec3s
@@ -127,8 +128,14 @@ function bakeAO(meshes, cfg) {
}
const occ = hits / SAMPLES;
const ao = 1 - STRENGTH * occ;
- const c = m.C[vi];
- m.C[vi] = [c[0] * ao, c[1] * ao, c[2] * ao];
+ // Keep AO as its own factor, and keep the normal that produced it. The
+ // L1-L8 stack needs both as INPUTS — its flesh and hardware shading each
+ // apply AO with their own amount and gamma — and it cannot recover either
+ // one once they have been multiplied into the colour. Storing them costs
+ // two arrays and lets `multiply:false` hand the decision downstream.
+ (m.AO || (m.AO = []))[vi] = ao;
+ (m.N || (m.N = []))[vi] = n;
+ if (MULT) { const c = m.C[vi]; m.C[vi] = [c[0] * ao, c[1] * ao, c[2] * ao]; }
vcount++; occSum += occ;
});
}
diff --git a/engine/core/checks.js b/engine/core/checks.js
index 0aaf3da..de30f3d 100644
--- a/engine/core/checks.js
+++ b/engine/core/checks.js
@@ -91,6 +91,53 @@ function foldCount(V, F, minArea2 = 0) {
return folds;
}
+
+// How much of one mesh's skin can show an edge: the share of interior edges
+// whose dihedral angle reaches the smoothing angle, i.e. exactly the edges
+// smoothSplit() will crease. Computed here rather than after the fact because
+// checks run before the GLB is assembled.
+
+// A correct walk still drifts forward a little across the contact frames as the
+// foot rolls through heel-strike and toe-off, so the bar is a share of stride,
+// not zero.
+const GAIT_FWD_MAX = 0.15;
+
+const SOFT_FLOOR = 10; // percent of volume edges that must be able to crease
+
+function creaseShare(V, F, deg) {
+ const tri = [];
+ for (const f of F) {
+ if (f.length === 3) tri.push(f);
+ else if (f.length === 4) { tri.push([f[0], f[1], f[2]]); tri.push([f[0], f[2], f[3]]); }
+ }
+ const fn = [];
+ for (const [a, b, c] of tri) {
+ const A = V[a], B = V[b], C = V[c];
+ const u = [B[0]-A[0], B[1]-A[1], B[2]-A[2]], w = [C[0]-A[0], C[1]-A[1], C[2]-A[2]];
+ const n = [u[1]*w[2]-u[2]*w[1], u[2]*w[0]-u[0]*w[2], u[0]*w[1]-u[1]*w[0]];
+ const l = Math.hypot(n[0], n[1], n[2]);
+ fn.push(l > 1e-12 ? [n[0]/l, n[1]/l, n[2]/l] : null);
+ }
+ const key = new Map();
+ const at = i => V[i].map(x => Math.round(x * 1e4)).join(',');
+ tri.forEach((f, i) => {
+ for (const [u, v] of [[f[0], f[1]], [f[1], f[2]], [f[2], f[0]]]) {
+ const a = at(u), b = at(v), k = a < b ? a + '|' + b : b + '|' + a;
+ (key.get(k) || key.set(k, []).get(k)).push(i);
+ }
+ });
+ const cos = Math.cos(deg * Math.PI / 180);
+ let hard = 0, tot = 0;
+ for (const fs of key.values()) {
+ if (fs.length !== 2) continue;
+ const p = fn[fs[0]], q = fn[fs[1]];
+ if (!p || !q) continue;
+ tot++;
+ if (p[0]*q[0] + p[1]*q[1] + p[2]*q[2] < cos) hard++;
+ }
+ return { hard, tot };
+}
+
function runChecks(spec, sk, meshes, animsCompiled) {
const fails = [];
const warns = []; // hoisted: checks above the part_overlap block also report measures
@@ -100,8 +147,8 @@ function runChecks(spec, sk, meshes, animsCompiled) {
// `faceted: true` on a VOLUME shatters the mass into one independent facet per
// triangle — an 800-triangle torso becomes 800 shards — and because AO bakes
// from those normals the mess ships inside COLOR_0, where no relighting can
- // reach it. Two real runs (gryphon, mammoth) came back 89% and 93% hard-edged
- // this way. Bodies are smooth-shaded. Parts — plates, spikes, claws, crystal,
+ // reach it — a faceted body comes back ~90% hard-edged. Bodies are
+ // smooth-shaded. Parts — plates, spikes, claws, crystal,
// armour — may still face freely; only volumes are covered.
if (spec.build !== 'rigid') {
const bad = (spec.volumes || []).filter(v => v.faceted).map(v => `"${v.chain}"`);
@@ -112,6 +159,48 @@ function runChecks(spec, sk, meshes, animsCompiled) {
+ '"build": "rigid" at spec level.');
}
+ // soft_mass — THE ROUNDED SAUSAGE. The opposite failure to `faceted`, and far
+ // more common, because it is what you get by DEFAULT.
+ //
+ // A volume is a tube of `sides` walls, so the angle between neighbouring walls
+ // is 360/sides, and `smooth_angle` (default 50) welds every edge under it: 9
+ // sides is 40 degrees, 16 is 22. Nothing on that mass can then break — not the
+ // shading, not the outline — and it renders as a smooth bean. The ruler is the
+ // share of VOLUME edges that reach their own smoothing angle.
+ if (spec.build !== 'rigid' && !spec.qa_isolate) {
+ const per = [];
+ let hard = 0, tot = 0;
+ for (const m of meshes) {
+ if (m.part) continue; // parts may be any shape they like
+ const vol = (spec.volumes || []).find(v => v.chain === m.chain);
+ if (vol && vol.soft) continue; // declared a soft organic lump
+ const deg = m.faceted ? 0 : (m.smoothAngle ?? 50);
+ const r = creaseShare(m.V, m.F, deg);
+ if (!r.tot) continue;
+ hard += r.hard; tot += r.tot;
+ per.push({ chain: m.chain, pct: 100 * r.hard / r.tot, edges: r.tot, deg });
+ }
+ if (tot) {
+ const pct = 100 * hard / tot;
+ if (pct < SOFT_FLOOR) {
+ per.sort((a, b) => (a.pct - b.pct) || (b.edges - a.edges));
+ const worst = per.slice(0, 3).map(p =>
+ `"${p.chain}" ${p.pct.toFixed(0)}% (smooth_angle ${p.deg})`).join(', ');
+ fails.push(`soft_mass: only ${pct.toFixed(0)}% of this creature's skin can show an edge `
+ + `at all (the floor is ${SOFT_FLOOR}%). Nothing breaks, so every mass renders as a smooth `
+ + `bean. Softest first: ${worst}. The lever that works is smooth_angle ON THE VOLUME: a volume's wall `
+ + `angle is 360/sides, so 9 sides is 40° and 16 sides is 22°, and the default 50° welds `
+ + `both perfectly smooth. Drop it under the wall angle on the masses named above — `
+ + `applying exactly this number to every volume of the creature that was `
+ + `rejected took it from 29% to 69% and left the side silhouette at IoU 1.000 — the FORM `
+ + `is untouched, only the shading hardens. Fewer "sides" works too and thins the outline a little. A "sharp" row `
+ + `is the SILHOUETTE lever, not this one, and it does nothing unless the radius steps `
+ + `across it. A mass that is genuinely meant to be a smooth lump — a slug, a bladder, a `
+ + `droplet — declares "soft": true and drops out of this count.`);
+ }
+ }
+ }
+
// QA isolation builds ("qa_isolate": true): a lone part rendered for the MID
// blind-read is not a creature — whole-body laws (balance, containment,
// proportion…) don't apply. Geometry must still be sound.
@@ -145,6 +234,17 @@ function runChecks(spec, sk, meshes, animsCompiled) {
const ys0 = allV0.map(v => v[1]);
const modelH = Math.max(...ys0) - Math.min(...ys0) || 1;
const edgeFloor = 0.015 * modelH; // edges shorter than 1.5% of height don't vote
+
+ // 0. declared size — "height" (metres, ground to crown). Size is identity:
+ // a 1.7 m "giant" is just a man. The build must land within ±15%.
+ if (spec.height) {
+ const err = Math.abs(modelH - spec.height) / spec.height;
+ if (err > 0.15)
+ fails.push(`size: spec declares height ${spec.height} m but the build stands `
+ + `${modelH.toFixed(2)} m (${Math.round(err * 100)}% off) — multiply every joint coordinate `
+ + `by ${(spec.height / modelH).toFixed(4)} to land on the declaration, or change the `
+ + `declaration to ${modelH.toFixed(2)}.`);
+ }
const areaFloor2 = Math.pow(0.0004 * modelH * modelH, 2); // ~sliver faces don't vote
// 1. anim_integrity
@@ -249,19 +349,47 @@ function runChecks(spec, sk, meshes, animsCompiled) {
const host = volsByChain[hostChain];
const rootRing = v._rings[0];
let inside = 0;
+ // Keep how far past the surface each ring point sits, and which host centre
+ // it is nearest. The check already computes both; throwing them away and
+ // saying only "deeper" makes the reader re-derive the geometry the engine
+ // just did — the same work, done twice, once in code and once by hand.
+ const over = []; let nearC = null, nearD = Infinity;
for (const p of rootRing) {
let best = Infinity, bs = 0;
host._pts.forEach((c2, si) => { const d = G.len(G.sub(p, c2)); if (d < best) { best = d; bs = si; } });
const ring = host._rings[bs]; const c2 = host._pts[bs];
const rad = Math.max(...ring.map(q => G.len(G.sub(q, c2))));
+ over.push(best - rad * 0.98);
+ if (best < nearD) { nearD = best; nearC = c2; }
if (best < rad * 0.98) inside++;
}
- if (inside < rootRing.length * 0.8)
- fails.push(`root_containment: chain "${cn}" root ring is ${Math.round(100 * (1 - inside / rootRing.length))}% outside its host "${hostChain}" — the open ring will show on the surface; bury the root joint deeper`);
+ if (inside < rootRing.length * 0.8) {
+ // 80% of the ring has to end up inside, so the move that fixes it is the
+ // 80th-percentile overshoot — not the worst point, which would bury it
+ // further than the rule asks for.
+ const sorted = over.slice().sort((a, b) => a - b);
+ const need = sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.8))];
+ // Name the CHAIN'S OWN first joint, not the host joint it hangs from.
+ // Moving the host drags this chain along with it, so that correction can
+ // never converge — applying it repeatedly just walks the pair across the
+ // model. The thing sitting outside the host is this chain's root ring.
+ const ownRoot = (spec.chains[cn] || [])[0] || hostJoint;
+ const jp = sk.joints[sk.index[ownRoot]] && sk.joints[sk.index[ownRoot]].pos;
+ let dirTxt = '';
+ if (nearC && jp) {
+ const d = G.sub(nearC, jp), L = G.len(d) || 1;
+ dirTxt = ` toward [${d.map(x => (x / L).toFixed(2)).join(', ')}]`;
+ }
+ fails.push(`root_containment: chain "${cn}" root ring is `
+ + `${Math.round(100 * (1 - inside / rootRing.length))}% outside its host "${hostChain}" `
+ + `— the open ring will show on the surface. Move joint "${ownRoot}" about `
+ + `${Math.max(0, need).toFixed(3)}m${dirTxt} (into the host), or widen "${hostChain}" `
+ + `there by the same amount.`);
+ }
}
// 5. limb clearance — mirrored volumes must not touch across the centreline
- // (measured only on exposed verts below the torso)
+ // (Verified:ly on exposed verts below the torso)
{
const hostOf = cn => {
const hj = (spec.attach || {})[cn]; if (!hj) return null;
@@ -286,7 +414,10 @@ function runChecks(spec, sk, meshes, animsCompiled) {
const minX = Math.min(...exposed.map(p => Math.abs(p[0])));
const clearance = 2 * minX;
if (clearance < 0.03 * modelH)
- fails.push(`limb_clearance: "${cn}" and its mirror are ${clearance.toFixed(3)} apart at the centreline (need ≥ ${(0.03 * modelH).toFixed(3)}) — legs will interpenetrate in motion`);
+ fails.push(`limb_clearance: "${cn}" and its mirror are ${clearance.toFixed(3)} apart at the `
+ + `centreline (need ≥ ${(0.03 * modelH).toFixed(3)}) — legs will interpenetrate in motion. `
+ + `Move "${cn}" ${(((0.03 * modelH) - clearance) / 2).toFixed(3)} further out in x `
+ + `(the mirror follows), or narrow the limb by the same amount.`);
}
}
@@ -309,6 +440,10 @@ function runChecks(spec, sk, meshes, animsCompiled) {
// host would measure the width of the creature. The source carries the
// verdict for both; any twin-only deformation is mirror_distortion's job.
if (m._mirrorSrc) continue;
+ // "join":"place" is the designer DECLARING deliberate detachment (a
+ // floating rune, an orbiting shard) — the strict law yields to it;
+ // part_seat still reports the measured burial for the record.
+ if (m.join === 'place') continue;
const host = volsByChain[m.hostChain];
if (!host || !host._rings) continue;
let nearest = Infinity;
@@ -320,11 +455,17 @@ function runChecks(spec, sk, meshes, animsCompiled) {
if (outside < nearest) nearest = outside;
}
if (nearest > gap)
+ // Say the MOVE, not just the gap. The engine measured the distance; a
+ // message that reports it and stops makes the reader work the
+ // subtraction back out of the prose. The first third of a root is meant
+ // to be embedded, so the useful number is the one that buries it, not
+ // the one that merely touches: gap + a third of the part's own reach.
fails.push(`part_attachment: "${m.part}" never meets its host "${m.hostChain}" — its closest `
+ `point still stands ${nearest.toFixed(3)} clear of the surface (tolerance ${gap.toFixed(3)}). `
- + `It is floating: it will read as a detached sticker and drift the moment the host animates. `
- + `Bury the root inside the host (the first third of a root is meant to be embedded — that is `
- + `what hides the seam), or move its anchor onto the surface.`);
+ + `Move it ${(nearest + gap).toFixed(3)} INTO the host along its own axis — touching is the `
+ + `floor, and the first third of a root is meant to be embedded, which is what hides the seam. `
+ + `Or move its anchor onto the surface. `
+ + `Floating, it reads as a detached sticker and drifts the moment the host animates.`);
}
}
@@ -435,6 +576,167 @@ function runChecks(spec, sk, meshes, animsCompiled) {
}
}
+ // 7b. gait_direction — A PLANTED FOOT MUST TRAVEL BACKWARD.
+ //
+ // The clips loop in place, so the ground does the moving: while a foot is on
+ // the ground it must sweep BACKWARD under the body, and that is what pushes
+ // the creature forward. Swing it backward and sweep it forward instead and you
+ // have a perfectly smooth walk cycle that plays in reverse — invisible in every
+ // still frame, obvious the moment it moves.
+ {
+ const mv = animsResolved.find(a => a.name === 'move');
+ if (mv) {
+ const feet = [];
+ for (const [cn, js] of Object.entries(spec.chains || {})) {
+ if (!/leg|foot|paw/i.test(cn)) continue;
+ const last = js[js.length - 1];
+ if (last && sk.index[last] != null) feet.push(last);
+ }
+ for (const jn of feet) {
+ const N = 24, path = [];
+ for (let s = 0; s <= N; s++) {
+ const w = jointWorlds(sk, locals, mv, s / N);
+ path.push(matVec(w[sk.index[jn]], [0, 0, 0]));
+ }
+ const ys = path.map(p => p[1]), zs = path.map(p => p[2]);
+ const ymin = Math.min(...ys), ymax = Math.max(...ys);
+ const stride = Math.max(...zs) - Math.min(...zs);
+ if (stride < 1e-3 || ymax - ymin < 1e-4) continue; // not a stepping leg
+ // Sum the per-step forward travel over contact frames, rather than
+ // (last - first): a contact phase that straddles the loop point would
+ // otherwise subtract two frames that are the same frame and read 0.
+ const low = path.map(p => p[1] < ymin + (ymax - ymin) * 0.30);
+ let net = 0, contact = 0;
+ for (let s = 0; s < path.length - 1; s++) {
+ if (!(low[s] && low[s + 1])) continue;
+ net += path[s + 1][2] - path[s][2];
+ contact++;
+ }
+ if (contact < 2) continue;
+ if (net > stride * GAIT_FWD_MAX) {
+ fails.push(`gait_direction: "${jn}" travels ${net.toFixed(3)} m FORWARD while it is on `
+ + `the ground — ${(100 * net / stride).toFixed(0)}% of its own ${stride.toFixed(2)} m `
+ + `stride, in the wrong direction. A planted foot must sweep BACKWARD under the body; `
+ + `that is what makes the creature look like it is going somewhere. This clip swings `
+ + `the leg back through the air and pushes it forward on the ground, which is a walk `
+ + `cycle playing in reverse — smooth, correct-looking in every still, and visibly `
+ + `backwards the moment it moves. THE FIX: write ONE leg correctly (negate its hip/knee/hock rx `
+ + `tracks so it reaches forward through the air and sweeps back on the ground), `
+ + `DELETE the hand-written opposite leg, and set "mirror_phase": 0.5 on the clip so `
+ + `the engine generates it half a cycle out. Hand-writing the second leg is where the `
+ + `phase error comes from and it is twice the authoring for a worse result.`);
+ }
+ }
+ }
+ }
+
+ // 7c. root_drive — DO NOT NAIL THE CREATURE DOWN BY ITS ROOT.
+ //
+ // A lunge written on a joint that is not the skeleton root moves everything
+ // BELOW that joint and leaves the root exactly where it was. On a creature
+ // whose root is the rump, the body lunges and the backside stays pinned to the
+ // floor, which reads as being nailed down.
+ {
+ const root = sk.joints.find(j => j.parent < 0);
+ for (const anim of animsResolved) {
+ const moved = Object.entries(anim.tracksResolved || {})
+ .filter(([, tr]) => tr.tz).map(([jn]) => jn);
+ if (!moved.length || !root) continue;
+ const bind = jointWorlds(sk, locals, null, 0);
+ let peak = 0, pu = 0;
+ for (let s = 0; s <= 20; s++) {
+ const w = jointWorlds(sk, locals, anim, s / 20);
+ for (const jn of moved) {
+ const d = matVec(w[sk.index[jn]], [0, 0, 0])[2] - matVec(bind[sk.index[jn]], [0, 0, 0])[2];
+ if (Math.abs(d) > Math.abs(peak)) { peak = d; pu = s / 20; }
+ }
+ }
+ if (Math.abs(peak) < 0.05) continue; // not really a lunge
+ const w = jointWorlds(sk, locals, anim, pu);
+ const rd = matVec(w[sk.index[root.name]], [0, 0, 0])[2]
+ - matVec(bind[sk.index[root.name]], [0, 0, 0])[2];
+ if (Math.abs(rd) < Math.abs(peak) * 0.6) {
+ fails.push(`root_drive: "${anim.name}" drives ${moved.map(m => `"${m}"`).join(', ')} `
+ + `${peak.toFixed(2)} m forward, but the skeleton ROOT "${root.name}" moves `
+ + `${rd.toFixed(3)} m. Everything below the driven joint lunges and the root stays where `
+ + `it was, so the creature reads as nailed to the floor by that end of itself. Put the `
+ + `"tz" track on "${root.name}" instead — it is the root, so the whole body follows it. `
+ + `Card 03's own example does exactly that.`);
+ }
+ }
+ }
+
+ // 7d. THE COLOUR QUESTIONS A READER WAS BEING PAID TO ANSWER.
+ //
+ // Both are arithmetic on the palette — microseconds, no render, no subagent.
+ //
+ // These are ADVICE. A number saying the eye will not separate two masses is
+ // worth reading and is not worth refusing a build over — camouflage and
+ // deliberately subtle detail are real design choices. What is NOT acceptable
+ // is spending a reader to learn them.
+ {
+ let hex2lab = null;
+ try { hex2lab = require('./shade.js').hex2lab; } catch { /* no stack, skip */ }
+ const pal = spec.palette || {};
+ const lab = {};
+ if (hex2lab) for (const [k, v] of Object.entries(pal)) {
+ const c = (v && v.color) || (typeof v === 'string' ? v : null);
+ if (typeof c === 'string' && /^#[0-9a-f]{6}$/i.test(c)) lab[k] = hex2lab(c.slice(1));
+ }
+ const dist = (a, b) => Math.hypot(lab[a][0]-lab[b][0], lab[a][1]-lab[b][1], lab[a][2]-lab[b][2]);
+
+ // value_order — the whole value plan, sorted, so nobody squints at a render.
+ const byL = Object.keys(lab).sort((a, b) => lab[b][0] - lab[a][0]);
+ if (byL.length > 1) {
+ warns.push('value_order: materials by lightness, brightest first — '
+ + byL.map(k => `${k} ${lab[k][0].toFixed(2)}`).join(' · '));
+ // whatever is brightest OWNS the eye. If something else is within 0.05 of
+ // it, they compete and neither wins.
+ const top = byL[0];
+ const tied = byL.slice(1).filter(k => lab[top][0] - lab[k][0] < 0.05);
+ if (tied.length)
+ warns.push(`value_order: "${top}" (L ${lab[top][0].toFixed(2)}) is tied for brightest with `
+ + tied.map(k => `"${k}" (${lab[k][0].toFixed(2)})`).join(', ')
+ + ' — nothing owns the eye when two masses sit at the same value. Drop the one that is '
+ + 'NOT the brief\'s dominant focal by at least 0.08 L, or accept that the eye will '
+ + 'ping-pong.');
+ }
+
+ // contrast_adjacent — a part must separate from what it SITS ON. Materials
+ // inside one visual mass are deliberately close (three shades of black
+ // quill are one mass), so this only compares a part to its host.
+ const volMat = {};
+ for (const m of meshes) if (!m.part && m.chain) volMat[m.chain] = m.material;
+ const seen = new Set();
+ for (const m of meshes) {
+ if (!m.part || !m.hostChain) continue;
+ const a = m.material, b = volMat[m.hostChain];
+ if (!a || !b || a === b) {
+ if (a && a === b) {
+ const k = `${m.part}|${a}`;
+ if (!seen.has(k)) {
+ seen.add(k);
+ warns.push(`contrast_adjacent: part "${m.part}" wears the SAME material "${a}" as the `
+ + `"${m.hostChain}" it sits on — at reading size it is not a part, it is a bump. `
+ + `Give it its own entry in the palette.`);
+ }
+ }
+ continue;
+ }
+ if (!lab[a] || !lab[b]) continue;
+ const d = dist(a, b);
+ if (d < 0.10) {
+ const k = `${a}|${b}`;
+ if (seen.has(k)) continue;
+ seen.add(k);
+ warns.push(`contrast_adjacent: part "${m.part}" (${a}, L ${lab[a][0].toFixed(2)}) against its `
+ + `host "${m.hostChain}" (${b}, L ${lab[b][0].toFixed(2)}) — OKLab distance ${d.toFixed(3)}, `
+ + `under 0.10. They will read as one mass at thumbnail size. Move one of them in `
+ + `LIGHTNESS, which is what survives shrinking; hue alone does not.`);
+ }
+ }
+ }
+
// 8. declared adjacency — "touch": [["chainA","chainB"], ...]. Declared-
// connected chains must actually meet; a gap reads as floating bodyparts.
{
@@ -457,7 +759,10 @@ function runChecks(spec, sk, meshes, animsCompiled) {
if (d < eps) { met = true; break outer; }
}
if (!met)
- fails.push(`touch: "${ca}" and "${cb}" are declared connected but their surfaces stay ${best.toFixed(3)} apart — overlap the volumes so the join is buried`);
+ fails.push(`touch: "${ca}" and "${cb}" are declared connected but their surfaces stay `
+ + `${best.toFixed(3)} apart. Close the gap by at least ${best.toFixed(3)} and then keep `
+ + `going — move one chain's end joint ${(best * 1.5).toFixed(3)} toward the other, so the `
+ + `join is BURIED rather than merely touching; a seam that only kisses still shows.`);
}
}
@@ -487,6 +792,55 @@ function runChecks(spec, sk, meshes, animsCompiled) {
}
}
+ // 10. part_seat — is the part's base ring actually buried in a body?
+ // The exposed-root class: tusks starting in mid-air, beaks hovering off
+ // the face, a trunk that reads as a bolted-on object. Every hosted
+ // curve/spike carries its base ring (`_seatIdx`); how it is ALLOWED to
+ // meet the body is the declared "join":
+ // "insert" → base ring ≥60% inside a volume, or BLOCK
+ // "extrude" → base ring CENTRE inside a volume (grows out of the skin), or BLOCK
+ // "snap" → the part must ride an anchor (surface conform), or BLOCK
+ // "place" → deliberately free-floating — no test (rare; justify it)
+ // Undeclared parts are measured anyway: a base ring under 50% buried is
+ // a warn — look at the junction and either sink it or declare the join.
+ {
+ const vols = Object.values(volsByChain);
+ const insideAnyVol = (q) => {
+ for (const vol of vols) {
+ let best = Infinity, bs = 0;
+ vol._pts.forEach((c2, si) => { const d = G.len(G.sub(q, c2)); if (d < best) { best = d; bs = si; } });
+ const c2 = vol._pts[bs];
+ const rad = Math.max(...vol._rings[bs].map(r2 => G.len(G.sub(r2, c2))));
+ if (best < rad * 0.98) return true;
+ }
+ return false;
+ };
+ const JOINS = new Set(['insert', 'extrude', 'snap', 'place', undefined]);
+ for (const pt of spec.parts || []) {
+ if (!JOINS.has(pt.join))
+ fails.push(`part_seat: unknown join "${pt.join}" on '${pt.name || pt.type}' — use insert / extrude / snap / place`);
+ if (pt.join === 'snap' && !pt.anchor)
+ fails.push(`part_seat: '${pt.name || pt.type}' declares join "snap" but has no "anchor" — snap means riding the surface`);
+ }
+ if (vols.length) for (const m of meshes) {
+ if (!m._seatIdx) continue;
+ let seat = m._seatIdx.map(i => m.V[i]).filter(Boolean);
+ if (!seat.length) continue;
+ // mirrored twins: the vols list holds the LEFT/axis volumes, so test the
+ // twin's seat in mirror space (x-flipped) — symmetric by construction
+ if (m.part && m.part.endsWith('.R')) seat = seat.map(q => [-q[0], q[1], q[2]]);
+ const buried = seat.filter(insideAnyVol).length / seat.length;
+ const centre = seat.reduce((a, q) => G.add(a, q), [0, 0, 0]).map(x => x / seat.length);
+ const label = m.part || 'part';
+ if (m.join === 'insert' && buried < 0.6)
+ fails.push(`part_seat: '${label}' declares join "insert" but its base ring is only ${Math.round(buried * 100)}% inside a body (need ≥60%) — sink the root deeper or thicken the host`);
+ else if (m.join === 'extrude' && !insideAnyVol(centre))
+ fails.push(`part_seat: '${label}' declares join "extrude" but its base centre sits outside every body — the part does not grow out of a surface`);
+ else if (!m.join && buried < 0.5)
+ warns.push(`part_seat: '${label}' base ring is ${Math.round(buried * 100)}% buried — the root may show; sink it, or declare the join (insert/extrude/snap/place)`);
+ }
+ }
+
return { fails, warns };
}
diff --git a/engine/core/compile.js b/engine/core/compile.js
index b0422f2..bb6b613 100644
--- a/engine/core/compile.js
+++ b/engine/core/compile.js
@@ -267,7 +267,8 @@ function buildSpike(spec, p) {
for (const s of p.segments) { pts.push(G.add(pts[pts.length - 1], G.mul(dir, s.len))); radii.push(Math.max(s.r * 0.35, 0.004)); }
const rings = G.chainRings(pts, radii, p.sides || 6, false);
const part = G.partFromRings(rings, p.sides || 6, 'ngon', 'fan', pts);
- return { material: p.material, V: part.v, F: part.fq,
+ return { material: p.material, V: part.v, F: part.fq, join: p.join,
+ _seatIdx: Array.from({ length: p.sides || 6 }, (_, i) => i), // base ring = the part's socket
skin: part.v.map(() => [[p.host, 1]]) };
}
@@ -351,7 +352,8 @@ function buildCurve(spec, p) {
const bend = Math.acos(Math.max(-1, Math.min(1, G.dot(d0, t)))) * 180 / Math.PI;
const dy = pts[pts.length - 1][1] - pts[0][1];
if (bend > 15) INFO.push(`curve '${p.name || p.host}': steering accumulated to ${bend.toFixed(0)}° — starts ${dirName(d0)}, finishes ${dirName(t)}, far end ${dy >= 0 ? '+' : ''}${dy.toFixed(2)} in y`);
- return { material: p.material, V: part.v, F: part.fq, faceted: p.faceted,
+ return { material: p.material, V: part.v, F: part.fq, faceted: p.faceted, join: p.join,
+ _seatIdx: Array.from({ length: sides }, (_, i) => i), // base ring = the part's socket
skin: part.v.map(() => [[p.host, 1]]) };
}
@@ -427,6 +429,129 @@ function buildMembrane(spec, p) {
return { material: p.material, V, F, skin, doubleSided: true, faceted: p.faceted };
}
+
+function buildHand(spec, p) {
+ // A REAL hand: palm slab + four fingers + an OPPOSABLE thumb — the anatomy
+ // the field kept failing to improvise from spheres and sticks. Everything
+ // scales from `size` (palm length, wrist to knuckles). Build the LEFT hand;
+ // `mirrored: true` makes the right one (the thumb lands correctly by the
+ // mirror). All verts ride the host joint; `curl` 0..1 relaxes/folds the
+ // fingers, `fist: true` is a full fold with the thumb wrapped across.
+ //
+ // ONE frame rules everything. The palm slab is hand-rolled IN THE HAND'S
+ // LOCAL FRAME (fingers +z, width x, thickness y) and only then mapped to
+ // world — an auto-framed tube would pick its own ring orientation and the
+ // thumb, placed in the hand frame, would miss the palm it belongs to.
+ const host = spec.joints[p.host];
+ if (!host) throw new Error(`hand host joint "${p.host}" missing`);
+ const S = p.size ?? 0.16; // palm length
+ const fist = !!p.fist;
+ const curl = fist ? 1.0 : (p.curl ?? 0.35);
+ const spread = p.spread ?? 0.5;
+ const F = G.nrm(p.dir || [0, -0.35, 1]); // knuckle direction
+ let U = p.up || [0, 1, 0];
+ U = G.nrm(G.sub(U, G.mul(F, G.dot(U, F))));
+ const Sx = G.cross(U, F);
+ const o = G.add(host, p.offset || [0, 0, 0]);
+ const toW = (q) => [o[0] + Sx[0]*q[0] + U[0]*q[1] + F[0]*q[2],
+ o[1] + Sx[1]*q[0] + U[1]*q[1] + F[1]*q[2],
+ o[2] + Sx[2]*q[0] + U[2]*q[1] + F[2]*q[2]];
+ const V = [], Fq = [];
+
+ // ── palm: boxy elliptical slab, rings authored in the LOCAL frame ──
+ const halfW = S * 0.44, thick = S * 0.17, PS = 10;
+ {
+ // stations: [z, widthScale, thickScale, yDrop]
+ const st = [[-0.22, 0.86, 0.88, 0], [0.10, 1.0, 1.0, 0], [0.45, 1.04, 0.98, -0.01],
+ [0.75, 1.0, 0.92, -0.03], [0.98, 0.92, 0.82, -0.05]];
+ const ring0 = V.length;
+ for (const [z, ws, ts, yd] of st) {
+ for (let k = 0; k < PS; k++) {
+ const a = (k / PS) * Math.PI * 2;
+ const cs = Math.cos(a), sn = Math.sin(a);
+ const bx = Math.sign(cs) * Math.pow(Math.abs(cs), 0.55); // superellipse: boxy
+ const by = Math.sign(sn) * Math.pow(Math.abs(sn), 0.55);
+ V.push(toW([bx * halfW * ws, by * thick * ts + yd * S, z * S]));
+ }
+ }
+ for (let r = 0; r < st.length - 1; r++)
+ for (let k = 0; k < PS; k++)
+ Fq.push([ring0 + r*PS + k, ring0 + r*PS + (k+1)%PS,
+ ring0 + (r+1)*PS + (k+1)%PS, ring0 + (r+1)*PS + k]);
+ const c0 = V.length; V.push(toW([0, 0, -0.22 * S]));
+ for (let k = 0; k < PS; k++) Fq.push([ring0 + (k+1)%PS, ring0 + k, c0]);
+ const c1 = V.length; V.push(toW([0, -0.05 * S, 0.98 * S]));
+ const last = ring0 + (st.length - 1) * PS;
+ for (let k = 0; k < PS; k++) Fq.push([last + k, last + (k+1)%PS, c1]);
+ }
+
+ // local circular tube (fingers/thumb) — rings framed in the LOCAL space too
+ const tube = (pts, radii, sides) => {
+ const base = V.length;
+ for (let i = 0; i < pts.length; i++) {
+ const q = pts[i];
+ const tn = i === 0 ? G.nrm(G.sub(pts[1], pts[0]))
+ : i === pts.length - 1 ? G.nrm(G.sub(pts[i], pts[i-1]))
+ : G.nrm(G.add(G.nrm(G.sub(pts[i], pts[i-1])), G.nrm(G.sub(pts[i+1], pts[i]))));
+ let ax = Math.abs(tn[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];
+ let u1 = G.nrm(G.cross(tn, ax));
+ const u2 = G.cross(tn, u1);
+ for (let k = 0; k < sides; k++) {
+ const a = (k / sides) * Math.PI * 2;
+ const r = radii[i];
+ V.push(toW([q[0] + (u1[0]*Math.cos(a) + u2[0]*Math.sin(a)) * r,
+ q[1] + (u1[1]*Math.cos(a) + u2[1]*Math.sin(a)) * r,
+ q[2] + (u1[2]*Math.cos(a) + u2[2]*Math.sin(a)) * r]));
+ }
+ }
+ for (let i = 0; i < pts.length - 1; i++)
+ for (let k = 0; k < sides; k++)
+ Fq.push([base + i*sides + k, base + i*sides + (k+1)%sides,
+ base + (i+1)*sides + (k+1)%sides, base + (i+1)*sides + k]);
+ const cb = V.length; V.push(toW(pts[0]));
+ for (let k = 0; k < sides; k++) Fq.push([base + (k+1)%sides, base + k, cb]);
+ const ct = V.length; V.push(toW(pts[pts.length - 1]));
+ const lastR = base + (pts.length - 1) * sides;
+ for (let k = 0; k < sides; k++) Fq.push([lastR + k, lastR + (k+1)%sides, ct]);
+ };
+
+ // ── four fingers off the knuckle edge (roots sunk INTO the palm) ──
+ const lens = [0.78, 0.94, 1.0, 0.90]; // pinky → index
+ const nf = p.fingers ?? 4;
+ for (let i = 0; i < nf; i++) {
+ const t = nf === 1 ? 0 : (i / (nf - 1)) * 2 - 1;
+ const x0 = -t * halfW * 0.72; // pinky at -x … index at +x (left hand)
+ const L = S * 0.80 * lens[Math.min(i, 3)];
+ const r = Math.min(S * 0.088, halfW * 0.72 / Math.max(nf - 1, 1) * 0.95);
+ const fan = t * spread * 0.20;
+ const segA = [0.42, 0.33, 0.25];
+ const pts = [[x0, -S*0.02, S*0.80]]; // root buried in the palm
+ let ang = curl * 0.5;
+ for (const sa of segA) {
+ const q = pts[pts.length - 1];
+ const d = G.nrm([fan, -Math.sin(ang) - 0.10, Math.cos(ang)]);
+ pts.push([q[0] + d[0]*L*sa, q[1] + d[1]*L*sa, q[2] + d[2]*L*sa]);
+ ang += curl * 0.85;
+ }
+ tube(pts, [r, r*0.92, r*0.78, r*0.5], 7);
+ }
+
+ // ── the thumb: root INSIDE the index-side palm edge, opposed, lower ──
+ if (p.thumb !== false) {
+ const L = S * 0.66, r = S * 0.105;
+ const root = [halfW * 0.62, -thick * 0.35, S * 0.30]; // sunk into the slab
+ const d1 = G.nrm(fist ? [0.55, -0.42, 0.72] : [0.66, -0.48, 0.58]);
+ const mid = [root[0] + d1[0]*L*0.55, root[1] + d1[1]*L*0.55, root[2] + d1[2]*L*0.55];
+ const d2 = G.nrm(fist ? [-0.80, -0.30, 0.52] : [0.28, -0.22, 0.93]); // fist: folds across
+ const tip = [mid[0] + d2[0]*L*0.5, mid[1] + d2[1]*L*0.5, mid[2] + d2[2]*L*0.5];
+ tube([root, mid, tip], [r, r*0.88, r*0.58], 7);
+ }
+
+ return { material: p.material, V, F: Fq, join: p.join,
+ _seatIdx: Array.from({ length: PS }, (_, i) => i), // palm base ring = the wrist socket
+ skin: V.map(() => [[p.host, 1]]) };
+}
+
function buildPaw(spec, p) {
// Independent paw object: flattened ellipsoid pad with a FLAT sole,
// snapped under the leg-end joint. size = [length(fwd), width, height].
@@ -450,6 +575,23 @@ function buildPaw(spec, p) {
// flat sole: ngon fan on bottom ring (faces down)
const ci = V.length; V.push([c[0], c[1], c[2]]);
for (let k = 0; k < N1; k++) F.push([k, (k + 1) % N1, ci]);
+ // optional toes: tapered nubs across the front edge ("toes": 3..5) — feet
+ // stop reading as bread loaves
+ const nt = p.toes | 0;
+ if (nt >= 2) {
+ const rt = Math.min(W2, L) * 0.16;
+ for (let k = 0; k < nt; k++) {
+ const tx = ((k / (nt - 1)) * 2 - 1) * (W2 / 2 - rt);
+ const base = [c[0] + tx, c[1] + rt * 0.9, c[2] + L * 0.42];
+ const tip = [c[0] + tx * 1.15, c[1] + rt * 0.75, c[2] + L * 0.42 + L * 0.34];
+ const wpts = [base, tip];
+ const rings = G.chainRings(wpts, [rt, rt * 0.55], 6, false);
+ const part = G.partFromRings(rings, 6, 'ngon', 'fan', wpts);
+ const b0 = V.length;
+ V.push(...part.v);
+ for (const f of part.fq) F.push(f.map(i => i + b0));
+ }
+ }
return { material: p.material, V, F, skin: V.map(() => [[p.host, 1]]) };
}
@@ -465,7 +607,7 @@ function buildFin(spec, p, builtVols) {
if (p.anchor) {
const sp = surfacePoint(builtVols, p.anchor);
o = sp.p;
- // `around` is measured in the host section's own frame. On a body chain that
+ // `around` is expressed in the host section's own frame. On a body chain that
// frame gives the documented 0=spine / 90=side / 180=belly. On a chain that
// runs vertically (a leg) the same numbers point somewhere else entirely —
// 90 comes out FRONT, 180 comes out OUTER — so a plate aimed at the outside
@@ -519,7 +661,14 @@ function mirrorMesh(m, rDelta) { // duplicate across X with flipped winding + L
}
return [v[0] + dx, v[1] + dy, v[2] + dz];
};
+ // `chain` has to come along. A mirrored VOLUME used to arrive with no chain
+ // name at all (compile() re-labels mirrored PARTS afterwards, volumes it
+ // does not), so the twin was anonymous to anything that identifies a mesh by
+ // the chain it was grown from — the shading stack read a right leg declared
+ // `"shade": "hard"` as flesh, because the declaration is keyed by chain and
+ // the twin no longer had one.
return { material: m.material, faceted: m.faceted, smoothAngle: m.smoothAngle,
+ join: m.join, _seatIdx: m._seatIdx, chain: m.chain,
doubleSided: m.doubleSided,
V: m.V.map((v, i) => shift([-v[0], v[1], v[2]], m.skin && m.skin[i])),
F: m.F.map(f => f.slice().reverse()),
@@ -558,7 +707,7 @@ function compile(spec) {
meshes.push(t);
}
}
- const BUILDERS = { spike: buildSpike, curve: buildCurve, membrane: buildMembrane,
+ const BUILDERS = { spike: buildSpike, curve: buildCurve, membrane: buildMembrane, hand: buildHand,
paw: buildPaw, fin: (s2, p2) => buildFin(s2, p2, builtVols) };
for (const p of spec.parts || []) {
const label = p.name || `${p.type}@${p.host || 'ribs'}`;
@@ -589,6 +738,13 @@ function compile(spec) {
return meshes;
}
+// Which shading pass owns this build. `"shading": {"stack": false}` falls back
+// to the 1.2.0 ramp-and-grain for a spec that was tuned against it.
+function useStack(spec) {
+ const sh = spec.shading || {};
+ return sh.stack !== false;
+}
+
// ── whole-body shading pass ────────────────────────────────────────────────
// ONE top-to-bottom value ramp and ONE grain size across the entire creature,
// applied to EVERY mesh — volumes, paws, ears, eyes, horns alike. Two reasons
@@ -604,6 +760,11 @@ function compile(spec) {
// spec on a giant produced grain finer than the vertex spacing and aliased.
function applyShading(spec, meshes) {
const sh = spec.shading || {};
+ // The L1-L8 stack supersedes this pass and runs LATER (it needs AO and vertex
+ // normals as inputs, and those do not exist until ao.js has run). When it is
+ // active this whole function is a no-op — running both would apply two
+ // top-to-bottom ramps to the same vertices.
+ if (useStack(spec)) return;
const grad = sh.gradient === undefined ? { top: 0.30, bottom: -0.88 } : sh.gradient;
const nz = sh.noise === undefined ? { size: 0.018, amount: 0.26 } : sh.noise;
if (!meshes.length) return;
@@ -639,4 +800,4 @@ function applyShading(spec, meshes) {
+ ` — applied to all ${meshes.length} meshes`);
}
-module.exports = { compile, drainInfo };
+module.exports = { compile, drainInfo, useStack };
diff --git a/engine/core/contract.js b/engine/core/contract.js
new file mode 100644
index 0000000..d676817
Binary files /dev/null and b/engine/core/contract.js differ
diff --git a/engine/core/glb.js b/engine/core/glb.js
index 2f25a35..2b82951 100644
--- a/engine/core/glb.js
+++ b/engine/core/glb.js
@@ -24,7 +24,44 @@ function hex2rgb(h) {
// meshes: [{material,color,rough,metal,V,F, skin?: [ [[jointName,w],...] per vertex ]}]
// skeleton: { joints:[{name,pos,parent}], index:{} } ibm: Float32Array(16*n)
// anims: [{name,duration,channels:[{joint,path,times,values}]}]
+// ── L8: soften the shipped NORMAL toward the bone field ───────────────────
+// The other seven layers bake into COLOR_0, which a viewer is free to ignore.
+// This one is different: NORMAL is part of the file and the user's lighting
+// cannot opt out of it. Verified in the lab against a blank viewer — one
+// directional light, stock material, none of our vertex colours — the shape
+// visibly softened, at 29-43° median from the mesh normals.
+//
+// FLESH ONLY, and that is a deliberate departure from the lab's settled value
+// of "hardware 50%". The lab needed a fake normal on hardware because its
+// smooth-normal path did not compute hardware at all — it substituted raw mesh
+// normals, so the only way to soften a plate was the bone field. This engine
+// does not have that hole: `smoothSplit` gives every piece angle-weighted
+// normals with real creases. Importing the workaround would import the cost
+// the lab measured with it — on hardware the bone field pointed at the BACK of
+// the surface for 28-44% of vertices, because a plate's facing has nothing to
+// do with where the nearest bone is. Flesh has no such problem: skin wraps
+// bone, so the direction from bone to vertex IS roughly the surface normal.
+function boneField(V, skin, sk) {
+ return V.map((v, i) => {
+ const infl = skin && skin[i];
+ if (!infl || !infl.length) return null;
+ let px = 0, py = 0, pz = 0, w = 0;
+ for (const [j, wt] of infl) {
+ const k = sk.index ? sk.index[j] : undefined;
+ if (k == null) continue;
+ const q = sk.joints[k].pos;
+ px += q[0] * wt; py += q[1] * wt; pz += q[2] * wt; w += wt;
+ }
+ if (!w) return null;
+ const d = [v[0] - px / w, v[1] - py / w, v[2] - pz / w];
+ const L = Math.hypot(d[0], d[1], d[2]);
+ return L > 1e-9 ? [d[0] / L, d[1] / L, d[2] / L] : null;
+ });
+}
+
+const L8_MOVED = [];
function writeGLB(build, outPath, opts = {}) {
+ L8_MOVED.length = 0;
const { meshes, skeleton, ibm, anims } = build;
const names = opts.names || {}; // internal joint name → public export name
const bufs = []; let byteLen = 0;
@@ -95,7 +132,27 @@ function writeGLB(build, outPath, opts = {}) {
const r = smoothSplit(m.V, tris, deg, { C: m.C, skin: m.skin, UV: m.UV });
m.V = r.V; if (m.C) m.C = r.C; if (m.skin) m.skin = r.skin; if (m.UV) m.UV = r.UV;
tris = r.tris;
- const N = r.N;
+ let N = r.N;
+ // L8, after the crease split so the blend lands on the shipped vertices
+ const l8 = opts.boneNormals;
+ if (l8 && m._cls === 'flesh' && skeleton && m.skin) {
+ const F = boneField(m.V, m.skin, skeleton);
+ let moved = 0;
+ N = N.map((n, i) => {
+ const f = F[i];
+ if (!f) return n;
+ // never let the blend cross to the back of the surface — a normal that
+ // has flipped is worse than one that was never softened
+ if (n[0] * f[0] + n[1] * f[1] + n[2] * f[2] <= 0) return n;
+ const a = l8;
+ const b = [n[0] * (1 - a) + f[0] * a, n[1] * (1 - a) + f[1] * a, n[2] * (1 - a) + f[2] * a];
+ const L = Math.hypot(b[0], b[1], b[2]);
+ if (L < 1e-9) return n;
+ moved++;
+ return [b[0] / L, b[1] / L, b[2] / L];
+ });
+ if (moved) L8_MOVED.push([m.material, moved, N.length]);
+ }
const key = [m.material, m.color, m.rough ?? 0.9, m.metal ?? 0, !!m.doubleSided, !!m.C, !!m.UV].join('|');
let g = groups.get(key);
if (!g) groups.set(key, g = { m, V: [], N: [], C: m.C ? [] : null, UV: m.UV ? [] : null,
@@ -109,6 +166,24 @@ function writeGLB(build, outPath, opts = {}) {
}
for (const g of groups.values()) {
const { m } = g;
+ // Portability: the hue lives in baseColorFactor, COLOR_0 carries only the
+ // shading multiplier. With baseColorFactor white (the old way) EVERY colour
+ // in the file lived in vertex colours, so any viewer that does not apply
+ // COLOR_0 — and there are many — rendered the creature pure white. Splitting
+ // it is lossless where COLOR_0 IS applied (base × vertex reproduces the same
+ // value per channel, since base is the per-channel MAXIMUM and the vertex
+ // ratios are therefore ≤ 1) and degrades to "right hue, flat shading" where
+ // it is not. Observed in the field: a creature published to a gallery came
+ // back white-and-black.
+ let base = [1, 1, 1, 1];
+ if (g.C) {
+ // NEW arrays, never in place: a vertex-colour array can be referenced from
+ // more than one vertex (flat fills, crease splits), and dividing in place
+ // would scale a shared object twice and shift the colour.
+ const mx = [0, 1, 2].map(k => Math.max(1e-4, ...g.C.map(c => c[k])));
+ g.C = g.C.map(c => [Math.min(1, c[0] / mx[0]), Math.min(1, c[1] / mx[1]), Math.min(1, c[2] / mx[2])]);
+ base = [mx[0], mx[1], mx[2], 1];
+ }
const mins = [0,1,2].map(k => Math.min(...g.V.map(v => v[k])));
const maxs = [0,1,2].map(k => Math.max(...g.V.map(v => v[k])));
const attrs = {
@@ -133,7 +208,7 @@ function writeGLB(build, outPath, opts = {}) {
const idxAcc = addAccessor(new Uint32Array(g.tris.flat()), 5125, 'SCALAR', 34963);
const mi = gltf.materials.length;
const mat = { name: m.material, pbrMetallicRoughness: {
- baseColorFactor: g.C ? [1, 1, 1, 1] : [...hex2rgb(m.color), 1],
+ baseColorFactor: g.C ? base : [...hex2rgb(m.color), 1],
metallicFactor: m.metal ?? 0, roughnessFactor: m.rough ?? 0.9 } };
if (m.doubleSided) mat.doubleSided = true; // zero-thickness membranes
gltf.materials.push(mat);
@@ -173,4 +248,4 @@ function writeGLB(build, outPath, opts = {}) {
return total;
}
-module.exports = { writeGLB, triangulate };
+module.exports = { writeGLB, triangulate, L8_MOVED };
diff --git a/engine/core/shade.js b/engine/core/shade.js
new file mode 100644
index 0000000..c23c5ed
--- /dev/null
+++ b/engine/core/shade.js
@@ -0,0 +1,421 @@
+// ── the vertex-colour shading stack (L1–L8) ────────────────────────────────
+//
+// Ported from an interactive lab where every layer here was settled against six
+// real creatures and every removed control was removed because it MEASURED as
+// dead, not because it looked redundant. The numbers in DEFAULTS are that lab's
+// final read-out.
+//
+// Two things are different here, and both are improvements the lab could not
+// have made:
+//
+// · CLASSIFICATION IS FREE. The lab worked on a finished GLB and had to GUESS
+// which parts were flesh and which were hardware, from bone counts. That
+// guess failed completely on two shipped creatures — the owl and the
+// some creatures classify as 100% hardware, so the whole stack skipped them. The
+// engine does not guess: the spec says what every piece IS. Volumes, hands
+// and paws are flesh; spikes, curves, membranes and fins are hardware; eyes
+// are features. `"shade"` on a volume or part overrides it, which is how a
+// trunk (a curve that is flesh) says so.
+//
+// · THERE IS NO ORIGINAL COLOUR TO PRESERVE. The lab's L1 spent its effort
+// recovering per-vertex colour that step 0 of that pipeline had thrown away.
+// Here the arc bands ARE the colour, first-hand. What survives from L1 is
+// the half that was never about recovery: the cross-part spatial smoothing
+// that kills seams, because a colour field that is a function of POSITION
+// gives two coincident points the same value by construction.
+//
+// Everything below is a pure function of position and classification. No
+// randomness, no dates — the same spec compiles to the same bytes.
+
+// ── OKLab ──────────────────────────────────────────────────────────────────
+// L is lightness, hypot(a,b) is chroma, and they are INDEPENDENT. That is the
+// whole reason this stack works in OKLab and not in RGB: "brighter and more
+// saturated" is two numbers here and is impossible in any blend mode, because
+// every mode that brightens moves toward white and white has chroma 0.
+function lin2oklab(c) {
+ const l = Math.cbrt(0.4122214708 * c[0] + 0.5363325363 * c[1] + 0.0514459929 * c[2]);
+ const m = Math.cbrt(0.2119034982 * c[0] + 0.6806995451 * c[1] + 0.1073969566 * c[2]);
+ const s = Math.cbrt(0.0883024619 * c[0] + 0.2817188376 * c[1] + 0.6299787005 * c[2]);
+ return [0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s,
+ 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
+ 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s];
+}
+function oklabToLinRaw(L) {
+ const l = (L[0] + 0.3963377774 * L[1] + 0.2158037573 * L[2]) ** 3;
+ const m = (L[0] - 0.1055613458 * L[1] - 0.0638541728 * L[2]) ** 3;
+ const s = (L[0] - 0.0894841775 * L[1] - 1.2914855480 * L[2]) ** 3;
+ return [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
+ -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s];
+}
+function oklab2lin(L) {
+ return oklabToLinRaw(L).map(v => (v < 0 ? 0 : v > 1 ? 1 : v));
+}
+function inGamut(c) {
+ const r = oklabToLinRaw(c);
+ return r.every(v => v >= -1e-4 && v <= 1.0001);
+}
+
+const ss = (a, b, x) => {
+ const t = Math.max(0, Math.min(1, (x - a) / ((b - a) || 1e-9)));
+ return t * t * (3 - 2 * t);
+};
+const mix = (a, b, t) => [a[0] + (b[0] - a[0]) * t,
+ a[1] + (b[1] - a[1]) * t,
+ a[2] + (b[2] - a[2]) * t];
+const s2l = v => Math.pow(v, 2.2);
+function hex2lab(h) {
+ const x = String(h).replace('#', '');
+ return lin2oklab([0, 2, 4].map(i => s2l(parseInt(x.substr(i, 2), 16) / 255)));
+}
+
+// ── settled values ─────────────────────────────────────────────────────────
+const DEFAULTS = {
+ seam: { radius_edges: 3, min_frac: 0.030 },
+ pattern: { color: null, sharpness: 0.45, amount: 1.00, scale: 0.06 },
+ ramp: { bottom: '#001370', mid: '#cfcfcf', top: '#fffcf0',
+ p0: 0.00, pm: 0.31, wm: 0.08, p1: 1.00,
+ sh0: 0.0, sh1: 0.0, chroma: 1.0, amount: 1.00 },
+ boost: { y0: 0.00, y1: 0.40, gamma: 0.30, dL: 0.03, dC: 1.50, amount: 1.00,
+ target: 'all' },
+ bleed: { radius: 0.025, sharpness: 0.35, amount: 0.45 },
+ hardsh: { amount: 0.54, gamma: 0.70 },
+ bodysh: { lights: 4, rot: 4, elev: 17, amount: 0.20, gamma: 1.95 },
+};
+
+// ── classification ─────────────────────────────────────────────────────────
+const HARD_TYPES = new Set(['spike', 'curve', 'membrane', 'fin']);
+const FX_MATERIAL = /^(eye|pupil|iris|sclera|nose|nostril|tooth|teeth|tongue)/i;
+
+function classOf(m, declared) {
+ if (declared) return declared; // spec wins, always
+ if (m.partType === 'eye' || FX_MATERIAL.test(m.material || '')) return 'fx';
+ if (m.partType && HARD_TYPES.has(m.partType)) return 'hard';
+ return 'flesh'; // volumes, hands, paws
+}
+
+/** Read `shade` off the spec for each mesh: per-part, then per-volume. */
+function declaredClasses(spec) {
+ const byName = new Map();
+ for (const v of spec.volumes || []) if (v.shade) byName.set(v.chain, v.shade);
+ for (const p of spec.parts || []) {
+ if (!p.shade) continue;
+ const label = p.name || `${p.type}@${p.host || 'ribs'}`;
+ byName.set(label, p.shade);
+ byName.set(label + '.R', p.shade);
+ }
+ return byName;
+}
+
+// ── spatial grid over a subset of vertices ─────────────────────────────────
+// Used twice: to smooth the flesh colour field across part boundaries (L1) and
+// to find the nearest hardware vertex to each flesh vertex (L5). One
+// implementation, because they are the same query.
+function grid(points, cell) {
+ const g = new Map();
+ const key = (a, b, c) => a + ',' + b + ',' + c;
+ const idx = p => [Math.floor(p[0] / cell), Math.floor(p[1] / cell), Math.floor(p[2] / cell)];
+ points.forEach((p, i) => {
+ const [a, b, c] = idx(p.v);
+ const k = key(a, b, c);
+ let bin = g.get(k);
+ if (!bin) g.set(k, bin = []);
+ bin.push(i);
+ });
+ return {
+ near(v, r) {
+ const out = [];
+ const [a, b, c] = idx(v);
+ const s = Math.ceil(r / cell);
+ for (let x = a - s; x <= a + s; x++)
+ for (let y = b - s; y <= b + s; y++)
+ for (let z = c - s; z <= c + s; z++) {
+ const bin = g.get(key(x, y, z));
+ if (bin) out.push(...bin);
+ }
+ return out;
+ },
+ };
+}
+
+/** Median edge length across every mesh — the sampling ruler. */
+function medianEdge(meshes, diag) {
+ const L = [];
+ for (const m of meshes)
+ for (const f of m.F || [])
+ for (let k = 0; k < f.length; k++) {
+ const a = m.V[f[k]], b = m.V[f[(k + 1) % f.length]];
+ L.push(Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]));
+ }
+ if (!L.length) return diag * 0.02;
+ L.sort((x, y) => x - y);
+ return L[Math.floor(L.length * 0.5)] || diag * 0.02;
+}
+
+// ── the stack ──────────────────────────────────────────────────────────────
+function shadeStack(spec, meshes, INFO) {
+ const cfg = spec.shading || {};
+ const on = k => cfg[k] !== false && cfg[k] !== 0;
+ const P = k => Object.assign({}, DEFAULTS[k], (cfg[k] && typeof cfg[k] === 'object') ? cfg[k] : {});
+
+ const live = meshes.filter(m => m.V && m.V.length);
+ if (!live.length) return;
+
+ const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
+ for (const m of live) for (const v of m.V) for (let k = 0; k < 3; k++) {
+ if (v[k] < lo[k]) lo[k] = v[k];
+ if (v[k] > hi[k]) hi[k] = v[k];
+ }
+ const diag = Math.hypot(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]) || 1;
+ const y0 = lo[1], yr = (hi[1] - lo[1]) || 1e-6;
+
+ const declared = declaredClasses(spec);
+ for (const m of live) m._cls = classOf(m, declared.get(m.part || m.chain));
+ const counts = { flesh: 0, hard: 0, fx: 0 };
+ const byClass = { flesh: new Set(), hard: new Set(), fx: new Set() };
+ for (const m of live) {
+ counts[m._cls] += m.V.length;
+ byClass[m._cls].add(m.part || m.chain || m.material || '?');
+ }
+ // Say WHICH pieces landed in which class. The lab could only guess at this
+ // and guessed wrong on two shipped creatures; the least the engine can do,
+ // having the answer for free, is print it — a trunk sitting in `hard` is a
+ // one-line spec fix, and invisible unless someone says so.
+ for (const k of ['flesh', 'hard', 'fx'])
+ if (byClass[k].size)
+ INFO.push(`shade class ${k}: ${[...byClass[k]].sort().join(', ')}`);
+
+ // every vertex, flattened, with a back-pointer
+ const pts = [];
+ for (const m of live)
+ m.V.forEach((v, i) => pts.push({ v, m, i, cls: m._cls }));
+
+ // colour in OKLab, per vertex, starting from the mesh's own arc/flat colour
+ for (const m of live) {
+ if (!m.C) m.C = m.V.map(() => null);
+ for (let i = 0; i < m.V.length; i++) {
+ const c = m.C[i];
+ m.C[i] = c ? lin2oklab(c) : hex2lab(m.color || '#888888');
+ }
+ }
+
+ // ── L1: seam-safe flesh colour ─────────────────────────────────────────
+ // A colour field that is a FUNCTION OF POSITION cannot have a seam: two
+ // coincident points on either side of a junction get the same value by
+ // construction. So the flesh colour is averaged spatially ACROSS parts.
+ // Hardware is deliberately excluded — a bolted-on plate is supposed to have
+ // a hard edge, and smoothing it would be smoothing away the design.
+ //
+ // The radius is tied to THIS creature's own median edge length, not to a
+ // fixed fraction of its diagonal. The lab measured why: at a fixed 3% of the
+ // diagonal the radius-to-edge ratio ran 1.1–1.7 across six creatures, and the
+ // leftover seam ranked in exact inverse order of that ratio. A field must
+ // vary slowly compared to the mesh that samples it; 1.1 edges is not slow.
+ if (on('seam') !== false) {
+ const sp = P('seam');
+ const edge = medianEdge(live, diag);
+ const R = Math.max(sp.min_frac * diag, edge * sp.radius_edges);
+ const fleshPts = pts.filter(p => p.cls === 'flesh');
+ if (fleshPts.length) {
+ const gg = grid(fleshPts, R);
+ const out = new Array(fleshPts.length);
+ const r2 = R * R, sig2 = (R / 2) * (R / 2);
+ fleshPts.forEach((p, n) => {
+ let wsum = 0, acc = [0, 0, 0];
+ for (const j of gg.near(p.v, R)) {
+ const q = fleshPts[j];
+ const dx = q.v[0] - p.v[0], dy = q.v[1] - p.v[1], dz = q.v[2] - p.v[2];
+ const d2 = dx * dx + dy * dy + dz * dz;
+ if (d2 > r2) continue;
+ const w = Math.exp(-d2 / (2 * sig2));
+ const c = q.m.C[q.i];
+ acc[0] += c[0] * w; acc[1] += c[1] * w; acc[2] += c[2] * w;
+ wsum += w;
+ }
+ out[n] = wsum > 0 ? [acc[0] / wsum, acc[1] / wsum, acc[2] / wsum] : p.m.C[p.i];
+ });
+ fleshPts.forEach((p, n) => { p.m.C[p.i] = out[n]; });
+ INFO.push(`shade L1: flesh colour smoothed across parts, r=${(R / diag * 100).toFixed(1)}% of diagonal `
+ + `(${(R / edge).toFixed(1)}x median edge) — seams cannot survive a position function`);
+ }
+ }
+
+ // ── L2: pattern ────────────────────────────────────────────────────────
+ // Flesh only, and only when the spec names a colour. The mask is the same
+ // deterministic value noise the engine already uses, so it is reproducible.
+ const pat = P('pattern');
+ if (pat.color) {
+ const PC = hex2lab(pat.color);
+ const w = Math.max(0.02, 0.55 * (1 - pat.sharpness));
+ const cell = Math.max(1e-6, pat.scale * diag);
+ for (const p of pts) {
+ if (p.cls !== 'flesh') continue;
+ const n = vnoise3(p.v, cell);
+ const t = pat.amount * ss(0.5 - w, 0.5 + w, n);
+ if (t > 0) p.m.C[p.i] = mix(p.m.C[p.i], PC, t);
+ }
+ INFO.push(`shade L2: pattern ${pat.color} at ${(pat.amount * 100) | 0}% on flesh`);
+ }
+
+ // ── L3: top-to-bottom ramp, multiplied over everything ─────────────────
+ const rp = P('ramp');
+ const A = hex2lab(rp.bottom), MM = hex2lab(rp.mid), B = hex2lab(rp.top);
+ const half = Math.max(0, rp.wm) / 2;
+ const e0 = Math.min(rp.p1, Math.max(rp.p0, rp.pm - half));
+ const e1 = Math.min(rp.p1, Math.max(e0, rp.pm + half));
+ const lo0 = rp.p0 + (e0 - rp.p0) * rp.sh0, hi0 = e0;
+ const lo1 = e1, hi1 = rp.p1 - (rp.p1 - e1) * rp.sh1;
+ const bandAt = y => {
+ const b0 = hi0 - lo0 < 1e-6 ? (y >= e0 ? 1 : 0) : ss(lo0, hi0, y);
+ const b1 = hi1 - lo1 < 1e-6 ? (y >= e1 ? 1 : 0) : ss(lo1, hi1, y);
+ let c = mix(A, MM, b0); c = mix(c, B, b1);
+ return [c[0], c[1] * rp.chroma, c[2] * rp.chroma];
+ };
+ if (rp.amount > 0) {
+ for (const p of pts) {
+ if (p.cls === 'fx') continue;
+ const y = (p.v[1] - y0) / yr;
+ const band = bandAt(y);
+ const c = p.m.C[p.i];
+ // multiply, in OKLab: L multiplies, chroma follows the band's own chroma
+ const t = rp.amount;
+ p.m.C[p.i] = [c[0] * (1 - t) + c[0] * band[0] * t,
+ c[1] * (1 - t) + (c[1] * band[0] + band[1] * c[0]) * t,
+ c[2] * (1 - t) + (c[2] * band[0] + band[2] * c[0]) * t];
+ }
+ INFO.push(`shade L3: ramp ${rp.bottom} -> ${rp.mid} @${rp.pm} -> ${rp.top}, multiply ${(rp.amount * 100) | 0}%`);
+ }
+
+ // ── L4: brighten AND saturate the upper region, exactly nothing below ───
+ // No blend mode can do this and it is not a tuning problem: screen and add
+ // only move toward white, and white has chroma 0, so every one of them LOSES
+ // chroma while gaining lightness. Observed on three creatures, every mode's
+ // delta-chroma was negative. In OKLab the two quantities are independent, so
+ // this just moves them:
+ // L' = L + dL*w chroma' = chroma * (1 + (dC-1)*w)
+ // Below y0 the ramp is exactly 0, so w is 0, so the vertex is returned
+ // unchanged — identity, not "almost unchanged". The lab measured the maximum
+ // change in the lower region across six creatures as exactly 0.
+ const bo = P('boost');
+ if (bo.amount > 0 && (bo.dL !== 0 || bo.dC !== 1)) {
+ let clipped = 0, touched = 0;
+ for (const p of pts) {
+ if (p.cls === 'fx') continue;
+ if (bo.target === 'flesh' && p.cls !== 'flesh') continue;
+ const y = (p.v[1] - y0) / yr;
+ let t = ss(bo.y0, bo.y1, y);
+ if (bo.gamma !== 1) t = Math.pow(t, bo.gamma);
+ if (t <= 0) continue; // identity, by construction
+ touched++;
+ const c = p.m.C[p.i];
+ const w = bo.amount * t;
+ const L = Math.min(1, c[0] + bo.dL * w);
+ let k = 1 + (bo.dC - 1) * w;
+ // Pushing chroma runs out of sRGB, and clamping per channel TURNS THE HUE
+ // rather than capping the chroma. So walk back to the gamut boundary
+ // instead: 12 bisections, error under 0.03%.
+ if (!inGamut([L, c[1] * k, c[2] * k])) {
+ clipped++;
+ let a = 0, b2 = k;
+ for (let it = 0; it < 12; it++) {
+ const mid = (a + b2) / 2;
+ if (inGamut([L, c[1] * mid, c[2] * mid])) a = mid; else b2 = mid;
+ }
+ k = a;
+ }
+ p.m.C[p.i] = [L, c[1] * k, c[2] * k];
+ }
+ INFO.push(`shade L4: boost dL+${bo.dL} chroma x${bo.dC} above y=${bo.y0}..${bo.y1}; `
+ + `${touched} vertices touched, ${clipped} walked back to the gamut edge (0 clamped)`);
+ }
+
+ // ── L5: hardware bleeds into the flesh around it ───────────────────────
+ const bl = P('bleed');
+ const hardPts = pts.filter(p => p.cls === 'hard');
+ if (bl.amount > 0 && hardPts.length) {
+ const R = bl.radius * diag;
+ const gg = grid(hardPts, R);
+ let hit = 0;
+ for (const p of pts) {
+ if (p.cls !== 'flesh') continue;
+ let best = -1, bestD = Infinity;
+ for (const j of gg.near(p.v, R)) {
+ const q = hardPts[j];
+ const d = Math.hypot(q.v[0] - p.v[0], q.v[1] - p.v[1], q.v[2] - p.v[2]);
+ if (d < bestD) { bestD = d; best = j; }
+ }
+ if (best < 0 || bestD >= R) continue;
+ const k = Math.pow(Math.max(0, 1 - bestD / R), 1 + 8 * bl.sharpness);
+ const q = hardPts[best];
+ p.m.C[p.i] = mix(p.m.C[p.i], q.m.C[q.i], bl.amount * k);
+ hit++;
+ }
+ INFO.push(`shade L5: hardware bled into ${hit} flesh vertices within ${(bl.radius * 100).toFixed(1)}% of diagonal`);
+ }
+
+ // ── L6 / L7: shading, mutually exclusive by class ──────────────────────
+ // Both read the AO already baked into m.AO by ao.js. L7's fourth input in the
+ // lab was a union-volume SDF that this engine does not build; what is here is
+ // the horizontal light ring times AO, which is the same formula with that
+ // term set to 1. Called out rather than quietly approximated.
+ const hs = P('hardsh'), bs = P('bodysh');
+ const ring = [];
+ for (let i = 0; i < Math.max(1, bs.lights | 0); i++) {
+ const az = (bs.rot + i * 360 / Math.max(1, bs.lights | 0)) * Math.PI / 180;
+ const el = bs.elev * Math.PI / 180;
+ ring.push([Math.cos(el) * Math.sin(az), Math.sin(el), Math.cos(el) * Math.cos(az)]);
+ }
+ let shaded = 0;
+ for (const m of live) {
+ if (m._cls === 'fx') continue;
+ for (let i = 0; i < m.V.length; i++) {
+ const ao = m.AO ? m.AO[i] : 1;
+ let sh;
+ if (m._cls === 'hard') {
+ const a = hs.gamma === 1 ? ao : Math.pow(ao, hs.gamma);
+ sh = 1 - hs.amount * (1 - a);
+ } else {
+ const n = m.N ? m.N[i] : [0, 1, 0];
+ let sum = 0;
+ for (const L of ring) sum += Math.max(0, n[0] * L[0] + n[1] * L[1] + n[2] * L[2]);
+ let v = Math.max(0, Math.min(1, (sum / ring.length) * ao));
+ if (bs.gamma !== 1) v = Math.pow(v, bs.gamma);
+ sh = 1 - bs.amount * (1 - v);
+ }
+ m.C[i] = [m.C[i][0] * sh, m.C[i][1], m.C[i][2]];
+ shaded++;
+ }
+ }
+ INFO.push(`shade L6/L7: ${ring.length}-light ring x AO — hardware ${(hs.amount * 100) | 0}%, `
+ + `flesh ${(bs.amount * 100) | 0}% over ${shaded} vertices`);
+
+ // features are returned untouched, exactly as authored
+ INFO.push(`shade: ${counts.flesh} flesh / ${counts.hard} hardware / ${counts.fx} feature vertices `
+ + `(features take no layer and no shadow)`);
+
+ // back to linear RGB for COLOR_0
+ for (const m of live)
+ for (let i = 0; i < m.C.length; i++) m.C[i] = oklab2lin(m.C[i]);
+}
+
+// deterministic value noise — same generator the compiler already uses
+function vnoise3(p, scale) {
+ const s = 1 / (scale || 1e-6);
+ const x = p[0] * s, y = p[1] * s, z = p[2] * s;
+ const xi = Math.floor(x), yi = Math.floor(y), zi = Math.floor(z);
+ const xf = x - xi, yf = y - yi, zf = z - zi;
+ const fade = t => t * t * (3 - 2 * t);
+ const h = (a, b, c) => {
+ let n = a * 374761393 + b * 668265263 + c * 1274126177;
+ n = (n ^ (n >> 13)) * 1274126177;
+ return ((n ^ (n >> 16)) >>> 0) / 4294967295;
+ };
+ const u = fade(xf), v = fade(yf), w = fade(zf);
+ const lerp = (a, b, t) => a + (b - a) * t;
+ return lerp(
+ lerp(lerp(h(xi, yi, zi), h(xi + 1, yi, zi), u), lerp(h(xi, yi + 1, zi), h(xi + 1, yi + 1, zi), u), v),
+ lerp(lerp(h(xi, yi, zi + 1), h(xi + 1, yi, zi + 1), u), lerp(h(xi, yi + 1, zi + 1), h(xi + 1, yi + 1, zi + 1), u), v),
+ w);
+}
+
+module.exports = { shadeStack, DEFAULTS, lin2oklab, oklab2lin, inGamut, hex2lab };
diff --git a/example/wolf.glb b/example/wolf.glb
index afca652..2268ef7 100644
Binary files a/example/wolf.glb and b/example/wolf.glb differ
diff --git a/example/wolf.json b/example/wolf.json
index 58d41fd..18f16ca 100644
--- a/example/wolf.json
+++ b/example/wolf.json
@@ -1,4 +1,5 @@
{
+ "height": 1.45,
"name": "quadruped_light",
"_template": "ANCHOR, not target. A validated light quadruped (wolf lineage, bred against the approved 1.2 reference over 3 measured rounds). Start here, then DEVIATE: declare your exaggeration vector (which 1-2 numbers you push past this anchor, and how far) in the design card. Converging back to these numbers means you designed nothing.",
"_anchor_numbers": {
@@ -300,7 +301,8 @@
"color": "#c9c1ae"
}
]
- }
+ },
+ "smooth_angle": 17
},
{
"chain": "head",
@@ -367,7 +369,8 @@
"color": "#e08a3c"
}
]
- }
+ },
+ "smooth_angle": 20
},
{
"chain": "tail",
@@ -407,7 +410,8 @@
"color": "#8a3d14"
}
]
- }
+ },
+ "smooth_angle": 31
},
{
"chain": "LFront",
@@ -439,7 +443,8 @@
"none",
"dome"
],
- "ring_step": 0.055
+ "ring_step": 0.055,
+ "smooth_angle": 35
},
{
"chain": "LBack",
@@ -482,7 +487,8 @@
"none",
"dome"
],
- "ring_step": 0.055
+ "ring_step": 0.055,
+ "smooth_angle": 35
}
],
"parts": [
diff --git a/harness/brief.py b/harness/brief.py
new file mode 100644
index 0000000..4345b8e
--- /dev/null
+++ b/harness/brief.py
@@ -0,0 +1,318 @@
+#!/usr/bin/env python3
+"""The brief, checked for PRESENCE — never for content.
+
+ python3 harness/brief.py <brief.md> [--spec spec.json] [--poles A/metrics.json B/metrics.json]
+
+WHAT THIS DOES AND DOES NOT DO. It never judges what you wrote. Declare any
+height, any identity, any palette — this passes all of them. It refuses exactly
+one thing: a BLANK slot, and only for the slots a later stage actually consumes.
+The brief is where the creature is designed and design has no right answer; the
+downstream rulers, however, read specific fields, and a field nobody filled in
+does not make them lenient — it makes them VANISH.
+
+WHY BLANK IS WORSE THAN WRONG. Read out of the engine and the cards:
+
+ height engine/core/checks.js guards the size gate with `if (spec.height)`.
+ No declaration, no check — silently. A creature ships at the
+ wrong scale and not one line of output ever mentions it.
+ identity identity.py falls back to a placeholder noun when --noun is
+ missing, so Gate 1 prints a verdict about nothing at all. That
+ is worse than failing, because it looks like passing.
+ signature card 01 §1's single customer question IS this slot. Law 7
+ forbids asking a second one, so a signature that was not written
+ down cannot be recovered — only guessed. Five consumers read it:
+ Gate 1's identity view, part_exists (block), part_signature, the
+ MID whitelist and HIGH's main colour.
+ value plan `value_order` prints every material sorted by OKLab lightness on
+ every build, but a sorted list only says what IS brightest — the
+ brief is the only thing that says what SHOULD be. No plan, no
+ bar. (Colour and VALUE only. Material is not judged anywhere in
+ this pipeline and does not belong in the slot.)
+ feel the 24px read costs a whole subagent (tokens minimum) and
+ has nothing to be compared against.
+ exaggeration §4b's two poles are two stagings of it. No exaggeration, nothing
+ to stage.
+
+The other four slots — mass hierarchy, two focals, stance, attack — lose an
+ADVISORY at most, or nothing at all (balance is computed from the geometry
+whatever the brief says). Those are noted, never blocked. Blocking them would
+buy nothing and cost design freedom, which is the whole point of this stage.
+
+THE NAMED-CHAIN CONTRACT. Slots that name PARTS may end with
+
+ ... chains: LClaw, RClaw
+
+and those names must exist in the spec. This is still presence, not content —
+you invent the names, the check only asks that what you promised got built. It
+exists because of a measured failure: one boss brief named "the boulder in the
+iron net at the beam's tip" as its second focal in minute four, part_exists sits
+at stage MID, and nothing required that part until MID — so rounds 1 to 3 built
+an incomplete brief and the shape the customer eventually singled out did not
+appear until round 4.
+
+TWO POLES, NOT THREE NEAR-COPIES (--poles). Card 01 §4b builds TWO variants that
+are opposite extremes of one declared axis, and this measures whether they
+really are. The ruler is where the mass sits in thirds of the frame, in the view
+the reader will actually be shown, because iou_vs_prev cannot tell two designs
+apart: it counts overlapping pixels, so changing proportions moves it a long way
+while the design stands still. Three rounds that were meant to be three attempts
+can sit 0.08 to 0.20 apart on this ruler — closer than any two different
+creatures — while their iou reads 0.6 to 0.7, which sounds like a great deal of
+change and is not.
+"""
+import sys, os, json, re
+
+VIEWS = ('front', 'side', 'top', 'hero')
+
+# Slot -> (must be filled?, who reads it later). Order is the card's order.
+SLOTS = [
+ ('identity', True, 'Gate 1 — identity.py has no noun without it'),
+ ('feel', True, 'the 24px read has nothing to be judged against'),
+ ('height', True, 'the engine size gate is skipped entirely without it'),
+ ('signature', True, 'Gate 1 identity view, part_exists, MID whitelist, HIGH main colour'),
+ ('mass hierarchy', False, 'share_hierarchy (advice only)'),
+ ('two focals', False, 'focal_contrast (advice only)'),
+ ('stance', False, 'nothing mechanical — balance is computed from the geometry'),
+ ('attack', False, 'nothing mechanical — attack_reach measures the clip, not the brief'),
+ ('value plan', True, 'value_order has nothing to compare its lightness table against (colour and value only — material is not judged)'),
+]
+# Slots that name parts and must therefore declare the chains they mean.
+NEEDS_CHAINS = ('signature', 'two focals')
+
+# How far apart two poles must sit on the mass-layout ruler. Measured, not
+# guessed, and deliberately set as a FLOOR rather than a target:
+#
+# 0.08 0.14 0.20 the three "variants" of a build's r1-r3 — one
+# design adjusted three times, which is the waste this stops
+# 0.15 r3 -> r4 of the same build
+# 0.38 two poses of ONE locked spec, authored here as opposites
+# (tail hauled back vs tail whipped forward) and built green
+# 0.42 0.56 0.61 the same build's rounds either side of a concept restart
+#
+# 0.25 clears every same-idea pair by a wide margin and passes every deliberate
+# restaging. It is a first cut off one creature's history plus one authored
+# pair; re-cut it when more runs exist, the way RESTART_IOU was.
+POLE_MIN = 0.25
+
+# A pole can be far away on the layout ruler and still be junk — the authored
+# pair above proved it. Whipping the tail forward moved the mass a long way and
+# folded the signature part flat onto the shell, and the silhouette stopped
+# reading as a creature at all. The number that catches that already exists:
+# FILL, the share of the bounding box the silhouette actually occupies. That
+# pole measured 0.514 against its twin's 0.319, and against 0.222-0.393 across
+# all thirteen rounds the creature ever had. High fill is a blob. It is advice,
+# not a block: one weak pole out of two is normal, and which one is weak is a
+# judgment for the reader.
+FILL_BLOB = 0.45
+
+
+def norm(s):
+ return re.sub(r'[^a-z ]', '', s.lower()).strip()
+
+
+def parse(path):
+ """brief.md -> {slot: value}, exaggeration text, [discards]."""
+ txt = open(path, encoding='utf-8').read()
+ slots, section, exag, disc = {}, None, '', []
+ for line in txt.splitlines():
+ s = line.strip()
+ if s.startswith('#'):
+ h = norm(s)
+ section = ('exag' if 'exaggeration' in h else
+ 'disc' if 'discard' in h else None)
+ continue
+ if s.startswith('|'):
+ cells = [c.strip() for c in s.strip('|').split('|')]
+ if len(cells) >= 2 and not set(cells[0]) <= set('-: '):
+ k = norm(cells[0])
+ if k and k not in ('slot',):
+ slots[k] = cells[1]
+ continue
+ if not s:
+ continue
+ if section == 'exag':
+ exag += ' ' + s
+ elif section == 'disc':
+ if re.match(r'^\d+[.)]', s) or s.startswith(('-', '*')):
+ disc.append(s)
+ return slots, exag.strip(), disc
+
+
+def declared_chains(value):
+ m = re.search(r'chains?\s*[::]\s*(.+)$', value, re.I)
+ if not m:
+ return []
+ return [c.strip().strip('`*_"\'') for c in re.split(r'[,、]', m.group(1)) if c.strip()]
+
+
+def spec_chains(spec):
+ names = set()
+ for key in ('volumes', 'parts'):
+ for o in spec.get(key, []) or []:
+ for f in ('chain', 'name', 'id'):
+ if o.get(f):
+ names.add(str(o[f]))
+ for c in (spec.get('chains') or {}):
+ names.add(str(c))
+ return names
+
+
+def check(brief_path, spec_path=None):
+ """Returns (blocks, notes, facts)."""
+ slots, exag, disc = parse(brief_path)
+ blocks, notes, facts = [], [], {}
+
+ for name, must, who in SLOTS:
+ val = slots.get(name, '').strip()
+ empty = (not val) or val in ('-', '—', 'TBD', 'tbd', '?')
+ if empty:
+ (blocks if must else notes).append(
+ f'{name}: not filled in — {who}.')
+ continue
+ if name == 'height':
+ m = re.search(r'(\d+(?:\.\d+)?)', val)
+ if not m or float(m.group(1)) <= 0:
+ blocks.append('height: no number in it. The engine needs a metre '
+ 'value to scale to; any value passes, a blank does not.')
+ else:
+ facts['height'] = float(m.group(1))
+ if name == 'identity':
+ m = re.search(r'reads as\s*[::]?\s*\**([^*|(]+)', val, re.I)
+ facts['noun'] = (m.group(1) if m else val).strip().strip('*` ')
+ if name == 'signature':
+ v = [w for w in VIEWS if w in val.lower()]
+ if not v:
+ blocks.append('signature: no view named. Gate 1 requires the '
+ 'brief\'s own identity view to be one of the views '
+ 'that read — name one of ' + '/'.join(VIEWS) + '.')
+ else:
+ facts['identity_view'] = v[0]
+ if name in NEEDS_CHAINS and not declared_chains(val):
+ blocks.append(f'{name}: names no chains. End the cell with '
+ f'"chains: a, b" so the spec check can confirm the '
+ f'thing you ordered was actually built. Any names you '
+ f'like — the check only asks that they exist.')
+
+ if not exag:
+ blocks.append('the one exaggeration: missing. §4b builds two opposite '
+ 'stagings of it, so there is nothing to stage without it.')
+ if len(disc) < 3:
+ notes.append(f'discarded ideas: {len(disc)} listed, the rule asks for 3. '
+ f'Nothing downstream reads them, so this does not block — but '
+ f'they are the mechanism that produced the design worth keeping.')
+
+ if spec_path:
+ try:
+ spec = json.load(open(spec_path, encoding='utf-8'))
+ except Exception as e:
+ blocks.append(f'spec {spec_path} could not be read: {e}')
+ return blocks, notes, facts
+ have = spec_chains(spec)
+ for name, _, _ in SLOTS:
+ for c in declared_chains(slots.get(name, '')):
+ if c not in have:
+ blocks.append(
+ f'{name} promised chain "{c}" and the spec has no such '
+ f'chain. Build it now, at r1, or change the brief — a part '
+ f'the brief named and the spec skipped is not caught until '
+ f'MID, which is exactly how one boss build reached round 4 '
+ f'before its second focal existed.')
+ if 'height' in facts and spec.get('height'):
+ d = abs(spec['height'] - facts['height']) / facts['height']
+ if d > 0.15:
+ blocks.append(
+ f'height: the brief declares {facts["height"]}m and the spec '
+ f'{spec["height"]}m — {d * 100:.0f}% apart, and the engine '
+ f'refuses over 15%. Fix it here, before anything is built on it.')
+ elif not spec.get('height'):
+ blocks.append('spec has no "height" — the engine SKIPS the size check '
+ 'entirely when it is absent (checks.js), so the creature '
+ 'can ship at any scale and nothing will say so.')
+ return blocks, notes, facts
+
+
+def layout(metrics, view=None):
+ """The six numbers that say where the mass sits, in ONE view."""
+ v = metrics.get('views', metrics)
+ pick = None
+ for k in ([view] if view else []) + ['side', 'hero', 'front', 'top']:
+ if k and isinstance(v.get(k), dict) and v[k].get('thirds_cols'):
+ pick = v[k]
+ break
+ kk = f'sil_{k}' if k else None
+ if kk and isinstance(v.get(kk), dict) and v[kk].get('thirds_cols'):
+ pick = v[kk]
+ break
+ if not pick:
+ return None
+ return pick['thirds_cols'] + pick['thirds_rows']
+
+
+def poles_apart(a, b, view=None):
+ """(distance, ok) for two variants' metrics dicts."""
+ la, lb = layout(a, view), layout(b, view)
+ if la is None or lb is None:
+ return None, None
+ d = round(sum(abs(x - y) for x, y in zip(la, lb)), 3)
+ return d, d >= POLE_MIN
+
+
+def fill_of(metrics, view=None):
+ v = metrics.get('views', metrics)
+ for k in ([view] if view else []) + ['side', 'hero', 'front', 'top']:
+ for kk in ((k, f'sil_{k}') if k else ()):
+ if isinstance(v.get(kk), dict) and v[kk].get('fill') is not None:
+ return v[kk]['fill']
+ return None
+
+
+def report(blocks, notes, facts, label='brief'):
+ for n in notes:
+ print(f' note {n}')
+ for b in blocks:
+ print(f' BLOCK {b}')
+ if not blocks:
+ bits = [f'{k}={v}' for k, v in facts.items()]
+ print(f'[{label}] every slot a later stage reads is filled'
+ + (f' — {", ".join(bits)}' if bits else '') + '.')
+ return 1 if blocks else 0
+
+
+def main():
+ a = sys.argv[1:]
+ if not a or (a[0].startswith('--') and '--poles' not in a):
+ print(__doc__)
+ return 2
+ if '--poles' in a:
+ i = a.index('--poles')
+ pa, pb = a[i + 1], a[i + 2]
+ va = a[a.index('--view') + 1] if '--view' in a else None
+ ma = json.load(open(pa, encoding='utf-8'))
+ mb = json.load(open(pb, encoding='utf-8'))
+ d, ok = poles_apart(ma, mb, va)
+ if d is None:
+ print('BLOCK: neither metrics file carries thirds — rerun outline.py.')
+ return 2
+ print(f'[poles] mass-layout distance {d:.2f} (needs {POLE_MIN:.2f})')
+ for tag, m in (('A', ma), ('B', mb)):
+ f = fill_of(m, va)
+ if f is not None and f >= FILL_BLOB:
+ print(f' note pole {tag} fills {f:.2f} of its own box — that is a '
+ f'BLOB, not a pose. Something has folded flat onto the body; '
+ f'check it before you show it to anyone.')
+ if ok:
+ print(' the two poles are genuinely opposite. Read them.')
+ return 0
+ print(' BLOCK: these are one idea built twice. Do not spend a reader on')
+ print(' them — a reader shown two versions of the same design tells you')
+ print(' what it already told you. Name the axis (coiled/released,')
+ print(' reared/flattened, front-loaded/rear-loaded) and push BOTH ends.')
+ return 1
+ brief = a[0]
+ spec = a[a.index('--spec') + 1] if '--spec' in a else None
+ blocks, notes, facts = check(brief, spec)
+ return report(blocks, notes, facts)
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/harness/calibrate.py b/harness/calibrate.py
index 76bfa0a..89ec3c7 100644
--- a/harness/calibrate.py
+++ b/harness/calibrate.py
@@ -1,25 +1,40 @@
#!/usr/bin/env python3
-"""Calibration (L1): prove the ruler tells good from bad, per ruler.
+"""Calibration: prove the rulers tell good from bad, per ruler.
+
+L1 — the ENGINE rulers (no browser needed)
green = the bred example wolf (must build clean)
red = legacy multi-fault wolf (must be blocked)
red_5050 = violates ONLY the 50:50 proportion rule — must be blocked AND the
block reason must actually be 'proportion' (a red sample that fails
- for other reasons proves nothing about this ruler)."""
-import subprocess, os, sys, tempfile
+ for other reasons proves nothing about this ruler).
+
+L2 — the COLOUR ruler (judge.mjs; skipped when no browser is installed)
+Same shape, both directions: the shipped example wolf must read as COLOURED
+(saturated area above the 10% floor), and a DESATURATED copy of that same file
+must be blocked BY saturation_area. A ruler is calibrated by proving it
+separates, not by pinning one sample inside a band — the band's ceiling is gone
+(saturation_area is advisory now, and the L1-L8 stack raises chroma by design).
+Added after a real miss: the 1.3.0 colour split moved the hue
+from COLOR_0 into baseColorFactor, the judge's albedo pass still forced the
+base to white, and saturation_area silently measured 0.0% on every creature —
+which would have failed every HIGH gate with "reads as a grey mass". Nothing
+caught it because calibration had never run the judge at all.
+"""
+import subprocess, os, sys, tempfile, json, struct
H = os.path.dirname(os.path.abspath(__file__))
R = os.path.join(H, '..')
tmp = tempfile.mkdtemp(prefix='calib_')
-def build(spec):
+def build(spec, folder='calibration'):
+ out = os.path.join(tmp, os.path.basename(spec) + '.glb')
p = subprocess.run(['node', os.path.join(R, 'engine', 'cli.js'),
- os.path.join(R, 'calibration', spec),
- os.path.join(tmp, spec + '.glb')],
+ os.path.join(R, folder, spec), out],
capture_output=True, text=True)
- return p.returncode, p.stderr
+ return p.returncode, p.stderr, out
-rc_g, _ = build('wolf_green.json')
-rc_r, _ = build('wolf_red.json')
-rc_5, err5 = build('red_5050.json')
+rc_g, _, green_glb = build('wolf_green.json')
+rc_r, _, _ = build('wolf_red.json')
+rc_5, err5, _ = build('red_5050.json')
ok_g = rc_g == 0
ok_r = rc_r != 0
ok_5 = rc_5 != 0 and 'proportion' in err5
@@ -27,7 +42,125 @@ ok_5 = rc_5 != 0 and 'proportion' in err5
print(f"green (known-good) -> {'PASS ✓' if ok_g else 'blocked ✗ (ruler too strict)'}")
print(f"red (multi-fault) -> {'blocked ✓' if ok_r else 'PASSED ✗ (ruler too loose)'}")
print(f"red_5050 (only 50:50) -> {'blocked by proportion ✓' if ok_5 else 'NOT blocked by proportion ✗'}")
-if ok_g and ok_r and ok_5:
+
+# ── L2: the colour ruler ─────────────────────────────────────────────────────
+# The upper bound is gone, and it had to go twice over. The gate restructure
+# made saturation_area advisory — there is no ceiling left to calibrate against
+# — and the L1-L8 shading stack then measured the shipped wolf at ~52%, because
+# L4 raises chroma on purpose in the upper region. Calibrating against a ceiling
+# that neither the gate nor the shading believes in would fail every fresh
+# install for a creature nothing is wrong with.
+#
+# What a ruler has to prove is that it SEPARATES, and that is what this tests:
+# the shipped wolf must read as coloured, and a desaturated copy of the same
+# file must read as grey. Both directions, one sample, no magic ceiling.
+SAT_CLAIM = {'name': 'colour-ruler', 'claims': [
+ {'type': 'saturation_area', 'view': 'tq', 'min': 0.10,
+ 'stage': 'HIGH', 'label': 'must not read as a grey mass (floor 10%)'}]}
+
+
+def desaturate(src, dst):
+ """A grey twin of a built GLB: every colour replaced by its own luminance.
+
+ Both halves of the albedo, and it has to be both. This used to grey only
+ `baseColorFactor` on the theory that COLOR_0 carries a neutral shading
+ ratio — which was true while one material meant one hue. The L1-L8 stack
+ makes hue vary per VERTEX, so the ratio carries real chroma, and greying the
+ factor alone left a creature that still measured 51% saturated. The test
+ then reported the ruler was broken when what was broken was the twin.
+
+ Geometry and animation are untouched, so the only thing that changed is
+ still the exact quantity this ruler claims to measure."""
+ d = open(src, 'rb').read()
+ jl, = struct.unpack('<I', d[12:16])
+ g = json.loads(d[20:20 + jl])
+ rest = bytearray(d[20 + jl:])
+ for m in g.get('materials', []):
+ p = m.setdefault('pbrMetallicRoughness', {})
+ b = p.get('baseColorFactor', [1, 1, 1, 1])
+ lum = 0.2126 * b[0] + 0.7152 * b[1] + 0.0722 * b[2]
+ p['baseColorFactor'] = [lum, lum, lum, b[3] if len(b) > 3 else 1]
+
+ # COLOR_0, in the binary chunk. rest = 8-byte BIN chunk header + payload.
+ acc_ids = {prim['attributes']['COLOR_0']
+ for mesh in g.get('meshes', []) for prim in mesh.get('primitives', [])
+ if 'COLOR_0' in prim.get('attributes', {})}
+ views, base = g.get('bufferViews', []), 8
+ for ai in acc_ids:
+ a = g['accessors'][ai]
+ if a.get('componentType') != 5126 or a.get('type') not in ('VEC3', 'VEC4'):
+ continue # only float colours are rewritten
+ n = 3 if a['type'] == 'VEC3' else 4
+ bv = views[a['bufferView']]
+ off = base + bv.get('byteOffset', 0) + a.get('byteOffset', 0)
+ stride = bv.get('byteStride') or 4 * n
+ for i in range(a['count']):
+ o = off + i * stride
+ r, gg, bb = struct.unpack_from('<fff', rest, o)
+ L = 0.2126 * r + 0.7152 * gg + 0.0722 * bb
+ struct.pack_into('<fff', rest, o, L, L, L)
+ js = json.dumps(g).encode()
+ js += b' ' * ((4 - len(js) % 4) % 4)
+ out = (b"glTF" + struct.pack("<II", 2, 0) + struct.pack("<II", len(js), 0x4E4F534A) + js + bytes(rest))
+ out = out[:8] + struct.pack('<I', len(out)) + out[12:]
+ open(dst, 'wb').write(out)
+
+
+def judge(glb, spec_path):
+ # --json because this is a machine reading the output: the judge prints a
+ # short human summary by default now (a 2KB blob on stdout every run is paid
+ # for again on every later turn), and calibration needs the numbers.
+ p = subprocess.run(['node', os.path.join(H, 'judge.mjs'), glb,
+ os.path.join(tmp, 'j'), 'calib', '--spec', spec_path,
+ '--json'],
+ capture_output=True, text=True)
+ return p.returncode, (p.stdout or '') + (p.stderr or '')
+
+
+# The colour sample is example/wolf.json, NOT calibration/wolf_green.json:
+# wolf_green carries the pre-1.2.0 beige palette (it measures 0.2% saturated
+# and exists to exercise the ENGINE blocks, where palette is irrelevant),
+# while example/wolf.json is the reshipped creature the colour norms were
+# written against. Using the wrong one here would calibrate the ruler against
+# a sample that the shipped norms themselves reject.
+rc_cbuild, _, colour_glb = build('wolf.json', 'example')
+ok_c = True
+if rc_cbuild != 0:
+ print('colour ruler -> skipped (example/wolf.json did not build)')
+ ok_c = False
+else:
+ spec_path = os.path.join(tmp, 'sat.json')
+ json.dump(SAT_CLAIM, open(spec_path, 'w'))
+ rc_cg, out_cg = judge(colour_glb, spec_path)
+ # A judge that never MEASURED anything (no metrics line) did not fail this
+ # ruler — it failed to run: no browser, no `npm install` yet, a sandbox with
+ # no /dev/shm. Saying "the colour ruler is blind" there would send someone
+ # hunting a bug in the ruler on a machine that simply has no browser.
+ measured = any(l.startswith('{') and 'hi_sat_share' in l for l in out_cg.splitlines())
+ if not measured:
+ why = ('no browser installed' if 'cannot start a browser' in out_cg
+ else "playwright is not installed (run setup.sh, or npm i)"
+ if 'ERR_MODULE_NOT_FOUND' in out_cg or "Cannot find package" in out_cg
+ else 'the judge could not run: ' + (out_cg.strip().splitlines() or [''])[-1][:120])
+ print(f'colour ruler -> SKIPPED ({why})')
+ else:
+ grey = os.path.join(tmp, 'grey.glb')
+ desaturate(colour_glb, grey)
+ rc_cr, out_cr = judge(grey, spec_path)
+ pass_green = rc_cg == 0
+ block_grey = rc_cr != 0 and 'saturation' in out_cr.lower()
+ share = ''
+ for line in out_cg.splitlines():
+ if line.startswith('{'):
+ try:
+ share = f" (measured {json.loads(line)['hi_sat_share']['tq'] * 100:.1f}%)"
+ except Exception:
+ pass
+ print(f"colour green (saturated) -> {'PASS ✓' + share if pass_green else 'BLOCKED ✗ (the wolf read as a grey mass — the colour ruler is not seeing baseColorFactor x COLOR_0)' + share}")
+ print(f"colour grey (desaturated) -> {'blocked by saturation ✓' if block_grey else 'NOT blocked ✗ (the colour ruler passes anything)'}")
+ ok_c = pass_green and block_grey
+
+if ok_g and ok_r and ok_5 and ok_c:
print('[calibrate] OK: the rulers separate good from bad.')
else:
print('[calibrate] FAILED — do not start work; report this.')
diff --git a/harness/canary/answers.json b/harness/canary/answers.json
new file mode 100644
index 0000000..660efb2
--- /dev/null
+++ b/harness/canary/answers.json
@@ -0,0 +1,41 @@
+{
+ "_readme": "Known-answer decoys for blind reads. Shuffle ONE into every batch under a neutral name; wrong canary answer = the reader was not looking = the whole read is void.",
+ "ball.png": {
+ "aspect": "square",
+ "bumps": 0,
+ "identity": [
+ "ball",
+ "sphere",
+ "circle",
+ "egg",
+ "blob"
+ ]
+ },
+ "spike.png": {
+ "aspect": "tall",
+ "bumps": 1,
+ "identity": [
+ "spike",
+ "cone",
+ "tooth",
+ "horn",
+ "triangle",
+ "obelisk"
+ ]
+ },
+ "wolf_side.png": {
+ "aspect": "wide",
+ "bumps": [
+ 3,
+ 7
+ ],
+ "identity": [
+ "wolf",
+ "dog",
+ "fox",
+ "quadruped",
+ "animal",
+ "canine"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/harness/canary/ball.png b/harness/canary/ball.png
new file mode 100644
index 0000000..b531fb8
Binary files /dev/null and b/harness/canary/ball.png differ
diff --git a/harness/canary/spike.png b/harness/canary/spike.png
new file mode 100644
index 0000000..65fc08d
Binary files /dev/null and b/harness/canary/spike.png differ
diff --git a/harness/canary/wolf_side.png b/harness/canary/wolf_side.png
new file mode 100644
index 0000000..0d704c0
Binary files /dev/null and b/harness/canary/wolf_side.png differ
diff --git a/harness/claims.json b/harness/claims.json
new file mode 100644
index 0000000..b605e1a
--- /dev/null
+++ b/harness/claims.json
@@ -0,0 +1,86 @@
+{
+ "name": "<creature name>",
+ "_role": "The one claims sheet. Every creature is judged at boss standard: viewed close up, exaggerated, signature thresholds high. Role tiers (minion/NPC/boss) were removed — a cheaper creature is not a different ruler, it is the same ruler with a smaller triangle budget, so adjust tri_budget here if you need one.",
+ "claims": [
+ {
+ "type": "part_exists",
+ "part": "<signature part>",
+ "stage": "MID",
+ "label": "signature part must exist",
+ "enforce": "block",
+ "when": "verify"
+ },
+ {
+ "type": "part_signature",
+ "part": "<signature part>",
+ "view": "side",
+ "min_share": 0.16,
+ "or_min_span": 0.12,
+ "stage": "MID",
+ "label": "signature presence",
+ "enforce": "advise",
+ "when": "allocate"
+ },
+ {
+ "type": "focal_contrast",
+ "a": "<primary focal>",
+ "b": "<secondary focal>",
+ "min_ratio": 2,
+ "stage": "MID",
+ "label": "focal points must not be equal weight",
+ "enforce": "advise",
+ "when": "allocate"
+ },
+ {
+ "type": "share_hierarchy",
+ "primary": [
+ "<primary mass…>"
+ ],
+ "secondary": [
+ "<secondary mass…>"
+ ],
+ "tertiary": [
+ "<detail part…>"
+ ],
+ "stage": "MID",
+ "label": "631 hierarchy",
+ "enforce": "advise",
+ "when": "allocate"
+ },
+ {
+ "type": "rig_skinned",
+ "stage": "HIGH",
+ "enforce": "block",
+ "when": "verify"
+ },
+ {
+ "type": "anim_named",
+ "names": [
+ "idle",
+ "move",
+ "attack"
+ ],
+ "stage": "HIGH",
+ "enforce": "block",
+ "when": "verify"
+ },
+ {
+ "type": "saturation_area",
+ "view": "tq",
+ "min": 0.1,
+ "stage": "HIGH",
+ "label": "reference only: below ~10% the creature reads as a grey lump. The upper end is the shading layer’s job, not a gate.",
+ "enforce": "advise",
+ "when": "allocate"
+ },
+ {
+ "type": "tri_budget",
+ "min": 4000,
+ "max": 9000,
+ "stage": "LOW",
+ "label": "triangle budget band",
+ "enforce": "advise",
+ "when": "allocate"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/harness/deliver.py b/harness/deliver.py
index 5b5f013..770d800 100644
--- a/harness/deliver.py
+++ b/harness/deliver.py
@@ -18,7 +18,7 @@ stamping (asset block):
extras.gate --gate JSON, ONLY if it holds really-run check results
CC0 licence is NOT stamped here — publish.mjs adds it at upload, after consent.
"""
-import sys, os, json, base64, struct, shutil, subprocess, html
+import sys, os, json, base64, struct, shutil, subprocess, html, re
HERE = os.path.dirname(os.path.abspath(__file__))
@@ -51,16 +51,30 @@ def pack_glb(g, bin_chunk):
+ struct.pack('<II', len(js), 0x4E4F534A) + js
+ struct.pack('<II', len(body), 0x004E4942) + bytes(body))
+def clean_text(v, limit):
+ """A creature name and a signature are typed by a human and then travel
+ inside the file, forever, to viewers and galleries we do not control. The
+ contract forbids control characters and angle brackets in stamped strings,
+ so they are removed HERE rather than being allowed to fail the delivery:
+ the person made a naming choice, not a mistake. (The viewer additionally
+ HTML-escapes them; caps match the community wall's own 80/60 limits.)"""
+ if not v:
+ return v
+ v = re.sub(r'[\x00-\x1f\x7f<>]', '', str(v))
+ v = re.sub(r'\s+', ' ', v).strip()
+ return v[:limit] or None
+
+
def stamp(g, name, title, author, gate):
a = g.setdefault('asset', {})
a['version'] = '2.0'
a['generator'] = f'anyCreature v{read_version()}'
- if author: a['copyright'] = author
+ if author: a['copyright'] = clean_text(author, 60)
x = a.setdefault('extras', {})
x['harness'] = 'anyCreature'
x['harness_version'] = read_version()
x['spec'] = x.get('spec') or name
- if title: x['monster'] = title
+ if title: x['monster'] = clean_text(title, 80)
if gate: x['gate'] = gate
return g
@@ -108,14 +122,45 @@ def main():
' Fix the check and re-run, or set "passed": false and deliver it honestly.')
g, bin_chunk = parse_glb(open(src, 'rb').read())
+
+ # ── this harness delivers what THIS harness built ──────────────────────
+ # Field failure, twice now: an agent handed the package skips the cards,
+ # writes its own GLB generator and its own render pipeline, and arrives
+ # here with a file that never passed a single gate — no blind reads, no
+ # attack_reach, no part_seat, no contract. The engine stamps everything it
+ # builds; a file without that stamp did not come through the pipeline, so
+ # delivering it would put this harness's name on work it never checked.
+ if (g.get('asset', {}).get('extras', {}) or {}).get('harness') != 'anyCreature':
+ sys.exit(
+ '[deliver] REFUSED: this GLB was not built by this engine.\n'
+ '[deliver] anyCreature delivers what anyCreature built — the gates, the blind reads\n'
+ '[deliver] and the output contract are the product; a file that skipped them cannot\n'
+ '[deliver] carry the stamp.\n'
+ '[deliver] The pipeline is: write a spec (cards/SYNTAX.md) →\n'
+ '[deliver] node engine/cli.js spec.json out/creature.glb\n'
+ '[deliver] and the stage cards in cards/ are the process. Start at MANUAL.md.')
g = stamp(g, name, title, author, gate)
glb = pack_glb(g, bin_chunk)
glb_path = os.path.join(outdir, f'{name}.glb')
open(glb_path, 'wb').write(glb)
+ # Contract gate on the STAMPED bytes: stamping rewrites the JSON chunk, so
+ # the file that leaves this script is not the file the engine verified. A
+ # violation here means the delivery path itself broke the contract — refuse
+ # to produce a package rather than hand out a file we cannot vouch for.
+ conf = subprocess.run(['node', os.path.join(HERE, 'glbcheck.mjs'), glb_path],
+ capture_output=True, text=True)
+ if conf.returncode != 0:
+ os.remove(glb_path)
+ sys.exit('[deliver] ABORT: the stamped GLB breaks docs/OUTPUT_CONTRACT.md\n'
+ + conf.stderr.strip()
+ + '\n[deliver] names are cleaned before stamping, so this is a harness bug, '
+ 'not a naming problem — nothing was delivered; please report it.')
+
# showroom viewer
bundle = open(os.path.join(HERE, 'assets', 'three-bundle.js'), encoding='utf-8').read()
- disp = title or name.replace('_', ' ').title()
+ disp = clean_text(title, 80) or name.replace('_', ' ').title()
+ author = clean_text(author, 60)
byline = (f'{author} · ' if author else '') + f'anyCreature {read_version()}'
# The name and the signature come from a human and land inside markup, so
# they are escaped before substitution. Unescaped, a creature called
@@ -127,16 +172,23 @@ def main():
.replace('__B64__', base64.b64encode(glb).decode()))
open(os.path.join(outdir, f'{name}_viewer.html'), 'w', encoding='utf-8').write(page)
- # hero shots (transparent + studio) — the hero NEVER shows the label card
- subprocess.run(['node', os.path.join(HERE, 'hero.mjs'), glb_path, outdir], check=True)
+ # hero shots (transparent + studio) — the hero NEVER shows the label card.
+ # A hero failure (usually: no browser installed) must NOT kill the delivery:
+ # the GLB and the viewer are the deliverable; heroes degrade to a warning.
+ hero_ok = subprocess.run(['node', os.path.join(HERE, 'hero.mjs'), glb_path, outdir]).returncode == 0
+ if not hero_ok:
+ print('[deliver] WARN: hero shots failed — delivery continues without hero.png/jpg.')
+ print('[deliver] fix: npx playwright install chromium (then rerun deliver.py)')
# backup upload pack (web drag path)
up = os.path.join(outdir, 'upload'); os.makedirs(up, exist_ok=True)
shutil.copy(glb_path, os.path.join(up, 'creature.glb'))
- shutil.copy(os.path.join(outdir, 'hero.png'), os.path.join(up, 'hero.png'))
+ if os.path.exists(os.path.join(outdir, 'hero.png')):
+ shutil.copy(os.path.join(outdir, 'hero.png'), os.path.join(up, 'hero.png'))
open(os.path.join(up, 'README.txt'), 'w').write(UPLOAD_README)
- print(f'[deliver] done: {name}.glb · {name}_viewer.html · hero.png/jpg · upload/'
+ heroes = 'hero.png/jpg' if hero_ok else 'NO heroes (see warning)'
+ print(f'[deliver] done: {name}.glb · {name}_viewer.html · {heroes} · upload/'
f'\n[deliver] stamped: {disp}{" " + byline if byline else ""} · gate={"yes" if gate else "no"}'
f'\n[deliver] checklist: glb, viewer, heroes, spec JSON, DEVLOG one-liner')
diff --git a/harness/fit.py b/harness/fit.py
new file mode 100644
index 0000000..27838bb
--- /dev/null
+++ b/harness/fit.py
@@ -0,0 +1,202 @@
+#!/usr/bin/env python3
+"""Make a spec LEGAL before you spend a round on it.
+
+ python3 harness/fit.py <spec.json> [-o fitted.json] [--dry]
+
+WHAT THIS IS FOR. A spec is refused for two completely different reasons and
+they deserve completely different treatment:
+
+ · DESIGN — the silhouette does not read, the poles are the same idea twice,
+ the creature is a bean. Those need a decision, and this tool never touches
+ them.
+ · LEGALITY — a root ring is not buried in its host, two neighbouring bones
+ are the same length, the build does not land on its declared height. Those
+ are arithmetic with one right answer, and nobody should be spending build
+ rounds on them.
+
+The engine already computes the exact correction for each of those and prints
+it inside the BLOCK — "move joint X about 0.043m toward [0.00,-1.00,0.12]",
+"multiply every joint coordinate by 1.3613". This reads those numbers back and
+APPLIES them, then rebuilds, then reads again, until the legality set is clear
+or a pass stops making progress.
+
+WHY IT ITERATES. The fixes are coupled: burying a root ring moves a joint,
+which changes two segment lengths, which can trip the proportion band, which
+moves a joint again. One pass is not enough and neither is a human doing it by
+hand — that is the loop this replaces.
+
+WHAT IT WILL NOT DO. Anything where the correction is a design decision:
+
+ · balance — moving the centre of mass means moving masses, and which mass
+ moves is a design choice. Reported, never applied.
+ · mesh_integrity, limb_clearance, touch, part_seat — these say a shape or a
+ relationship is wrong, not by how much.
+ · every style check — soft_mass, thinnest_px48, poles_apart, the identity
+ gates. A tool that auto-satisfied a style threshold would be optimising the
+ ruler instead of the creature.
+
+So a clean run of this does not mean the creature is good. It means the round
+you are about to spend is about the creature, not about arithmetic.
+"""
+import sys, os, json, re, subprocess, copy
+
+H = os.path.dirname(os.path.abspath(__file__))
+R = os.path.dirname(H)
+MAX_PASSES = 6
+
+# Only these are auto-applied. Everything else is reported and left alone.
+FIXABLE = ('root_containment', 'proportion', 'size')
+
+
+def build(spec, tmp):
+ json.dump(spec, open(tmp, 'w', encoding='utf-8'))
+ p = subprocess.run(['node', os.path.join('engine', 'cli.js'), tmp,
+ os.path.join(os.path.dirname(tmp), '_fit.glb')],
+ capture_output=True, text=True, cwd=R)
+ out = (p.stdout or '') + (p.stderr or '')
+ return [l for l in out.splitlines() if l.startswith('BLOCK:')], out
+
+
+def joint_axes(j):
+ return [k for k in ('up', 'fwd', 'side', 'out') if k in j]
+
+
+def apply_root(spec, line):
+ """root_containment: move the named joint into its host by the stated metres."""
+ m = re.search(r'Move joint "([^"]+)" about ([\d.]+)m(?: toward \[([-\d., ]+)\])?', line)
+ if not m:
+ return False
+ jn, dist = m.group(1), float(m.group(2))
+ if dist <= 0:
+ return False
+ d = [float(x) for x in m.group(3).split(',')] if m.group(3) else None
+ j = (spec.get('joints') or {}).get(jn)
+ if j is None:
+ return False
+ if isinstance(j, list): # absolute [x, y, z]
+ if not d:
+ return False
+ for i in range(3):
+ j[i] = round(j[i] + d[i] * dist, 4)
+ return True
+ if not isinstance(j, dict):
+ return False
+ # relational: push along whichever axes it already uses, toward the host
+ ax = joint_axes(j)
+ if not ax:
+ return False
+ # The direction the engine prints is already a unit world vector, so each
+ # relational axis takes its own component of it directly. Dividing by the
+ # sum of the components (the obvious-looking normalisation) under-shoots
+ # every time and the loop then walks toward the target without arriving.
+ comp = {'side': (d[0] if d else 0), 'up': (d[1] if d else -1),
+ 'fwd': (d[2] if d else 0), 'out': (d[0] if d else 0)}
+ # `need` is the 80th-percentile overshoot — the move that lands the ring
+ # exactly ON the boundary. Overshoot it slightly so the next pass is not
+ # spent on the rounding.
+ dist *= 1.25
+ for a in ax:
+ j[a] = round(j[a] + comp[a] * dist, 4)
+ return True
+
+
+def apply_proportion(spec, line):
+ """proportion: break a 50:50 pair by shortening the SECOND bone."""
+ m = re.search(r'chain "([^"]+)" segments (\S+)→(\S+)→(\S+) are 50:50 \(([\d.]+)\)', line)
+ if not m:
+ return False
+ _, a, b, c, ratio = m.groups()
+ j = (spec.get('joints') or {}).get(c)
+ if not isinstance(j, dict):
+ return False
+ ax = joint_axes(j)
+ if not ax:
+ return False
+ # aim for the middle of the 0.62-0.85 band rather than the edge of it, so
+ # the next pass does not land back on the boundary
+ k = 0.74
+ for a_ in ax:
+ j[a_] = round(j[a_] * k, 4)
+ return True
+
+
+def apply_size(spec, line):
+ m = re.search(r'multiply every joint coordinate by ([\d.]+)', line)
+ if not m:
+ return False
+ f = float(m.group(1))
+ for jn, j in (spec.get('joints') or {}).items():
+ if isinstance(j, list):
+ spec['joints'][jn] = [round(v * f, 4) for v in j]
+ elif isinstance(j, dict):
+ for a in joint_axes(j) + ['len', 'ground']:
+ if a in j:
+ j[a] = round(j[a] * f, 4)
+ return True
+
+
+APPLY = {'root_containment': apply_root, 'proportion': apply_proportion, 'size': apply_size}
+
+
+def main():
+ a = sys.argv[1:]
+ if not a or a[0].startswith('-'):
+ print(__doc__)
+ return 2
+ src = a[0]
+ out = a[a.index('-o') + 1] if '-o' in a else None
+ dry = '--dry' in a
+ spec = json.load(open(src, encoding='utf-8'))
+ tmp = os.path.join(os.path.dirname(os.path.abspath(src)), '_fit_spec.json')
+
+ applied, history = [], []
+ for p in range(1, MAX_PASSES + 1):
+ blocks, _ = build(spec, tmp)
+ kinds = [b.split(':')[1].strip() if ':' in b else b for b in blocks]
+ legal = [b for b in blocks if any(b.startswith('BLOCK: ' + f) for f in FIXABLE)]
+ history.append((p, len(blocks), len(legal)))
+ if not blocks:
+ print(f'[fit] pass {p}: green.')
+ break
+ if not legal:
+ print(f'[fit] pass {p}: {len(blocks)} block(s) left, none of them arithmetic.')
+ break
+ if dry:
+ print(f'[fit] pass {p}: {len(legal)} fixable of {len(blocks)} — dry run, stopping.')
+ break
+ moved = 0
+ for b in legal:
+ key = b[len('BLOCK: '):].split(':')[0]
+ fn = APPLY.get(key)
+ if fn and fn(spec, b):
+ moved += 1
+ applied.append(key)
+ print(f'[fit] pass {p}: {len(blocks)} block(s), {len(legal)} arithmetic, applied {moved}')
+ if not moved:
+ print('[fit] nothing moved — the remaining ones need a decision.')
+ break
+
+ blocks, raw = build(spec, tmp)
+ try:
+ os.remove(tmp)
+ os.remove(os.path.join(os.path.dirname(tmp), '_fit.glb'))
+ except OSError:
+ pass
+ print()
+ from collections import Counter
+ if applied:
+ print(' applied: ' + ', '.join(f'{k}x{v}' for k, v in Counter(applied).items()))
+ if blocks:
+ print(f' {len(blocks)} block(s) remain — these are yours to decide:')
+ for b in blocks:
+ print(' ' + b[:150])
+ else:
+ print(' the spec is legal. The round you spend next is about the creature.')
+ if out and not dry:
+ json.dump(spec, open(out, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
+ print(f' written: {out}')
+ return 1 if blocks else 0
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/harness/gates.json b/harness/gates.json
new file mode 100644
index 0000000..d2a7b42
--- /dev/null
+++ b/harness/gates.json
@@ -0,0 +1,415 @@
+{
+ "_": [
+ "THE MAP. Every check in the system, in one place, tagged on five axes.",
+ "",
+ "enforce — block | advise",
+ "when — allocate (decidable before the build) | verify (only after it exists)",
+ "by — A | B | C (which judgment source runs it)",
+ "kind — legality (a defect; only ever gets stricter) | style (a tunable threshold)",
+ "dept — design | model | surface | rig | animation | process",
+ "",
+ "stage is a FIELD, not a hard-coded branch: LOW/MID/HIGH are levels of",
+ "refinement, not a fixed department order. Any stage may run any department at",
+ "its own resolution, and moving a check between stages is a data edit.",
+ "",
+ "The 18 checks tagged `allocate` are decidable before the build. `harness/fit.py`",
+ "applies the arithmetic subset of them (root_containment, proportion, size) from",
+ "the numbers the engine already prints, so a build round is spent on the",
+ "creature rather than on legality.",
+ "",
+ "Rule of placement: put a check as early as the thing it measures can exist,",
+ "at the coarsest resolution that can still show it."
+ ],
+ "stages": {
+ "LOW": "coarse resolution — the whole creature, big masses",
+ "MID": "part resolution — named parts and colour",
+ "HIGH": "finishing resolution — rig, clips, shading"
+ },
+ "checks": [
+ {
+ "id": "mesh_integrity",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "geometry that is not geometry — degenerate or broken faces",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "root_containment",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "the root bone must sit inside the body",
+ "by": "A",
+ "kind": "legality",
+ "dept": "rig"
+ },
+ {
+ "id": "part_attachment",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "a part must actually be seated on what it claims to attach to",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "touch",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "parts that should touch must touch",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "balance",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "the creature must not fall over",
+ "by": "A",
+ "kind": "legality",
+ "dept": "rig"
+ },
+ {
+ "id": "size",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "built height must land within ±15% of the declared height",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "proportion",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "limb and body proportions inside sane bounds",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "limb_clearance",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "limbs must not pass through each other while animating",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "anim_integrity",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "the animation clips must be valid and must not tear the mesh",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "attack_reach",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "the attack must actually reach out, not mime",
+ "by": "A",
+ "kind": "style",
+ "dept": "animation"
+ },
+ {
+ "id": "gait_direction",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "a planted foot must sweep BACKWARD — a forward sweep is a walk cycle playing in reverse",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "root_drive",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "a lunge must be driven on the skeleton ROOT, not on one of its children",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "faceted",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "a body that is all flat facets when it should read as flesh",
+ "by": "A",
+ "kind": "style",
+ "dept": "surface"
+ },
+ {
+ "id": "soft_mass",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "a volume that cannot break anywhere — the rounded sausage",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "mirror_distortion",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "advise",
+ "when": "verify",
+ "plain": "mirrored twins deformed differently",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "part_overlap",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "advise",
+ "when": "verify",
+ "plain": "how deeply parts interpenetrate",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "part_seat",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "advise",
+ "when": "verify",
+ "plain": "how well a part sits on its host surface",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "brief_slots",
+ "where": "harness/brief.py",
+ "stage": "LOW",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "every brief slot a later stage READS must be filled in — presence only, never content",
+ "by": "A",
+ "kind": "legality",
+ "dept": "process"
+ },
+ {
+ "id": "brief_coverage",
+ "where": "harness/brief.py",
+ "stage": "LOW",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "the chains the brief NAMED must exist in the r1 spec",
+ "by": "A",
+ "kind": "legality",
+ "dept": "process"
+ },
+ {
+ "id": "poles_apart",
+ "where": "harness/brief.py + round.py",
+ "stage": "LOW",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "the two versions in a round must be opposite ends of one axis, not one design built twice",
+ "by": "A",
+ "kind": "style",
+ "dept": "process"
+ },
+ {
+ "id": "pole_fill",
+ "where": "harness/brief.py + round.py",
+ "stage": "LOW",
+ "enforce": "advise",
+ "when": "verify",
+ "plain": "a pole that fills too much of its own bounding box is a blob, not a pose",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "gate1_recognised",
+ "where": "card 01",
+ "stage": "LOW",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "a reader who knows nothing must rank the brief's creature high enough, in enough views (harness/identity.py)",
+ "by": "B",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "gate2_punchier",
+ "where": "card 01",
+ "stage": "LOW",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "the exaggerated silhouette must beat the previous round's",
+ "by": "B",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "thinnest_px48",
+ "where": "harness/maskmetrics.py + roundcheck.py",
+ "stage": "LOW",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "the width of the thinnest feature on the 48px thumbnail the reader sees",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "tri_budget",
+ "where": "harness/claims.json",
+ "stage": "LOW",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "triangle budget band",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "value_order",
+ "where": "engine",
+ "stage": "MID",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "every material sorted by OKLab lightness — the value plan, computed instead of eyeballed",
+ "by": "A",
+ "kind": "style",
+ "dept": "surface"
+ },
+ {
+ "id": "contrast_adjacent",
+ "where": "engine",
+ "stage": "MID",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "a part must separate in colour from the thing it SITS ON",
+ "by": "A",
+ "kind": "style",
+ "dept": "surface"
+ },
+ {
+ "id": "part_exists",
+ "where": "harness/claims.json",
+ "stage": "MID",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "the signature part the brief named must exist",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "part_signature",
+ "where": "harness/claims.json",
+ "stage": "MID",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "how much of the side view the signature part holds",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "focal_contrast",
+ "where": "harness/claims.json",
+ "stage": "MID",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "the signature part should read clearly bigger than the head",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "share_hierarchy",
+ "where": "harness/claims.json",
+ "stage": "MID",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "main mass : signature : detail ≈ 6:3:1",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "rig_skinned",
+ "where": "harness/claims.json",
+ "stage": "HIGH",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "RIG — the mesh must actually be skinned to the skeleton",
+ "by": "A",
+ "kind": "legality",
+ "dept": "rig"
+ },
+ {
+ "id": "anim_named",
+ "where": "harness/claims.json",
+ "stage": "HIGH",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "CLIP — idle, move and attack must all be present",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "saturation_area",
+ "where": "harness/claims.json",
+ "stage": "HIGH",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "how much of the creature carries a strongly saturated colour",
+ "by": "A",
+ "kind": "style",
+ "dept": "surface"
+ },
+ {
+ "id": "output_contract",
+ "where": "harness/glbcheck.mjs",
+ "stage": "SHIP",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "the delivered file must satisfy the output contract",
+ "by": "A",
+ "kind": "legality",
+ "dept": "process"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/harness/gates.py b/harness/gates.py
new file mode 100644
index 0000000..9483ef1
--- /dev/null
+++ b/harness/gates.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python3
+"""Print the gate map: every check in the system, tagged on five axes.
+
+usage: python3 harness/gates.py [LOW|MID|HIGH|SHIP|any]
+ python3 harness/gates.py --by dept|kind|by
+
+Five questions, asked of every check. The first two are about ENFORCEMENT, the
+last three are about ARCHITECTURE — they exist so a piece can be swapped without
+the pipeline changing shape.
+
+ · does it BLOCK or only ADVISE?
+ · is it ALLOCATED before the build, or VERIFIED after?
+ · WHICH SOURCE decides it — A, B or C?
+ · WHAT KIND — legality (a defect, no debate) or style (taste with a number)?
+ · WHICH DEPARTMENT — model / material / skeleton / animation / process?
+
+"allocate vs verify" is where the money is: anything decidable up front that is
+only checked afterwards is a rebuild waiting to happen. "legality vs style" is
+where the FLEXIBILITY is: a legality check only ever gets better, while every
+style threshold is a candidate to become a swappable profile, and none of them
+should ever be mistaken for a law.
+"""
+import sys, os, json
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+G = json.load(open(os.path.join(HERE, 'gates.json'), encoding='utf-8'))
+want = (sys.argv[1].upper() if len(sys.argv) > 1 else None)
+
+def w(s, n):
+ width = sum(2 if ord(c) > 127 else 1 for c in s)
+ return s + ' ' * max(0, n - width)
+
+rows = [c for c in G['checks'] if not want or c['stage'].upper() == want]
+order = {'LOW': 0, 'MID': 1, 'HIGH': 2, 'SHIP': 3, 'ANY': 4}
+rows.sort(key=lambda c: (order.get(c['stage'].upper(), 9), c['enforce'], c['id']))
+
+print()
+for k, v in G['stages'].items():
+ print(f' {k:5} {v}')
+print()
+print(w('stage', 7) + w('enforce', 22) + w('when', 10) + w('id', 20) + 'what it is')
+print('-' * 100)
+# ▣ = advises the first time, blocks if the next round still has not fixed it
+MARK = {'block': '■', 'advise': '·', 'advise-then-block': '▣'}
+last = None
+for c in rows:
+ if c['stage'] != last:
+ print()
+ last = c['stage']
+ print(w(c['stage'], 7) + w(MARK.get(c['enforce'], '?') + ' ' + c['enforce'], 22)
+ + w(c['when'], 10) + w(c['id'], 20) + c['plain'])
+
+# ── the architecture axes ────────────────────────────────────────────────
+def group(field, title, note):
+ from collections import defaultdict
+ g = defaultdict(list)
+ for c in rows:
+ g[c.get(field, '?')].append(c['id'])
+ print()
+ print(f' {title}')
+ for k in sorted(g, key=lambda k: -len(g[k])):
+ print(f' {w(k, 11)} {len(g[k]):>2} ' + ', '.join(sorted(g[k]))[:74])
+ print(f' {note}')
+
+if len(sys.argv) > 2 and sys.argv[1] == '--by':
+ pass
+group('kind', 'BY KIND — legality is a defect and only gets better; style is taste with a number on it',
+ 'every style row is a candidate to become a swappable profile. None of them is a law.')
+group('by', 'BY SOURCE — which source produces the verdict for this check',
+ 'the source is fixed per check in gates.json; changing it changes what the check costs to run.')
+group('dept', 'BY DEPARTMENT — two checks in one department should share their tools',
+ 'a measure defined twice is a measure that will drift; synccheck.py lists any that are.')
+
+nb = sum(1 for c in rows if c['enforce'] == 'block')
+nt = sum(1 for c in rows if c['enforce'] == 'advise-then-block')
+na = len(rows) - nb - nt
+al = sum(1 for c in rows if c['when'] == 'allocate')
+mis = [c for c in rows if c['when'] == 'allocate' and c['enforce'] == 'block']
+print()
+print(f' {nb} block · {na} advise · {nt} advise-then-block · '
+ f'{al} of {len(rows)} are decidable before the build')
+if mis:
+ print()
+ print(' Blocking, but decidable up front — each of these can refuse a build over')
+ print(' something that should simply have been budgeted:')
+ for c in mis:
+ print(f' · {c["id"]}: {c["plain"]}')
+print()
diff --git a/harness/glbcheck.mjs b/harness/glbcheck.mjs
new file mode 100644
index 0000000..e4d1af4
Binary files /dev/null and b/harness/glbcheck.mjs differ
diff --git a/harness/graft.py b/harness/graft.py
new file mode 100644
index 0000000..d539454
--- /dev/null
+++ b/harness/graft.py
@@ -0,0 +1,164 @@
+#!/usr/bin/env python3
+"""Graft — transplant a part from one creature's GLB onto another, at SPEC level.
+
+Every anyCreature GLB carries its authored spec inside (`asset.extras.
+source_spec`). Grafting therefore never touches meshes: it copies the part's
+spec block (plus everything it depends on) from the donor into the recipient's
+spec, rescales it by the two creatures' declared heights, and writes a fused
+spec. YOU then compile it — and the normal gates (part_seat, part_attachment,
+touch, anim_integrity) judge the transplant like any other build. A graft that
+does not seat gets BLOCKED, not shipped.
+
+ python3 harness/graft.py <donor.glb> <recipient.glb> \\
+ --part <name-or-material> --host <recipient joint> \\
+ [--out fused_spec.json] [--offset x,y,z] [--scale N]
+
+Then: node engine/cli.js fused_spec.json out/fused.glb
+
+Covers automatically: hosted parts (curve / spike / hand / paw / fin / eye) and
+membranes (their rib chains, joints, attach entries, mirror registration and
+matching animation tracks come along, rebased onto the new host). Anchored
+parts are copied with a TODO printed — re-aim the anchor at a recipient chain.
+"""
+import sys, os, json, struct, copy
+
+def load_spec(path):
+ d = open(path, 'rb').read()
+ if d[:4] != b'glTF':
+ return json.load(open(path)) # a bare spec.json also works
+ jl, = struct.unpack('<I', d[12:16])
+ g = json.loads(d[20:20 + jl])
+ src = (g.get('asset', {}).get('extras', {}) or {}).get('source_spec')
+ if not src:
+ sys.exit(f'[graft] {os.path.basename(path)} has no embedded spec '
+ '(built before 1.3.0?) — recompile it, or pass its spec.json instead')
+ return src
+
+def resolve_joints(spec):
+ """Mini mirror of engine/core/relative.js — absolute positions for rebasing."""
+ J = copy.deepcopy(spec.get('joints', {}))
+ pending = [n for n, v in J.items() if not isinstance(v, list)]
+ guard = len(pending) + 1
+ while pending and guard > 0:
+ guard -= 1
+ nxt = []
+ for n in pending:
+ d = J[n]; base = J.get(d.get('from'))
+ if not isinstance(base, list):
+ nxt.append(n); continue
+ if 'dir' in d and 'len' in d:
+ dx = d['dir']; L = (dx[0]**2 + dx[1]**2 + dx[2]**2) ** 0.5 or 1
+ p = [base[k] + dx[k] / L * d['len'] for k in range(3)]
+ else:
+ p = [base[0] + d.get('side', 0), base[1] + d.get('up', 0), base[2] + d.get('fwd', 0)]
+ if 'ground' in d: p[1] = d['ground']
+ J[n] = p
+ pending = nxt
+ return J
+
+def main():
+ args = sys.argv[1:]
+ def opt(flag, default=None):
+ if flag in args:
+ i = args.index(flag); v = args[i + 1]; del args[i:i + 2]; return v
+ return default
+ part_key = opt('--part'); new_host = opt('--host')
+ out = opt('--out', 'fused_spec.json')
+ off = opt('--offset'); scale_opt = opt('--scale')
+ if len(args) < 2 or not part_key:
+ sys.exit(__doc__)
+ donor, recip = load_spec(args[0]), load_spec(args[1])
+ fused = copy.deepcopy(recip)
+ todos = []
+
+ # ── find the part in the donor ──
+ cand = [p for p in donor.get('parts', [])
+ if p.get('name') == part_key or p.get('material') == part_key]
+ if not cand:
+ names = [(p.get('name') or p.get('material') or p.get('type')) for p in donor.get('parts', [])]
+ sys.exit(f'[graft] no part "{part_key}" in donor. Available: {", ".join(names)}')
+ part = copy.deepcopy(cand[0])
+
+ # ── scale: declared heights, unless overridden ──
+ if scale_opt:
+ k = float(scale_opt)
+ elif donor.get('height') and recip.get('height'):
+ k = recip['height'] / donor['height']
+ else:
+ k = 1.0
+ todos.append('no height declared on both sides — grafted at 1:1, check the size by eye')
+ def sc(v): return round(v * k, 5)
+
+ # ── palette entries travel with the part ──
+ fused.setdefault('palette', {})
+ for mat in {part.get('material')} - {None}:
+ if mat in fused['palette'] and fused['palette'][mat] != donor['palette'].get(mat):
+ nm = mat + '_g'
+ todos.append(f'material name "{mat}" already exists — grafted copy renamed "{nm}"')
+ part['material'] = nm; mat = nm
+ fused['palette'][mat] = copy.deepcopy(donor['palette'][cand[0]['material']])
+
+ dJ = resolve_joints(donor); rJ = resolve_joints(recip)
+
+ if part.get('type') == 'membrane':
+ # membranes ride chains: copy each rib chain + joints, rebased onto the new host
+ if not new_host: sys.exit('[graft] a membrane graft needs --host <recipient joint>')
+ if new_host not in rJ: sys.exit(f'[graft] recipient has no joint "{new_host}"')
+ anchor_old = None
+ rename = {}
+ for rib in part.get('ribs', []):
+ cn = rib.get('chain')
+ if not cn: continue
+ names = donor['chains'][cn]
+ if anchor_old is None:
+ anchor_old = dJ[names[0]] # first rib root = old shoulder
+ cn2 = cn if cn not in fused.get('chains', {}) else cn + 'G'
+ if cn2 != cn: rename[cn] = cn2
+ fused.setdefault('chains', {})[cn2] = []
+ for n in names:
+ n2 = n if n not in fused.get('joints', {}) else n + 'G'
+ p0 = dJ[n]
+ fused.setdefault('joints', {})[n2] = [
+ round(rJ[new_host][0] + (p0[0] - anchor_old[0]) * k, 5),
+ round(rJ[new_host][1] + (p0[1] - anchor_old[1]) * k, 5),
+ round(rJ[new_host][2] + (p0[2] - anchor_old[2]) * k, 5)]
+ fused['chains'][cn2].append(n2)
+ fused.setdefault('attach', {})[cn2] = new_host
+ if cn in donor.get('mirror', []) and cn2 not in fused.setdefault('mirror', []):
+ fused['mirror'].append(cn2)
+ rib['chain'] = cn2
+ # matching animation tracks come along (same-named clips only)
+ for an, clip in (donor.get('animations') or {}).items():
+ dst = (fused.get('animations') or {}).get(an)
+ if not dst: continue
+ for jn, tr in (clip.get('tracks') or {}).items():
+ if jn in names:
+ dst.setdefault('tracks', {})[jn if jn not in rename else rename[jn]] = copy.deepcopy(tr)
+ todos.append('membrane grafted: check rib pose (the wing carries its old pose, rebased) and clearance')
+ else:
+ # hosted part: rescale local numbers, point it at the new host
+ if not new_host: sys.exit('[graft] --host <recipient joint> is required')
+ if new_host not in rJ: sys.exit(f'[graft] recipient has no joint "{new_host}"')
+ part['host'] = new_host
+ if 'offset' in part: part['offset'] = [sc(v) for v in part['offset']]
+ if off: part['offset'] = [float(x) for x in off.split(',')]
+ if 'size' in part:
+ part['size'] = sc(part['size']) if isinstance(part['size'], (int, float)) \
+ else [sc(v) for v in part['size']]
+ for seg in part.get('segments', []) or []:
+ if 'len' in seg: seg['len'] = sc(seg['len'])
+ if 'r' in seg: seg['r'] = sc(seg['r'])
+ if 'thickness' in part: part['thickness'] = sc(part['thickness'])
+ if 'points' in part: part['points'] = [[sc(u), sc(v)] for u, v in part['points']]
+ if 'anchor' in part:
+ todos.append(f'part is anchored to donor chain "{part["anchor"].get("chain")}" — '
+ 're-aim "anchor" at a recipient chain (or remove it and place by offset)')
+
+ fused.setdefault('parts', []).append(part)
+ json.dump(fused, open(out, 'w'), indent=1)
+ print(f'[graft] "{part_key}" → host "{new_host}" · scale ×{k:.3f} · wrote {out}')
+ for t in todos: print('[graft] TODO: ' + t)
+ print(f'[graft] next: node engine/cli.js {out} out/fused.glb (the gates judge the transplant)')
+
+if __name__ == '__main__':
+ main()
diff --git a/harness/hero.mjs b/harness/hero.mjs
index a79d370..36671cb 100644
--- a/harness/hero.mjs
+++ b/harness/hero.mjs
@@ -4,7 +4,7 @@
// idle mid-frame, ≥8% margin on every side (nothing cropped)
// hero.jpg same shot over the studio grey backdrop
// usage: node harness/hero.mjs <model.glb> <outdir>
-import { chromium } from 'playwright';
+import { launchBrowser } from './pwlaunch.mjs';
import fs from 'fs'; import path from 'path'; import http from 'http';
import { fileURLToPath } from 'url';
@@ -71,10 +71,9 @@ const srv = http.createServer((q, res) => {
// whenever two runs overlapped.
await new Promise(r => srv.listen(0, '127.0.0.1', r));
const port = srv.address().port;
-// Let Playwright locate its own browser; PW_CHROMIUM_PATH pins it if needed.
-const br = await chromium.launch({ executablePath: process.env.PW_CHROMIUM_PATH || undefined,
- args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader']
- .concat(process.env.PW_NO_SANDBOX === '1' ? ['--no-sandbox'] : []) });
+// Shared launcher: PW_CHROMIUM_PATH pins a binary; a missing browser dies with
+// ONE actionable line ("run npx playwright install chromium"), never a stack.
+const br = await launchBrowser();
const pg = await br.newPage({ viewport: { width: 1044, height: 1044 } });
await pg.goto(`http://127.0.0.1:${port}/`);
await pg.evaluate(() => window.load('/model.glb'));
diff --git a/harness/identity.py b/harness/identity.py
new file mode 100644
index 0000000..9b6db7d
--- /dev/null
+++ b/harness/identity.py
@@ -0,0 +1,123 @@
+#!/usr/bin/env python3
+"""The identity verdict, weighted and counted — not argued.
+
+ python3 harness/identity.py --round 1 --noun scorpion \\
+ --ranks front=none side=2 top=2 hero=1
+
+Each view's rank is WHERE the brief's noun appeared in that reader's ranked
+guesses (1 = its first guess), or `none` if it was not in the list at all.
+Synonyms count as the noun; that judgment is yours, and it is the only one this
+tool leaves you.
+
+THE RULE. A rank of R passes if the noun reached R in at least R views:
+
+ rank 1 in 1 view one reader's FIRST guess is the creature — done
+ rank 2 in 2 views agreement at second place
+ rank 3 in 3 views broad agreement, weakly
+ rank 4 in 4 views every view has it somewhere in four — the floor
+
+Rank 5 and beyond does not count. A noun that never gets above fifth is not
+being recognised, it is being listed.
+
+AND IT LOOSENS EACH ROUND. The required number of views drops by one per repair
+round (never below one), because the cost of another round rises while the
+information it buys does not:
+
+ round 1 rank1:1 rank2:2 rank3:3 rank4:4
+ round 2 rank1:1 rank2:1 rank3:2 rank4:3
+ round 3 rank1:1 rank2:1 rank3:1 rank4:2
+
+WHY WEIGHTED AT ALL. The bar used to be one word, exactly right. A 48px
+silhouette is a genuinely ambiguous object, and that bar measured the reader's
+confidence as much as the creature's clarity. A reader will answer "a generic
+bat/moth/gargoyle silhouette" with the ordered noun sitting INSIDE that
+sentence, and a one-word bar throws the whole read away. Recognition is not
+binary and this scores it as what it is.
+"""
+import sys
+
+MAX_RANK = 4
+
+
+def needed(rank, rnd):
+ """Views required at this rank, for this round."""
+ return max(1, rank - (rnd - 1))
+
+
+def verdict(ranks, rnd):
+ """ranks: {view: int|None}. Returns (passed, rank_that_carried, detail)."""
+ lines = []
+ best = None
+ for r in range(1, MAX_RANK + 1):
+ hit = [v for v, k in ranks.items() if k is not None and k <= r]
+ need = needed(r, rnd)
+ ok = len(hit) >= need
+ lines.append((r, len(hit), need, ok, hit))
+ if ok and best is None:
+ best = r
+ return best is not None, best, lines
+
+
+def main():
+ a = sys.argv[1:]
+ if '--ranks' not in a:
+ print(__doc__)
+ return 2
+ rnd = int(a[a.index('--round') + 1]) if '--round' in a else 1
+ noun = a[a.index('--noun') + 1] if '--noun' in a else 'the brief\'s noun'
+ ranks = {}
+ for x in a[a.index('--ranks') + 1:]:
+ if x.startswith('--'):
+ break
+ if '=' not in x:
+ print(f'BLOCK: "{x}" should look like side=2 or front=none')
+ return 2
+ v, k = x.split('=', 1)
+ ranks[v] = None if k.lower() in ('none', 'no', '-', 'x') else int(k)
+ if not ranks:
+ print('BLOCK: --ranks needs at least one view')
+ return 2
+
+ passed, carried, lines = verdict(ranks, rnd)
+ print(f'identity r{rnd} — "{noun}" across {len(ranks)} view(s)')
+ for v, k in ranks.items():
+ print(f' {v:<7} {"not in the list" if k is None else f"guess {k}"}')
+ print()
+ for r, got, need, ok, hit in lines:
+ mark = '✓' if ok else ' '
+ print(f' {mark} rank {r}: {got} view(s) at {r} or better, needs {need}'
+ + (f' [{", ".join(hit)}]' if hit else ''))
+ print()
+ if passed:
+ note = ''
+ if carried >= 3:
+ note = (' It reads, but not loudly — say so in the closing line.'
+ if carried == 3 else
+ ' This is the floor. It reads only just; the closing line should say so.')
+ print(f'PASS — carried at rank {carried}.{note}')
+ print(f' record it: roundcheck.py <out> --record r{rnd} ID pass "{noun} (rank {carried})"')
+ return 0
+ print(f'FAIL — "{noun}" did not reach any rank in enough views.')
+ unread = [v for v in ('front', 'side', 'top', 'hero') if v not in ranks]
+ if unread:
+ print()
+ print(f' LOOK BEFORE YOU REBUILD. {len(unread)} view(s) of THIS shape have not been')
+ print(f' read yet: {", ".join(unread)}. Show them to one reader before you change')
+ print(' a single number. Three more images inside one reader is a fraction of a')
+ print(' round; a rebuild is a whole one, and it throws away a shape that may')
+ print(' already work from another angle.')
+ print(' Measured: a build failed on SIDE at r1 and r2, restarted the concept at')
+ print(' r3, and at r5 its TOP view came back "a lizard, gecko, or SALAMANDER seen')
+ print(' from above" — the ordered noun, first guess, unprompted. The creature was')
+ print(' not wrong. The declared identity view was. Four reads and a concept')
+ print(' restart to learn that, when one extra image would have said it at r1.')
+ print(' If another view reads, CHANGE THE BRIEF\'s identity view and record why.')
+ print()
+ print(' The verdict IS the work order: repair the BIG masses, and remember a')
+ print(' repair must clear roundcheck\'s minimum change or the next read is refused.')
+ print(f' record it: roundcheck.py <out> --record r{rnd} ID fail "<what they saw instead>"')
+ return 1
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/harness/judge.mjs b/harness/judge.mjs
index 0de74e0..8a3c61c 100644
--- a/harness/judge.mjs
+++ b/harness/judge.mjs
@@ -20,7 +20,7 @@
// saturation_area {view?, min?, max?} — share of the view carrying a highly saturated colour
// (HSV S ≥ 0.50 on the UNLIT baked colour). Default band
// 0.10–0.34. Says how much, never where.
-import { chromium } from 'playwright';
+import { launchBrowser } from './pwlaunch.mjs';
import path from 'path'; import fs from 'fs'; import http from 'http';
import { fileURLToPath } from 'url';
@@ -107,16 +107,25 @@ scene.remove(hemi,key,fill);
r.outputColorSpace=THREE.LinearSRGBColorSpace;
// 1b) albedo — the baked vertex colours with NO lighting, so saturation can be
-// measured independently of brightness. gradient, grain and AO are all uniform
+// Verified:dependently of brightness. gradient, grain and AO are all uniform
// multiplies, so they move a pixel's value but never its HSV saturation; lights
// do move it (a white key washes colour out, a blue rim invents it). Measuring
// here is the only way "how much of this creature is highly saturated" comes out
// as an honest area rather than a lighting artefact.
+// ALBEDO = baseColorFactor × COLOR_0, ALWAYS BOTH. This line used to force the
+// base colour to white whenever COLOR_0 existed, which was correct only while
+// the entire palette lived in the vertices. Since 1.3.0 the engine splits the
+// baked colour — the HUE into baseColorFactor, the shading RATIO (≤1) into
+// COLOR_0 — so measuring COLOR_0 alone measures a deliberately near-grey
+// multiplier: the wolf's saturated area read 26.0% before the split and 0.0%
+// after it, and every creature would have been told it "reads as a grey mass".
+// A ruler that does not follow the format it measures is worse than no ruler.
r.outputColorSpace=THREE.SRGBColorSpace;
const albedoMat=new Map();
model.traverse(o=>{ if(o.isMesh){ albedoMat.set(o,o.material);
o.material=new THREE.MeshBasicMaterial({vertexColors:!!o.geometry.attributes.color,
- color:o.geometry.attributes.color?0xffffff:(o.material.color?o.material.color.clone():0xffffff),
+ color:o.material.color?o.material.color.clone():0xffffff,
+ map:o.material.map||null,
side:THREE.DoubleSide}); }});
const albedo=shoot(d=>{ let body=0,hi=0;
for(let i=0;i<d.length;i+=4){ const R=d[i],G=d[i+1],B=d[i+2];
@@ -182,12 +191,10 @@ await new Promise(r=>server.listen(0,'127.0.0.1',r));
const port=server.address().port;
// Let Playwright find its own browser. A hardcoded container path breaks every
// clone on macOS/Windows; PW_CHROMIUM_PATH stays available for pinned setups.
-const exe = process.env.PW_CHROMIUM_PATH || undefined;
-// --no-sandbox drops a real defence and is only needed where the OS sandbox is
-// unavailable (docker without SYS_ADMIN, CI images). Opt in, never by default.
-const launchArgs=['--use-gl=angle','--use-angle=swiftshader','--enable-unsafe-swiftshader'];
-if(process.env.PW_NO_SANDBOX==='1') launchArgs.push('--no-sandbox');
-const browser=await chromium.launch({executablePath:exe,args:launchArgs});
+// Shared launcher (harness/pwlaunch.mjs): PW_CHROMIUM_PATH pins a binary,
+// PW_NO_SANDBOX=1 opts out of the OS sandbox only where it cannot run, and a
+// missing browser dies with ONE actionable line instead of a stack.
+const browser=await launchBrowser();
const page=await browser.newPage({viewport:{width:560,height:560}});
const errs=[]; page.on('pageerror',e=>errs.push(String(e)));
await page.goto(`http://127.0.0.1:${port}/`);
@@ -213,8 +220,26 @@ const m={ name, stats:R.stats, names:R.names,
lum:Object.fromEntries(Object.entries(R.lum).map(([vn,x])=>[vn,+x.medianLum.toFixed(1)])),
hi_sat_share:Object.fromEntries(Object.entries(R.sat).map(([vn,x])=>[vn,+x.hiSatShare.toFixed(4)])),
parts, whole:{size:whole} };
-fs.writeFileSync(path.join(outDir,`${name}_metrics.json`),JSON.stringify(m,null,1));
-console.log(JSON.stringify(m));
+const metricsPath=path.join(outDir,`${name}_metrics.json`);
+fs.writeFileSync(metricsPath,JSON.stringify(m,null,1));
+// A SUMMARY, not the blob. This used to print the entire metrics object — every
+// part, every view, every share, about 2KB — straight to stdout, on every run.
+// Tool output lands in the conversation permanently and the conversation is
+// re-read on every turn afterwards, so a 2KB dump at round 3 is still being
+// paid for at round 30. The file has always held the full record; print where it
+// is and the handful of numbers a decision actually turns on. `--json` restores
+// the old behaviour for anything parsing this.
+if(process.argv.includes('--json')) console.log(JSON.stringify(m));
+else {
+ const v='tq';
+ console.log(`[judge] ${name}: ${m.stats.triangles} tris · ${m.names.length} materials · `
+ +`clips ${m.stats.animations.join('/')||'none'} · skinned ${m.stats.skinnedMeshes}`);
+ console.log(` ${v} view: luminance ${m.lum[v]} · saturated area `
+ +`${(m.hi_sat_share[v]*100).toFixed(1)}%`);
+ const top=Object.entries(m.parts).sort((a,b)=>(b[1].share[v]||0)-(a[1].share[v]||0)).slice(0,3);
+ console.log(' biggest in view: '+top.map(([n,p])=>`${n} ${(p.share[v]*100).toFixed(0)}%`).join(' · '));
+ console.log(` full numbers: ${metricsPath}`);
+}
// ── Spec mode: check every claim, symptom first ──
if(specFile){
@@ -235,15 +260,22 @@ if(specFile){
if(L>c.max_median_lum) bad.push(`Declared dark but does not read dark on screen: ${v}-view body median luminance ${L.toFixed(0)}/255 (need ≤${c.max_median_lum}) — push the material colour values darker`); },
style_light(c){ const v=c.view||'side'; const L=R.lum[v].medianLum;
if(L<c.min_median_lum) bad.push(`Declared light but reads too dark on screen: ${v}-view body median luminance ${L.toFixed(0)}/255 (need ≥${c.min_median_lum})`); },
- // High-saturation AREA, measured on the unlit baked colour (HSV S ≥ 0.50).
+ // High-saturation AREA, Verified: the unlit baked colour (HSV S ≥ 0.50).
// Too little and the creature is a grey lump; too much and saturation stops
// being a spotlight and the whole thing screams. Do NOT name which surfaces
// carry it — where the colour goes is the designer's call, only how much.
saturation_area(c){ const v=c.view||'tq';
const s=R.sat[v]; if(!s) return;
- const pct=s.hiSatShare*100, lo=(c.min??0.10)*100, hi=(c.max??0.34)*100;
+ // There is NO default ceiling. Dropping `max` from claims.json did not
+ // remove the old 0.34 one, because it lived here as a fallback — so the
+ // ceiling went on refusing creatures after it had supposedly been
+ // retired, and it took the shading stack (which raises chroma on purpose)
+ // to expose that. A ceiling only applies now if a spec asks for one by
+ // name. The floor keeps its default: "reads as a grey lump" is a real
+ // failure and nobody has to opt into catching it.
+ const pct=s.hiSatShare*100, lo=(c.min??0.10)*100;
if(pct<lo) bad.push(`Too little colour: only ${pct.toFixed(1)}% of the ${v} view is highly saturated (need ≥${lo.toFixed(0)}%) — the creature reads as a grey mass. Raise the saturation of a mass that deserves the attention, do not tint everything.`);
- if(pct>hi) bad.push(`Too much colour: ${pct.toFixed(1)}% of the ${v} view is highly saturated (need ≤${hi.toFixed(0)}%) — saturation stops reading as a spotlight when it covers this much. Desaturate the supporting masses and keep the loud colour on the signature.`); },
+ if(c.max!=null && pct>c.max*100) bad.push(`Too much colour: ${pct.toFixed(1)}% of the ${v} view is highly saturated (need ≤${(c.max*100).toFixed(0)}%) — saturation stops reading as a spotlight when it covers this much. Desaturate the supporting masses and keep the loud colour on the signature.`); },
rig_skinned(){ if(R.stats.skinnedMeshes<1)
bad.push('Model is not skinned: the rig is not bound to the mesh, so animating the bones moves nothing'); },
anim_named(c){ for(const a of c.names) if(!R.stats.animations.includes(a))
@@ -269,17 +301,34 @@ if(specFile){
if(lo>0 && hi/lo<ratio) bad.push(`Two focal points of equal weight compete: "${c.a}" ${(A*100).toFixed(1)}% vs "${c.b}" ${(B*100).toFixed(1)}% (need ≥${ratio}× apart) — the eye ping-pongs between them; open up the dominance gap`); },
};
const claims=(S.claims||[]).filter(c=>!stageFilter || !c.stage || c.stage.toUpperCase()===stageFilter);
+ // enforce: "block" stops the build; "advise" measures and reports and never
+ // stops it. Taste is advice — a number that says the eye will ping-pong is
+ // worth reading and is not worth a rebuild. Correctness is a gate: a rig that
+ // does not deform or a clip that does not exist is broken, not debatable.
+ // Every claim carries the tag explicitly; see harness/gates.json for the map
+ // of the whole system, and for `when` (allocate up front vs verify after).
+ const advice=[];
for(const c of claims){
const fn=CHECKS[c.type];
if(!fn){ bad.push(`Spec contains a claim type the engine does not recognise: "${c.type}"`); continue; }
const before=bad.length; fn(c);
- if(bad.length>before && c.label) bad[bad.length-1] += ` [${c.label}]`;
+ if(bad.length===before) continue;
+ // a check may push more than one line; the tag applies to all of them
+ const mine=bad.splice(before);
+ if(c.label) mine[mine.length-1] += ` [${c.label}]`;
+ if((c.enforce||'block')==='advise') advice.push(...mine); else bad.push(...mine);
}
+ if(advice.length){ console.log('\n'+'-'.repeat(68));
+ console.log('ADVICE — measured, not blocking. Your judgment, your call:');
+ for(const a of advice) console.log(' · '+a);
+ console.log('-'.repeat(68)); }
if(bad.length){ console.log('\n'+'='.repeat(68));
console.log(`BLOCKING — against spec "${S.name||path.basename(specFile)}", the following fail and must be fixed:`);
for(const b of bad) console.log(' ✗ '+b);
console.log('='.repeat(68)+`\n${bad.length} blocking item(s). exit 1 — cannot ship.`);
await browser.close(); server.close(); process.exit(1); }
- console.log(`[judge] Spec \"${S.name||''}\" — all claims pass.`);
+ console.log(advice.length
+ ? `[judge] Spec \"${S.name||''}\" — nothing blocking. ${advice.length} advisory item(s) above; read them, then decide.`
+ : `[judge] Spec \"${S.name||''}\" — all claims pass.`);
}
await browser.close(); server.close();
diff --git a/harness/maskmetrics.py b/harness/maskmetrics.py
index 21b899e..fb744d7 100644
--- a/harness/maskmetrics.py
+++ b/harness/maskmetrics.py
@@ -49,8 +49,19 @@ for p in sys.argv[2:]:
ys2, xs2 = np.where(blob)
ext = max(ys2.max()-ys2.min(), xs2.max()-xs2.min()) + 1
thin = ext*ext / max(s, 1) # higher = longer/thinner = sharper read
- protr.append({'dir_deg': round(ang), 'size': round(s/area, 3), 'thinness': round(thin, 1)})
+ # WIDTH AT READING SIZE. The blind read happens on a 48px thumbnail, so
+ # an arm two pixels across is not a thin arm, it is an invisible one —
+ # and no amount of repositioning will make the reader see it. This is
+ # arithmetic available on the FIRST build; a run that discovers it at
+ # round 22 has spent sixteen rounds moving something nobody could see.
+ # Twice the max inscribed radius = the blob's own thickness, scaled to 48.
+ dt = ndimage.distance_transform_edt(blob)
+ px48 = round(2 * float(dt.max()) * 48.0 / max(H, W), 1)
+ protr.append({'dir_deg': round(ang), 'size': round(s/area, 3),
+ 'thinness': round(thin, 1), 'px48': px48})
protr.sort(key=lambda x: -x['size'])
+ # the thinnest thing that is still trying to be a feature
+ thinnest = min([p['px48'] for p in protr], default=None)
# ── dullness flags (MEASURES ONLY, the reader/LLM judges) ──
# 1:1-frame fill: the silhouette in a square frame must carry real volume
Ssq = max(H, W)
@@ -88,13 +99,27 @@ for p in sys.argv[2:]:
'neg_pockets': pockets[:6],
'com': [round(float(cx)/W, 2), round(float(cy)/H, 2)],
'protrusions': protr[:8],
+ 'thinnest_px48': thinnest,
'sq_fill': round(sq_fill, 3),
'mirror_sym': round(mirror_sym, 2),
'straight_max': round(float(straight), 2),
}
sil = Image.fromarray((~m*255).astype(np.uint8))
+ # ASPECT IS THE BINDING QUESTION. Card 01 §4 asks every reader "wider or
+ # taller?" and voids the whole read when the answer disagrees with
+ # W_over_H in metrics.json. A hard resize((px,px)) makes every thumbnail
+ # square, so the honest answer is always "square-ish" and no read can ever
+ # bind — measured cost: 21 of 52 reads in the 1.3.0 three-creature batch
+ # were re-runs, ~40% of the blind-read budget, for a trap that was
+ # mechanically unanswerable. Fit inside the box instead and pad with the
+ # background, so the shape keeps the proportion the reader is asked about.
for px in (24, 48):
- sil.resize((px, px), Image.LANCZOS).resize((240, 240), Image.NEAREST)\
+ w = max(1, round(px * W / H)) if W < H else px
+ h = px if W < H else max(1, round(px * H / W))
+ small = sil.resize((w, h), Image.LANCZOS)
+ box = Image.new('L', (px, px), 255)
+ box.paste(small, ((px - w) // 2, (px - h) // 2))
+ box.resize((240, 240), Image.NEAREST)\
.save(os.path.join(outdir, f'{name}_thumb{px}.png'))
sheets.append((name, sil))
if sheets:
@@ -108,6 +133,23 @@ if sheets:
for n, t in tiles:
sheet.paste(t, (x, 30)); d.text((x, 8), n, fill=0); x += t.width + 10
sheet.save(os.path.join(outdir, 'sheet.png'))
-with open(os.path.join(outdir, 'metrics.json'), 'w') as f:
- json.dump(report, f, indent=1)
+# MERGE, never overwrite. silmetrics writes its own report to this same file in
+# this same round directory — including iou_vs_prev, the regression guard — and
+# card 01 runs silmetrics first, then this. A plain write therefore deleted the
+# guard a second after it was computed, in every round of every run since it was
+# added. Our keys are image names, silmetrics' are flat scalars, so they merge
+# without collision; a stale key from a re-run is harmless and worth keeping.
+mpath = os.path.join(outdir, 'metrics.json')
+merged = {}
+if os.path.exists(mpath):
+ try:
+ with open(mpath, encoding='utf-8') as f:
+ prev = json.load(f)
+ if isinstance(prev, dict):
+ merged = prev
+ except Exception:
+ pass
+merged.update(report)
+with open(mpath, 'w') as f:
+ json.dump(merged, f, indent=1)
print(json.dumps(report))
diff --git a/harness/outline.py b/harness/outline.py
new file mode 100644
index 0000000..f72af35
--- /dev/null
+++ b/harness/outline.py
@@ -0,0 +1,422 @@
+#!/usr/bin/env python3
+"""Silhouettes straight from the geometry — no browser, no renderer, no images to read.
+
+ python3 harness/outline.py <model.glb> <outdir> [--prev <dir>] [--views front,side,top,hero]
+
+WHY. The silhouette is the single most-used measurement in this harness, and
+until now getting one meant launching a headless Chromium, loading three.js,
+uploading the mesh to a GPU, drawing it black-on-white, and reading the pixels
+back. That is a lot of machinery to answer a question the vertices already
+contain: this is low-poly, a few thousand triangles, and the outline of a solid
+under a known camera is arithmetic.
+
+So this projects the triangles and fills them. Same camera as silmetrics.mjs
+(perspective, 30 degrees, distance = longest dimension x 2.4, 640x640, same view
+directions and up vectors), same mask convention, same metrics. The point is not
+only speed — it is that the numbers stop being *estimates read off a picture*
+and become the thing itself.
+
+WHAT THIS DOES NOT REPLACE. It cannot tell you WHAT the shape looks like. "Is
+this a bison" is a judgment about resemblance and it needs eyes; that is the
+blind reader's job and no amount of coordinate data does it. What this removes
+is everything AROUND that question — aspect, protrusions, thinnest feature,
+round-to-round similarity — so the reader can be handed one picture and one
+question instead of thirteen pictures and a questionnaire.
+"""
+import sys, os, json, struct, math
+
+try:
+ import numpy as np
+ from PIL import Image, ImageDraw
+except ImportError:
+ print('BLOCK: outline.py needs numpy and pillow — run setup.sh')
+ sys.exit(2)
+
+RES = 640
+FOV = 30.0
+
+
+# ── GLB ────────────────────────────────────────────────────────────────────
+def read_glb(path):
+ b = open(path, 'rb').read()
+ if b[:4] != b'glTF':
+ raise ValueError('not a GLB')
+ jlen, = struct.unpack('<I', b[12:16])
+ g = json.loads(b[20:20 + jlen])
+ bin_off = 20 + jlen + 8
+ return g, b, bin_off
+
+
+def accessor(g, b, base, idx):
+ a = g['accessors'][idx]
+ bv = g['bufferViews'][a['bufferView']]
+ off = base + bv.get('byteOffset', 0) + a.get('byteOffset', 0)
+ n = {'SCALAR': 1, 'VEC2': 2, 'VEC3': 3, 'VEC4': 4}[a['type']]
+ ct = a['componentType']
+ fmt, size = {5126: ('f', 4), 5125: ('I', 4), 5123: ('H', 2), 5121: ('B', 1)}[ct]
+ stride = bv.get('byteStride') or size * n
+ out = np.empty((a['count'], n), dtype=np.float64 if ct == 5126 else np.int64)
+ for i in range(a['count']):
+ out[i] = struct.unpack_from('<' + fmt * n, b, off + i * stride)
+ return out
+
+
+def triangles_by_material(path):
+ """Triangles grouped by material name, so a share can be attributed."""
+ g, b, base = read_glb(path)
+ mats = [m.get('name', f'mat{i}') for i, m in enumerate(g.get('materials', []))]
+ V, F, MID = [], [], []
+ for mesh in g.get('meshes', []):
+ for pr in mesh.get('primitives', []):
+ at = pr.get('attributes', {})
+ if 'POSITION' not in at:
+ continue
+ off = sum(len(x) for x in V)
+ pos = accessor(g, b, base, at['POSITION'])
+ V.append(pos)
+ if 'indices' in pr:
+ f = accessor(g, b, base, pr['indices']).reshape(-1, 3) + off
+ else:
+ n = len(pos) - len(pos) % 3
+ f = np.arange(n).reshape(-1, 3) + off
+ F.append(f)
+ mi = pr.get('material', -1)
+ MID.append(np.full(len(f), mi, dtype=np.int64))
+ if not V:
+ raise ValueError('no geometry in the file')
+ return np.vstack(V), np.vstack(F), np.concatenate(MID), mats
+
+
+def triangles(path):
+ """Every triangle in the file, as world-space vertex positions.
+
+ Bind pose only, which is what a silhouette gate looks at: this engine writes
+ inverse bind matrices that are pure translations of the joint's world
+ position, so the stored POSITION values are already world-space at rest."""
+ g, b, base = read_glb(path)
+ V, F = [], []
+ for mesh in g.get('meshes', []):
+ for pr in mesh.get('primitives', []):
+ at = pr.get('attributes', {})
+ if 'POSITION' not in at:
+ continue
+ off = sum(len(x) for x in V)
+ pos = accessor(g, b, base, at['POSITION'])
+ V.append(pos)
+ if 'indices' in pr:
+ ix = accessor(g, b, base, pr['indices']).reshape(-1)
+ F.append(ix.reshape(-1, 3) + off)
+ else:
+ n = len(pos) - len(pos) % 3
+ F.append(np.arange(n).reshape(-1, 3) + off)
+ if not V:
+ raise ValueError('no geometry in the file')
+ return np.vstack(V), np.vstack(F)
+
+
+# ── camera, matching silmetrics.mjs exactly ────────────────────────────────
+def view_dir(view, size):
+ long_axis = 'x' if size[0] > size[2] else 'z'
+ if view == 'top':
+ return np.array([0., 1., 0.]), np.array([1., 0., 0.]) if long_axis == 'x' else np.array([0., 0., 1.])
+ if view == 'hero':
+ return np.array([1., 0.5, 1.]), np.array([0., 1., 0.])
+ if view == 'side':
+ d = [0., 0., 1.] if long_axis == 'x' else [1., 0., 0.]
+ else: # front
+ d = [1., 0., 0.] if long_axis == 'x' else [0., 0., 1.]
+ return np.array(d), np.array([0., 1., 0.])
+
+
+def render_mask(V, F, view):
+ lo, hi = V.min(axis=0), V.max(axis=0)
+ centre, size = (lo + hi) / 2, hi - lo
+ d, up = view_dir(view, size)
+ rad = float(size.max())
+ # NOT normalised, deliberately. three.js does
+ # cam.position = centre + new Vector3(...dir) * (rad * 2.4)
+ # on the raw vector, and the hero direction [1, 0.5, 1] has length 1.5 — so
+ # the hero camera really does sit 1.5x further out than the axis views. A
+ # pixel-level comparison caught this: front/side/top matched at IoU 0.98+
+ # because their directions are already unit, and hero came back at 0.39.
+ eye = centre + d * rad * 2.4
+
+ fwd = centre - eye
+ fwd /= np.linalg.norm(fwd)
+ right = np.cross(fwd, up)
+ if np.linalg.norm(right) < 1e-9: # looking straight down the up axis
+ right = np.cross(fwd, np.array([0., 0., 1.]))
+ right /= np.linalg.norm(right)
+ trueup = np.cross(right, fwd)
+
+ rel = V - eye
+ cam = np.stack([rel @ right, rel @ trueup, rel @ fwd], axis=1)
+ z = np.maximum(cam[:, 2], 1e-6)
+ f = 1.0 / math.tan(math.radians(FOV) / 2)
+ sx = (cam[:, 0] / z) * f
+ sy = (cam[:, 1] / z) * f
+ px = (sx * 0.5 + 0.5) * RES
+ py = (0.5 - sy * 0.5) * RES # image y grows downward
+
+ img = Image.new('1', (RES, RES), 0)
+ drw = ImageDraw.Draw(img)
+ for a, b_, c in F:
+ drw.polygon([(px[a], py[a]), (px[b_], py[b_]), (px[c], py[c])], fill=1)
+ return np.array(img, dtype=bool)
+
+
+# ── measures, on the mask ──────────────────────────────────────────────────
+def measures(mask):
+ ys, xs = np.nonzero(mask)
+ if len(xs) == 0:
+ return {'empty': True}
+ w = int(xs.max() - xs.min() + 1)
+ h = int(ys.max() - ys.min() + 1)
+ area = int(mask.sum())
+ m = {
+ 'W_over_H': round(w / h, 3),
+ 'fill': round(area / (w * h), 3),
+ 'px': [w, h],
+ }
+ # WHERE THE MASS SITS, in thirds of its own bounding box. Same definition as
+ # maskmetrics.py, on the cropped mask, so the two agree to the decimal.
+ #
+ # This is the number that tells two DESIGNS apart, which iou_vs_prev does
+ # not: iou counts overlapping pixels, so a proportion change moves it a lot
+ # while the design stays put. Read off a shipped 13-round build, iou swung
+ # 0.476-0.873 while thirds_cols never left [~0.23, ~0.33, ~0.44] — thirteen
+ # rounds, one layout, including both rounds the log calls concept restarts.
+ crop = mask[ys.min():ys.max() + 1, xs.min():xs.max() + 1]
+ m['thirds_cols'] = [round(float(crop[:, i * w // 3:(i + 1) * w // 3].sum() / area), 2)
+ for i in range(3)]
+ m['thirds_rows'] = [round(float(crop[i * h // 3:(i + 1) * h // 3].sum() / area), 2)
+ for i in range(3)]
+ try:
+ from scipy import ndimage
+ except ImportError:
+ return m
+ # Protrusions and thinnest_px48 use maskmetrics.py's definitions EXACTLY —
+ # erode hard to get a core, subtract to get appendages, and measure each
+ # appendage's own thickness as twice its maximum inscribed radius, scaled to
+ # the 48px thumbnail the reader actually sees. Two implementations of the
+ # same number must agree or one of them is lying; the first version here
+ # took the global minimum of the distance transform instead, which is the
+ # one-pixel boundary and therefore always ~1px, on every creature.
+ H, W = mask.shape
+ it = max(2, int(min(H, W) * 0.06))
+ core = ndimage.binary_erosion(mask, iterations=it)
+ app = mask & ~ndimage.binary_dilation(core, iterations=it)
+ la, na = ndimage.label(app)
+ protr = []
+ for i in range(1, na + 1):
+ blob = la == i
+ s = int(blob.sum())
+ if s < area * 0.01:
+ continue
+ dt = ndimage.distance_transform_edt(blob)
+ protr.append(round(2 * float(dt.max()) * 48.0 / max(H, W), 1))
+ m['protrusions'] = len(protr)
+ m['thinnest_px48'] = min(protr) if protr else None
+ return m
+
+
+def project(V, view):
+ """World vertices -> screen x, y and camera depth, for one view."""
+ lo, hi = V.min(axis=0), V.max(axis=0)
+ centre, size = (lo + hi) / 2, hi - lo
+ d, up = view_dir(view, size)
+ rad = float(size.max())
+ eye = centre + d * rad * 2.4
+ fwd = centre - eye
+ fwd /= np.linalg.norm(fwd)
+ right = np.cross(fwd, up)
+ if np.linalg.norm(right) < 1e-9:
+ right = np.cross(fwd, np.array([0., 0., 1.]))
+ right /= np.linalg.norm(right)
+ trueup = np.cross(right, fwd)
+ rel = V - eye
+ cam = np.stack([rel @ right, rel @ trueup, rel @ fwd], axis=1)
+ z = np.maximum(cam[:, 2], 1e-6)
+ f = 1.0 / math.tan(math.radians(FOV) / 2)
+ px = ((cam[:, 0] / z) * f * 0.5 + 0.5) * RES
+ py = (0.5 - (cam[:, 1] / z) * f * 0.5) * RES
+ return px, py, z
+
+
+def material_shares(V, F, MID, mats, view):
+ """Which material OWNS each silhouette pixel, with a depth test.
+
+ The share of the frame a part holds is a geometry question, and it was being
+ answered by a browser: render every material in a distinct colour, read the
+ pixels back, count them. That needs a GPU only because of occlusion — a wing
+ behind the torso must not be counted — and occlusion is a z-buffer, which is
+ thirty lines. So: rasterise every triangle with a depth test, keep the
+ winning material per pixel, and count."""
+ px, py, z = project(V, view)
+ depth = np.full((RES, RES), np.inf)
+ owner = np.full((RES, RES), -1, dtype=np.int64)
+ for tri, mi in zip(F, MID):
+ a, b, c = tri
+ xs = np.array([px[a], px[b], px[c]])
+ ys = np.array([py[a], py[b], py[c]])
+ x0, x1 = int(max(0, np.floor(xs.min()))), int(min(RES - 1, np.ceil(xs.max())))
+ y0, y1 = int(max(0, np.floor(ys.min()))), int(min(RES - 1, np.ceil(ys.max())))
+ if x1 < x0 or y1 < y0:
+ continue
+ det = (ys[1] - ys[2]) * (xs[0] - xs[2]) + (xs[2] - xs[1]) * (ys[0] - ys[2])
+ if abs(det) < 1e-12:
+ continue
+ gx, gy = np.meshgrid(np.arange(x0, x1 + 1) + 0.5,
+ np.arange(y0, y1 + 1) + 0.5)
+ l0 = ((ys[1] - ys[2]) * (gx - xs[2]) + (xs[2] - xs[1]) * (gy - ys[2])) / det
+ l1 = ((ys[2] - ys[0]) * (gx - xs[2]) + (xs[0] - xs[2]) * (gy - ys[2])) / det
+ l2 = 1.0 - l0 - l1
+ inside = (l0 >= 0) & (l1 >= 0) & (l2 >= 0)
+ if not inside.any():
+ continue
+ zz = l0 * z[a] + l1 * z[b] + l2 * z[c]
+ sub = depth[y0:y1 + 1, x0:x1 + 1]
+ win = inside & (zz < sub)
+ if win.any():
+ sub[win] = zz[win]
+ owner[y0:y1 + 1, x0:x1 + 1][win] = mi
+ total = int((owner >= 0).sum())
+ out = {}
+ if total:
+ for mi in np.unique(owner):
+ if mi < 0:
+ continue
+ name = mats[mi] if 0 <= mi < len(mats) else f'mat{mi}'
+ out[name] = round(float((owner == mi).sum()) / total, 5)
+ return out, owner >= 0
+
+
+def exaggeration(mask):
+ """The numbers that answer 'is this bold enough' — no reader required.
+
+ Every one of these used to be a thing someone squinted at. They are all
+ properties of a set of pixels, and the pixels are a projection of vertices,
+ so they were always arithmetic."""
+ ys, xs = np.nonzero(mask)
+ if len(xs) == 0:
+ return {}
+ w = float(xs.max() - xs.min() + 1)
+ h = float(ys.max() - ys.min() + 1)
+ area = float(mask.sum())
+ m = {
+ 'box_fill': round(area / (w * h), 3), # spindly vs blobby
+ 'sq_fill': round(area / (max(w, h) ** 2), 3), # volume in a 1:1 frame
+ 'extent': round(max(w, h) / min(w, h), 3), # how far from square
+ }
+ try:
+ from scipy import ndimage
+ from scipy.spatial import ConvexHull
+ pts = np.stack([xs, ys], axis=1).astype(float)
+ if len(pts) >= 3:
+ try:
+ hull = ConvexHull(pts)
+ # bites taken out of the outline: 1.0 = a blob, lower = real
+ # negative space
+ m['convexity'] = round(area / max(hull.volume, 1.0), 3)
+ except Exception:
+ pass
+ half = mask[:, :mask.shape[1] // 2]
+ other = np.fliplr(mask[:, mask.shape[1] - half.shape[1]:])
+ m['mirror_sym'] = round(float((half == other).mean()), 3)
+ except ImportError:
+ pass
+ return m
+
+
+def iou(a, b):
+ if a.shape != b.shape:
+ return None
+ u = int((a | b).sum())
+ return round(int((a & b).sum()) / u, 4) if u else None
+
+
+def thumb(mask, px, path):
+ """Letterboxed, exactly like maskmetrics: the proportion the reader sees is
+ the proportion the file records."""
+ ys, xs = np.nonzero(mask)
+ if len(xs) == 0:
+ Image.new('L', (px, px), 255).resize((240, 240), Image.NEAREST).save(path)
+ return
+ sub = mask[ys.min():ys.max() + 1, xs.min():xs.max() + 1]
+ im = Image.fromarray(np.where(sub, 0, 255).astype(np.uint8), 'L')
+ W, H = im.size
+ w = px if W >= H else max(1, round(px * W / H))
+ h = px if H > W else max(1, round(px * H / W))
+ box = Image.new('L', (px, px), 255)
+ box.paste(im.resize((w, h), Image.LANCZOS), ((px - w) // 2, (px - h) // 2))
+ box.resize((240, 240), Image.NEAREST).save(path)
+
+
+def main():
+ a = sys.argv[1:]
+ if len(a) < 2:
+ print(__doc__)
+ return 2
+ model, outdir = a[0], a[1]
+ prev = a[a.index('--prev') + 1] if '--prev' in a else None
+ views = (a[a.index('--views') + 1].split(',') if '--views' in a
+ else ['front', 'side', 'top', 'hero'])
+ os.makedirs(outdir, exist_ok=True)
+
+ V, F, MID, mats = triangles_by_material(model)
+ report = {'vertices': int(len(V)), 'triangles': int(len(F)),
+ 'materials': mats, 'views': {}}
+ thin_all = []
+ for v in views:
+ shares, mask = material_shares(V, F, MID, mats, v)
+ np.save(os.path.join(outdir, f'mask_{v}.npy'), mask)
+ Image.fromarray(np.where(mask, 0, 255).astype(np.uint8), 'L').save(
+ os.path.join(outdir, f'sil_{v}.png'))
+ for px in (24, 48):
+ thumb(mask, px, os.path.join(outdir, f'sil_{v}_thumb{px}.png'))
+ mm = measures(mask)
+ mm.update(exaggeration(mask))
+ mm['share'] = shares
+ if mm.get('thinnest_px48') is not None:
+ thin_all.append(mm['thinnest_px48'])
+ if prev:
+ p = os.path.join(prev, f'mask_{v}.npy')
+ if os.path.exists(p):
+ mm['iou_vs_prev'] = iou(mask, np.load(p))
+ report['views'][v] = mm
+
+ if thin_all:
+ report['thinnest_px48'] = min(thin_all)
+ ious = [d['iou_vs_prev'] for d in report['views'].values()
+ if d.get('iou_vs_prev') is not None]
+ if ious:
+ # the round moved as much as its most-changed view says it did
+ report['iou_vs_prev'] = min(ious)
+
+ mpath = os.path.join(outdir, 'metrics.json')
+ merged = {}
+ if os.path.exists(mpath):
+ try:
+ prevj = json.load(open(mpath, encoding='utf-8'))
+ if isinstance(prevj, dict):
+ merged = prevj
+ except Exception:
+ pass
+ merged.update(report)
+ json.dump(merged, open(mpath, 'w', encoding='utf-8'), indent=1)
+
+ print(f"{report['triangles']} triangles, {len(views)} views, no browser")
+ for v, d in report['views'].items():
+ bits = [f"W/H {d.get('W_over_H')}"]
+ if d.get('thinnest_px48') is not None:
+ bits.append(f"thinnest {d['thinnest_px48']}px")
+ if d.get('protrusions') is not None:
+ bits.append(f"{d['protrusions']} protrusion(s)")
+ if d.get('iou_vs_prev') is not None:
+ bits.append(f"iou {d['iou_vs_prev']}")
+ print(f' {v:<6} ' + ' '.join(bits))
+ return 0
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/harness/partreads.py b/harness/partreads.py
new file mode 100644
index 0000000..df5901e
--- /dev/null
+++ b/harness/partreads.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+"""Every MID part read, ONE command — build, render, and hand back one batch.
+
+ python3 harness/partreads.py <outdir> --spec face.json claw.json tail.json
+ [--colour hero.png]
+
+The MID whitelist reads used to be two commands PER PART — a compile and a
+silhouette render — issued one at a time, and then one reader per part. Card 02
+already merged the reads into a single batch; this merges the building too, so
+four parts cost one turn instead of eight.
+
+The turn is the unit that costs. A compile is 1.4 seconds and a view is half a
+second; a round-trip re-reads the entire conversation so far. A measured a run
+build spent 150-odd turns on tool calls that could have been a handful.
+
+Prints the shuffled batch the reader should see, and the answer key you keep to
+yourself. Python and stdlib only — the harness ships to other people.
+"""
+import sys, os, json, subprocess, random, hashlib
+
+H = os.path.dirname(os.path.abspath(__file__))
+R = os.path.dirname(H)
+CANARY = os.path.join(H, 'canary')
+
+
+def run(cmd):
+ p = subprocess.run(cmd, capture_output=True, text=True, cwd=R)
+ return p.returncode, (p.stdout or '') + (p.stderr or '')
+
+
+def main():
+ a = sys.argv[1:]
+ if len(a) < 2 or '--spec' not in a:
+ print(__doc__)
+ return 2
+ outdir = a[0]
+ si = a.index('--spec')
+ specs = []
+ for x in a[si + 1:]:
+ if x.startswith('--'):
+ break
+ specs.append(x)
+ if not specs:
+ print('BLOCK: --spec needs at least one part spec')
+ return 2
+ colour = a[a.index('--colour') + 1] if '--colour' in a else None
+
+ os.makedirs(outdir, exist_ok=True)
+ images, key = [], {}
+ for spec in specs:
+ name = os.path.basename(spec).replace('.json', '')
+ dest = os.path.join(outdir, name)
+ os.makedirs(dest, exist_ok=True)
+ glb = os.path.join(dest, 'part.glb')
+ rc, out = run(['node', os.path.join('engine', 'cli.js'), spec, glb])
+ if rc != 0:
+ blocks = [l for l in out.splitlines() if l.startswith('BLOCK:')]
+ print(f' {name:<22} BUILD REFUSED')
+ for b in (blocks or out.strip().splitlines()[-2:]):
+ print(' ' + b[:140])
+ continue
+ # ONE tool reads geometry and produces measures, and it is outline.py.
+ # This used to be silmetrics.mjs (launch a browser, render, read pixels)
+ # followed by maskmetrics.py (letterbox and measure) — two commands, a
+ # browser dependency, and a SECOND definition of every number outline.py
+ # already computes. Two implementations of one measure have to be kept
+ # in agreement by hand, and they were not: outline.py's first
+ # thinnest_px48 took the global minimum of the distance transform and
+ # read ~0.25px on every creature, because it was re-derived instead of
+ # shared. Departments share their tools; synccheck.py lists any measure
+ # that still has more than one definition.
+ rc2, out2 = run(['python3', os.path.join('harness', 'outline.py'), glb, dest])
+ if rc2 != 0:
+ print(f' {name:<22} silhouette failed: '
+ + (out2.strip().splitlines() or [''])[-1][:120])
+ continue
+ # a part is read from the 3/4 view; it shows depth that side flattens
+ thumbs = [f'sil_{v}_thumb48.png' for v in ('hero', 'side', 'front', 'top')]
+ pick = next((t for t in thumbs if os.path.exists(os.path.join(dest, t))), None)
+ if not pick:
+ print(f' {name:<22} no thumb48 produced (maskmetrics did not run?)')
+ continue
+ p = os.path.join(dest, pick)
+ images.append(p)
+ key[p] = name
+ print(f' {name:<22} built and rendered')
+
+ if colour:
+ images.append(colour)
+ key[colour] = 'COLOUR READ (describe the colouring, not the shape)'
+
+ # one canary, as card 01 §4 requires — the batch is void without it
+ if os.path.isdir(CANARY):
+ cands = sorted(f for f in os.listdir(CANARY) if f.endswith('.png'))
+ if cands:
+ # deterministic pick, so a re-run of the same round is reproducible
+ seed = int(hashlib.sha256(''.join(specs).encode()).hexdigest()[:8], 16)
+ rnd = random.Random(seed)
+ c = os.path.join(CANARY, rnd.choice(cands))
+ images.append(c)
+ key[c] = f'CANARY ({os.path.basename(c)}) — see canary/answers.json'
+ rnd.shuffle(images)
+ else:
+ random.Random(0).shuffle(images)
+ else:
+ print('\nnote: harness/canary/ is missing — a batch without a canary is not '
+ 'a verified read (card 01 §4).')
+
+ if not images:
+ print('\nBLOCK: nothing rendered — no batch to read.')
+ return 1
+
+ print()
+ print('SHOW THESE TO ONE READER, in this order, labelled IMG-A, IMG-B, ...')
+ print('-' * 64)
+ for i, p in enumerate(images):
+ print(f' IMG-{chr(65 + i)} {p}')
+ print()
+ print('Ask, and nothing more:')
+ print(' For each image: what is this? Answer with the name of the thing or')
+ print(' body part you see. One line per image.')
+ print(' (Plus the binding questions from card 01 §4, per image.)')
+ print()
+ print('ANSWER KEY — keep this to yourself:')
+ for i, p in enumerate(images):
+ print(f' IMG-{chr(65 + i)} {key[p]}')
+ return 0
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/harness/presets/boss.json b/harness/presets/boss.json
deleted file mode 100644
index aeca32e..0000000
--- a/harness/presets/boss.json
+++ /dev/null
@@ -1,71 +0,0 @@
-{
- "name": "<creature name> (BOSS)",
- "_role": "Viewed close up + exaggerated; signature thresholds raised.",
- "claims": [
- {
- "type": "part_exists",
- "part": "<signature part>",
- "stage": "MID",
- "label": "signature part must exist"
- },
- {
- "type": "part_signature",
- "part": "<signature part>",
- "view": "side",
- "min_share": 0.16,
- "or_min_span": 0.12,
- "stage": "MID",
- "label": "signature presence"
- },
- {
- "type": "focal_contrast",
- "a": "<primary focal>",
- "b": "<secondary focal>",
- "min_ratio": 2,
- "stage": "MID",
- "label": "focal points must not be equal weight"
- },
- {
- "type": "share_hierarchy",
- "primary": [
- "<primary mass…>"
- ],
- "secondary": [
- "<secondary mass…>"
- ],
- "tertiary": [
- "<detail part…>"
- ],
- "stage": "MID",
- "label": "631 hierarchy"
- },
- {
- "type": "rig_skinned",
- "stage": "HIGH"
- },
- {
- "type": "anim_named",
- "names": [
- "idle",
- "move",
- "attack"
- ],
- "stage": "HIGH"
- },
- {
- "type": "saturation_area",
- "view": "tq",
- "min": 0.1,
- "max": 0.34,
- "stage": "HIGH",
- "label": "high-saturation area must sit in the 10%-34% band: amount of colour, not where it goes"
- },
- {
- "type": "tri_budget",
- "min": 4000,
- "max": 9000,
- "stage": "LOW",
- "label": "triangle budget band"
- }
- ]
-}
\ No newline at end of file
diff --git a/harness/presets/minion.json b/harness/presets/minion.json
deleted file mode 100644
index bddfff6..0000000
--- a/harness/presets/minion.json
+++ /dev/null
@@ -1,71 +0,0 @@
-{
- "name": "<creature name> (minion)",
- "_role": "Must read at distance; silhouette judged strictly; triangle count kept lean.",
- "claims": [
- {
- "type": "part_exists",
- "part": "<signature part>",
- "stage": "MID",
- "label": "signature part must exist"
- },
- {
- "type": "part_signature",
- "part": "<signature part>",
- "view": "side",
- "min_share": 0.12,
- "or_min_span": 0.12,
- "stage": "MID",
- "label": "signature presence"
- },
- {
- "type": "focal_contrast",
- "a": "<primary focal>",
- "b": "<secondary focal>",
- "min_ratio": 2,
- "stage": "MID",
- "label": "focal points must not be equal weight"
- },
- {
- "type": "share_hierarchy",
- "primary": [
- "<primary mass…>"
- ],
- "secondary": [
- "<secondary mass…>"
- ],
- "tertiary": [
- "<detail part…>"
- ],
- "stage": "MID",
- "label": "631 hierarchy"
- },
- {
- "type": "rig_skinned",
- "stage": "HIGH"
- },
- {
- "type": "anim_named",
- "names": [
- "idle",
- "move",
- "attack"
- ],
- "stage": "HIGH"
- },
- {
- "type": "saturation_area",
- "view": "tq",
- "min": 0.1,
- "max": 0.34,
- "stage": "HIGH",
- "label": "high-saturation area must sit in the 10%-34% band: amount of colour, not where it goes"
- },
- {
- "type": "tri_budget",
- "min": 800,
- "max": 3000,
- "stage": "LOW",
- "label": "triangle budget band"
- }
- ]
-}
\ No newline at end of file
diff --git a/harness/presets/npc.json b/harness/presets/npc.json
deleted file mode 100644
index cde9259..0000000
--- a/harness/presets/npc.json
+++ /dev/null
@@ -1,71 +0,0 @@
-{
- "name": "<creature name> (NPC)",
- "_role": "Viewed at mid distance; balanced.",
- "claims": [
- {
- "type": "part_exists",
- "part": "<signature part>",
- "stage": "MID",
- "label": "signature part must exist"
- },
- {
- "type": "part_signature",
- "part": "<signature part>",
- "view": "side",
- "min_share": 0.12,
- "or_min_span": 0.12,
- "stage": "MID",
- "label": "signature presence"
- },
- {
- "type": "focal_contrast",
- "a": "<primary focal>",
- "b": "<secondary focal>",
- "min_ratio": 2,
- "stage": "MID",
- "label": "focal points must not be equal weight"
- },
- {
- "type": "share_hierarchy",
- "primary": [
- "<primary mass…>"
- ],
- "secondary": [
- "<secondary mass…>"
- ],
- "tertiary": [
- "<detail part…>"
- ],
- "stage": "MID",
- "label": "631 hierarchy"
- },
- {
- "type": "rig_skinned",
- "stage": "HIGH"
- },
- {
- "type": "anim_named",
- "names": [
- "idle",
- "move",
- "attack"
- ],
- "stage": "HIGH"
- },
- {
- "type": "saturation_area",
- "view": "tq",
- "min": 0.1,
- "max": 0.34,
- "stage": "HIGH",
- "label": "high-saturation area must sit in the 10%-34% band: amount of colour, not where it goes"
- },
- {
- "type": "tri_budget",
- "min": 1500,
- "max": 5000,
- "stage": "LOW",
- "label": "triangle budget band"
- }
- ]
-}
\ No newline at end of file
diff --git a/harness/publish.mjs b/harness/publish.mjs
index ef88c42..1d6a9f0 100644
--- a/harness/publish.mjs
+++ b/harness/publish.mjs
@@ -1,5 +1,8 @@
// anyCreature — Gobkit community publisher. Author: Ariescar.
//
+// Run `node harness/glbcheck.mjs <glb>` first — the file must satisfy
+// docs/OUTPUT_CONTRACT.md before it is offered to anyone.
+//
// IRON RULE: run this ONLY after the user has explicitly said yes to sharing.
// Never on your own initiative, never in the background, never "to test".
//
@@ -25,6 +28,12 @@
// 3. prints ONE machine-readable JSON line:
// {"status":"published","share_url":"https://gobkit.com/s/…","title":…,"creator":…}
// {"status":"pending_review"} → uploaded; a reviewer lists it shortly
+// SUCCESS IS NOT A MAGIC WORD: any 2xx the server acknowledges, carrying a
+// share_url/slug and not naming a review state, counts as published — the
+// server renamed 'published' to 'visible' once already and a word-matching
+// client reported a successful upload as a failure.
+// published/pending also carry manage_token (+ the file it was saved to):
+// a ONE-TIME takedown key. Read it out to the user — it cannot be re-issued.
// {"status":"blocked","reason":…} → could not reach the server. NOT an error,
// NOT a key problem — offer the backup path.
// {"status":"error",…} → the server answered and refused; read it out.
@@ -72,6 +81,16 @@ const out = Buffer.concat([head, jh, js, rest]);
out.writeUInt32LE(out.length, 8);
fs.writeFileSync(glbPath, out);
+// ── 1b. contract gate: never hand a non-conforming file to a public wall ──
+const { checkGLB } = await import('./glbcheck.mjs');
+const conf = checkGLB(out);
+if (!conf.ok) {
+ console.log(JSON.stringify({ status: 'error',
+ error: 'the file breaks docs/OUTPUT_CONTRACT.md and was NOT uploaded: '
+ + conf.errors.map(e => `[${e.code}] ${e.msg}`).join(' | ') }));
+ process.exit(0);
+}
+
// ── 2. multipart POST ──
const form = new FormData();
form.append('model', new Blob([out], { type: 'model/gltf-binary' }), path.basename(glbPath));
@@ -93,9 +112,30 @@ const blocked = (reason) => {
process.exit(0);
};
+// Transient failures lose submissions silently: a flaky connection, a cold
+// start, a 502 from an edge node. Retry twice with a backoff before deciding
+// the network is against us — every retry that succeeds is a creature on the
+// wall instead of a file in a folder.
+async function post(attempt = 1) {
+ try {
+ const r = await fetch(endpoint, { method: 'POST', body: form, signal: AbortSignal.timeout(60000) });
+ if (r.status >= 500 && attempt < 3) {
+ await new Promise(z => setTimeout(z, attempt * 2000));
+ return post(attempt + 1);
+ }
+ return r;
+ } catch (e) {
+ if (attempt < 3) {
+ await new Promise(z => setTimeout(z, attempt * 2000));
+ return post(attempt + 1);
+ }
+ throw e;
+ }
+}
+
let res, body;
try {
- res = await fetch(endpoint, { method: 'POST', body: form, signal: AbortSignal.timeout(60000) });
+ res = await post();
} catch (e) {
blocked('cannot reach the server: ' + String((e && e.message) || e));
}
@@ -109,12 +149,174 @@ try {
}
// ── 3. one JSON line for the closing dialogue ──
-if ((res.status === 200 || res.status === 201) && body.ok && body.status === 'published') {
- const share = body.share_url?.startsWith('http') ? body.share_url : 'https://gobkit.com' + (body.share_url || '');
+// AND ITS NAME IS NOT OURS TO ASSUME. The comment forty lines below this one says
+// "the server's vocabulary is ITS to change ... never match a fixed word again",
+// because a status word changed once and this client called a successful upload
+// an error and dropped the takedown handle on the floor. Then this function
+// matched exactly one fixed word, `manage_token`, one section further down the
+// same file — so the day the server started returning a claim URL instead of a
+// code, the client would have silently thrown it away and told the person
+// nothing. Same mistake, same file. It reads a FAMILY of names now, and it does
+// not care whether the value is a link or a code: it looks at the value.
+// `claim_page_url` is first because it is the name the server settled on. It is
+// deliberately NOT `claim_url`: a sibling build of this file takes the FIRST hit
+// in this list, and `claim_url` sorts above `manage_token` there — so that name
+// would make those clients silently lose a takedown code that cannot be
+// re-issued. The server keeps the old field names free for that reason.
+const MANAGE_KEYS = ['claim_page_url',
+ 'manage_url', 'claim_url', 'manage_link', 'claim_link', 'edit_url',
+ 'manage_token', 'claim_token', 'manage', 'claim', 'token'];
+
+// 2026-09-03: the server now returns BOTH a claim link and a takedown code, and
+// they are NOT interchangeable — one puts the model under your account (needs a
+// sign-in, and the link dies the moment it is used), the other takes it down
+// (one-time, cannot be re-issued, no sign-in). This used to `return` on the
+// first hit in the family, and `claim_url` sorts before `manage_token`, so the
+// day the server started sending both, the takedown code was silently dropped
+// on the floor — the same class of bug the comment above is about, one level up.
+// It still looks at the VALUE, not the name: whatever comes back is classified
+// as a link or a code by its shape, and the first of EACH kind is kept.
+function manageHandles(b) {
+ const take = (v) => (typeof v === 'string' && v.trim()) ? v.trim() : null;
+ const found = [];
+ for (const k of MANAGE_KEYS) {
+ const v = take(b?.[k]);
+ if (v) found.push({ field: k, value: v });
+ }
+ // some servers nest it: { manage: { url } } / { claim: { token } }
+ for (const k of ['manage', 'claim', 'links']) {
+ const o = b?.[k];
+ if (o && typeof o === 'object') {
+ for (const kk of ['url', 'link', 'href', 'token', 'code']) {
+ const v = take(o[kk]);
+ if (v) found.push({ field: `${k}.${kk}`, value: v });
+ }
+ }
+ }
+ return {
+ link: found.find((h) => isLink(h.value)) || null,
+ code: found.find((h) => !isLink(h.value)) || null,
+ };
+}
+
+const isLink = (v) => /^https?:\/\//i.test(v) || v.startsWith('/');
+const absolute = (v) => v.startsWith('/') ? 'https://gobkit.com' + v : v;
+
+// The claim page that ALWAYS exists. The per-model claim link is generated from
+// a server-side secret; if that secret is not bound, or the route moves, the
+// link is a 404 and the person is left holding a code with nowhere to type it.
+// This page takes the same code and is not derived from anything, so it is the
+// floor under the promise "you get two links and both of them work".
+const CLAIM_FALLBACK = 'https://gobkit.com/community/claim';
+
+// Do not print a link without knowing it resolves. The whole reason the earlier
+// wording patch was held back was that it would have sent people to a 404; the
+// answer is not to guess whether the page is up, it is to ask it.
+// true → it answered
+// false → it answered, and said no. Use the fallback.
+// null → could not ask (offline, filtered). Say nothing either way: the
+// upload itself already succeeded, and a flaky probe must never
+// downgrade a link that is probably fine.
+async function linkLive(u) {
+ try {
+ const c = new AbortController();
+ const t = setTimeout(() => c.abort(), 8000);
+ const r = await fetch(u, { method: 'GET', redirect: 'follow', signal: c.signal });
+ clearTimeout(t);
+ return r.status >= 200 && r.status < 400;
+ } catch { return null; }
+}
+
+function writeBeside(name, text) {
+ const f = path.join(path.dirname(path.resolve(glbPath)), name);
+ try { fs.writeFileSync(f, text); return f; } catch { return null; }
+}
+
+// One file per handle. Writing both into one file was tempting, but a person
+// who was told "your takedown code is in manage_token.txt" must find it there.
+function saveManage(hs, slug, live) {
+ const id = `model: ${slug || '(slug unknown)'}\n`;
+ // A dead link on disk is worse than no file: the person keeps it, comes back
+ // in a week, and clicks a 404 with no idea what to do instead. When the probe
+ // said no, this file holds the way in that does work.
+ const linkFile = !hs.link ? null : live === false ? writeBeside('claim_link.txt',
+ `gobkit claim — KEEP THIS\n` +
+ `the per-model claim link for this upload did not resolve, so use the\n` +
+ `standing claim page instead: sign in with Google and paste the key from\n` +
+ `manage_token.txt. same result — the model gets listed under your name.\n\n` +
+ id + `page: ${CLAIM_FALLBACK}\n`) : writeBeside('claim_link.txt',
+ `gobkit claim link — KEEP THIS\n` +
+ `open it and sign in with Google to put this model under your account.\n` +
+ `it stops working the moment it is used, so it is harmless if it leaks.\n` +
+ `this is NOT the takedown key — that one is in manage_token.txt.\n` +
+ `if it ever stops resolving: ${CLAIM_FALLBACK} takes the same key.\n\n` +
+ id + `link: ${absolute(hs.link.value)}\n`);
+ const codeFile = hs.code ? writeBeside('manage_token.txt',
+ `gobkit manage token — KEEP THIS\n` +
+ `it is shown once, cannot be re-issued, and is the only way to take this\n` +
+ `model down later. no sign-in needed. do not post it anywhere.\n\n` +
+ id + `token: ${hs.code.value}\n`) : null;
+ return { linkFile, codeFile };
+}
+
+// One shape for every branch below, so a handle can never be reported by one
+// path and dropped by another.
+async function manageFields(b, slug) {
+ const hs = manageHandles(b);
+ const url = hs.link ? absolute(hs.link.value) : null;
+ const live = url ? await linkLive(url) : null;
+ const { linkFile, codeFile } = saveManage(hs, slug, live);
+ if (!hs.link && !hs.code) {
+ return { manage_kind: null, manage_url: null, manage_token: null,
+ manage_file: null, manage_token_file: null };
+ }
+ return {
+ // 'both' is the normal case now; 'url' / 'token' still happen if the server
+ // only sends one of them, and older servers send only a token.
+ manage_kind: hs.link && hs.code ? 'both' : (hs.link ? 'url' : 'token'),
+ manage_url: url,
+ manage_token: hs.code ? hs.code.value : null,
+ manage_field: [hs.link && hs.link.field, hs.code && hs.code.field].filter(Boolean).join('+'),
+ manage_file: linkFile || codeFile,
+ manage_token_file: codeFile || linkFile, // kept: older callers read this name
+ claim_link_file: linkFile,
+ // true / false / null — see linkLive(). false is the only value that means
+ // "do not show this link", and then claim_fallback_url is the way in.
+ claim_link_live: live,
+ claim_fallback_url: CLAIM_FALLBACK,
+ };
+}
+
+// The server's vocabulary is ITS to change: 'published' became 'visible' and
+// this client called a successful upload an error, told the user it failed, and
+// dropped the takedown token on the floor. Never match a fixed word again —
+// anything the server acknowledges (2xx + ok) with a link or a slug IS a
+// success; only an explicit review state or an outright refusal is not.
+// one probe, one shape, shared by every branch below
+const M = await manageFields(body, body.slug);
+const ACK = res.status >= 200 && res.status < 300 && body.ok !== false;
+const REVIEW = /pending|review|queue/i.test(String(body.status || ''));
+const located = body.share_url || body.slug || body.url;
+if (ACK && located && !REVIEW) {
+ // share_url is preferred; a bare slug is enough to build it
+ const share = body.share_url
+ ? (body.share_url.startsWith('http') ? body.share_url : 'https://gobkit.com' + body.share_url)
+ : (body.slug ? `https://gobkit.com/s/${body.slug}` : 'https://gobkit.com/community');
console.log(JSON.stringify({ status: 'published', share_url: share,
+ ...M,
title: body.title ?? title, creator: body.creator ?? creator, thumb: hasThumb }));
-} else if (body.ok && body.status === 'pending_review') {
- console.log(JSON.stringify({ status: 'pending_review', thumb: hasThumb }));
+} else if (ACK && REVIEW) {
+ // held for a human: still a successful upload, and it can still carry a token
+ console.log(JSON.stringify({ status: 'pending_review', server_status: body.status ?? null,
+ ...M, thumb: hasThumb }));
+} else if (ACK) {
+ // acknowledged but nothing to link to yet — treat as uploaded, not refused
+ console.log(JSON.stringify({ status: 'pending_review', server_status: body.status ?? null,
+ ...M, thumb: hasThumb }));
} else {
- console.log(JSON.stringify({ status: 'error', http: res.status, error: body.error || 'unexpected response' }));
+ // even a refusal can carry a token for an earlier upload — never swallow it
+ console.log(JSON.stringify({ status: 'error', http: res.status,
+ server_status: body.status ?? null,
+ error: body.error || `unexpected response: ${JSON.stringify(body).slice(0, 200)}`,
+ ...M }));
}
diff --git a/harness/pwlaunch.mjs b/harness/pwlaunch.mjs
new file mode 100644
index 0000000..82e55cc
--- /dev/null
+++ b/harness/pwlaunch.mjs
@@ -0,0 +1,62 @@
+// One browser launcher for every render tool. Author: Ariescar.
+// PW_CHROMIUM_PATH pins a binary; PW_NO_SANDBOX=1 only where the OS sandbox
+// genuinely cannot run. On failure, dies with ONE actionable line — the fix is
+// always the same and a stack trace never says it.
+//
+// AND IT LOOKS IN THE BROWSER CACHE BEFORE IT GIVES UP. Playwright asks for the
+// exact build number its own package was pinned to, so a machine holding
+// chromium-1194 while the installed playwright wants 1234 reports "Executable
+// doesn't exist" and the setup script goes off to download one. On a host whose
+// egress is filtered that download can never succeed: measured, one run spent
+// a run on four retries of a fetch that was never going to complete, on a
+// container that already had a working Chromium in /opt/pw-browsers. A build
+// number mismatch is not a missing browser. Look first, download second.
+import { chromium } from 'playwright';
+import fs from 'fs';
+import path from 'path';
+
+const BIN = ['chrome', 'chrome-headless-shell', 'headless_shell', 'chrome.exe'];
+
+export function findCachedChromium() {
+ const roots = [process.env.PLAYWRIGHT_BROWSERS_PATH,
+ path.join(process.env.HOME || '', '.cache', 'ms-playwright'),
+ path.join(process.env.LOCALAPPDATA || '', 'ms-playwright')].filter(Boolean);
+ const hits = [];
+ const walk = (dir, depth) => {
+ if (depth > 4) return;
+ let ents;
+ try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
+ for (const e of ents) {
+ const p = path.join(dir, e.name);
+ if (e.isDirectory()) walk(p, depth + 1);
+ else if (BIN.includes(e.name)) hits.push(p);
+ }
+ };
+ for (const r of roots) walk(r, 0);
+ // a full chromium beats a headless shell: the render tools take screenshots
+ hits.sort((a, b) => (a.includes('headless') ? 1 : 0) - (b.includes('headless') ? 1 : 0));
+ return hits[0] || null;
+}
+
+export async function launchBrowser() {
+ const args = ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader']
+ .concat(process.env.PW_NO_SANDBOX === '1' ? ['--no-sandbox'] : []);
+ const tries = [process.env.PW_CHROMIUM_PATH || undefined];
+ let first = null;
+ for (const executablePath of tries) {
+ try { return await chromium.launch({ executablePath, args }); }
+ catch (e) { first = e; }
+ }
+ // playwright could not find its own pinned build — look for ANY cached one
+ const found = findCachedChromium();
+ if (found) {
+ try {
+ const br = await chromium.launch({ executablePath: found, args });
+ console.error(`note: playwright's pinned build is absent; using the cached browser at ${found}`);
+ return br;
+ } catch (e) { first = e; }
+ }
+ console.error('render tool cannot start a browser: ' + String(first && first.message || first).split('\n')[0]);
+ console.error('Fix: run npx playwright install chromium (or set PW_CHROMIUM_PATH to a Chromium/Chrome binary)');
+ process.exit(3);
+}
diff --git a/harness/pwprobe.mjs b/harness/pwprobe.mjs
new file mode 100644
index 0000000..6448129
--- /dev/null
+++ b/harness/pwprobe.mjs
@@ -0,0 +1,13 @@
+// Launch-and-quit probe: proves the render tools can start a browser.
+// Prints ONE actionable line on failure instead of a stack trace.
+import { launchBrowser } from './pwlaunch.mjs';
+try {
+ const br = await launchBrowser();
+ await br.close();
+ console.log('render tools OK (browser launches)');
+} catch (e) {
+ console.error(String(e && e.message || e).split('\n')[0]);
+ console.error('render tools need a browser. Fix: run npx playwright install chromium');
+ console.error('(or point PW_CHROMIUM_PATH at an existing Chromium/Chrome binary)');
+ process.exit(3);
+}
diff --git a/harness/round.py b/harness/round.py
new file mode 100644
index 0000000..f1de1aa
--- /dev/null
+++ b/harness/round.py
@@ -0,0 +1,273 @@
+#!/usr/bin/env python3
+"""One round, ONE command — build, render, measure, and pre-check.
+
+ python3 harness/round.py <outdir> rN --spec a.json [b.json]
+ [--prev rM] [--gate ID|PUNCH] [--brief brief.md]
+
+WHY THIS EXISTS. A round used to be five or six separate commands: build, then
+silmetrics, then maskmetrics, then roundcheck --preflight, then (after the
+read) --record and --check. Each of those is a TURN, and a turn is the unit
+that actually costs money here — every one re-reads the whole conversation so
+far, which keeps growing, so the same command issued at round 20 costs several
+times what it cost at round 3.
+
+Split across separate commands, the measure phase is most of a run's round
+trips. The tools themselves are trivial — a compile is 1.4s and a view 0.5s —
+so the machine is never the bottleneck. The round trips are.
+
+This collapses the whole measure phase into one invocation and prints ONE
+consolidated report. Give it TWO specs and it treats them as card 01 §4b's two
+poles, building each into out/rN/vK/ and judging the round by the better of
+them. Give it one spec and it is an ordinary repair round.
+
+AT r1 IT ALSO CHECKS THE BRIEF, because r1 is the last moment anything there is
+cheap to change. Two things, both from harness/brief.py: every slot a later
+stage actually reads is filled in, and the two poles are really two designs
+rather than one design built twice. Three separate rounds that are all the same
+design cost three builds, three renders and three turns and produce zero
+comparisons.
+
+Python and stdlib only, so it behaves the same on Windows, macOS and Linux —
+the harness ships to other people and cannot assume a shell.
+"""
+import sys, os, json, subprocess, shutil, itertools
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import brief as briefmod
+
+H = os.path.dirname(os.path.abspath(__file__))
+R = os.path.dirname(H)
+
+
+def run(cmd):
+ p = subprocess.run(cmd, capture_output=True, text=True, cwd=R)
+ return p.returncode, (p.stdout or '') + (p.stderr or '')
+
+
+def die(msg, code=2):
+ print('BLOCK: ' + msg)
+ sys.exit(code)
+
+
+def find_brief(outdir):
+ for d in (outdir, os.path.dirname(os.path.abspath(outdir)), '.'):
+ p = os.path.join(d, 'brief.md')
+ if os.path.isfile(p):
+ return p
+ return None
+
+
+def main():
+ a = sys.argv[1:]
+ if len(a) < 3 or '--spec' not in a:
+ print(__doc__)
+ return 2
+ outdir, rn = a[0], a[1]
+ si = a.index('--spec')
+ # everything after --spec until the next flag
+ specs = []
+ for x in a[si + 1:]:
+ if x.startswith('--'):
+ break
+ specs.append(x)
+ if not specs:
+ die('--spec needs at least one spec file')
+ prev = None
+ if '--prev' in a:
+ prev = a[a.index('--prev') + 1]
+ gate = a[a.index('--gate') + 1] if '--gate' in a else 'ID'
+ brief_path = a[a.index('--brief') + 1] if '--brief' in a else find_brief(outdir)
+ first = rn.lower() in ('r1', 'r01')
+
+ # ── the brief, before anything is built on it ──────────────────────────
+ # r1 only. Presence, never content: any height, any identity, any palette
+ # passes — a BLANK does not, and only for the slots a later stage reads.
+ facts = {}
+ if first:
+ print('brief')
+ print('-' * 64)
+ if not brief_path:
+ die('no brief.md found (looked next to the spec, in ' + outdir +
+ ', and in the working directory). Card 01 §2 fills nine slots '
+ 'before anything is built; pass --brief <path> if it lives '
+ 'somewhere else. This is the cheapest place in the whole run to '
+ 'fix any of them.')
+ blocks, notes, facts = briefmod.check(brief_path, specs[0])
+ if briefmod.report(blocks, notes, facts, 'brief') != 0:
+ print()
+ die('fix the brief first — every one of those is a text edit now and '
+ 'a rebuilt creature later.')
+ print()
+
+ rdir = os.path.join(outdir, rn)
+ os.makedirs(rdir, exist_ok=True)
+ multi = len(specs) > 1
+ prev_dir = os.path.join(outdir, prev) if prev else None
+ if prev_dir and not os.path.isdir(prev_dir):
+ print(f'note: --prev {prev} does not exist yet; iou_vs_prev will be null '
+ f'and the tweak detector is blind for this round.')
+ prev_dir = None
+
+ rows = []
+ for i, spec in enumerate(specs):
+ tag = f'v{i + 1}' if multi else None
+ dest = os.path.join(rdir, tag) if tag else rdir
+ os.makedirs(dest, exist_ok=True)
+ glb = os.path.join(dest, 'creature.glb')
+
+ rc, out = run(['node', os.path.join('engine', 'cli.js'), spec, glb])
+ blocks = [l for l in out.splitlines() if l.startswith('BLOCK:')]
+ if rc != 0:
+ print(f'--- {tag or rn}: BUILD REFUSED ({spec})')
+ for b in blocks or out.strip().splitlines()[-3:]:
+ print(' ' + b)
+ rows.append({'tag': tag or rn, 'built': False})
+ continue
+ # the compiler's own narration is worth seeing once, not five times
+ shade = [l for l in out.splitlines() if 'shade class' in l or l.startswith('info: shade')]
+
+ # Silhouettes come from the GEOMETRY, not from a browser. Same camera,
+ # same masks (verified against the rendered ones at IoU 0.980-0.989 on
+ # all four views; the remainder is the renderer's antialiased edge), and
+ # no Chromium in the LOW loop at all.
+ cmd = ['python3', os.path.join('harness', 'outline.py'), glb, dest]
+ if prev_dir:
+ cmd += ['--prev', prev_dir]
+ rc2, out2 = run(cmd)
+ if rc2 != 0:
+ print(f'--- {tag or rn}: silhouette failed')
+ print(' ' + (out2.strip().splitlines() or [''])[-1][:160])
+ rows.append({'tag': tag or rn, 'built': True, 'rendered': False})
+ continue
+
+ m = {}
+ mp = os.path.join(dest, 'metrics.json')
+ if os.path.exists(mp):
+ try:
+ m = json.load(open(mp, encoding='utf-8'))
+ except Exception:
+ pass
+ thin = m.get('thinnest_px48')
+ if thin is None:
+ vals = [v.get('thinnest_px48') for v in m.values()
+ if isinstance(v, dict) and v.get('thinnest_px48') is not None]
+ thin = min(vals) if vals else None
+ rows.append({'tag': tag or rn, 'built': True, 'rendered': True,
+ 'spec': spec, 'iou': m.get('iou_vs_prev'), 'thin': thin,
+ 'shade': shade, 'metrics': m})
+
+ # ── one report ─────────────────────────────────────────────────────────
+ print()
+ print(f'round {rn} — {len(specs)} attempt(s)')
+ print('-' * 64)
+ for r in rows:
+ if not r.get('rendered'):
+ print(f" {r['tag']:<4} {'build refused' if not r.get('built') else 'render failed'}")
+ continue
+ iou = 'n/a' if r['iou'] is None else f"{r['iou']:.3f}"
+ thin = 'n/a' if r['thin'] is None else f"{r['thin']:.1f}px"
+ note = ''
+ if r['thin'] is not None and r['thin'] < 3.0:
+ note = ' <- thinnest feature is invisible at reading size'
+ elif r['iou'] is not None and r['iou'] > 0.85:
+ note = ' <- barely moved from the previous round'
+ print(f" {r['tag']:<4} iou {iou:<7} thinnest {thin:<8}{note}")
+ good = [r for r in rows if r.get('rendered')]
+ if not good:
+ die('no attempt in this round produced a silhouette — nothing to read.')
+
+ if rows and rows[0].get('shade'):
+ print()
+ for l in rows[0]['shade']:
+ print(' ' + l)
+
+ # ── are these really two poles, or one idea built twice? ───────────────
+ # Checked on the identity view, because that is the ONE image each pole is
+ # shown to the reader as. iou cannot answer this: it counts overlapping
+ # pixels, so a proportion change moves it a long way while the design stands
+ # still — the failing r1-r3 scored iou 0.609 and 0.703 and were the same
+ # creature three times.
+ if multi and len(good) > 1:
+ view = facts.get('identity_view') if first else None
+ pairs = [(x, y, briefmod.poles_apart(x['metrics'], y['metrics'], view)[0])
+ for x, y in itertools.combinations(good, 2)]
+ pairs = [p for p in pairs if p[2] is not None]
+ if pairs:
+ print()
+ worst = min(pairs, key=lambda p: p[2])
+ for x, y, d in sorted(pairs, key=lambda p: p[2]):
+ print(f' {x["tag"]} vs {y["tag"]}: mass-layout distance {d:.2f}'
+ + ('' if d >= briefmod.POLE_MIN else ' <- the same design twice'))
+ for r in good:
+ f = briefmod.fill_of(r['metrics'], view)
+ if f is not None and f >= briefmod.FILL_BLOB:
+ print(f' note {r["tag"]} fills {f:.2f} of its own box — that is a '
+ f'blob, not a pose; something has folded flat onto the body.')
+ if worst[2] < briefmod.POLE_MIN:
+ print()
+ die(f'{worst[0]["tag"]} and {worst[1]["tag"]} are {worst[2]:.2f} apart and '
+ f'{briefmod.POLE_MIN:.2f} is the floor. Do not spend a reader on them: '
+ f'shown two versions of one design, a reader tells you what it would '
+ f'have told you about either. Name the axis — coiled/released, '
+ f'reared/flattened, front-loaded/rear-loaded — and push BOTH ends of '
+ f'it. Moving the signature part is usually enough; folding it flat '
+ f'onto the body is not a pose, it is a blob.', 1)
+
+ print()
+ rc3, out3 = run(['python3', os.path.join('harness', 'roundcheck.py'),
+ outdir, '--preflight', rn, gate])
+ print(out3.rstrip())
+ if rc3 != 0:
+ print()
+ print(' -> do NOT spawn a reader. Change the shape and run this again.')
+ return 1
+ print()
+ def thumbs_of(d):
+ return sorted(os.path.join(d, f) for f in os.listdir(d)
+ if f.endswith('_thumb48.png'))
+ if multi:
+ # ONE image per pole: the identity view. Everything the other views were
+ # shown for is computed above, from the geometry. Card 01 §4b.
+ print(' -> show these to ONE reader, shuffled, with a canary')
+ print(' (identity view only — the other views are measured, not read):')
+ # The brief NAMES the view that carries the creature, and Gate 1 requires
+ # that view to be one of the ones that read — so it is the view each pole
+ # is shown as. Falling back to hero when the brief did not say was a bug:
+ # a creature whose identity view is "side" was being read on its hero.
+ want = facts.get('identity_view') or 'hero'
+ for r in good:
+ ts = thumbs_of(os.path.join(rdir, r['tag']))
+ pick = next((t for t in ts if want in os.path.basename(t)), None) \
+ or next((t for t in ts if 'hero' in t), None) or (ts[0] if ts else None)
+ if pick:
+ print(f' {pick} ({want} — the brief\'s identity view)')
+ print(' -> then copy the winner up: python3 harness/round.py '
+ f'{outdir} {rn} --promote vK')
+ else:
+ print(' -> show these to ONE reader, shuffled, with a canary:')
+ for t in thumbs_of(rdir):
+ print(f' {t}')
+ print(f' -> then: python3 harness/roundcheck.py {outdir} --record {rn} {gate} '
+ f'pass|fail "<noun>"')
+ return 0
+
+
+def promote(outdir, rn, tag):
+ """Make one variant THE output of its round, so the iou chain follows it."""
+ rdir = os.path.join(outdir, rn)
+ src = os.path.join(rdir, tag)
+ if not os.path.isdir(src):
+ die(f'{src} does not exist')
+ for f in os.listdir(src):
+ s, d = os.path.join(src, f), os.path.join(rdir, f)
+ if os.path.isfile(s):
+ shutil.copy2(s, d)
+ print(f'[round] promoted {tag} to {rn} — the next round\'s --prev is this shape.')
+ return 0
+
+
+if __name__ == '__main__':
+ if '--promote' in sys.argv:
+ i = sys.argv.index('--promote')
+ sys.exit(promote(sys.argv[1], sys.argv[2], sys.argv[i + 1]))
+ sys.exit(main())
diff --git a/harness/roundcheck.py b/harness/roundcheck.py
new file mode 100644
index 0000000..f1899ee
--- /dev/null
+++ b/harness/roundcheck.py
@@ -0,0 +1,376 @@
+#!/usr/bin/env python3
+"""Round gatekeeper — iron law 3, taken out of the session's own hands.
+
+usage:
+ python3 harness/roundcheck.py <outdir> --preflight rN ID|PUNCH BEFORE spawning the reader
+ python3 harness/roundcheck.py <outdir> --record rN ID|PUNCH pass|fail "<reader's noun>"
+ python3 harness/roundcheck.py <outdir> --check ID|PUNCH after recording
+
+Law 2 exists because a session cannot grade its own thumbnails. Law 3 —
+"same symptom failed twice = no third tweak" — has exactly the same problem and
+was left to the session to apply to itself, so it did not hold: one measured run
+spent rounds 6 through 15 nudging the same head and the same ears eight times
+before restarting the concept at r16, and eight of those rounds bought nothing.
+The rule was right; nobody was counting.
+
+This counts. It reads what the round actually produced rather than what the
+session says it did:
+
+ · the verdict, from out/rN/round.json (written by --record; no record means
+ the round did not happen and the next check refuses to pass it)
+ · whether the round was a TWEAK or a real restart, from iou_vs_prev in
+ out/rN/metrics.json — a nudged silhouette stays >0.85 similar to the last
+ one no matter what the session calls it. Run silmetrics with
+ `--prev out/r<N-1>` or this number is null and the guard is blind.
+ · whether the feature being argued about is even visible at reading size,
+ from thinnest_px48 — the blind read happens on a 48px thumbnail.
+
+Exit 1 with a BLOCK: line = the next round may not be another tweak.
+"""
+import sys, os, json, glob, re
+
+TWEAK_IOU = 0.85 # above this, the silhouette did not really change
+RESTART_IOU = 0.70 # a repair after an IDENTITY failure must clear this
+MIN_PX48 = 3.0 # thinner than this cannot be read at thumbnail size
+MAX_TWEAKS = 2 # iron law 3: two failures, then no third tweak
+MAX_FAILS_TOTAL = 5 # hard ceiling per gate, counted regardless of iou
+
+# Two different bars, for two different situations, and the gap between them is
+# the point.
+#
+# TWEAK_IOU is the nudge detector: above 0.85 the shape did not really move, and
+# law 3 refuses a third of those. RESTART_IOU is a FLOOR on a repair, and it only
+# applies to the identity gate after a reader has failed it. The reason they
+# differ: "a fox, not a dragon" is not a fine-tuning verdict. Nothing between
+# 0.70 and 0.85 — a moved ear, a longer tail — changes what a stranger calls the
+# animal, so a repair in that band is a round spent to be told the same noun
+# again.
+#
+# The number is enforceable now because `outline.py` computes iou from the
+# geometry rather than from a rasterised picture, so it is exact and free.
+
+# Why the hard ceiling exists on top of the nudge detector. The detector walks
+# backwards and STOPS at the first round whose silhouette really moved, on the
+# theory that a real change is a fresh start deserving a fresh count. A measured
+# run defeated that without trying: rounds 5–9 each moved one variable — claw
+# height, then tail angle, then leg thickness — and the sizes of those moves
+# alternated, so one of them always scored under the threshold and reset the
+# streak. Eleven rounds on one gate, and the counter never reached three.
+#
+# iou is a good detector of "did the shape move". It is a bad detector of "is
+# this a different idea", and only the second one is what law 3 is about. So the
+# streak logic stays for what it is good at, and a plain total — which nothing
+# can alternate its way around — carries the rest. The card budgets 2 repair
+# rounds; 5 leaves room for one honest concept restart and refuses the eleventh.
+
+
+def rounds(outdir):
+ out = []
+ for d in sorted(glob.glob(os.path.join(outdir, 'r*')),
+ key=lambda p: int(re.sub(r'\D', '', os.path.basename(p)) or 0)):
+ if not os.path.isdir(d):
+ continue
+ r = {'dir': d, 'n': int(re.sub(r'\D', '', os.path.basename(d)) or 0),
+ 'round': None, 'metrics': None}
+ for key, fn in (('round', 'round.json'), ('metrics', 'metrics.json')):
+ p = os.path.join(d, fn)
+ if os.path.exists(p):
+ try:
+ r[key] = json.load(open(p, encoding='utf-8'))
+ except Exception:
+ pass
+ out.append(r)
+ return out
+
+
+def iou_of(m):
+ """metrics.json is either the silmetrics shape (flat) or the maskmetrics
+ shape (keyed by image name). Only silmetrics computes iou_vs_prev."""
+ if not isinstance(m, dict):
+ return None
+ if 'iou_vs_prev' in m:
+ return m['iou_vs_prev']
+ for v in m.values():
+ if isinstance(v, dict) and 'iou_vs_prev' in v:
+ return v['iou_vs_prev']
+ return None
+
+
+def thinnest_of(m):
+ if not isinstance(m, dict):
+ return None
+ vals = []
+ if 'thinnest_px48' in m and m['thinnest_px48'] is not None:
+ vals.append(m['thinnest_px48'])
+ for v in m.values():
+ if isinstance(v, dict) and v.get('thinnest_px48') is not None:
+ vals.append(v['thinnest_px48'])
+ return min(vals) if vals else None
+
+
+def record(outdir, rn, gate, verdict, noun):
+ d = os.path.join(outdir, rn)
+ os.makedirs(d, exist_ok=True)
+ rec = {'round': rn, 'gate': gate, 'verdict': verdict, 'reader_noun': noun}
+ json.dump(rec, open(os.path.join(d, 'round.json'), 'w', encoding='utf-8'),
+ ensure_ascii=False, indent=1)
+ print(f'[roundcheck] recorded {rn}: {gate} {verdict} — reader said "{noun}"')
+
+
+def variant_metrics(rdir):
+ """metrics.json for each variant of a round: out/rN/v*/metrics.json."""
+ out = []
+ for d in sorted(glob.glob(os.path.join(rdir, 'v*'))):
+ p = os.path.join(d, 'metrics.json')
+ if os.path.isdir(d) and os.path.exists(p):
+ try:
+ out.append(json.load(open(p, encoding='utf-8')))
+ except Exception:
+ pass
+ return out
+
+
+def preflight(outdir, rn, gate):
+ """Is this round worth a reader AT ALL? Run BEFORE spawning one.
+
+ The order used to be: spend the reader, record what it said, then ask
+ whether another round was allowed. So the thing that stops waste sat AFTER
+ the thing that costs money, and a round that could never have read
+ differently still paid full price for being told so.
+
+ A reader is not free, and its price is almost entirely the cost of the
+ subagent EXISTING rather than the pictures inside it.
+
+ Two ways a read is knowably wasted before it happens, and both are facts
+ the machine already has:
+ · the silhouette is the one that was rejected last round. A reader that
+ said "Horse" to a shape is going to say "Horse" to the same shape.
+ · the thing being argued about is under 3px at reading size, twice
+ running. Nobody can see it, so nobody can report on it.
+ """
+ rs = rounds(outdir)
+ cur = next((r for r in rs if os.path.basename(r['dir']) == rn), None)
+ if cur is None:
+ print(f'[roundcheck] {rn} has no directory yet — nothing to pre-check.')
+ return 0
+
+ # the most recent recorded FAILURE on this gate, before this round
+ prev_fail = None
+ for r in rs:
+ if r is cur:
+ break
+ rec = r['round']
+ if rec and rec.get('gate') == gate and rec.get('verdict') == 'fail':
+ prev_fail = r
+
+ problems, notes_thin = [], []
+ # A repair round builds three variants (card 01 §4b), so "this round's
+ # silhouette" is not one file — it is whichever variant is least like the
+ # shape that was already rejected. Judge the round by its BEST attempt:
+ # blocking a round because two of its three tries were near-copies would
+ # punish exactly the behaviour this is meant to encourage.
+ ious = [iou_of(v) for v in variant_metrics(cur['dir'])]
+ ious = [i for i in ious if i is not None]
+ own = iou_of(cur['metrics'])
+ if own is not None:
+ ious.append(own)
+ iou = min(ious) if ious else None
+ nvar = len(variant_metrics(cur['dir']))
+ if nvar:
+ print(f'[roundcheck] {rn} has {nvar} variant(s); judging the round by its '
+ f'least-similar one (iou {iou}).')
+
+ bar = RESTART_IOU if gate.upper() == 'ID' else TWEAK_IOU
+ if prev_fail is not None and iou is not None and iou > bar:
+ pn = os.path.basename(prev_fail['dir'])
+ noun = prev_fail['round'].get('reader_noun', '?')
+ if gate.upper() == 'ID':
+ problems.append(
+ f'do not spend a reader on {rn}: its best attempt is still {iou} similar to '
+ f'{pn}, which a reader called "{noun}". An IDENTITY repair has to clear '
+ f'{RESTART_IOU} — a reader is naming the ANIMAL, and nothing in the '
+ f'{RESTART_IOU}-{TWEAK_IOU} band (a moved ear, a longer tail) changes which '
+ f'animal a stranger says. Move the big masses: proportion, stance, the '
+ f'signature part\'s size relative to the body.')
+ else:
+ problems.append(
+ f'do not spend a reader on {rn}: its silhouette is {iou} similar to {pn}, '
+ f'which a reader has ALREADY rejected ("{noun}"). The same shape gets the '
+ f'same answer, and a read costs tokens to be told so. Change the shape '
+ f'first, then read it.')
+
+ # same for legibility: the round is as legible as its most legible attempt
+ ts = [thinnest_of(v) for v in variant_metrics(cur['dir'])]
+ ts = [x for x in ts if x is not None]
+ own_t = thinnest_of(cur['metrics'])
+ if own_t is not None:
+ ts.append(own_t)
+ t = max(ts) if ts else None
+ prev_t = thinnest_of(prev_fail['metrics']) if prev_fail is not None else None
+ # thinnest_px48 NO LONGER BLOCKS. It was a gate; it is now a note, and the
+ # reason is a measurement, not a change of mind. Run across every creature
+ # this harness has ever shipped: 10 of 10 come in under the 3px bar on at
+ # least one view, including one that a blind reader named at rank 1, first
+ # guess, unprompted. A bar nothing has ever passed is not measuring quality,
+ # it is measuring the fact that a 48px thumbnail of a four-limbed animal has
+ # thin limbs. On one measured build it refused EIGHT readers, the session
+ # thickened a different feature each time, and the file that finally shipped
+ # still measures 0.8-1.8px. Eight round-trips, no change in the outcome —
+ # and worse, "thicken it" is the wrong instruction for a creature whose idea
+ # IS a thin thing: that build's signature was a rib CAGE, and thickening the
+ # bars until they passed closed the cage into a solid lump.
+ if t is not None and t < MIN_PX48:
+ notes_thin.append(
+ f'thinnest feature is {t} px at reading size. The reader may not resolve it — '
+ f'worth knowing, not worth a round. Every creature on the shelf ships under '
+ f'this number; do NOT thicken a feature whose thinness is the design.')
+
+ if iou is None and cur['n'] > 1:
+ print('[roundcheck] iou_vs_prev is null — run silmetrics with `--prev out/r<N-1>` '
+ 'or this pre-check is blind and every round pays for its reader.')
+
+ for n in notes_thin:
+ print(' note ' + n)
+ for p in problems:
+ print('BLOCK: ' + p)
+ if not problems:
+ print(f'[roundcheck] {rn} is worth reading — spawn the reader.')
+ return 1 if problems else 0
+
+
+def check(outdir, gate):
+ rs = rounds(outdir)
+ if not rs:
+ print(f'[roundcheck] no rounds under {outdir}/ yet — first build, nothing to enforce.')
+ return 0
+
+ latest = rs[-1]
+ problems, notes = [], []
+
+ # ── legibility, on the newest round — INFORMATION, never a gate ────────
+ # This used to advise once and block on the second consecutive reading. It
+ # was wrong, and the measurement that says so is simple: run the number over
+ # every creature this harness has ever shipped and 10 of 10 are under the
+ # bar on at least one view. Nothing has ever passed it. One shipped build
+ # was refused a reader EIGHT times over it, thickened a different feature
+ # each time, and still measures 0.8-1.8px in the delivered file — while its
+ # blind reader named the creature at rank 1, first guess, from a view whose
+ # thinnest feature was 1.8px.
+ #
+ # It also gives the wrong instruction when the design IS thin. That build's
+ # signature was a rib CAGE; "thicken it" closed the bars into a solid lump
+ # and the idea died to satisfy a number no creature has ever satisfied.
+ t = thinnest_of(latest['metrics'])
+ prev_t = thinnest_of(rs[-2]['metrics']) if len(rs) > 1 else None
+ if t is not None:
+ if t < MIN_PX48:
+ notes.append(f'thinnest feature is {t} px at reading size. The reader may not '
+ f'resolve it. Every creature on the shelf ships under this number, '
+ f'so it is information, not a verdict — and do NOT thicken a feature '
+ f'whose thinness is the design.')
+ else:
+ notes.append(f'thinnest feature {t} px at reading size — readable.')
+
+ # ── iron law 3, counted ────────────────────────────────────────────────
+ # walk backwards over rounds of THIS gate until a pass or a real restart
+ streak, blind = [], False
+ for r in reversed(rs):
+ rec = r['round']
+ if rec is None:
+ continue
+ if rec.get('gate') != gate:
+ continue
+ if rec.get('verdict') == 'pass':
+ break
+ iou = iou_of(r['metrics'])
+ if iou is None:
+ # round 1 has nothing to compare against — that is not a blind spot,
+ # it is the start. Only a later round with a null iou means --prev
+ # was forgotten.
+ if r['n'] > 1:
+ blind = True
+ elif iou <= TWEAK_IOU:
+ streak.append((r, iou)) # a real change — count it and stop
+ break
+ streak.append((r, iou))
+
+ # the plain total: every recorded failure on this gate since the last pass,
+ # with no opinion about whether the shape moved
+ total_fails, seen_pass = 0, False
+ for r in reversed(rs):
+ rec = r['round']
+ if rec is None or rec.get('gate') != gate:
+ continue
+ if rec.get('verdict') == 'pass':
+ seen_pass = True
+ break
+ total_fails += 1
+ if total_fails:
+ notes.append(f'{gate} round budget: {total_fails} failed round(s) so far'
+ f'{"" if seen_pass else " (none passed yet)"} — the card budgets 2 '
+ f'repairs, the hard ceiling is {MAX_FAILS_TOTAL}.')
+ if total_fails >= MAX_FAILS_TOTAL:
+ problems.append(
+ f'round ceiling: {gate} has now failed {total_fails} times. The card budgets TWO '
+ f'repair rounds and allows one concept restart after that; {MAX_FAILS_TOTAL} is the '
+ f'ceiling and you are at it. Whatever this is, it is not converging — and every '
+ f'further round costs more than the one before it, because the context it rides on '
+ f'keeps growing. Ship your best version of this gate and write one honest DEVLOG '
+ f'line about what did not land.')
+
+ fails = len(streak)
+ if fails:
+ shown = ', '.join(f"{os.path.basename(r['dir'])}"
+ f"{'' if i is None else f' (iou {i})'}" for r, i in reversed(streak))
+ notes.append(f'{gate} has failed {fails} time(s) in a row: {shown}')
+
+ if blind:
+ problems.append('iou_vs_prev is null — silmetrics was run without `--prev out/r<N-1>`, '
+ 'so the tweak detector is switched off and law 3 cannot be enforced. '
+ 'Re-run the measure step with --prev.')
+
+ if fails >= MAX_TWEAKS and not blind:
+ nudges = [i for _, i in streak if i is not None and i > TWEAK_IOU]
+ if len(nudges) >= MAX_TWEAKS:
+ problems.append(
+ f'iron law 3: {gate} has failed {fails} times and every one of those rounds left the '
+ f'silhouette more than {TWEAK_IOU} similar to the round before it (iou '
+ f'{", ".join(str(n) for n in reversed(nudges))}) — that is the same shape nudged, not a '
+ f'different answer tried. A third tweak is not allowed. Restart this view or element '
+ f'from a DIFFERENT concept; if the restart also fails, ship your best version and write '
+ f'one honest DEVLOG line.')
+
+ for n in notes:
+ print(f'[roundcheck] {n}')
+ for p in problems:
+ print(f'BLOCK: {p}')
+ if not problems:
+ print(f'[roundcheck] OK — another repair round on {gate} is allowed.')
+ return 1 if problems else 0
+
+
+def main():
+ a = sys.argv[1:]
+ if len(a) < 2:
+ print(__doc__)
+ return 2
+ outdir = a[0]
+ if a[1] == '--record':
+ if len(a) < 6:
+ print('usage: roundcheck.py <outdir> --record rN ID|PUNCH pass|fail "<noun>"')
+ return 2
+ record(outdir, a[2], a[3], a[4], a[5])
+ return 0
+ if a[1] == '--preflight':
+ if len(a) < 3:
+ print('usage: roundcheck.py <outdir> --preflight rN ID|PUNCH')
+ return 2
+ return preflight(outdir, a[2], a[3] if len(a) > 3 else 'ID')
+ if a[1] == '--check':
+ return check(outdir, a[2] if len(a) > 2 else 'ID')
+ print(__doc__)
+ return 2
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/harness/ship.py b/harness/ship.py
new file mode 100644
index 0000000..7777959
--- /dev/null
+++ b/harness/ship.py
@@ -0,0 +1,155 @@
+#!/usr/bin/env python3
+"""Ship — the whole closing in ONE command: package, then (only if asked) publish.
+
+ python3 harness/ship.py out/creature.glb --name "Ash Wolf" --author "Ariescar"
+ python3 harness/ship.py out/creature.glb --name "Ash Wolf" --author "Ariescar" --publish
+
+Without --publish it packages and stops. With --publish it packages and uploads,
+and prints the share link and the one-time takedown token. --publish must only
+ever be passed after the person has said yes, in this session (card 04).
+
+Why this exists: the closing used to be two commands with the same arguments
+typed twice, so the signature drifted between the file and the listing, and the
+upload got skipped when the second command was forgotten. One command, one set
+of arguments, one report.
+
+The signature is remembered in ~/.anyCreature.json after the first time — pass
+--author once, never again; --author on a later run updates it.
+"""
+import sys, os, json, subprocess, re
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+STORE = os.path.join(os.path.expanduser('~'), '.anyCreature.json')
+
+
+def remembered_author():
+ try:
+ return (json.load(open(STORE)).get('author') or '').strip() or None
+ except Exception:
+ return None
+
+
+def remember_author(a):
+ try:
+ d = {}
+ if os.path.exists(STORE):
+ d = json.load(open(STORE))
+ d['author'] = a
+ json.dump(d, open(STORE, 'w'))
+ except Exception:
+ pass
+
+
+def main():
+ args = sys.argv[1:]
+
+ def opt(flag, default=None):
+ if flag in args:
+ i = args.index(flag); v = args[i + 1]; del args[i:i + 2]; return v
+ return default
+
+ publish = '--publish' in args
+ if publish:
+ args.remove('--publish')
+ # --upload-only: the package already exists (they said no earlier, or the
+ # upload failed). Publish it as-is; never rebuild, never re-stamp.
+ upload_only = '--upload-only' in args
+ if upload_only:
+ args.remove('--upload-only'); publish = True
+ name = opt('--name')
+ author = opt('--author')
+ gate = opt('--gate')
+ outdir = opt('--out', 'delivery')
+ if not args:
+ sys.exit(__doc__)
+ src = args[0]
+ if not os.path.isfile(src):
+ sys.exit(f'[ship] no such model: {src}')
+
+ if author:
+ remember_author(author)
+ else:
+ author = remembered_author()
+
+ slug = re.sub(r'[^A-Za-z0-9_.-]', '_', (name or os.path.basename(src).rsplit('.', 1)[0])).strip('_') or 'creature'
+
+ if upload_only:
+ glb = src if src.endswith('.glb') else os.path.join(outdir, f'{slug}.glb')
+ outdir = os.path.dirname(os.path.abspath(glb)) or outdir
+ hero = os.path.join(outdir, 'hero.png')
+ print(f'[ship] uploading the existing package in {outdir}/ (nothing rebuilt)')
+ return do_publish(glb, hero, name, author, outdir)
+
+ cmd = ['python3', os.path.join(HERE, 'deliver.py'), src, outdir, slug]
+ if name: cmd += ['--title', name]
+ if author: cmd += ['--author', author]
+ if gate: cmd += ['--gate', gate]
+ if subprocess.run(cmd).returncode != 0:
+ sys.exit('[ship] delivery failed — nothing was published')
+
+ glb = os.path.join(outdir, f'{slug}.glb')
+ hero = os.path.join(outdir, 'hero.png')
+ print(f'[ship] packaged → {outdir}/ ({slug}.glb · {slug}_viewer.html · hero · upload/)')
+
+ if not publish:
+ print('[ship] not published (no --publish). The files are the deliverable; '
+ 'pass --publish only after the person says yes.')
+ print(f'[ship] to upload later, one command: python3 harness/ship.py {glb} --upload-only')
+ return
+
+ return do_publish(glb, hero, name, author, outdir)
+
+
+def do_publish(glb, hero, name, author, outdir):
+ HERE_ = HERE
+ pcmd = ['node', os.path.join(HERE_, 'publish.mjs'), glb]
+ pcmd += [hero] if os.path.exists(hero) else []
+ if name: pcmd += ['--title', name]
+ if author: pcmd += ['--creator', author]
+ res = subprocess.run(pcmd, capture_output=True, text=True)
+ line = (res.stdout or '').strip().splitlines()[-1] if res.stdout.strip() else '{}'
+ try:
+ r = json.loads(line)
+ except Exception:
+ sys.exit(f'[ship] publisher said something unreadable:\n{res.stdout}{res.stderr}')
+
+ st = r.get('status')
+ # Same lesson as publish.mjs: never let an unrecognised word turn a
+ # successful upload into "the server refused". A link is proof of success.
+ if st == 'published' or (r.get('share_url') and st not in ('blocked', 'error')):
+ print(f'[ship] PUBLISHED → {r["share_url"]}')
+ elif st == 'pending_review':
+ print('[ship] UPLOADED — the server is verifying it; it will appear shortly.')
+ elif st == 'blocked':
+ print('[ship] could not reach Gobkit. The upload pack is ready in '
+ f'{outdir}/upload/ — drag creature.glb into https://gobkit.com/community/upload '
+ '(no account, no key needed).')
+ else:
+ print(f'[ship] the server refused: {r.get("error", line)}')
+
+ # 認領那條連結,publish.mjs 上傳完會實際去敲一次:
+ # claim_link_live is True → 敲得到,直接給連結
+ # claim_link_live is None → 敲不到(離線/被擋),不因為探測失敗就降級
+ # claim_link_live is False → 它真的回 404。這時候給那頁「一定在」的認領頁,
+ # 下面那組碼貼進去一樣認得回來 —— 絕不叫人去點 404。
+ fallback = r.get('claim_fallback_url') or 'https://gobkit.com/community/claim'
+ if r.get('manage_url') and r.get('claim_link_live') is not False:
+ where = r.get('claim_link_file') or r.get('manage_file') or outdir
+ print(f'[ship] claim link (saved to {where}): {r["manage_url"]}')
+ print('[ship] -> open it, sign in with Google, and the model is yours;'
+ ' then you can enter it in the Arena')
+ elif r.get('manage_token'):
+ print(f'[ship] claim page: {fallback}')
+ print('[ship] -> sign in with Google there and paste the code below —'
+ ' that is how this model gets listed under your name')
+ if r.get('manage_token'):
+ where = r.get('manage_token_file') or outdir
+ print(f'[ship] takedown code (shown ONCE, saved to {where}): {r["manage_token"]}')
+ print('[ship] -> the only way to take the model down later, and it cannot'
+ f' be re-issued. it is also the key you paste at {fallback}')
+ # one machine-readable line last, so the calling agent can quote it verbatim
+ print(json.dumps(r, ensure_ascii=False))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/harness/silmetrics.mjs b/harness/silmetrics.mjs
index 4998ea9..fd9ab32 100644
--- a/harness/silmetrics.mjs
+++ b/harness/silmetrics.mjs
@@ -28,7 +28,7 @@
//
// These are not pass/fail thresholds. The design card DECLARES a position per
// axis (tension targets); this tool verifies the declared position was reached.
-import { chromium } from 'playwright';
+import { launchBrowser } from './pwlaunch.mjs';
import fs from 'fs'; import path from 'path'; import http from 'http';
import { fileURLToPath } from 'url';
@@ -79,10 +79,9 @@ const srv = http.createServer((q, res) => {
// whenever two runs overlapped.
await new Promise(r => srv.listen(0, '127.0.0.1', r));
const port = srv.address().port;
-// Let Playwright locate its own browser; PW_CHROMIUM_PATH pins it if needed.
-const br = await chromium.launch({ executablePath: process.env.PW_CHROMIUM_PATH || undefined,
- args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader']
- .concat(process.env.PW_NO_SANDBOX === '1' ? ['--no-sandbox'] : []) });
+// Shared launcher: PW_CHROMIUM_PATH pins a binary; a missing browser dies with
+// ONE actionable line ("run npx playwright install chromium"), never a stack.
+const br = await launchBrowser();
const pg = await br.newPage({ viewport: { width: 660, height: 660 } });
await pg.goto(`http://127.0.0.1:${port}/`);
await pg.evaluate(() => window.load('/model.glb'));
diff --git a/harness/synccheck.py b/harness/synccheck.py
new file mode 100644
index 0000000..3db8f81
--- /dev/null
+++ b/harness/synccheck.py
@@ -0,0 +1,371 @@
+#!/usr/bin/env python3
+"""Sync check — proves the tree about to ship is INTERNALLY CONSISTENT.
+
+Born from a real leak: before the first public push, two finished features
+(part_seat, the browser install) existed in one working copy but not in the
+one that got pushed. Three copies, no gatekeeper. This script IS the
+gatekeeper: run it before every push (CI runs it too).
+
+ python3 harness/synccheck.py # exit 0 = ship, exit 1 = stop
+
+What it verifies:
+ 1. versions agree VERSION == CHANGELOG's top entry (the engine reads
+ VERSION at build time, so the GLB stamp follows)
+ 2. promised features every feature the CHANGELOG promises is present in
+ the code that ships (the 1.2.0 leak class)
+ 3. required files everything the cards and scripts point at exists
+ 4. leak scan strings that must never appear in a public tree
+ 5. no dangling docs a shipped file may not point at a doc that stayed home
+ 6. no forward refs nothing ships describing a version that is not out yet
+"""
+import os, re, sys
+
+ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
+bad = []
+
+def read(p):
+ try:
+ return open(os.path.join(ROOT, p), encoding='utf-8').read()
+ except OSError:
+ return None
+
+# ── 1. versions agree ────────────────────────────────────────────────────────
+version = (read('VERSION') or '').strip()
+chlog = read('CHANGELOG.md') or ''
+m = re.search(r'^## (\d+\.\d+\.\d+)', chlog, re.M)
+top = m.group(1) if m else '?'
+if not version:
+ bad.append('VERSION file missing or empty')
+elif top != version:
+ bad.append(f'version drift: VERSION says {version}, CHANGELOG top entry says {top}')
+
+# the version is also written into prose and into a README badge; those drift
+# silently because nothing reads them back. 1.3.1 shipped with three 1.3.0
+# strings still in place, which is how this check got written.
+if version:
+ for p, pat in (('MANUAL.md', r'anyCreature (\d+\.\d+\.\d+)'),
+ ('MANUAL.md', r'^VERSION\s+(\d+\.\d+\.\d+)'),
+ ('README.md', r'badge/version-(\d+\.\d+\.\d+)')):
+ for found in re.findall(pat, read(p) or '', re.M):
+ if found != version:
+ bad.append(f'version drift: {p} still says {found}, VERSION says {version}')
+
+# ── 2. promised features exist in the shipping code ──────────────────────────
+# One line per promise. ADD A LINE WHEN YOU ADD A FEATURE — this list is the
+# contract between the release notes and the code.
+FEATURES = [
+ ('engine/core/checks.js', 'part_seat', 'declared joins / exposed-root check'),
+ ('engine/core/checks.js', 'attack_reach', 'attack must lunge'),
+ ('engine/core/checks.js', 'gait_direction', 'a planted foot must sweep backward'),
+ ('harness/fit.py', 'FIXABLE', 'the arithmetic blocks are applied, not hand-fixed'),
+ ('cards/01_LOW.md', 'harness/fit.py', 'the card runs the fitter before the first round'),
+ ('engine/core/checks.js', 'root_drive', 'a lunge is driven on the skeleton root'),
+ ('harness/pwlaunch.mjs', 'findCachedChromium', 'the cached browser is found before any download'),
+ ('engine/core/checks.js', 'touch:', 'declared adjacency'),
+ ('engine/core/checks.js', 'part_overlap', 'part interpenetration measure'),
+ ('engine/core/checks.js', 'faceted_body', 'faceted volumes blocked'),
+ ('engine/core/checks.js', 'soft_mass', 'the rounded-sausage volume is blocked'),
+ ('cards/SYNTAX.md', '"soft": true', 'the soft_mass opt-out is documented'),
+ ('engine/core/compile.js', '_seatIdx', 'parts carry their base ring'),
+ ('engine/core/compile.js', 'applyShading', 'whole-body shading pass (1.2.0 fallback)'),
+ ('engine/core/shade.js', 'shadeStack', 'L1-L8 vertex-colour stack'),
+ ('engine/core/shade.js', 'inGamut', 'L4 chroma walks back to the sRGB edge'),
+ ('engine/core/shade.js', 'classOf', 'flesh / hardware / feature classification'),
+ ('engine/core/glb.js', 'boneField', 'L8 normals softened toward the bone field'),
+ ('engine/core/compile.js', 'chain: m.chain', 'mirrored volumes keep their chain name'),
+ ('engine/core/relative.js', 'joints_R', 'right-side pose overrides'),
+ ('engine/core/ao.js', 'bakeAO', 'vertex AO bake'),
+ ('engine/core/normals.js', 'smoothSplit', 'smoothing-angle normals'),
+ ('harness/pwlaunch.mjs', 'launchBrowser', 'shared browser launcher'),
+ ('setup.sh', 'playwright install', 'browser installed at setup'),
+ ('setup.sh', 'pwprobe', 'browser probed at setup'),
+ ('cards/02_MID.md', 'join', 'join doctrine in the MID card'),
+ ('cards/SYNTAX.md', '"join"', 'join in the syntax page'),
+ ('engine/core/compile.js', 'buildHand', 'hand part type (palm/fingers/thumb)'),
+ ('engine/core/compile.js', 'p.toes', 'paw toes'),
+ ('engine/core/checks.js', 'size: spec declares height', 'declared-height gate'),
+ ('README.md', 'Read MANUAL.md in this folder and follow it exactly', 'copy-paste agent prompt'),
+ ('cards/03_HIGH.md', 'Gait for many legs', 'multi-leg gait doctrine'),
+ ('cards/02_MID.md', '"type":"hand"', 'hands doctrine in MID card'),
+ ('cards/01_LOW.md', 'ASSUME EVERY READER IS LAZY', 'reader verification protocol'),
+ ('cards/01_LOW.md', 'canary', 'canary decoys in blind reads'),
+ ('cards/00_START.md', 'never trust a reader', 'reader distrust doctrine'),
+ ('engine/cli.js', 'source_spec', 'embedded birth certificate'),
+ ('harness/graft.py', 'source_spec', 'graft tool reads embedded specs'),
+ ('cards/SYNTAX.md', 'embed_spec', 'embed opt-out documented'),
+ ('harness/glbcheck.mjs', 'checkGLB', 'output conformance checker'),
+ ('cards/04_SHIP.md', 'Conformance is automatic', 'card states conformance is enforced, not manual'),
+ ('cards/01_LOW.md', 'harness/claims.json', 'single claims sheet, no role tiers'),
+ ('cards/01_LOW.md', 'expand the order yourself, never ask', 'thin orders are expanded, not queried'),
+ ('cards/01_LOW.md', 'Discard your first three ideas', 'anti-trope rule'),
+ ('cards/01_LOW.md', 'ONE question — REQUIRED', 'the single question is mandatory'),
+ ('cards/00_START.md', 'Never ask about:', 'forbidden question list'),
+ ('engine/cli.js', 'example_copy', 'recoloured-example builds are refused'),
+ ('cards/01_LOW.md', 'The verdict is SCORED', 'identity is scored by rank and view count'),
+ ('harness/identity.py', 'def verdict', 'the identity score is counted, not argued'),
+ ('harness/publish.mjs', 'manage_token', 'one-time takedown token surfaced'),
+ ('harness/ship.py', '--publish', 'one-command closing (package [+ publish])'),
+ ('cards/04_SHIP.md', 'ship.py', 'card uses the one-command closing'),
+ ('docs/OUTPUT_CONTRACT.md', 'exactly two', 'output contract documented'),
+ ('engine/cli.js', 'BLOCK: contract', 'every build is contract-checked'),
+ ('harness/deliver.py', 'OUTPUT_CONTRACT', 'delivery re-checks the stamped file'),
+ ('harness/deliver.py', 'was not built by this engine', 'delivery refuses foreign GLBs'),
+ ('MANUAL.md', 'STOP — read this before you write a single line of code', 'anti-bypass opener'),
+ ('harness/publish.mjs', 'checkGLB', 'publish refuses non-conforming files'),
+ ('engine/core/glb.js', 'the hue lives in baseColorFactor', 'hue split into the material'),
+ ('harness/glbcheck.mjs', 'flat_white_base', 'white-base portability warning'),
+ ('harness/glbcheck.mjs', 'high_metal', 'metal-without-environment warning'),
+ ('cards/03_HIGH.md', 'Keep `metal` low', 'material limits stated in the card'),
+ ('harness/glbcheck.mjs', 'anisotropy_without_direction', 'anisotropy without UV/TANGENT is blocked'),
+ ('cards/03_HIGH.md', 'No anisotropy', 'anisotropy limit stated in the card'),
+ ('harness/publish.mjs', 'SUCCESS IS NOT A MAGIC WORD', 'upload success is not matched by a literal word'),
+ ('harness/judge.mjs', 'ALBEDO = baseColorFactor', 'the colour ruler reads the material, not COLOR_0 alone'),
+ ('harness/calibrate.py', 'saturation_area', 'the colour ruler is calibrated both ways'),
+ ('harness/roundcheck.py', 'def preflight', 'the reader is gated BEFORE it is spent'),
+ ('cards/01_LOW.md', '--preflight', 'card runs the pre-check before the read'),
+ ('cards/01_LOW.md', 'TWO OPPOSITE POLES', 'a round builds two opposite poles, not three near-copies'),
+ ('cards/01_LOW.md', 'chains: LClaw, RClaw', 'the brief names the chains it means'),
+ ('harness/brief.py', 'POLE_MIN', 'the two-pole floor is a named constant, not a magic number'),
+ ('cards/01_LOW.md', 'Two speeds of repair', 'trap repair depends on which trap tripped'),
+ ('harness/roundcheck.py', 'def variant_metrics', 'preflight judges a round by its best variant'),
+ ('cards/02_MID.md', 'The isolated part read is deleted', 'the isolated part read is gone; MID reads the whole body once'),
+ ('harness/round.py', 'def promote', 'a whole round is one command'),
+ ('harness/partreads.py', 'ANSWER KEY', 'part reads are built and batched in one command'),
+ ('cards/01_LOW.md', 'A whole round is ONE command', 'card uses the one-command round'),
+ ('cards/00_START.md', 'The thing that actually costs money: TURNS', 'turn cost stated up front'),
+ ('cards/01_LOW.md', 'Build THREE different pushes', 'Gate 2 judges three pushes in one round'),
+ ('cards/02_MID.md', 'MID SPENDS NO READER', 'MID spends no reader at all'),
+ ('engine/core/checks.js', 'contrast_adjacent', 'part-vs-host colour distance is computed, not read'),
+ ('cards/02_MID.md', 'still BLOCKS', 'part presence is a machine check on the spec, not a read'),
+ ('engine/core/checks.js', 'value_order', 'the value plan is sorted by the machine, not eyeballed'),
+ ('harness/gates.json', '"kind": "legality"', 'every check is tagged legality vs style'),
+ ('harness/gates.json', '"by": "B"', 'every check names which source judges it'),
+ ('cards/01_LOW.md', 'this gate is FINISHED', 'Gate 2 stops when the incumbent wins'),
+ ('cards/02_MID.md', 'Author the WHOLE part set in one pass', 'parts are authored in one pass, not incrementally'),
+ ('cards/04_SHIP.md', 'ONE line. Not a narrative', 'the closing DEVLOG is one line'),
+ ('engine/cli.js', 'ENGINE_CHECKS', 'the engine writes its own gate stamp'),
+ ('cards/04_SHIP.md', 'checks.json', 'card 04 copies the stamp instead of retyping it'),
+ ('cards/03_HIGH.md', 'Write all three, then build ONCE', 'all three clips authored in one pass'),
+ ('harness/outline.py', 'def render_mask', 'silhouettes computed from geometry, no browser'),
+ ('harness/round.py', 'outline.py', 'the round loop uses the geometry silhouette'),
+ ('cards/00_START.md', 'LOW no longer needs a browser', 'the LOW loop is browser-free'),
+ ('harness/roundcheck.py', 'RESTART_IOU', 'an identity repair has a minimum change'),
+ ('cards/01_LOW.md', 'IDENTITY VIEW ONLY', 'variants are read on one image each'),
+ ('harness/judge.mjs', "includes('--json')", 'the judge prints a summary, not the blob'),
+ ('harness/outline.py', 'def material_shares', 'part shares come from a z-buffer, not a GPU'),
+ ('harness/outline.py', 'def exaggeration', 'boldness measures computed, not eyeballed'),
+ ('engine/core/checks.js', 'Move joint', 'blocks say how far to move, not just which way'),
+ ('engine/core/checks.js', 'multiply every joint coordinate', 'size states the scale factor'),
+]
+for path, needle, label in FEATURES:
+ s = read(path)
+ if s is None:
+ bad.append(f'promised file missing: {path} ({label})')
+ elif needle not in s:
+ bad.append(f'promised feature missing: "{needle}" not in {path} ({label})')
+
+# ── 3. required files ────────────────────────────────────────────────────────
+REQUIRED = [
+ 'MANUAL.md', 'README.md', 'CHANGELOG.md', 'LICENSE', 'SECURITY.md',
+ 'setup.sh', 'setup.ps1',
+ 'cards/00_START.md', 'cards/01_LOW.md', 'cards/02_MID.md',
+ 'cards/03_HIGH.md', 'cards/04_SHIP.md', 'cards/SYNTAX.md',
+ 'engine/cli.js',
+ 'harness/silmetrics.mjs', 'harness/maskmetrics.py', 'harness/judge.mjs',
+ 'harness/deliver.py', 'harness/hero.mjs', 'harness/publish.mjs',
+ 'harness/pwlaunch.mjs', 'harness/pwprobe.mjs', 'harness/calibrate.py',
+ 'harness/gobkit.json', 'harness/assets/showroom.html',
+ 'harness/assets/three-bundle.js',
+ 'harness/claims.json', 'harness/roundcheck.py',
+ 'harness/gates.json', 'harness/gates.py',
+ 'harness/round.py', 'harness/partreads.py', 'harness/outline.py', 'harness/brief.py',
+ 'harness/fit.py',
+ 'harness/identity.py',
+ 'engine/core/shade.js',
+ 'calibration/wolf_green.json', 'calibration/wolf_red.json',
+ 'calibration/red_5050.json',
+ 'example/wolf.json', 'example/wolf.glb',
+ 'harness/graft.py', 'harness/glbcheck.mjs', 'engine/core/contract.js',
+ 'harness/ship.py',
+ 'tools/sync-contract.mjs',
+ 'docs/OUTPUT_CONTRACT.md', 'docs/HANDOVER_sanitize.md',
+ 'harness/canary/answers.json', 'harness/canary/ball.png',
+ 'harness/canary/spike.png', 'harness/canary/wolf_side.png',
+]
+for p in REQUIRED:
+ if not os.path.isfile(os.path.join(ROOT, p)):
+ bad.append(f'required file missing: {p}')
+
+# cards may reference harness/engine paths — every referenced path must exist
+for card in ('cards/00_START.md', 'cards/01_LOW.md', 'cards/02_MID.md',
+ 'cards/03_HIGH.md', 'cards/04_SHIP.md', 'MANUAL.md'):
+ s = read(card) or ''
+ for ref in set(re.findall(r'(?:harness|engine|cards|calibration|example)/[A-Za-z0-9_./-]+\.(?:json|mjs|py|js|md|sh|ps1)', s)):
+ if not os.path.isfile(os.path.join(ROOT, ref)):
+ bad.append(f'{card} points at a file that does not ship: {ref}')
+
+# ── 3b. the contract check exists in both module systems, byte-identically ──
+# engine/core/contract.js is generated from harness/glbcheck.mjs; if someone
+# edits one and not the other, builds and submissions would be judged by two
+# different rulers. Regenerate with: node tools/sync-contract.mjs
+esm = read('harness/glbcheck.mjs') or ''
+cjs = read('engine/core/contract.js') or ''
+if esm and cjs:
+ core = esm[esm.find("'use strict';"):esm.find('// \u2500\u2500 CLI \u2500\u2500')]
+ core = core.replace('export function checkGLB', 'function checkGLB')
+ if core.strip() and core.strip() not in cjs:
+ bad.append('contract drift: engine/core/contract.js is out of date — '
+ 'run `node tools/sync-contract.mjs`')
+
+# ── 3b. one measure, one definition ──────────────────────────────────────────
+# Departments share their tools. A number defined in two files has to be kept in
+# agreement BY HAND, and it was not: outline.py's first thinnest_px48 re-derived
+# maskmetrics' definition, took the global minimum of the distance transform
+# instead of the per-appendage inscribed radius, and read ~0.25px on every
+# creature — a bar nothing could pass, discovered only by comparing pixels.
+# This does not fail the build; it prints the standing work queue, the way
+# gates.py prints the blocking-but-allocatable list.
+MEASURES = ['thirds_cols', 'thirds_rows', 'protrusions', 'thinnest_px48',
+ 'sq_fill', 'mirror_sym', 'compactness', 'W_over_H']
+DEFINES = ['harness/outline.py', 'harness/maskmetrics.py', 'harness/silmetrics.mjs']
+dupes = []
+for m in MEASURES:
+ where = [f for f in DEFINES if re.search(r"['\"]?" + m + r"['\"]?\s*[:=]", read(f) or '')]
+ if len(where) > 1:
+ dupes.append((m, where))
+if dupes:
+ print('[synccheck] SHARED-TOOL QUEUE — one measure should have one definition:')
+ for m, where in dupes:
+ print(f' {m:16} defined in {len(where)}: ' + ', '.join(where))
+ print(' No card invokes maskmetrics.py or silmetrics.mjs any more (partreads.py')
+ print(' moved to outline.py). They are superseded, kept one release for anyone')
+ print(' calling them by hand, and the definitions above are the reason to finish.')
+
+# ── 3c. STRATEGY LEAK — the harness ships the architecture, not the reasoning ──
+# What the pipeline DOES is the product. Why it was tuned that way, what each
+# round cost, how long a build took, and which creature failed are the
+# operator's business and do not leave the local machine.
+# State a rule and its threshold; never state where the threshold came from.
+STRATEGY = [
+ (r'\b\d{1,3},\d{3}\s*(?:tokens|characters|turns|reads|weighted)', 'a raw cost count'),
+ (r'~?\d+(?:\.\d+)?\s*[kKmM]?\s*tokens', 'a token cost'),
+ (r'\b\d+h\d+m\b|\b\d+m\d+s\b', 'a wall-clock timing'),
+ (r'\b\d+\s*minutes?\b', 'a wall-clock timing'),
+ (r'[Mm]easured (?:on|across|in|,)', 'a field-report citation'),
+ (r'a (?:shipped|delivered|measured|real) (?:build|creature|boss|run)', 'a field-report citation'),
+ (r'field report|its customer|a customer (?:said|singled|rejected)', 'a customer reference'),
+ (r'\b(?:322|327|315) turns\b', 'a run-length citation'),
+ (r'\b\d+(?:\.\d+)?[x×] the (?:tokens|wall clock|model turns|cost)', 'a cost ratio'),
+ (r'(?i)\b(scorpion|salamander|cassowary|bison|hippo|pagoda|millipede|elephant|boar|snail|gryphon|mammoth|naga|avian)\b[^.\n]{0,60}\b(?:read|round|run|build|shipped|failed|took)\b', 'a named creature tied to a run'),
+]
+SKIP = ('node_modules', '.git', 'example/', 'calibration/', 'assets/',
+ 'harness/synccheck.py') # this file IS the pattern list
+leaks = []
+for root, dirs, files in os.walk(ROOT):
+ dirs[:] = [d for d in dirs if d not in ('node_modules', '.git')]
+ for fn in files:
+ if not fn.endswith(('.md', '.py', '.js', '.mjs', '.json', '.sh', '.ps1')):
+ continue
+ rel = os.path.relpath(os.path.join(root, fn), ROOT).replace(os.sep, '/')
+ if any(k in rel for k in SKIP):
+ continue
+ txt = read(rel) or ''
+ for pat, what in STRATEGY:
+ for mm in re.finditer(pat, txt):
+ line = txt[:mm.start()].count('\n') + 1
+ leaks.append((rel, line, what, mm.group(0)[:40]))
+if leaks:
+ bad.append(f'strategy leak: {len(leaks)} place(s) state WHY, not WHAT — '
+ 'the harness ships the architecture only')
+ for rel, line, what, frag in leaks[:40]:
+ print(f' {rel}:{line} {what}: "{frag}"')
+
+# ── 4. leak scan ─────────────────────────────────────────────────────────────
+# Only GENERIC patterns ship. Site-specific words — the names of whatever else
+# lives on the author's disk — must never be written here: a list of names you
+# refuse to publish is itself a publication, and this file is public. Put one
+# regex per line in SITE_WORDS instead; it is git-ignored, is not packed, and
+# its absence simply means the generic scan runs alone.
+SITE_WORDS = 'harness/leakwords.local.txt'
+FORBIDDEN = [
+ # An author's own absolute path: a drive letter and at least TWO real path
+ # segments. One segment matches documentation ("C:\path\to\chrome.exe" is a
+ # placeholder, not a leak) and a bare "e:\n" is a string escape, not a path.
+ r'[A-Za-z]:\\[A-Za-z][\w .-]*\\[A-Za-z][\w .-]*\\',
+ r'/home/[a-z][a-z0-9_-]*/', # any absolute POSIX home path
+ r'/Users/[A-Za-z][\w.-]*/',
+ # An e-mail address. The TLD must be letters, or npm version specifiers
+ # like "[email protected]" match.
+ r'[\w.+-]+@[\w-]+\.[A-Za-z]{2,}',
+]
+_site = read(SITE_WORDS)
+if _site:
+ FORBIDDEN += [ln.strip() for ln in _site.splitlines()
+ if ln.strip() and not ln.lstrip().startswith('#')]
+PLACEHOLDERS = ('C:\\path\\to\\', '/path/to/', 'D:\\path\\to\\')
+SCAN_EXT = ('.md', '.js', '.mjs', '.py', '.sh', '.json', '.html', '.ps1', '.yml')
+for dirpath, dirs, files in os.walk(ROOT):
+ dirs[:] = [d for d in dirs if d not in ('node_modules', '.git', 'out', 'delivery')]
+ for f in files:
+ if not f.endswith(SCAN_EXT) or f in ('three-bundle.js', 'synccheck.py'):
+ continue
+ rel = os.path.relpath(os.path.join(dirpath, f), ROOT)
+ s = read(rel) or ''
+ # Documentation placeholders are structurally identical to a real path,
+ # so they are named explicitly rather than pattern-matched around. The
+ # list fails safe: anything NOT on it still blocks.
+ for ph in PLACEHOLDERS:
+ s = s.replace(ph, '<placeholder>')
+ for pat in FORBIDDEN:
+ mm = re.search(pat, s)
+ if mm:
+ bad.append(f'leaked string in {rel}: "{mm.group(0)}"')
+
+# ── 5. no shipped file points at a doc that does not ship ────────────────────
+# A dangling docs/ path is worse than a broken link: the FILENAME is the leak.
+# "see docs/<name>.md" tells a reader that an internal document exists and what
+# it is called, and then no one can open it. Four of these survived 1.3.1's
+# first pack, left behind when their targets were held back from the release.
+for dirpath, dirs, files in os.walk(ROOT):
+ dirs[:] = [d for d in dirs if d not in ('node_modules', '.git', 'out', 'delivery')]
+ for f in files:
+ if not f.endswith(SCAN_EXT) or f == 'three-bundle.js':
+ continue
+ rel = os.path.relpath(os.path.join(dirpath, f), ROOT)
+ for ref in sorted(set(re.findall(r'docs/[A-Za-z0-9_.-]+\.md', read(rel) or ''))):
+ if not os.path.exists(os.path.join(ROOT, ref)):
+ bad.append(f'{rel} points at {ref}, which does not ship')
+
+# ── 6. nothing describes a version that has not been released ────────────────
+# A public tree that says it behaves "identically to" a version that is not out
+# announces that version, its feature set, and that it has users. Three such
+# lines survived into the first pack of this release, backported from work that
+# has not shipped. CHANGELOG entries BELOW the current release are history and
+# exempt — old numbering schemes live there legitimately.
+# Skipped: npm specifiers ([email protected]) and dotted quads (127.0.0.1).
+VER_RE = re.compile(r'(?<![\w@.])(\d+)\.(\d+)\.(\d+)(?![\w.])')
+here = tuple(int(x) for x in version.split('.')) if re.fullmatch(r'\d+\.\d+\.\d+', version) else None
+if here:
+ for dirpath, dirs, files in os.walk(ROOT):
+ dirs[:] = [d for d in dirs if d not in ('node_modules', '.git', 'out', 'delivery')]
+ for f in files:
+ if not f.endswith(SCAN_EXT) or f == 'three-bundle.js':
+ continue
+ rel = os.path.relpath(os.path.join(dirpath, f), ROOT)
+ s = read(rel) or ''
+ if rel.replace('\\', '/') == 'CHANGELOG.md':
+ parts = re.split(r'^## ', s, flags=re.M)
+ s = '## '.join(parts[:2])
+ for mm in VER_RE.finditer(s):
+ if tuple(int(g) for g in mm.groups()) > here:
+ line = s[:mm.start()].count('\n') + 1
+ bad.append(f'{rel}:{line} describes {mm.group(0)}, which is newer than {version}')
+
+# ── verdict ──────────────────────────────────────────────────────────────────
+if bad:
+ print(f'[synccheck] {len(bad)} problem(s) — DO NOT PUSH:')
+ for b in bad:
+ print(' - ' + b)
+ sys.exit(1)
+print(f'[synccheck] OK — version {version}, {len(FEATURES)} promised features present, '
+ f'{len(REQUIRED)} required files present, no leaked strings. Safe to ship.')
diff --git a/harness/wash.py b/harness/wash.py
new file mode 100644
index 0000000..af76dd1
--- /dev/null
+++ b/harness/wash.py
@@ -0,0 +1,186 @@
+#!/usr/bin/env python3
+"""Wash — rebuild a GLB as a clean, standardised file. Whitelist, not blacklist.
+
+A GLB is a moving box: loaders only look at the furniture they recognise and
+SKIP everything else — which is exactly where a bad actor hides an executable
+or where private metadata (EXIF GPS, local paths) survives. Scanning for bad
+things loses to the next new trick; washing wins by construction: parse the
+incoming file and carry ONLY recognised furniture into a brand-new box.
+Anything hidden simply does not get moved.
+
+ python3 harness/wash.py <in.glb> <out.glb> # out may equal in
+
+What survives: geometry, skeleton, skins, animations, material parameters,
+ texture PIXELS (re-encoded PNG — EXIF/XMP die), sanitised
+ names, and OUR OWN asset fields (whitelisted keys only).
+What dies: extra chunks, trailing bytes, gaps between buffer views,
+ unknown extensions, every foreign `extras`, image metadata.
+What REJECTS the file (exit 1, machine-readable reason on stdout):
+ external URIs (a downloader would phone another server),
+ required extensions we cannot parse (Draco/Meshopt),
+ broken images, structures that fail to re-parse.
+
+deliver.py runs this on every delivery; publish.mjs runs it again right
+before upload. The harness is open source, so a modified copy can skip this —
+the server MUST still keep its own cheap gate (chunk count, no external URI).
+Washing here is standardisation and courtesy; the server's gate is the law.
+"""
+import sys, os, json, struct, io, re
+
+KEEP_TOP = ['scene', 'scenes', 'nodes', 'meshes', 'accessors', 'bufferViews',
+ 'buffers', 'materials', 'textures', 'images', 'samplers', 'skins',
+ 'animations', 'cameras']
+EXT_WHITELIST = {'KHR_texture_transform', 'KHR_materials_unlit',
+ 'KHR_materials_emissive_strength'}
+ASSET_EXTRAS_KEYS = {'harness', 'harness_version', 'spec', 'monster', 'author',
+ 'license', 'gate', 'parts', 'source_spec'}
+MAX_SOURCE_SPEC = 64 * 1024
+
+def fail(reason, detail=''):
+ print(json.dumps({'ok': False, 'error': reason, 'detail': detail}))
+ sys.exit(1)
+
+def clean_str(s, cap=80):
+ if not isinstance(s, str): return None
+ s = re.sub(r'[<>\x00-\x1f\x7f]', '', s).strip()
+ return s[:cap] if s else None
+
+def strip_obj(o, notes, keep_name=True):
+ """Remove extras + unknown extensions from one glTF object, sanitise name."""
+ if not isinstance(o, dict): return
+ if 'extras' in o:
+ del o['extras']; notes.add('foreign extras dropped')
+ if 'extensions' in o:
+ bad = [k for k in o['extensions'] if k not in EXT_WHITELIST]
+ for k in bad:
+ del o['extensions'][k]; notes.add(f'extension stripped: {k}')
+ if not o['extensions']: del o['extensions']
+ if keep_name and 'name' in o:
+ nm = clean_str(o['name'])
+ if nm is None: o.pop('name', None)
+ else: o['name'] = nm
+
+def wash(src_path, out_path):
+ try:
+ from PIL import Image
+ except ImportError:
+ fail('missing_dependency', 'pillow (pip install pillow)')
+ raw = open(src_path, 'rb').read()
+ if raw[:4] != b'glTF' or len(raw) < 20: fail('parse_error', 'not a GLB')
+ jlen, jtype = struct.unpack('<II', raw[12:20])
+ if jtype != 0x4E4F534A: fail('parse_error', 'first chunk is not JSON')
+ try:
+ g = json.loads(raw[20:20 + jlen])
+ except Exception as e:
+ fail('parse_error', str(e)[:120])
+ off = 20 + jlen
+ body = b''
+ if off + 8 <= len(raw):
+ blen, btype = struct.unpack('<II', raw[off:off + 8])
+ if btype == 0x004E4942: body = raw[off + 8: off + 8 + blen]
+ notes = set()
+ tail = len(raw) - (off + 8 + len(body) + (-len(body)) % 4)
+ if tail > 0: notes.add(f'{tail} trailing bytes discarded')
+
+ # ── red flags that reject the whole file ──
+ for b in g.get('buffers', []) or []:
+ u = b.get('uri', '')
+ if u and not u.startswith('data:'): fail('external_uri', u[:100])
+ for im in g.get('images', []) or []:
+ u = im.get('uri', '')
+ if u and not u.startswith('data:'): fail('external_uri', u[:100])
+ for ext in g.get('extensionsRequired', []) or []:
+ if ext not in EXT_WHITELIST: fail('unsupported_compression', ext)
+
+ # ── new document: only recognised furniture moves in ──
+ out = {}
+ for k in KEEP_TOP:
+ if k in g: out[k] = g[k]
+
+ # asset: version + whitelisted own fields, everything else dies
+ a = g.get('asset', {}) or {}
+ na = {'version': '2.0'}
+ if isinstance(a.get('generator'), str): na['generator'] = clean_str(a['generator'], 60)
+ if isinstance(a.get('copyright'), str): na['copyright'] = clean_str(a['copyright'], 60)
+ x = a.get('extras', {}) or {}
+ nx = {}
+ for k in ASSET_EXTRAS_KEYS:
+ if k not in x: continue
+ v = x[k]
+ if k == 'source_spec':
+ try:
+ s2 = json.dumps(v, separators=(',', ':'))
+ if len(s2) <= MAX_SOURCE_SPEC: nx[k] = json.loads(s2)
+ else: notes.add('source_spec over 64KB dropped')
+ except Exception: notes.add('source_spec unparseable, dropped')
+ elif isinstance(v, str):
+ c = clean_str(v)
+ if c: nx[k] = c
+ else:
+ nx[k] = json.loads(json.dumps(v)) # re-serialise: kills exotica
+ if nx: na['extras'] = nx
+ out['asset'] = na
+
+ # strip extras/unknown extensions on every object that can carry them
+ for key in KEEP_TOP:
+ for o in (out.get(key) or ([] if key != 'scene' else [])):
+ if isinstance(o, dict):
+ strip_obj(o, notes)
+ for sub in ('pbrMetallicRoughness', 'primitives', 'channels', 'samplers'):
+ v = o.get(sub)
+ if isinstance(v, dict): strip_obj(v, notes, keep_name=False)
+ if isinstance(v, list):
+ for it in v:
+ if isinstance(it, dict): strip_obj(it, notes, keep_name=False)
+ if 'extensionsUsed' in g:
+ used = [e for e in g['extensionsUsed'] if e in EXT_WHITELIST]
+ if used: out['extensionsUsed'] = used
+ g.pop('extensionsRequired', None) # nothing left requires anything
+
+ # ── repack the binary: views copied tightly, images re-encoded ──
+ img_view = {im['bufferView']: i for i, im in enumerate(out.get('images', []))
+ if isinstance(im, dict) and 'bufferView' in im}
+ nbin = bytearray(); nviews = []
+ for vi, v in enumerate(out.get('bufferViews', []) or []):
+ start = v.get('byteOffset', 0); data = body[start:start + v['byteLength']]
+ if vi in img_view:
+ try:
+ pic = Image.open(io.BytesIO(bytes(data))); pic.load()
+ buf = io.BytesIO()
+ pic.save(buf, format='PNG', optimize=False) # pixels only — metadata dies
+ data = buf.getvalue()
+ out['images'][img_view[vi]]['mimeType'] = 'image/png'
+ notes.add('images re-encoded')
+ except Exception as e:
+ fail('broken_image', str(e)[:120])
+ while len(nbin) % 4: nbin.append(0)
+ nv = {'buffer': 0, 'byteOffset': len(nbin), 'byteLength': len(data)}
+ for k in ('byteStride', 'target'):
+ if k in v: nv[k] = v[k]
+ nbin.extend(data); nviews.append(nv)
+ if nviews:
+ out['bufferViews'] = nviews
+ out['buffers'] = [{'byteLength': len(nbin)}]
+ else:
+ out.pop('buffers', None)
+
+ # ── write: exactly two chunks, exact declared length, nothing after ──
+ js = json.dumps(out, separators=(',', ':')).encode()
+ js += b' ' * ((-len(js)) % 4)
+ bb = bytes(nbin) + b'\x00' * ((-len(nbin)) % 4)
+ total = 12 + 8 + len(js) + (8 + len(bb) if bb else 0)
+ w = bytearray(struct.pack('<4sII', b'glTF', 2, total))
+ w += struct.pack('<II', len(js), 0x4E4F534A) + js
+ if bb: w += struct.pack('<II', len(bb), 0x004E4942) + bb
+ open(out_path, 'wb').write(w)
+
+ # self-check: the washed file must re-parse
+ chk = open(out_path, 'rb').read()
+ jl2, = struct.unpack('<I', chk[12:16]); json.loads(chk[20:20 + jl2])
+ print(json.dumps({'ok': True, 'bytes_in': len(raw), 'bytes_out': len(chk),
+ 'notes': sorted(notes)}))
+
+if __name__ == '__main__':
+ if len(sys.argv) < 3:
+ sys.exit('usage: python3 wash.py <in.glb> <out.glb>')
+ wash(sys.argv[1], sys.argv[2])
diff --git a/setup.ps1 b/setup.ps1
new file mode 100644
index 0000000..2c73677
--- /dev/null
+++ b/setup.ps1
@@ -0,0 +1,43 @@
+# anyCreature one-command start (Windows PowerShell).
+# Same steps as setup.sh: deps -> browser -> calibration -> browser probe.
+$ErrorActionPreference = "Stop"
+Set-Location $PSScriptRoot
+npm install [email protected] [email protected] --no-fund --no-audit
+# Same rule as setup.sh: a download is the normal path, skipped only when
+# Playwright can already launch a browser (prebuilt images, warm CI caches).
+# No hunting for chrome.exe, no remembered path — PW_CHROMIUM_PATH is the only
+# pin, and whoever sets it owns it.
+if ($env:PW_CHROMIUM_PATH) {
+ Write-Output "browser: pinned by PW_CHROMIUM_PATH"
+} else {
+ node harness/pwprobe.mjs *> $null
+ if ($LASTEXITCODE -eq 0) {
+ Write-Output "browser: Playwright can already launch one, skipping the download"
+ } else {
+ # Same bound as setup.sh: a blocked CDN must fail in minutes, not tens of
+ # them. A measured run lost ~minutes to an install that could never
+ # finish, because nothing capped it.
+ $limit = if ($env:PW_INSTALL_TIMEOUT) { [int]$env:PW_INSTALL_TIMEOUT } else { 420 }
+ Write-Output "browser: downloading chromium (up to ${limit}s)…"
+ $p = Start-Process -FilePath "npx" -ArgumentList "playwright","install","chromium" `
+ -NoNewWindow -PassThru
+ if (-not $p.WaitForExit($limit * 1000)) {
+ try { $p.Kill($true) } catch {}
+ $code = 124
+ } else { $code = $p.ExitCode }
+ if ($code -ne 0) {
+ Write-Output ""
+ Write-Output "browser download did not finish (exit $code)."
+ Write-Output "If this machine cannot reach the Playwright CDN, point PW_CHROMIUM_PATH at a"
+ Write-Output "Chromium or Chrome you already have and run setup.ps1 again:"
+ Write-Output ' $env:PW_CHROMIUM_PATH="C:\path\to\chrome.exe"; .\setup.ps1'
+ Write-Output 'A slow-but-working line just needs longer: $env:PW_INSTALL_TIMEOUT=1200'
+ exit 1
+ }
+ }
+}
+pip install numpy pillow scipy -q
+python -c "import numpy, PIL, scipy.ndimage"
+python harness/calibrate.py
+node harness/pwprobe.mjs
+Write-Output "calibrate OK"
diff --git a/setup.sh b/setup.sh
index 2fb2f60..5f5078b 100644
--- a/setup.sh
+++ b/setup.sh
@@ -2,10 +2,56 @@
# anyCreature one-command start: install deps → red/green ruler calibration
set -e
cd "$(dirname "$0")"
-npm install [email protected] playwright --no-fund --no-audit
+npm install [email protected] [email protected] --no-fund --no-audit
+# The npm package alone ships NO browser. Without a browser, setup prints
+# "calibrate OK" and then every render tool (silmetrics/hero/judge) dies at its
+# first launch on a fresh machine — so a download here is the normal path and
+# must stay the normal path.
+#
+# The one case worth skipping: Playwright can ALREADY launch. Some CI images and
+# prebuilt containers ship a browser cache, and there the installer runs, fails,
+# retries six times and gives up ~minutes later for nothing. Ask Playwright
+# itself — one probe, its own resolution, no guessing where a browser might be.
+# We do NOT go hunting for chrome on PATH and we do NOT remember a path in a
+# file: a pinned absolute path is how 1.2.0 broke every clone on macOS and
+# Windows, and re-deriving it automatically is the same bug wearing a hat. An
+# environment that needs a specific binary sets PW_CHROMIUM_PATH and owns it.
+if [ -n "$PW_CHROMIUM_PATH" ]; then
+ echo "browser: pinned by PW_CHROMIUM_PATH"
+elif node harness/pwprobe.mjs >/dev/null 2>&1; then
+ echo "browser: Playwright can already launch one, skipping the download"
+else
+ # Nothing used to bound this. On a machine whose network blocks the Playwright
+ # CDN the installer retries and retries: a build lost ~minutes here,
+ # 21% of the whole build, to a download that was never going to complete. The
+ # 1.3.1 fix above only covers "a browser already works, don't download" — it
+ # said nothing about how long failing is allowed to take.
+ #
+ # A watchdog rather than `timeout`: timeout(1) is GNU coreutils and is NOT on
+ # a stock macOS (there it is `gtimeout`, if it is there at all). Reaching for
+ # it would be the same mistake as pinning a browser path — works here, breaks
+ # on someone else's machine.
+ echo "browser: downloading chromium (up to ${PW_INSTALL_TIMEOUT:-420}s)…"
+ npx playwright install chromium & PW_PID=$!
+ ( sleep "${PW_INSTALL_TIMEOUT:-420}"; kill -TERM "$PW_PID" 2>/dev/null ) & PW_WD=$!
+ wait "$PW_PID"; PW_RC=$?
+ kill -TERM "$PW_WD" 2>/dev/null
+ if [ "$PW_RC" -ne 0 ]; then
+ echo ""
+ echo "browser download did not finish (exit $PW_RC)."
+ echo "If this machine cannot reach the Playwright CDN, point PW_CHROMIUM_PATH at a"
+ echo "Chromium or Chrome you already have and run setup.sh again:"
+ echo " PW_CHROMIUM_PATH=/path/to/chromium bash setup.sh"
+ echo "A slow-but-working line just needs longer: PW_INSTALL_TIMEOUT=1200 bash setup.sh"
+ exit 1
+ fi
+fi
# scipy is NOT optional: harness/maskmetrics.py imports scipy.ndimage. Leaving it
# out let setup print "calibrate OK" and then blow up mid-LOW on the first measure.
pip install numpy pillow scipy --break-system-packages -q 2>/dev/null || pip install numpy pillow scipy -q
python3 -c "import numpy, PIL, scipy.ndimage" || { echo "python deps missing"; exit 1; }
python3 harness/calibrate.py
+# probe an actual browser launch NOW — a missing/broken browser must fail setup
+# loudly here, not mid-LOW on the first silhouette
+node harness/pwprobe.mjs
echo "calibrate OK"
diff --git a/tools/sync-contract.mjs b/tools/sync-contract.mjs
new file mode 100644
index 0000000..c40fdc6
--- /dev/null
+++ b/tools/sync-contract.mjs
@@ -0,0 +1,13 @@
+// Regenerates engine/core/contract.js (CommonJS) from harness/glbcheck.mjs (ESM).
+// One implementation of the contract, two module systems: the engine is CJS and
+// dependency-free, the harness copy is importable by a server/Worker. Run this
+// after editing glbcheck.mjs; synccheck.py fails the build if they drift.
+import fs from 'fs';
+const src = fs.readFileSync('harness/glbcheck.mjs', 'utf8');
+const body = src.slice(src.indexOf("'use strict';"), src.indexOf('// ── CLI ──'))
+ .replace('export function checkGLB', 'function checkGLB');
+fs.writeFileSync('engine/core/contract.js',
+ '// ACS engine — GLB output contract check (CommonJS mirror of harness/glbcheck.mjs).\n' +
+ '// GENERATED by tools/sync-contract.mjs — do not edit; edit the harness copy.\n' +
+ body + '\nmodule.exports = { checkGLB };\n');
+console.log('engine/core/contract.js regenerated from harness/glbcheck.mjs');