From 94cff5599eabf35d3a8b4ced16d42ff5a6337e9a Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 03:10:03 +0000 Subject: [PATCH 01/10] Add optional named clips to the character pack contract Characters may now declare an animations.extra map of named clips beyond the states: fixed vocabulary names (locomotion, weapon handling, damage reactions, melee, round outcomes) or an emote_ prefix with a suffix. Keys match ^[a-z][a-z0-9_]{1,40}$; each entry carries file, duration, loop, rootMotion and source. Extra files are declared in files under the animations.extra. role, so duplicates, missing paths and the byte budget (extras included) are enforced before any payload is hashed, and each extra GLB must contain an animation named exactly as its key. Agent: Claude Code Signed-off-by: rubenmarcus --- docs/character-pack.md | 25 ++++++++++++---- schemas/asset-pack.schema.json | 18 +++++++++++- tools/lib/character-pack.mjs | 53 ++++++++++++++++++++++++++++++++-- 3 files changed, 88 insertions(+), 8 deletions(-) diff --git a/docs/character-pack.md b/docs/character-pack.md index 9c01da0..7b8bc15 100644 --- a/docs/character-pack.md +++ b/docs/character-pack.md @@ -10,13 +10,13 @@ On top of the common fields (`schemaVersion`, `kind`, `id`, `version`, `source`, | --- | --- | | `model` | One package path ending in `.glb`: the rigged, skinned character. | | `skeleton` | `"meshy-28"` (see below). | -| `animations` | Object keyed by state. Required: `idle`, `walk`, `run`, `shoot`, `death`, `crouch`, `crouchwalk`, `jump`. Optional: `idle1h`, `walk1h`, `walkfire`. No other keys. Each value is a distinct `.glb` path. | +| `animations` | Object keyed by state. Required: `idle`, `walk`, `run`, `shoot`, `death`, `crouch`, `crouchwalk`, `jump`. Optional: `idle1h`, `walk1h`, `walkfire`, plus one optional `extra` map of named clips (see below). No other keys. Each state value is a distinct `.glb` path. | | `previews` | At least one portrait image path (`.png`, `.jpg`, `.jpeg` or `.webp`). | | `rights` | `{ "status": "original" \| "public-domain" \| "political-satire", "basis": "", "references": ["", ...] }`; `references` is optional. | | `budgets` | `{ "triangles": , "bytes": }`. `triangles` bounds the model; `bytes` bounds the sum of every `files[].bytes`. | | `evidence` | Optional extra paths (for example a provenance sidecar). | -Every file in `files` must be declared by exactly one role (`model`, `animations.`, `previews`, `evidence`) and every declared path must appear in `files`. +Every file in `files` must be declared by exactly one role (`model`, `animations.`, `animations.extra.`, `previews`, `evidence`) and every declared path must appear in `files`. Extra-clip files count toward `budgets.bytes` like any other file. ```json { @@ -28,7 +28,8 @@ Every file in `files` must be declared by exactly one role (`model`, `animations "files": [{ "path": "model/capitao-caveira.glb", "sha256": "…", "bytes": 1 }], "model": "model/capitao-caveira.glb", "skeleton": "meshy-28", - "animations": { "idle": "animations/idle.glb", "walk": "animations/walk.glb", "…": "…" }, + "animations": { "idle": "animations/idle.glb", "walk": "animations/walk.glb", "…": "…", + "extra": { "strafe_left": { "file": "animations/extra/strafe-left.glb", "duration": 0.9, "loop": true, "rootMotion": false, "source": "Mixamo Strafe Left retargeted to meshy-28" } } }, "previews": ["previews/portrait.jpg"], "rights": { "status": "original", "basis": "Invented character; concept prompt forbids likeness of real people and existing characters." }, "budgets": { "triangles": 6000, "bytes": 8388608 } @@ -42,9 +43,23 @@ Every file in `files` must be declared by exactly one role (`model`, `animations - The model is a GLB 2 container with in-bounds buffer views and accessors, finite positions and in-range indices. Every primitive is a triangle list (mode 4), and the triangle count must not exceed `budgets.triangles`. - The model has exactly one skin, and `inverseBindMatrices` holds one float `MAT4` per joint. Every skinned primitive has a `JOINTS_0` unsigned byte/short `VEC4` and a float or normalized `WEIGHTS_0` `VEC4` per vertex, and every joint index stays inside the skin. - The skin is exactly meshy-28: 28 joints whose (name, nearest joint ancestor) pairs match the list below as a multiset. -- Each animation GLB contains an animation named exactly as its state that drives at least one meshy-28 bone through a `translation`, `rotation` or `scale` channel. A `weights` channel must target a mesh with morph targets. Every sampler has at least one float keyframe time and the output type and count that match its interpolation (and, for `weights`, the number of morph targets). +- Each animation GLB contains an animation named exactly as its state that drives at least one meshy-28 bone through a `translation`, `rotation` or `scale` channel. A `weights` channel must target a mesh with morph targets. Every sampler has at least one float keyframe time and the output type and count that match its interpolation (and, for `weights`, the number of morph targets). The same rules apply to every `animations.extra` clip, with the animation named exactly as its key. - Each preview starts with the PNG, JPEG or WebP signature for its extension. + +## Optional clips (`animations.extra`) + +`animations.extra` is an optional map of named clips beyond the states, for movement set, weapon handling, damage reactions, melee, round outcomes and emotes. Keys match `^[a-z][a-z0-9_]{1,40}$` and must be either a name from the fixed vocabulary below or an `emote_` prefix followed by at least one character. Anything else — including state names and the bare `emote_` prefix — is rejected. The vocabulary is `extraClipNames`/`extraClipPrefixes` in `tools/lib/character-pack.mjs`; the client mirrors it in `public/js/data/content-releases.js`. + +- Locomotion: `strafe_left`, `strafe_right`, `walk_back`, `run_back`, `strafe_left_pistol`, `strafe_right_pistol`, `walk_back_pistol` +- Weapon handling: `reload_rifle`, `reload_pistol`, `draw_rifle`, `holster_rifle`, `draw_pistol`, `holster_pistol` +- Damage reactions: `hit_front`, `hit_back`, `hit_left`, `hit_right`, `hit_head` +- Melee and utility: `grenade_throw`, `knife_idle`, `knife_stab` +- Round outcomes: `victory`, `defeat` +- Emotes: any key starting with `emote_` (for example `emote_danca`) + +Each entry is an object with exactly five fields: `file` (a distinct `.glb` package path, declared in `files`), `duration` (seconds, positive), `loop` (boolean), `rootMotion` (boolean) and `source` (provenance string, for example the source animation and rig pipeline). `duration`, `loop` and `rootMotion` are declared metadata for the runtime; the GLB itself still carries the authoritative keyframes. A missing `extra` map is valid — optional means absent, not empty promises. + ## meshy-28 The shared Meshy humanoid skeleton the runtime clips are baked against, taken from the client donor `public/models/characters/mst.glb` and identical in all 37 offline-rigged Creepypasta Season characters. Skin joint order, with the nearest joint ancestor in parentheses: @@ -63,7 +78,7 @@ Photos of real people never enter either repository. ## Checks -`npm run check` builds a synthetic character pack (a programmatic 12-triangle skinned GLB and eleven one-channel clips, no real asset bytes), validates it, and requires each contract mutant to be rejected for its stated reason: missing states, unknown state, misnamed clip, clip driving no meshy-28 bone, clip channel without a path, clip without keyframes or with mismatched output, wrong skeleton id, renamed, reparented or missing bone, missing skin or weights, missing, mistyped or out-of-skin `JOINTS_0`, triangle strips, bad GLB magic or version, triangle and byte budgets (including the byte budget before hashing), bad rights, missing or invalid previews, undeclared files, and hash or size mutations. +`npm run check` builds a synthetic character pack (a programmatic 12-triangle skinned GLB, one-channel state clips and two extra clips, no real asset bytes), validates it, and requires each contract mutant to be rejected for its stated reason: missing states, unknown state, misnamed clip, clip driving no meshy-28 bone, clip channel without a path, clip without keyframes or with mismatched output, wrong skeleton id, renamed, reparented or missing bone, missing skin or weights, missing, mistyped or out-of-skin `JOINTS_0`, triangle strips, bad GLB magic or version, triangle and byte budgets (including the byte budget before hashing), bad rights, missing or invalid previews, undeclared files, hash or size mutations, and the extra-clip rules: unknown, pattern-violating, state-colliding or bare-prefix names, entries with missing or mistyped fields, non-GLB files, missing, duplicate or misnamed clip files, and extras pushing the pack over its byte budget. `npm run check` also runs `tools/checks/character-rig-check.mjs`, the deterministic half of the Blender rig pipeline that produces these models (configs, `joints.json` validation, meshy-28 assembly, the pose test on a synthetic humanoid, and the runner's step freshness with a fake Blender); see [character-rig.md](character-rig.md). diff --git a/schemas/asset-pack.schema.json b/schemas/asset-pack.schema.json index 725e51d..4652c9b 100644 --- a/schemas/asset-pack.schema.json +++ b/schemas/asset-pack.schema.json @@ -109,7 +109,23 @@ "jump": { "$ref": "#/$defs/glbPath" }, "idle1h": { "$ref": "#/$defs/glbPath" }, "walk1h": { "$ref": "#/$defs/glbPath" }, - "walkfire": { "$ref": "#/$defs/glbPath" } + "walkfire": { "$ref": "#/$defs/glbPath" }, + "extra": { + "type": "object", + "propertyNames": { "pattern": "^[a-z][a-z0-9_]{1,40}$" }, + "additionalProperties": { + "type": "object", + "required": ["file", "duration", "loop", "rootMotion", "source"], + "properties": { + "file": { "$ref": "#/$defs/glbPath" }, + "duration": { "type": "number", "exclusiveMinimum": 0 }, + "loop": { "type": "boolean" }, + "rootMotion": { "type": "boolean" }, + "source": { "type": "string", "minLength": 1 } + }, + "additionalProperties": false + } + } }, "additionalProperties": false }, diff --git a/tools/lib/character-pack.mjs b/tools/lib/character-pack.mjs index 2bef959..01c3fdb 100644 --- a/tools/lib/character-pack.mjs +++ b/tools/lib/character-pack.mjs @@ -4,6 +4,24 @@ import { inspectGlb, readAccessorComponent, readGlb } from './glb-inspect.mjs'; export const requiredCharacterStates = Object.freeze(['idle', 'walk', 'run', 'shoot', 'death', 'crouch', 'crouchwalk', 'jump']); export const optionalCharacterStates = Object.freeze(['idle1h', 'walk1h', 'walkfire']); +// Optional named clips a pack may carry beyond the states, as `animations.extra` entries. +// Fixed names for locomotion, weapon handling, damage reactions, melee and round outcomes, +// plus free-form emotes under the `emote_` prefix (at least one character after the prefix). +// State names are never valid extra names, so the two key spaces stay disjoint. +export const extraClipNames = Object.freeze([ + 'strafe_left', 'strafe_right', 'walk_back', 'run_back', + 'strafe_left_pistol', 'strafe_right_pistol', 'walk_back_pistol', + 'reload_rifle', 'reload_pistol', 'draw_rifle', 'holster_rifle', 'draw_pistol', 'holster_pistol', + 'hit_front', 'hit_back', 'hit_left', 'hit_right', 'hit_head', + 'grenade_throw', 'knife_idle', 'knife_stab', 'victory', 'defeat', +]); +export const extraClipPrefixes = Object.freeze(['emote_']); + +export function isExtraClipName(name) { + return extraClipNames.includes(name) + || extraClipPrefixes.some(prefix => name.length > prefix.length && name.startsWith(prefix)); +} + // The shared Meshy humanoid skeleton every runtime clip is baked against: skin joint order // and the nearest joint ancestor of each joint (null for the root). Derived from the client // donor `public/models/characters/mst.glb` and the 37 offline-rigged lote30 characters; the @@ -29,13 +47,32 @@ const imageMagic = [ export function characterRoleEntries(manifest) { if (manifest.kind !== 'character') return []; const entries = [{ role: 'model', path: manifest.model }]; - for (const [state, file] of Object.entries(manifest.animations || {})) entries.push({ role: `animations.${state}`, path: file }); + for (const [state, file] of Object.entries(manifest.animations || {})) { + if (state === 'extra') continue; + entries.push({ role: `animations.${state}`, path: file }); + } + entries.push(...characterExtraEntries(manifest)); for (const role of ['previews', 'evidence']) { for (const file of manifest[role] || []) entries.push({ role, path: file }); } return entries; } +// Extra-clip role entries. This is also the structural gate that rejects names outside the +// vocabulary (bare prefixes, state names, anything else) during validateManifestStructure, +// before any payload is hashed. +export function characterExtraEntries(manifest) { + const extras = manifest.animations?.extra; + if (extras === undefined) return []; + if (typeof extras !== 'object' || Array.isArray(extras)) throw new Error('animations.extra must be an object keyed by extra clip name'); + const entries = []; + for (const [name, entry] of Object.entries(extras)) { + if (!isExtraClipName(name)) throw new Error(`animations.extra has an unknown clip name: ${name}`); + entries.push({ role: `animations.extra.${name}`, path: entry?.file }); + } + return entries; +} + const pairKey = ([name, parent]) => `${name}<${parent ?? ''}`; function multiset(pairs) { @@ -179,9 +216,21 @@ export async function validateCharacterPack(manifest, absolutes) { } for (const [state, file] of Object.entries(manifest.animations)) { + if (state === 'extra') continue; const { document } = await readGlb(absolutes.get(file), file); assertStateAnimation(document, state, file); } + for (const [name, entry] of Object.entries(manifest.animations.extra || {})) { + const { document } = await readGlb(absolutes.get(entry.file), entry.file); + assertStateAnimation(document, name, entry.file); + } for (const file of manifest.previews) await assertImage(file, absolutes.get(file)); - return { triangles: model.triangles, bytes: characterDeclaredBytes(manifest), joints: meshy28Joints.length, animations: Object.keys(manifest.animations).length }; + const states = Object.keys(manifest.animations).filter(key => key !== 'extra').length; + return { + triangles: model.triangles, + bytes: characterDeclaredBytes(manifest), + joints: meshy28Joints.length, + animations: states, + extraClips: Object.keys(manifest.animations.extra || {}).length, + }; } From 8665245e41ede1f2a0f162ad0b3c8ee9e56e688b Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 03:10:08 +0000 Subject: [PATCH 02/10] Require every extra-clip rule with synthetic mutants The valid fixture now ships two extra clips (a vocabulary name and an emote_ name) and a no-extras pack stays valid. Twelve new mutants cover the contract: unknown, state-colliding, bare-prefix and pattern-violating names; missing, duplicated, shared, non-GLB and misnamed clip files; entries with missing or mistyped fields; and extras pushing the pack over its byte budget. Agent: Claude Code Signed-off-by: rubenmarcus --- tools/checks/character-pack-check.mjs | 65 +++++++++++++++++++++++++-- 1 file changed, 61 insertions(+), 4 deletions(-) diff --git a/tools/checks/character-pack-check.mjs b/tools/checks/character-pack-check.mjs index 15524c9..e90ac50 100755 --- a/tools/checks/character-pack-check.mjs +++ b/tools/checks/character-pack-check.mjs @@ -127,6 +127,8 @@ const allStates = [...requiredCharacterStates, ...optionalCharacterStates]; function validFiles() { const files = { 'model/fixture-character.glb': modelGlb(), 'previews/portrait.png': png }; for (const state of allStates) files[`animations/${state}.glb`] = clipGlb(state); + files['animations/extra/strafe-left.glb'] = clipGlb('strafe_left'); + files['animations/extra/emote-danca.glb'] = clipGlb('emote_danca'); return files; } @@ -140,7 +142,13 @@ function manifestFor(files) { files: Object.entries(files).map(([file, bytes]) => ({ path: file, sha256: sha256(bytes), bytes: bytes.length })), model: 'model/fixture-character.glb', skeleton: 'meshy-28', - animations: Object.fromEntries(allStates.map(state => [state, `animations/${state}.glb`])), + animations: { + ...Object.fromEntries(allStates.map(state => [state, `animations/${state}.glb`])), + extra: { + strafe_left: { file: 'animations/extra/strafe-left.glb', duration: 0.8, loop: true, rootMotion: false, source: 'Synthetic strafe-left fixture clip' }, + emote_danca: { file: 'animations/extra/emote-danca.glb', duration: 2.5, loop: false, rootMotion: false, source: 'Synthetic emote fixture clip' }, + }, + }, previews: ['previews/portrait.png'], rights: { status: 'original', basis: 'Invented synthetic test character with no likeness or third-party design.' }, budgets: { triangles: 100, bytes: 1048576 }, @@ -177,11 +185,18 @@ const dropState = state => manifest => { manifest.files = manifest.files.filter(file => file.path !== `animations/${state}.glb`); }; +const dropExtras = manifest => { + for (const entry of Object.values(manifest.animations.extra || {})) { + manifest.files = manifest.files.filter(file => file.path !== entry.file); + } + delete manifest.animations.extra; +}; + try { const valid = await validateCase(); - console.log(`PASS Valid synthetic character pack (${valid.character.triangles} triangles, ${valid.character.joints} meshy-28 joints, ${valid.character.animations} state clips)`); - const requiredOnly = await validateCase({ mutate: manifest => optionalCharacterStates.forEach(state => dropState(state)(manifest)) }); - console.log(`PASS Valid character pack with only the ${requiredOnly.character.animations} required states`); + console.log(`PASS Valid synthetic character pack (${valid.character.triangles} triangles, ${valid.character.joints} meshy-28 joints, ${valid.character.animations} state clips, ${valid.character.extraClips} extra clips)`); + const requiredOnly = await validateCase({ mutate: manifest => { optionalCharacterStates.forEach(state => dropState(state)(manifest)); dropExtras(manifest); } }); + console.log(`PASS Valid character pack with only the ${requiredOnly.character.animations} required states and ${requiredOnly.character.extraClips} extra clips`); await validateCase({ replace: { 'animations/idle.glb': clipGlb('idle', { morph: 'valid' }) } }); console.log('PASS Valid clip with a bone channel plus a morph-weights channel'); @@ -201,6 +216,48 @@ try { await expectRejection('Clip without keyframes', /animation "death" has no keyframes/, { replace: { 'animations/death.glb': clipGlb('death', { keyframes: 0 }) } }); await expectRejection('Clip output count differs from keyframes', /output values that do not match its rotation keyframes/, { replace: { 'animations/crouch.glb': clipGlb('crouch', { keyframes: 2, outputValues: 1 }) } }); await expectRejection('Same clip declared for two states', /Duplicate declared path/, { mutate: manifest => { manifest.animations.walk = manifest.animations.idle; } }); + await expectRejection('Unknown extra clip name', /animations\.extra has an unknown clip name: moonwalk/, { + replace: { 'animations/extra/moonwalk.glb': clipGlb('moonwalk') }, + mutate: manifest => { manifest.animations.extra.moonwalk = { file: 'animations/extra/moonwalk.glb', duration: 1, loop: false, rootMotion: false, source: 'Not in the vocabulary' }; }, + }); + await expectRejection('Extra clip name equal to a state', /unknown clip name: idle/, { + mutate: manifest => { manifest.animations.extra.idle = manifest.animations.extra.strafe_left; }, + }); + await expectRejection('Bare emote prefix as an extra clip name', /unknown clip name: emote_/, { + replace: { 'animations/extra/emote-puro.glb': clipGlb('emote_') }, + mutate: manifest => { manifest.animations.extra.emote_ = { file: 'animations/extra/emote-puro.glb', duration: 1, loop: false, rootMotion: false, source: 'Bare prefix' }; }, + }); + await expectRejection('Extra clip name outside the key pattern', /\/animations\/extra must match pattern "\^\[a-z\]\[a-z0-9_\]\{1,40\}\$"/, { + replace: { 'animations/extra/Strafe-left.glb': clipGlb('strafe_left') }, + mutate: manifest => { manifest.animations.extra.Strafe_left = { file: 'animations/extra/Strafe-left.glb', duration: 1, loop: true, rootMotion: false, source: 'Uppercase key' }; }, + }); + await expectRejection('Extra clip file missing from files', /Declared path is missing from files: animations\/extra\/strafe-left\.glb/, { + mutate: manifest => { manifest.files = manifest.files.filter(file => file.path !== 'animations/extra/strafe-left.glb'); }, + }); + await expectRejection('Extra clip file shared with a state', /Duplicate declared path: animations\/idle\.glb \(animations\.idle and animations\.extra\.strafe_left\)/, { + mutate: manifest => { manifest.animations.extra.strafe_left.file = manifest.animations.idle; }, + }); + await expectRejection('Extras counted in the byte budget', /over its \d+-byte budget/, { + mutate: manifest => { + const extraBytes = manifest.files.filter(file => file.path.startsWith('animations/extra/')).reduce((sum, file) => sum + file.bytes, 0); + manifest.budgets.bytes = manifest.files.reduce((sum, file) => sum + file.bytes, 0) - extraBytes; + }, + }); + await expectRejection('Extra clip misnamed inside its GLB', /animations\/extra\/strafe-left\.glb: no animation named "strafe_left"/, { + replace: { 'animations/extra/strafe-left.glb': clipGlb('Strafe') }, + }); + await expectRejection('Extra clip file is not a GLB', /animations\/extra\/strafe_left\/file must match pattern/, { + mutate: manifest => { manifest.animations.extra.strafe_left.file = 'animations/extra/strafe-left.gltf'; }, + }); + await expectRejection('Extra entry missing a required field', /animations\/extra\/strafe_left must have required property 'duration'/, { + mutate: manifest => { delete manifest.animations.extra.strafe_left.duration; }, + }); + await expectRejection('Extra entry with a mistyped loop', /animations\/extra\/strafe_left\/loop must be boolean/, { + mutate: manifest => { manifest.animations.extra.strafe_left.loop = 'yes'; }, + }); + await expectRejection('Extra entry with a non-numeric duration', /animations\/extra\/strafe_left\/duration must be number/, { + mutate: manifest => { manifest.animations.extra.strafe_left.duration = '0.8'; }, + }); await expectRejection('Wrong skeleton id', /\/skeleton must be equal to constant/, { mutate: manifest => { manifest.skeleton = 'mixamo-65'; } }); const renamed = meshy28Joints.map(([name, parent]) => [name === 'LeftForeArm' ? 'LeftElbow' : name, parent === 'LeftForeArm' ? 'LeftElbow' : parent]); From 0431e5e37cb8b53061fdda147793010ff477917f Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 04:31:23 +0000 Subject: [PATCH 03/10] Extend the extra-clip vocabulary with the converter library names Adopt the 45 names the animation conversion library proposes (branch feat/animation-conversion-20261109, PROPOSED_EXTRA_NAMES; every name is used by at least one key of library/index.json): 8-way walk/run/sprint diagonals, sprint gaits, crouched locomotion and aim, standing turns, jump phases, pistol variants and death variants. extraClipNames is now coreExtraClipNames (23) plus converterExtraClipNames (45, sorted to diff against the converter's own sorted export). assertExtraClipVocabulary enforces the single source: the vocabulary must equal the core set plus the converter set, with no duplicates, state collisions or pattern breaks. The converter must import extraClipNames from this module instead of keeping its own copy (noted in docs/character-pack.md). Agent: Claude Code Signed-off-by: rubenmarcus --- docs/character-pack.md | 14 ++++++++--- tools/lib/character-pack.mjs | 48 +++++++++++++++++++++++++++++++++++- 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/docs/character-pack.md b/docs/character-pack.md index 7b8bc15..b2df6cf 100644 --- a/docs/character-pack.md +++ b/docs/character-pack.md @@ -49,15 +49,23 @@ Every file in `files` must be declared by exactly one role (`model`, `animations ## Optional clips (`animations.extra`) -`animations.extra` is an optional map of named clips beyond the states, for movement set, weapon handling, damage reactions, melee, round outcomes and emotes. Keys match `^[a-z][a-z0-9_]{1,40}$` and must be either a name from the fixed vocabulary below or an `emote_` prefix followed by at least one character. Anything else — including state names and the bare `emote_` prefix — is rejected. The vocabulary is `extraClipNames`/`extraClipPrefixes` in `tools/lib/character-pack.mjs`; the client mirrors it in `public/js/data/content-releases.js`. - -- Locomotion: `strafe_left`, `strafe_right`, `walk_back`, `run_back`, `strafe_left_pistol`, `strafe_right_pistol`, `walk_back_pistol` +`animations.extra` is an optional map of named clips beyond the states, for movement set, weapon handling, damage reactions, melee, round outcomes and emotes. Keys match `^[a-z][a-z0-9_]{1,40}$` and must be either a name from the fixed vocabulary below or an `emote_` prefix followed by at least one character. Anything else — including state names and the bare `emote_` prefix — is rejected. The vocabulary is `extraClipNames`/`extraClipPrefixes` in `tools/lib/character-pack.mjs` (68 names: `coreExtraClipNames` plus `converterExtraClipNames`); the client mirrors it in `public/js/data/content-releases.js`. + +- Locomotion (cardinals and diagonals; diagonals follow `__`): `strafe_left`, `strafe_right`, `walk_back`, `walk_fwd_left`, `walk_fwd_right`, `walk_back_left`, `walk_back_right`, `run_back`, `run_left`, `run_right`, `run_fwd_left`, `run_fwd_right`, `run_back_left`, `run_back_right` +- Sprint: `sprint`, `sprint_back`, `sprint_left`, `sprint_right`, `sprint_fwd_left`, `sprint_fwd_right`, `sprint_back_left`, `sprint_back_right` +- Crouched locomotion and aim: `crouchwalk_left`, `crouchwalk_right`, `crouchwalk_back`, `crouchwalk_fwd_left`, `crouchwalk_fwd_right`, `crouchwalk_back_left`, `crouchwalk_back_right`, `crouch_aim`, `crouch_pistol`, `crouch_turn_left`, `crouch_turn_right` +- Turns (standing): `turn_left`, `turn_right` +- Jump phases: `jump_start`, `jump_loop`, `jump_land`, `jump_pistol` +- Aim, pistol and crouch fire: `idle_aim`, `shoot_pistol`, `shoot_crouch`, `run_pistol`, `run_back_pistol`, `strafe_left_pistol`, `strafe_right_pistol`, `walk_back_pistol` - Weapon handling: `reload_rifle`, `reload_pistol`, `draw_rifle`, `holster_rifle`, `draw_pistol`, `holster_pistol` - Damage reactions: `hit_front`, `hit_back`, `hit_left`, `hit_right`, `hit_head` +- Death variants: `death_front`, `death_right`, `death_headshot_front`, `death_headshot_back`, `death_crouch` - Melee and utility: `grenade_throw`, `knife_idle`, `knife_stab` - Round outcomes: `victory`, `defeat` - Emotes: any key starting with `emote_` (for example `emote_danca`) +The converter group (`converterExtraClipNames`) is a snapshot of the names proposed by the animation conversion library (branch `feat/animation-conversion-20261109`, `tools/lib/animation-library.mjs`, 2026-11-09; every name is used by at least one key of its `library/index.json`). `assertExtraClipVocabulary` in `tools/lib/character-pack.mjs` enforces the single source: the vocabulary must equal the core names plus the converter set, with no duplicates, no state collisions and no pattern breaks; `tools/checks/character-pack-check.mjs` proves it against the real exports and synthetic mutants. The conversion tooling must import `extraClipNames` from `tools/lib/character-pack.mjs` instead of maintaining its own name list. + Each entry is an object with exactly five fields: `file` (a distinct `.glb` package path, declared in `files`), `duration` (seconds, positive), `loop` (boolean), `rootMotion` (boolean) and `source` (provenance string, for example the source animation and rig pipeline). `duration`, `loop` and `rootMotion` are declared metadata for the runtime; the GLB itself still carries the authoritative keyframes. A missing `extra` map is valid — optional means absent, not empty promises. ## meshy-28 diff --git a/tools/lib/character-pack.mjs b/tools/lib/character-pack.mjs index 01c3fdb..54e479b 100644 --- a/tools/lib/character-pack.mjs +++ b/tools/lib/character-pack.mjs @@ -8,15 +8,61 @@ export const optionalCharacterStates = Object.freeze(['idle1h', 'walk1h', 'walkf // Fixed names for locomotion, weapon handling, damage reactions, melee and round outcomes, // plus free-form emotes under the `emote_` prefix (at least one character after the prefix). // State names are never valid extra names, so the two key spaces stay disjoint. -export const extraClipNames = Object.freeze([ +export const coreExtraClipNames = Object.freeze([ 'strafe_left', 'strafe_right', 'walk_back', 'run_back', 'strafe_left_pistol', 'strafe_right_pistol', 'walk_back_pistol', 'reload_rifle', 'reload_pistol', 'draw_rifle', 'holster_rifle', 'draw_pistol', 'holster_pistol', 'hit_front', 'hit_back', 'hit_left', 'hit_right', 'hit_head', 'grenade_throw', 'knife_idle', 'knife_stab', 'victory', 'defeat', ]); +// Every name the animation conversion library proposes (branch feat/animation-conversion-20261109, +// tools/lib/animation-library.mjs PROPOSED_EXTRA_NAMES; snapshot 2026-11-09 — each name is used +// by at least one key of library/index.json). 8-way diagonals follow `__`; +// cardinal walk keeps strafe_left/strafe_right/walk_back and run backwards keeps run_back. Kept +// sorted to diff against the converter's own sorted export. The converter must import +// `extraClipNames` from this module as the single source instead of maintaining its own copy. +export const converterExtraClipNames = Object.freeze([ + 'crouch_aim', 'crouch_pistol', 'crouch_turn_left', 'crouch_turn_right', + 'crouchwalk_back', 'crouchwalk_back_left', 'crouchwalk_back_right', + 'crouchwalk_fwd_left', 'crouchwalk_fwd_right', 'crouchwalk_left', 'crouchwalk_right', + 'death_crouch', 'death_front', 'death_headshot_back', 'death_headshot_front', 'death_right', + 'idle_aim', 'jump_land', 'jump_loop', 'jump_pistol', 'jump_start', + 'run_back_left', 'run_back_pistol', 'run_back_right', 'run_fwd_left', 'run_fwd_right', + 'run_left', 'run_pistol', 'run_right', + 'shoot_crouch', 'shoot_pistol', 'sprint', 'sprint_back', 'sprint_back_left', 'sprint_back_right', + 'sprint_fwd_left', 'sprint_fwd_right', 'sprint_left', 'sprint_right', + 'turn_left', 'turn_right', + 'walk_back_left', 'walk_back_right', 'walk_fwd_left', 'walk_fwd_right', +]); +export const extraClipNames = Object.freeze([...coreExtraClipNames, ...converterExtraClipNames]); export const extraClipPrefixes = Object.freeze(['emote_']); +const extraClipKeyPattern = /^[a-z][a-z0-9_]{1,40}$/; +const stateNameSet = new Set([...requiredCharacterStates, ...optionalCharacterStates]); + +// Single-source invariant: the published vocabulary must equal the core contract names plus the +// converter set above. A name the converter proposes but the contract lacks, a dropped core name, +// a name outside both sets, a duplicate, a state collision or a pattern break all fail here. +// `tools/checks/character-pack-check.mjs` runs this against the real exports and against +// synthetic mutants; the converter branch runs it with its own proposed names once it adopts +// the import. +export function assertExtraClipVocabulary({ vocabulary = extraClipNames, converter = converterExtraClipNames } = {}) { + const seen = new Set(); + for (const name of vocabulary) { + if (seen.has(name)) throw new Error(`duplicate extra clip name in the vocabulary: ${name}`); + seen.add(name); + if (stateNameSet.has(name)) throw new Error(`extra clip name collides with a state name: ${name}`); + if (!extraClipKeyPattern.test(name)) throw new Error(`extra clip name breaks the key pattern: ${name}`); + } + const missing = converter.filter(name => !seen.has(name)); + if (missing.length) throw new Error(`converter clip names missing from the vocabulary: ${missing.join(', ')}`); + const lostCore = coreExtraClipNames.filter(name => !seen.has(name)); + if (lostCore.length) throw new Error(`core extra clip names missing from the vocabulary: ${lostCore.join(', ')}`); + const expected = new Set([...coreExtraClipNames, ...converter]); + const orphans = vocabulary.filter(name => !expected.has(name)); + if (orphans.length) throw new Error(`extra clip names outside the core and converter sets: ${orphans.join(', ')}`); +} + export function isExtraClipName(name) { return extraClipNames.includes(name) || extraClipPrefixes.some(prefix => name.length > prefix.length && name.startsWith(prefix)); From 6e689f465be5f4d6c340637f350875c3e95b3128 Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 04:31:35 +0000 Subject: [PATCH 04/10] Require the vocabulary to cover the converter set with mutants The synthetic fixture now carries a converter-named extra (sprint_fwd_left) alongside strafe_left and emote_danca, proving the new names validate end to end through the pack contract. New check cases: - PASS: assertExtraClipVocabulary on the real exports (68 names = 23 core + 45 converter) - Mutant: a converter key outside the vocabulary (vault_low) fails for the missing-name reason - Mutant: a vocabulary name outside the core and converter sets - Mutant: a dropped core name - Mutant: a duplicate vocabulary entry Agent: Claude Code Signed-off-by: rubenmarcus --- tools/checks/character-pack-check.mjs | 33 ++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/tools/checks/character-pack-check.mjs b/tools/checks/character-pack-check.mjs index e90ac50..c6601e1 100755 --- a/tools/checks/character-pack-check.mjs +++ b/tools/checks/character-pack-check.mjs @@ -5,7 +5,7 @@ import { createHash } from 'node:crypto'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { meshy28Joints, optionalCharacterStates, requiredCharacterStates } from '../lib/character-pack.mjs'; +import { assertExtraClipVocabulary, converterExtraClipNames, coreExtraClipNames, extraClipNames, meshy28Joints, optionalCharacterStates, requiredCharacterStates } from '../lib/character-pack.mjs'; import { validatePack } from '../lib/pack.mjs'; const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64'); @@ -128,6 +128,7 @@ function validFiles() { const files = { 'model/fixture-character.glb': modelGlb(), 'previews/portrait.png': png }; for (const state of allStates) files[`animations/${state}.glb`] = clipGlb(state); files['animations/extra/strafe-left.glb'] = clipGlb('strafe_left'); + files['animations/extra/sprint-fwd-left.glb'] = clipGlb('sprint_fwd_left'); files['animations/extra/emote-danca.glb'] = clipGlb('emote_danca'); return files; } @@ -147,6 +148,7 @@ function manifestFor(files) { extra: { strafe_left: { file: 'animations/extra/strafe-left.glb', duration: 0.8, loop: true, rootMotion: false, source: 'Synthetic strafe-left fixture clip' }, emote_danca: { file: 'animations/extra/emote-danca.glb', duration: 2.5, loop: false, rootMotion: false, source: 'Synthetic emote fixture clip' }, + sprint_fwd_left: { file: 'animations/extra/sprint-fwd-left.glb', duration: 0.7, loop: true, rootMotion: false, source: 'Synthetic converter-vocabulary fixture clip' }, }, }, previews: ['previews/portrait.png'], @@ -172,6 +174,18 @@ async function validateCase({ files = validFiles(), replace = {}, mutate = () => return validatePack({ manifestPath, packageRoot }); } +// Synchronous form of expectRejection for the pure vocabulary invariant (no pack fixture). +function expectVocabularyFailure(label, pattern, options) { + try { + assertExtraClipVocabulary(options); + } catch (caught) { + if (!pattern.test(caught.message)) throw new Error(`${label} was rejected for the wrong reason: ${caught.message}`); + console.log(`PASS ${label} rejected`); + return; + } + throw new Error(`${label} was not rejected`); +} + async function expectRejection(label, pattern, options) { let error; try { await validateCase(options); } catch (caught) { error = caught; } @@ -200,6 +214,23 @@ try { await validateCase({ replace: { 'animations/idle.glb': clipGlb('idle', { morph: 'valid' }) } }); console.log('PASS Valid clip with a bone channel plus a morph-weights channel'); + // Single-source vocabulary invariant: the contract vocabulary must equal the core names plus + // the animation conversion library's proposed names (snapshot in character-pack.mjs). + assertExtraClipVocabulary(); + console.log(`PASS Extra clip vocabulary covers the conversion library (${extraClipNames.length} names = ${coreExtraClipNames.length} core + ${converterExtraClipNames.length} converter)`); + expectVocabularyFailure('Converter key missing from the vocabulary', /converter clip names missing from the vocabulary: vault_low/, { + converter: [...converterExtraClipNames, 'vault_low'], + }); + expectVocabularyFailure('Vocabulary name outside the core and converter sets', /extra clip names outside the core and converter sets: moonwalk/, { + vocabulary: [...extraClipNames, 'moonwalk'], + }); + expectVocabularyFailure('Core name dropped from the vocabulary', /core extra clip names missing from the vocabulary: victory/, { + vocabulary: extraClipNames.filter(name => name !== 'victory'), + }); + expectVocabularyFailure('Duplicate vocabulary entry', /duplicate extra clip name in the vocabulary: sprint/, { + vocabulary: [...extraClipNames, 'sprint'], + }); + for (const state of requiredCharacterStates) { await expectRejection(`Missing required state ${state}`, new RegExp(`must have required property '${state}'`), { mutate: dropState(state) }); } From 7f108a73ef00624266240f4b96cc139b4e8a041e Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 07:29:54 +0000 Subject: [PATCH 05/10] Allow family packs and a shared states.glb in the character pack contract The animation converter now emits per character one GLB per family (states, loco, combat, ceremony) plus one GLB per emote. The contract accepts that layout without dropping the per-state/per-clip one: - several animations. roles may share one states pack whose clip names are the state names, and several animations.extra. roles may share one family-pack file whose clip names are the keys; a file can never mix state and extra roles, and emote keys always keep one file per key; - extra entries gain an optional family field (loco|combat|ceremony| emote) that must match clipFamily, a mirror of the converter's packFamily (that branch is stacked on this one, so the mirror is proven against a snapshot of its answers instead of an import); - every key must exist as an animation name inside its shared GLB, and shared animation GLBs are read once per file during validation. Agent: Claude Code Signed-off-by: rubenmarcus --- docs/character-pack.md | 26 +++++++++++++----- schemas/asset-pack.schema.json | 3 ++- tools/lib/character-pack.mjs | 49 +++++++++++++++++++++++++++++----- tools/lib/pack.mjs | 10 +++++-- 4 files changed, 72 insertions(+), 16 deletions(-) diff --git a/docs/character-pack.md b/docs/character-pack.md index b2df6cf..224a627 100644 --- a/docs/character-pack.md +++ b/docs/character-pack.md @@ -10,13 +10,13 @@ On top of the common fields (`schemaVersion`, `kind`, `id`, `version`, `source`, | --- | --- | | `model` | One package path ending in `.glb`: the rigged, skinned character. | | `skeleton` | `"meshy-28"` (see below). | -| `animations` | Object keyed by state. Required: `idle`, `walk`, `run`, `shoot`, `death`, `crouch`, `crouchwalk`, `jump`. Optional: `idle1h`, `walk1h`, `walkfire`, plus one optional `extra` map of named clips (see below). No other keys. Each state value is a distinct `.glb` path. | +| `animations` | Object keyed by state. Required: `idle`, `walk`, `run`, `shoot`, `death`, `crouch`, `crouchwalk`, `jump`. Optional: `idle1h`, `walk1h`, `walkfire`, plus one optional `extra` map of named clips (see below). No other keys. Each state value is a `.glb` path; states may each have their own file (the clip inside named exactly as the state) or all share one `states.glb` whose clip names are the state names. | | `previews` | At least one portrait image path (`.png`, `.jpg`, `.jpeg` or `.webp`). | | `rights` | `{ "status": "original" \| "public-domain" \| "political-satire", "basis": "", "references": ["", ...] }`; `references` is optional. | | `budgets` | `{ "triangles": , "bytes": }`. `triangles` bounds the model; `bytes` bounds the sum of every `files[].bytes`. | | `evidence` | Optional extra paths (for example a provenance sidecar). | -Every file in `files` must be declared by exactly one role (`model`, `animations.`, `animations.extra.`, `previews`, `evidence`) and every declared path must appear in `files`. Extra-clip files count toward `budgets.bytes` like any other file. +Every file in `files` must be declared by at least one role (`model`, `animations.`, `animations.extra.`, `previews`, `evidence`) and every declared path must appear in `files`. One role *kind* per file: several `animations.` roles may share one states-pack file, several `animations.extra.` roles may share one family-pack file, but a file can never be both a state file and an extra file, nor carry a non-animation role besides. Extra-clip files count toward `budgets.bytes` like any other file. ```json { @@ -28,8 +28,12 @@ Every file in `files` must be declared by exactly one role (`model`, `animations "files": [{ "path": "model/capitao-caveira.glb", "sha256": "…", "bytes": 1 }], "model": "model/capitao-caveira.glb", "skeleton": "meshy-28", - "animations": { "idle": "animations/idle.glb", "walk": "animations/walk.glb", "…": "…", - "extra": { "strafe_left": { "file": "animations/extra/strafe-left.glb", "duration": 0.9, "loop": true, "rootMotion": false, "source": "Mixamo Strafe Left retargeted to meshy-28" } } }, + "animations": { "idle": "animations/states.glb", "walk": "animations/states.glb", "…": "…", + "extra": { + "strafe_left": { "file": "animations/extra/loco.glb", "duration": 0.9, "loop": true, "rootMotion": false, "source": "Mixamo Strafe Left retargeted to meshy-28", "family": "loco" }, + "walk_back": { "file": "animations/extra/loco.glb", "duration": 1.2, "loop": true, "rootMotion": false, "source": "Mixamo Walk Back retargeted to meshy-28" }, + "emote_salute": { "file": "animations/extra/emote-salute.glb", "duration": 2.0, "loop": false, "rootMotion": false, "source": "Mixamo Salute retargeted to meshy-28", "family": "emote" } + } }, "previews": ["previews/portrait.jpg"], "rights": { "status": "original", "basis": "Invented character; concept prompt forbids likeness of real people and existing characters." }, "budgets": { "triangles": 6000, "bytes": 8388608 } @@ -43,7 +47,7 @@ Every file in `files` must be declared by exactly one role (`model`, `animations - The model is a GLB 2 container with in-bounds buffer views and accessors, finite positions and in-range indices. Every primitive is a triangle list (mode 4), and the triangle count must not exceed `budgets.triangles`. - The model has exactly one skin, and `inverseBindMatrices` holds one float `MAT4` per joint. Every skinned primitive has a `JOINTS_0` unsigned byte/short `VEC4` and a float or normalized `WEIGHTS_0` `VEC4` per vertex, and every joint index stays inside the skin. - The skin is exactly meshy-28: 28 joints whose (name, nearest joint ancestor) pairs match the list below as a multiset. -- Each animation GLB contains an animation named exactly as its state that drives at least one meshy-28 bone through a `translation`, `rotation` or `scale` channel. A `weights` channel must target a mesh with morph targets. Every sampler has at least one float keyframe time and the output type and count that match its interpolation (and, for `weights`, the number of morph targets). The same rules apply to every `animations.extra` clip, with the animation named exactly as its key. +- Each animation GLB contains an animation named exactly as its state (or extra key) that drives at least one meshy-28 bone through a `translation`, `rotation` or `scale` channel. A `weights` channel must target a mesh with morph targets. Every sampler has at least one float keyframe time and the output type and count that match its interpolation (and, for `weights`, the number of morph targets). When several states share one `states.glb`, or several extras share one family-pack file, each declared name must exist as an animation inside that shared GLB, and the GLB is read once per file, not once per clip. - Each preview starts with the PNG, JPEG or WebP signature for its extension. @@ -66,7 +70,15 @@ Every file in `files` must be declared by exactly one role (`model`, `animations The converter group (`converterExtraClipNames`) is a snapshot of the names proposed by the animation conversion library (branch `feat/animation-conversion-20261109`, `tools/lib/animation-library.mjs`, 2026-11-09; every name is used by at least one key of its `library/index.json`). `assertExtraClipVocabulary` in `tools/lib/character-pack.mjs` enforces the single source: the vocabulary must equal the core names plus the converter set, with no duplicates, no state collisions and no pattern breaks; `tools/checks/character-pack-check.mjs` proves it against the real exports and synthetic mutants. The conversion tooling must import `extraClipNames` from `tools/lib/character-pack.mjs` instead of maintaining its own name list. -Each entry is an object with exactly five fields: `file` (a distinct `.glb` package path, declared in `files`), `duration` (seconds, positive), `loop` (boolean), `rootMotion` (boolean) and `source` (provenance string, for example the source animation and rig pipeline). `duration`, `loop` and `rootMotion` are declared metadata for the runtime; the GLB itself still carries the authoritative keyframes. A missing `extra` map is valid — optional means absent, not empty promises. +Each entry is an object with exactly six fields: `file` (a `.glb` package path, declared in `files`), `duration` (seconds, positive), `loop` (boolean), `rootMotion` (boolean), `source` (provenance string, for example the source animation and rig pipeline) and the optional `family` (`"loco"`, `"combat"`, `"ceremony"` or `"emote"`). `duration`, `loop` and `rootMotion` are declared metadata for the runtime; the GLB itself still carries the authoritative keyframes. A missing `extra` map is valid — optional means absent, not empty promises. + +### Family packs + +Extras arrive the way the animation converter packs them (`tools/lib/clip-pack.mjs`, `character-clips@2`): one GLB per family — `states.glb` (the 11 runtime states), `loco.glb`, `combat.glb`, `ceremony.glb` — plus one GLB per emote. The contract accepts both this layout and the older one-file-per-clip layout: + +- Several non-emote keys may point at the same `file`; every key must then exist as an animation name inside that GLB, and all keys sharing a file must belong to one single family (`clipFamily` in `tools/lib/character-pack.mjs`, which mirrors the converter's `packFamily`; the check suite proves the mirror against a snapshot of the converter's own answers). A declared `family` must match the name's family. +- Emote keys always keep one file per key: an `emote_*` entry may never share its file with any other key. +- States may all point at one `states.glb` whose clip names are the state names; the per-state layout remains valid, and the two cannot mix files (`animations.` and `animations.extra.` are different role kinds). ## meshy-28 @@ -86,7 +98,7 @@ Photos of real people never enter either repository. ## Checks -`npm run check` builds a synthetic character pack (a programmatic 12-triangle skinned GLB, one-channel state clips and two extra clips, no real asset bytes), validates it, and requires each contract mutant to be rejected for its stated reason: missing states, unknown state, misnamed clip, clip driving no meshy-28 bone, clip channel without a path, clip without keyframes or with mismatched output, wrong skeleton id, renamed, reparented or missing bone, missing skin or weights, missing, mistyped or out-of-skin `JOINTS_0`, triangle strips, bad GLB magic or version, triangle and byte budgets (including the byte budget before hashing), bad rights, missing or invalid previews, undeclared files, hash or size mutations, and the extra-clip rules: unknown, pattern-violating, state-colliding or bare-prefix names, entries with missing or mistyped fields, non-GLB files, missing, duplicate or misnamed clip files, and extras pushing the pack over its byte budget. +`npm run check` builds a synthetic character pack (a programmatic 12-triangle skinned GLB, one-channel state clips, a loco family pack shared by two extras and a per-file extra, no real asset bytes), validates it — once per layout, including all states in one `states.glb` — and requires each contract mutant to be rejected for its stated reason: missing states, unknown state, misnamed clip, clip driving no meshy-28 bone, clip channel without a path, clip without keyframes or with mismatched output, wrong skeleton id, renamed, reparented or missing bone, missing skin or weights, missing, mistyped or out-of-skin `JOINTS_0`, triangle strips, bad GLB magic or version, triangle and byte budgets (including the byte budget before hashing), bad rights, missing or invalid previews, undeclared files, hash or size mutations, and the extra-clip rules: unknown, pattern-violating, state-colliding or bare-prefix names, entries with missing or mistyped fields, non-GLB files, missing, duplicate or misnamed clip files, extras pushing the pack over its byte budget, a key missing inside the family pack, an emote sharing any file, a declared family mismatching the clip name, a family outside the enum, one file mixing families, and a states pack missing a state clip. It also proves the `clipFamily` mirror against a snapshot of the converter's `packFamily` answers, including a poisoned-mirror mutant. `npm run check` also runs `tools/checks/character-rig-check.mjs`, the deterministic half of the Blender rig pipeline that produces these models (configs, `joints.json` validation, meshy-28 assembly, the pose test on a synthetic humanoid, and the runner's step freshness with a fake Blender); see [character-rig.md](character-rig.md). diff --git a/schemas/asset-pack.schema.json b/schemas/asset-pack.schema.json index 4652c9b..e3ecaa3 100644 --- a/schemas/asset-pack.schema.json +++ b/schemas/asset-pack.schema.json @@ -121,7 +121,8 @@ "duration": { "type": "number", "exclusiveMinimum": 0 }, "loop": { "type": "boolean" }, "rootMotion": { "type": "boolean" }, - "source": { "type": "string", "minLength": 1 } + "source": { "type": "string", "minLength": 1 }, + "family": { "enum": ["loco", "combat", "ceremony", "emote"] } }, "additionalProperties": false } diff --git a/tools/lib/character-pack.mjs b/tools/lib/character-pack.mjs index 54e479b..73ee0f5 100644 --- a/tools/lib/character-pack.mjs +++ b/tools/lib/character-pack.mjs @@ -40,6 +40,23 @@ export const extraClipPrefixes = Object.freeze(['emote_']); const extraClipKeyPattern = /^[a-z][a-z0-9_]{1,40}$/; const stateNameSet = new Set([...requiredCharacterStates, ...optionalCharacterStates]); +// Clip family of a name, mirroring the converter's `packFamily` (branch +// feat/animation-conversion-20261109, tools/lib/clip-pack.mjs). That branch is stacked on this +// one, so it cannot be imported here without a circular dependency; the mirror is kept honest by +// a snapshot parity check in tools/checks/character-pack-check.mjs, and the converter must import +// `clipFamily` from this module once it rebases. Two deliberate vocabulary differences: the +// contract says `emote` where the converter's pack id is `emotes` (emotes are never packed as a +// family file), and `states` is a valid answer here even though only the converter emits it. +export const extraClipFamilies = Object.freeze(['loco', 'combat', 'ceremony', 'emote']); +export function clipFamily(name) { + if (stateNameSet.has(name)) return 'states'; + if (name.startsWith('emote_')) return 'emote'; + if (/^(victory|defeat|death_)/.test(name)) return 'ceremony'; + if (/^(reload_|draw_|holster_|hit_|grenade_|knife_|shoot_)/.test(name)) return 'combat'; + return 'loco'; +} + + // Single-source invariant: the published vocabulary must equal the core contract names plus the // converter set above. A name the converter proposes but the contract lacks, a dropped core name, // a name outside both sets, a duplicate, a state collision or a pattern break all fail here. @@ -105,16 +122,31 @@ export function characterRoleEntries(manifest) { } // Extra-clip role entries. This is also the structural gate that rejects names outside the -// vocabulary (bare prefixes, state names, anything else) during validateManifestStructure, -// before any payload is hashed. +// vocabulary (bare prefixes, state names, anything else), wrong `family` declarations and illegal +// file sharing during validateManifestStructure, before any payload is hashed. Non-emote keys may +// share one family-pack file (all of them must belong to a single family, exactly like the +// converter packs them); emote keys always keep one file per key. export function characterExtraEntries(manifest) { const extras = manifest.animations?.extra; if (extras === undefined) return []; if (typeof extras !== 'object' || Array.isArray(extras)) throw new Error('animations.extra must be an object keyed by extra clip name'); const entries = []; + const namesByFile = new Map(); for (const [name, entry] of Object.entries(extras)) { if (!isExtraClipName(name)) throw new Error(`animations.extra has an unknown clip name: ${name}`); + if (entry?.family !== undefined && entry.family !== clipFamily(name)) { + throw new Error(`animations.extra.${name} declares family "${entry.family}" but its name belongs to "${clipFamily(name)}"`); + } entries.push({ role: `animations.extra.${name}`, path: entry?.file }); + namesByFile.set(entry?.file, [...(namesByFile.get(entry?.file) || []), name]); + } + for (const [file, names] of namesByFile) { + if (names.length < 2) continue; + if (names.some(name => name.startsWith('emote_'))) { + throw new Error(`animations.extra: emote clips keep one file per clip, but ${file} is shared by ${names.join(', ')}`); + } + const families = [...new Set(names.map(clipFamily))]; + if (families.length > 1) throw new Error(`animations.extra: ${file} mixes clip families (${families.join(' and ')})`); } return entries; } @@ -261,14 +293,19 @@ export async function validateCharacterPack(manifest, absolutes) { throw new Error(`${manifest.model}: ${model.triangles} triangles, over the ${manifest.budgets.triangles}-triangle budget`); } + // States may share one states.glb and extras may share one family-pack file, so every + // animation GLB is read once per file, not once per clip that points at it. + const documents = new Map(); + const animationDocument = async file => { + if (!documents.has(file)) documents.set(file, (await readGlb(absolutes.get(file), file)).document); + return documents.get(file); + }; for (const [state, file] of Object.entries(manifest.animations)) { if (state === 'extra') continue; - const { document } = await readGlb(absolutes.get(file), file); - assertStateAnimation(document, state, file); + assertStateAnimation(await animationDocument(file), state, file); } for (const [name, entry] of Object.entries(manifest.animations.extra || {})) { - const { document } = await readGlb(absolutes.get(entry.file), entry.file); - assertStateAnimation(document, name, entry.file); + assertStateAnimation(await animationDocument(entry.file), name, entry.file); } for (const file of manifest.previews) await assertImage(file, absolutes.get(file)); const states = Object.keys(manifest.animations).filter(key => key !== 'extra').length; diff --git a/tools/lib/pack.mjs b/tools/lib/pack.mjs index 6bc9139..d81f934 100644 --- a/tools/lib/pack.mjs +++ b/tools/lib/pack.mjs @@ -59,12 +59,18 @@ export function validateManifestStructure(manifest) { fileIndexes.set(file.path, index); } + // One role kind per file. Many `animations.` roles may share one state-pack file and + // many `animations.extra.` roles may share one family-pack file, but a file can never mix + // state and extra clips, nor take a non-animation role on the side. + const roleKind = role => (role.startsWith('animations.extra.') ? 'animations.extra' : role.startsWith('animations.') ? 'animations.state' : role); const roleOwners = new Map(); for (const entry of [...mapRoleEntries(manifest), ...characterRoleEntries(manifest)]) { assertPackageRelativePath(entry.path, `${entry.role} path`); assertNotExecutableJavaScript(entry.path); - if (roleOwners.has(entry.path)) { - throw new Error(`Duplicate declared path: ${entry.path} (${roleOwners.get(entry.path)} and ${entry.role})`); + const kind = roleKind(entry.role); + const owner = roleOwners.get(entry.path); + if (owner !== undefined && roleKind(owner) !== kind) { + throw new Error(`Duplicate declared path: ${entry.path} (${owner} and ${entry.role})`); } if (!fileIndexes.has(entry.path)) throw new Error(`Declared path is missing from files: ${entry.path}`); roleOwners.set(entry.path, entry.role); From 1ea580f92100475f3a13fdbb8986d2010c4b10fa Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 07:29:59 +0000 Subject: [PATCH 06/10] Require every family-pack rule with synthetic mutants The fixture now carries a loco family pack shared by two extras next to a per-file extra and proves both layouts valid, plus a states.glb pass case. New rejections, each for its stated reason: a key missing inside the family pack, an emote sharing any file (family or another emote), a declared family mismatching the clip name, a family outside the enum, one file mixing clip families, and a states pack missing a state clip. A snapshot parity table locks clipFamily to the converter's packFamily answers (83 names, emotes mapped to the contract family emote), with a poisoned-mirror mutant. Agent: Claude Code Signed-off-by: rubenmarcus --- tools/checks/character-pack-check.mjs | 140 ++++++++++++++++++++++++-- 1 file changed, 131 insertions(+), 9 deletions(-) diff --git a/tools/checks/character-pack-check.mjs b/tools/checks/character-pack-check.mjs index c6601e1..2f0d5f6 100755 --- a/tools/checks/character-pack-check.mjs +++ b/tools/checks/character-pack-check.mjs @@ -5,7 +5,7 @@ import { createHash } from 'node:crypto'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { assertExtraClipVocabulary, converterExtraClipNames, coreExtraClipNames, extraClipNames, meshy28Joints, optionalCharacterStates, requiredCharacterStates } from '../lib/character-pack.mjs'; +import { assertExtraClipVocabulary, clipFamily, converterExtraClipNames, coreExtraClipNames, extraClipNames, meshy28Joints, optionalCharacterStates, requiredCharacterStates } from '../lib/character-pack.mjs'; import { validatePack } from '../lib/pack.mjs'; const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64'); @@ -123,11 +123,38 @@ function clipGlb(name, { target = 'Hips', path: channelPath = 'rotation', keyfra }, chunks); } +// A family pack (or a states pack): several named clips sharing one GLB, all driving the Hips +// rotation channel, exactly how the converter merges per-clip GLBs into states/loco/combat/ +// ceremony files. +function clipsGlb(names) { + const nodes = skeletonNodes(meshy28Joints); + const targetNode = nodes.findIndex(node => node.name === 'Hips'); + return glb({ + scene: 0, + scenes: [{ nodes: [0] }], + nodes, + animations: names.map(name => ({ + name, + channels: [{ sampler: 0, target: { node: targetNode, path: 'rotation' } }], + samplers: [{ input: 0, output: 1, interpolation: 'LINEAR' }], + })), + accessors: [ + { bufferView: 0, componentType: 5126, count: 2, type: 'SCALAR', min: [0], max: [1] }, + { bufferView: 1, componentType: 5126, count: 2, type: 'VEC4' }, + ], + }, [ + { bytes: floats([0, 1]) }, + { bytes: floats([0, 0, 0, 1, 0, 0, 0, 1]) }, + ]); +} + const allStates = [...requiredCharacterStates, ...optionalCharacterStates]; function validFiles() { const files = { 'model/fixture-character.glb': modelGlb(), 'previews/portrait.png': png }; for (const state of allStates) files[`animations/${state}.glb`] = clipGlb(state); - files['animations/extra/strafe-left.glb'] = clipGlb('strafe_left'); + // strafe_left and walk_back share the loco family pack; sprint_fwd_left keeps the old + // one-file-per-clip layout; the emote keeps its own file. Family declared on some keys only. + files['animations/extra/loco.glb'] = clipsGlb(['strafe_left', 'walk_back']); files['animations/extra/sprint-fwd-left.glb'] = clipGlb('sprint_fwd_left'); files['animations/extra/emote-danca.glb'] = clipGlb('emote_danca'); return files; @@ -146,8 +173,9 @@ function manifestFor(files) { animations: { ...Object.fromEntries(allStates.map(state => [state, `animations/${state}.glb`])), extra: { - strafe_left: { file: 'animations/extra/strafe-left.glb', duration: 0.8, loop: true, rootMotion: false, source: 'Synthetic strafe-left fixture clip' }, - emote_danca: { file: 'animations/extra/emote-danca.glb', duration: 2.5, loop: false, rootMotion: false, source: 'Synthetic emote fixture clip' }, + strafe_left: { file: 'animations/extra/loco.glb', duration: 0.8, loop: true, rootMotion: false, source: 'Synthetic strafe-left fixture clip', family: 'loco' }, + walk_back: { file: 'animations/extra/loco.glb', duration: 1.1, loop: true, rootMotion: false, source: 'Synthetic walk-back fixture clip' }, + emote_danca: { file: 'animations/extra/emote-danca.glb', duration: 2.5, loop: false, rootMotion: false, source: 'Synthetic emote fixture clip', family: 'emote' }, sprint_fwd_left: { file: 'animations/extra/sprint-fwd-left.glb', duration: 0.7, loop: true, rootMotion: false, source: 'Synthetic converter-vocabulary fixture clip' }, }, }, @@ -214,6 +242,22 @@ try { await validateCase({ replace: { 'animations/idle.glb': clipGlb('idle', { morph: 'valid' }) } }); console.log('PASS Valid clip with a bone channel plus a morph-weights channel'); + // Every state may also come from one shared states pack whose clip names are the state names. + const statesPack = await validateCase({ + files: { + 'model/fixture-character.glb': modelGlb(), + 'previews/portrait.png': png, + 'animations/states.glb': clipsGlb(allStates), + 'animations/extra/loco.glb': clipsGlb(['strafe_left', 'walk_back']), + 'animations/extra/sprint-fwd-left.glb': clipGlb('sprint_fwd_left'), + 'animations/extra/emote-danca.glb': clipGlb('emote_danca'), + }, + mutate: manifest => { + for (const state of allStates) manifest.animations[state] = 'animations/states.glb'; + }, + }); + console.log(`PASS Valid character pack with all ${statesPack.character.animations} states in one states.glb`); + // Single-source vocabulary invariant: the contract vocabulary must equal the core names plus // the animation conversion library's proposed names (snapshot in character-pack.mjs). assertExtraClipVocabulary(); @@ -231,6 +275,48 @@ try { vocabulary: [...extraClipNames, 'sprint'], }); + + // Family parity: the contract mirror must classify every name exactly like the converter's + // packFamily. Snapshot generated 2026-11-09 by importing packFamily from + // feat/animation-conversion-20261109 tools/lib/clip-pack.mjs over every state, vocabulary and + // sample emote name; the converter's pack id `emotes` is the contract family `emote`. + const converterPackFamilies = Object.freeze({ + idle: 'states', walk: 'states', run: 'states', shoot: 'states', death: 'states', crouch: 'states', + crouchwalk: 'states', jump: 'states', idle1h: 'states', walk1h: 'states', walkfire: 'states', + strafe_left: 'loco', strafe_right: 'loco', walk_back: 'loco', run_back: 'loco', strafe_left_pistol: 'loco', + strafe_right_pistol: 'loco', walk_back_pistol: 'loco', reload_rifle: 'combat', reload_pistol: 'combat', + draw_rifle: 'combat', holster_rifle: 'combat', draw_pistol: 'combat', holster_pistol: 'combat', + hit_front: 'combat', hit_back: 'combat', hit_left: 'combat', hit_right: 'combat', hit_head: 'combat', + grenade_throw: 'combat', knife_idle: 'combat', knife_stab: 'combat', victory: 'ceremony', defeat: 'ceremony', + crouch_aim: 'loco', crouch_pistol: 'loco', crouch_turn_left: 'loco', crouch_turn_right: 'loco', + crouchwalk_back: 'loco', crouchwalk_back_left: 'loco', crouchwalk_back_right: 'loco', crouchwalk_fwd_left: 'loco', + crouchwalk_fwd_right: 'loco', crouchwalk_left: 'loco', crouchwalk_right: 'loco', death_crouch: 'ceremony', + death_front: 'ceremony', death_headshot_back: 'ceremony', death_headshot_front: 'ceremony', death_right: 'ceremony', + idle_aim: 'loco', jump_land: 'loco', jump_loop: 'loco', jump_pistol: 'loco', jump_start: 'loco', + run_back_left: 'loco', run_back_pistol: 'loco', run_back_right: 'loco', run_fwd_left: 'loco', run_fwd_right: 'loco', + run_left: 'loco', run_pistol: 'loco', run_right: 'loco', shoot_crouch: 'combat', shoot_pistol: 'combat', + sprint: 'loco', sprint_back: 'loco', sprint_back_left: 'loco', sprint_back_right: 'loco', sprint_fwd_left: 'loco', + sprint_fwd_right: 'loco', sprint_left: 'loco', sprint_right: 'loco', turn_left: 'loco', turn_right: 'loco', + walk_back_left: 'loco', walk_back_right: 'loco', walk_fwd_left: 'loco', walk_fwd_right: 'loco', + emote_salute: 'emotes', emote_danca: 'emotes', emote_breakdance_uprock: 'emotes', emote_capoeira_bencao: 'emotes', + }); + const assertFamilyParity = (classifier, label) => { + for (const [name, converter] of Object.entries(converterPackFamilies)) { + const expected = converter === 'emotes' ? 'emote' : converter; + if (classifier(name) !== expected) throw new Error(`${label}: family of ${name} is ${classifier(name)}, converter says ${expected}`); + } + }; + assertFamilyParity(clipFamily, 'Clip family mirror'); + console.log(`PASS Clip family mirror matches the converter's packFamily for ${Object.keys(converterPackFamilies).length} names`); + try { + assertFamilyParity(name => (name === 'hit_head' ? 'loco' : clipFamily(name)), 'Poisoned family mirror'); + throw new Error('Poisoned family mirror was not rejected'); + } catch (caught) { + if (!/Poisoned family mirror: family of hit_head is loco, converter says combat/.test(caught.message)) { + throw new Error(`Poisoned family mirror rejected for the wrong reason: ${caught.message}`); + } + console.log('PASS Poisoned family mirror rejected'); + } for (const state of requiredCharacterStates) { await expectRejection(`Missing required state ${state}`, new RegExp(`must have required property '${state}'`), { mutate: dropState(state) }); } @@ -246,7 +332,12 @@ try { await expectRejection('Morph weights channel on a mesh without morph targets', /animation "idle" has an invalid channel/, { replace: { 'animations/idle.glb': clipGlb('idle', { morph: 'no-targets' }) } }); await expectRejection('Clip without keyframes', /animation "death" has no keyframes/, { replace: { 'animations/death.glb': clipGlb('death', { keyframes: 0 }) } }); await expectRejection('Clip output count differs from keyframes', /output values that do not match its rotation keyframes/, { replace: { 'animations/crouch.glb': clipGlb('crouch', { keyframes: 2, outputValues: 1 }) } }); - await expectRejection('Same clip declared for two states', /Duplicate declared path/, { mutate: manifest => { manifest.animations.walk = manifest.animations.idle; } }); + await expectRejection('State pointed at another state per-state file', /animations\/idle\.glb: no animation named "walk"/, { + mutate: manifest => { + manifest.animations.walk = manifest.animations.idle; + manifest.files = manifest.files.filter(file => file.path !== 'animations/walk.glb'); + }, + }); await expectRejection('Unknown extra clip name', /animations\.extra has an unknown clip name: moonwalk/, { replace: { 'animations/extra/moonwalk.glb': clipGlb('moonwalk') }, mutate: manifest => { manifest.animations.extra.moonwalk = { file: 'animations/extra/moonwalk.glb', duration: 1, loop: false, rootMotion: false, source: 'Not in the vocabulary' }; }, @@ -262,8 +353,8 @@ try { replace: { 'animations/extra/Strafe-left.glb': clipGlb('strafe_left') }, mutate: manifest => { manifest.animations.extra.Strafe_left = { file: 'animations/extra/Strafe-left.glb', duration: 1, loop: true, rootMotion: false, source: 'Uppercase key' }; }, }); - await expectRejection('Extra clip file missing from files', /Declared path is missing from files: animations\/extra\/strafe-left\.glb/, { - mutate: manifest => { manifest.files = manifest.files.filter(file => file.path !== 'animations/extra/strafe-left.glb'); }, + await expectRejection('Family pack file missing from files', /Declared path is missing from files: animations\/extra\/loco\.glb/, { + mutate: manifest => { manifest.files = manifest.files.filter(file => file.path !== 'animations/extra/loco.glb'); }, }); await expectRejection('Extra clip file shared with a state', /Duplicate declared path: animations\/idle\.glb \(animations\.idle and animations\.extra\.strafe_left\)/, { mutate: manifest => { manifest.animations.extra.strafe_left.file = manifest.animations.idle; }, @@ -274,8 +365,39 @@ try { manifest.budgets.bytes = manifest.files.reduce((sum, file) => sum + file.bytes, 0) - extraBytes; }, }); - await expectRejection('Extra clip misnamed inside its GLB', /animations\/extra\/strafe-left\.glb: no animation named "strafe_left"/, { - replace: { 'animations/extra/strafe-left.glb': clipGlb('Strafe') }, + await expectRejection('Extra clip misnamed inside its one-clip file', /animations\/extra\/sprint-fwd-left\.glb: no animation named "sprint_fwd_left"/, { + replace: { 'animations/extra/sprint-fwd-left.glb': clipGlb('SprintFwdLeft') }, + }); + await expectRejection('Key missing inside the family pack', /animations\/extra\/loco\.glb: no animation named "walk_back"/, { + replace: { 'animations/extra/loco.glb': clipsGlb(['strafe_left']) }, + }); + await expectRejection('Emote clip sharing a family-pack file', /emote clips keep one file per clip, but animations\/extra\/loco\.glb is shared by /, { + mutate: manifest => { manifest.animations.extra.emote_danca.file = 'animations/extra/loco.glb'; }, + }); + await expectRejection('Emote clips sharing one file', /emote clips keep one file per clip/, { + mutate: manifest => { manifest.animations.extra.emote_salute = { ...manifest.animations.extra.emote_danca, file: manifest.animations.extra.emote_danca.file }; }, + }); + await expectRejection('Declared family mismatching the clip name', /animations\.extra\.strafe_left declares family "combat" but its name belongs to "loco"/, { + mutate: manifest => { manifest.animations.extra.strafe_left.family = 'combat'; }, + }); + await expectRejection('Family outside the contract enum', /animations\/extra\/strafe_left\/family must be equal to one of the allowed values/, { + mutate: manifest => { manifest.animations.extra.strafe_left.family = 'states'; }, + }); + await expectRejection('Family pack mixing clip families', /animations\/extra\/loco\.glb mixes clip families \(loco and combat\)/, { + mutate: manifest => { manifest.animations.extra.reload_rifle = { file: 'animations/extra/loco.glb', duration: 2, loop: false, rootMotion: false, source: 'Combat clip in a loco pack' }; }, + }); + await expectRejection('States pack missing one state clip', /animations\/states\.glb: no animation named "walkfire"/, { + files: { + 'model/fixture-character.glb': modelGlb(), + 'previews/portrait.png': png, + 'animations/states.glb': clipsGlb(allStates.filter(state => state !== 'walkfire')), + 'animations/extra/loco.glb': clipsGlb(['strafe_left', 'walk_back']), + 'animations/extra/sprint-fwd-left.glb': clipGlb('sprint_fwd_left'), + 'animations/extra/emote-danca.glb': clipGlb('emote_danca'), + }, + mutate: manifest => { + for (const state of allStates) manifest.animations[state] = 'animations/states.glb'; + }, }); await expectRejection('Extra clip file is not a GLB', /animations\/extra\/strafe_left\/file must match pattern/, { mutate: manifest => { manifest.animations.extra.strafe_left.file = 'animations/extra/strafe-left.gltf'; }, From f2a02de3498bf55f15eaa10daca98ccd9f9ef0d8 Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 07:45:27 +0000 Subject: [PATCH 07/10] Accept the converter's meshopt animation packs in the validator The real family GLBs (legacy-out capitao-caveira, character-clips@2) store buffer 0 as the EXT_meshopt_compression stream in the BIN chunk plus a virtual fallback buffer for the uncompressed view sizes, which the strict one-self-contained-buffer rule rejected. readGlb gains allowMeshoptFallback: animation reads accept that layout with the compressed stream ranges bounds-checked against the BIN chunk, while the model read stays strict because its skin bytes are read raw. Proved on the real pack (14 files, 4596362 bytes, 11 states, 74 extras across loco/combat/ceremony/emotes) and with synthetic cases: a meshopt-shaped family pack validates, the strict default still rejects it, a second buffer without the fallback marker is refused, and a stream past the BIN chunk is out of bounds. Agent: Claude Code Signed-off-by: rubenmarcus --- docs/character-pack.md | 1 + tools/checks/character-pack-check.mjs | 54 ++++++++++++++++++++++++++- tools/lib/character-pack.mjs | 6 ++- tools/lib/glb-inspect.mjs | 30 +++++++++++++-- 4 files changed, 83 insertions(+), 8 deletions(-) diff --git a/docs/character-pack.md b/docs/character-pack.md index 224a627..7169582 100644 --- a/docs/character-pack.md +++ b/docs/character-pack.md @@ -44,6 +44,7 @@ Every file in `files` must be declared by at least one role (`model`, `animation `node tools/validate-pack.mjs [package-root]` runs the schema, safe-path, role, size and SHA-256 checks shared by every pack. Before any payload is hashed, the sum of `files[].bytes` must not exceed `budgets.bytes`. It then reads the character bytes as data only (no renderer, no code execution): +- Animation GLBs may use the converter's `EXT_meshopt_compression` layout: buffer 0 is the compressed stream inside the BIN chunk and a virtual fallback buffer carries the uncompressed view sizes. Every compressed stream range is bounds-checked against the BIN chunk. The model keeps the strict single-buffer container, because the validator reads its skin bytes raw. - The model is a GLB 2 container with in-bounds buffer views and accessors, finite positions and in-range indices. Every primitive is a triangle list (mode 4), and the triangle count must not exceed `budgets.triangles`. - The model has exactly one skin, and `inverseBindMatrices` holds one float `MAT4` per joint. Every skinned primitive has a `JOINTS_0` unsigned byte/short `VEC4` and a float or normalized `WEIGHTS_0` `VEC4` per vertex, and every joint index stays inside the skin. - The skin is exactly meshy-28: 28 joints whose (name, nearest joint ancestor) pairs match the list below as a multiset. diff --git a/tools/checks/character-pack-check.mjs b/tools/checks/character-pack-check.mjs index 2f0d5f6..7b0aae8 100755 --- a/tools/checks/character-pack-check.mjs +++ b/tools/checks/character-pack-check.mjs @@ -6,6 +6,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { assertExtraClipVocabulary, clipFamily, converterExtraClipNames, coreExtraClipNames, extraClipNames, meshy28Joints, optionalCharacterStates, requiredCharacterStates } from '../lib/character-pack.mjs'; +import { readGlb } from '../lib/glb-inspect.mjs'; import { validatePack } from '../lib/pack.mjs'; const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64'); @@ -13,7 +14,7 @@ const sha256 = bytes => createHash('sha256').update(bytes).digest('hex'); const clone = value => JSON.parse(JSON.stringify(value)); const pad4 = bytes => Buffer.concat([bytes, Buffer.alloc((4 - (bytes.length % 4)) % 4)]); -function glb(document, chunks) { +function glb(document, chunks, extraBuffers = []) { const views = []; const parts = []; let offset = 0; @@ -24,7 +25,7 @@ function glb(document, chunks) { offset += padded.length; } const bin = Buffer.concat(parts); - const json = Buffer.from(JSON.stringify({ asset: { version: '2.0', generator: 'coro-solto-studio character-pack-check' }, ...document, buffers: [{ byteLength: bin.length }], bufferViews: views })); + const json = Buffer.from(JSON.stringify({ asset: { version: '2.0', generator: 'coro-solto-studio character-pack-check' }, ...document, buffers: [{ byteLength: bin.length }, ...extraBuffers], bufferViews: [...document.bufferViews ?? [], ...views] })); const paddedJson = Buffer.concat([json, Buffer.alloc((4 - (json.length % 4)) % 4, 0x20)]); const header = Buffer.alloc(20); header.writeUInt32LE(0x46546c67, 0); @@ -148,6 +149,34 @@ function clipsGlb(names) { ]); } +// The converter's EXT_meshopt_compression shape: buffer 0 holds the compressed stream (the +// BIN chunk), buffer 1 is the virtual fallback buffer, and every bufferView lives in the +// fallback with a compressed range pointing into buffer 0. +function meshoptClipsGlb(names, { markFallback = true, overshootStream = false } = {}) { + const nodes = skeletonNodes(meshy28Joints); + const targetNode = nodes.findIndex(node => node.name === 'Hips'); + const stream = Buffer.alloc(16, 7); + const secondHalf = overshootStream ? 16 : 8; + return glb({ + scene: 0, + scenes: [{ nodes: [0] }], + nodes, + animations: names.map(name => ({ + name, + channels: [{ sampler: 0, target: { node: targetNode, path: 'rotation' } }], + samplers: [{ input: 0, output: 1, interpolation: 'LINEAR' }], + })), + accessors: [ + { bufferView: 0, componentType: 5126, count: 2, type: 'SCALAR', min: [0], max: [1] }, + { bufferView: 1, componentType: 5126, count: 2, type: 'VEC4' }, + ], + bufferViews: [ + { buffer: 1, byteOffset: 0, byteLength: 8, extensions: { EXT_meshopt_compression: { buffer: 0, byteOffset: 0, byteLength: 8 } } }, + { buffer: 1, byteOffset: 8, byteLength: 32, extensions: { EXT_meshopt_compression: { buffer: 0, byteOffset: secondHalf, byteLength: secondHalf === 16 ? 16 : 8 } } }, + ], + }, [{ bytes: stream }], [{ byteLength: 40, ...(markFallback ? { extensions: { EXT_meshopt_compression: { fallback: true } } } : {}) }]); +} + const allStates = [...requiredCharacterStates, ...optionalCharacterStates]; function validFiles() { const files = { 'model/fixture-character.glb': modelGlb(), 'previews/portrait.png': png }; @@ -258,6 +287,21 @@ try { }); console.log(`PASS Valid character pack with all ${statesPack.character.animations} states in one states.glb`); + // The converter's meshopt family packs (fallback buffer + compressed streams) validate as + // animation files, while the raw model read keeps the strict single-buffer container. + await validateCase({ replace: { 'animations/extra/loco.glb': meshoptClipsGlb(['strafe_left', 'walk_back']) } }); + console.log('PASS Valid meshopt-compressed family pack accepted'); + const meshoptShape = path.join(directory, 'meshopt-shape.glb'); + fs.writeFileSync(meshoptShape, meshoptClipsGlb(['strafe_left'])); + await readGlb(meshoptShape, 'meshopt-shape.glb', { allowMeshoptFallback: true }); + try { + await readGlb(meshoptShape, 'meshopt-shape.glb'); + throw new Error('Strict readGlb accepted the meshopt fallback layout'); + } catch (caught) { + if (!/one self-contained buffer/.test(caught.message)) throw new Error(`Strict readGlb rejected for the wrong reason: ${caught.message}`); + } + console.log('PASS Strict readGlb still rejects the meshopt fallback layout (model path)'); + // Single-source vocabulary invariant: the contract vocabulary must equal the core names plus // the animation conversion library's proposed names (snapshot in character-pack.mjs). assertExtraClipVocabulary(); @@ -399,6 +443,12 @@ try { for (const state of allStates) manifest.animations[state] = 'animations/states.glb'; }, }); + await expectRejection('Second buffer without the meshopt fallback marker', /GLB validation failed for animations\/extra\/loco\.glb: GLB must contain one self-contained buffer/, { + replace: { 'animations/extra/loco.glb': meshoptClipsGlb(['strafe_left', 'walk_back'], { markFallback: false }) }, + }); + await expectRejection('Meshopt stream past the BIN chunk', /bufferView 1 has an out-of-bounds meshopt stream/, { + replace: { 'animations/extra/loco.glb': meshoptClipsGlb(['strafe_left', 'walk_back'], { overshootStream: true }) }, + }); await expectRejection('Extra clip file is not a GLB', /animations\/extra\/strafe_left\/file must match pattern/, { mutate: manifest => { manifest.animations.extra.strafe_left.file = 'animations/extra/strafe-left.gltf'; }, }); diff --git a/tools/lib/character-pack.mjs b/tools/lib/character-pack.mjs index 73ee0f5..982f076 100644 --- a/tools/lib/character-pack.mjs +++ b/tools/lib/character-pack.mjs @@ -294,10 +294,12 @@ export async function validateCharacterPack(manifest, absolutes) { } // States may share one states.glb and extras may share one family-pack file, so every - // animation GLB is read once per file, not once per clip that points at it. + // animation GLB is read once per file, not once per clip that points at it. Animation packs + // accept the converter's EXT_meshopt_compression fallback-buffer layout; the model does not + // (its skin bytes are read raw, so it keeps the strict single-buffer container). const documents = new Map(); const animationDocument = async file => { - if (!documents.has(file)) documents.set(file, (await readGlb(absolutes.get(file), file)).document); + if (!documents.has(file)) documents.set(file, (await readGlb(absolutes.get(file), file, { allowMeshoptFallback: true })).document); return documents.get(file); }; for (const [state, file] of Object.entries(manifest.animations)) { diff --git a/tools/lib/glb-inspect.mjs b/tools/lib/glb-inspect.mjs index e60e7de..5593282 100644 --- a/tools/lib/glb-inspect.mjs +++ b/tools/lib/glb-inspect.mjs @@ -18,7 +18,11 @@ function integer(value) { // Parses and bounds-checks the GLB 2 container, buffer views and accessors without // interpreting any scene content. Returns the JSON document and the BIN chunk bytes. -export async function readGlb(absolute, label = absolute) { +// `allowMeshoptFallback` also accepts the EXT_meshopt_compression layout the animation +// converter emits (buffer 0 = compressed stream in the BIN chunk, further buffers marked +// `EXT_meshopt_compression.fallback` = virtual uncompressed views that exist only logically); +// callers that read raw component bytes (the character model) keep the strict single buffer. +export async function readGlb(absolute, label = absolute, { allowMeshoptFallback = false } = {}) { const handle = await open(absolute, 'r'); try { const { size } = await handle.stat(); @@ -45,14 +49,32 @@ export async function readGlb(absolute, label = absolute) { if (!Array.isArray(document.accessors) || !Array.isArray(document.bufferViews) || !Array.isArray(document.buffers)) { fail(label, 'missing accessor, bufferView or buffer inventories'); } - if (document.buffers.length !== 1 || document.buffers[0].uri !== undefined || !integer(document.buffers[0].byteLength) || document.buffers[0].byteLength > binBytes) { + const meshoptFallback = allowMeshoptFallback && document.buffers.slice(1).every( + buffer => buffer.uri === undefined && integer(buffer.byteLength) + && buffer.extensions?.EXT_meshopt_compression?.fallback === true, + ); + if (document.buffers[0].uri !== undefined || !integer(document.buffers[0].byteLength) || document.buffers[0].byteLength > binBytes + || (document.buffers.length > 1 && !meshoptFallback)) { fail(label, 'GLB must contain one self-contained buffer within the BIN chunk'); } for (const [index, view] of document.bufferViews.entries()) { - if (view.buffer !== 0 || !integer(view.byteOffset ?? 0) || !integer(view.byteLength) || view.byteLength < 1) fail(label, `invalid bufferView ${index}`); + if (!integer(view.byteOffset ?? 0) || !integer(view.byteLength) || view.byteLength < 1) fail(label, `invalid bufferView ${index}`); const offset = view.byteOffset ?? 0; - if (offset + view.byteLength > document.buffers[0].byteLength || offset + view.byteLength > binBytes) fail(label, `bufferView ${index} exceeds its buffer`); + const compression = view.extensions?.EXT_meshopt_compression; + if (view.buffer === 0) { + if (offset + view.byteLength > document.buffers[0].byteLength || offset + view.byteLength > binBytes) fail(label, `bufferView ${index} exceeds its buffer`); + } else if (meshoptFallback && compression !== undefined + && document.buffers[view.buffer]?.extensions?.EXT_meshopt_compression?.fallback === true) { + // The bytes live in the compressed stream: bounds-check the stream range instead. + const streamOffset = compression.byteOffset ?? 0; + if (compression.buffer !== 0 || !integer(streamOffset) || !integer(compression.byteLength) || compression.byteLength < 1 + || streamOffset + compression.byteLength > document.buffers[0].byteLength) { + fail(label, `bufferView ${index} has an out-of-bounds meshopt stream`); + } + } else { + fail(label, `bufferView ${index} exceeds its buffer`); + } if (view.byteStride !== undefined && (!integer(view.byteStride) || view.byteStride < 4 || view.byteStride > 256 || view.byteStride % 4 !== 0)) { fail(label, `invalid byteStride on bufferView ${index}`); } From b914b85a1f379eb40e5557ecdbe0fdaf32107188 Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Tue, 10 Nov 2026 03:07:43 +0000 Subject: [PATCH 08/10] Repair the pilot's Curl influences without changing mesh or clips Keep the immutable pack repair separate from visual weapon-contact approval. Share the existing hand stretch ceiling and provide causal mutants. Agent: Claude Code Signed-off-by: rubenmarcus --- characters/capitao-caveira/grip.json | 11 ++ docs/character-rig.md | 59 ++++++++- tools/characters/repair-grip-pack.mjs | 138 +++++++++++++++++++++ tools/checks/character-grip-check.mjs | 168 ++++++++++++++++++++++++++ 4 files changed, 375 insertions(+), 1 deletion(-) create mode 100644 characters/capitao-caveira/grip.json create mode 100755 tools/characters/repair-grip-pack.mjs create mode 100755 tools/checks/character-grip-check.mjs diff --git a/characters/capitao-caveira/grip.json b/characters/capitao-caveira/grip.json new file mode 100644 index 0000000..c81bce7 --- /dev/null +++ b/characters/capitao-caveira/grip.json @@ -0,0 +1,11 @@ +{ + "id": "capitao-caveira", + "sourceSha256": "cbdc5595ceb2b4650b3c05b71c3bb379d53d2f1318111ddf66c1701d26ccdcbe", + "donorSha256": "acecd2a763dc417f6b132a2d555bffd2c6a5e7cf3b1a83a50ee24d938fce4b0f", + "units": "hand-local-metres", + "reference": "meshy-28 mst: Hand local +X flexion, +Y distal; Curl inherits Hand rotation. Existing tools/finger-curl.mjs uses a longitudinal weight ramp. No donor geometry or nearest-neighbour weights are copied.", + "hands": [ + { "hand": "LeftHand", "curl": "Curl_L", "knuckleY": 0.17, "fullY": 0.20, "palmY": 0.15, "thumbSign": -1, "thumbX": 0.075, "branchY": 0.185 }, + { "hand": "RightHand", "curl": "Curl_R", "knuckleY": 0.18, "fullY": 0.21, "palmY": 0.16, "thumbSign": 1, "thumbX": 0.075, "branchY": 0.195 } + ] +} diff --git a/docs/character-rig.md b/docs/character-rig.md index c67de76..74d34e6 100644 --- a/docs/character-rig.md +++ b/docs/character-rig.md @@ -122,5 +122,62 @@ The plush mascot keeps human-like clip motion: idle, walk, run, crouch, crouchwa - `shoulderAt: "junction"`, `spineDepth`, `thighCeiling`/`clavicleFloor` and a larger `gradientRamp` (0.04) are per-character levers, not defaults: on the 37-character set of 2026-11-09 each fixed some rigs and broke others when applied to all (junction shoulders: 7 passing rigs failed; `spineDepth` 0.4 worsened barbudo-creepy and bebezao-de-feira). - Heat weighting can fail on non-manifold meshes; the voxel proxy covers it, but check `weights.json` (`method`, `heat.unweightedVertices`). - Hips translation and in-place motion come from `retarget-glb.mjs`; this pipeline does not author clips. -- `Curl_L`/`Curl_R` carry no skin (hands are 100% `Hand`), as in the rigs from `rig-from-donor.mjs`: the client's grip curl rotates those bones but the fingers do not close around the weapon. +- The Blender weights still treat `Curl_L`/`Curl_R` as non-deforming. A body pose PASS is **not** a playable-hand approval. The explicit offline pilot repair below is required before evaluating capitao-caveira's grip; it is not enabled for the other characters. - The pipeline run (`rig-character.mjs`) fails when the pose test fails (`--strict`); `--no-clips` limits it to the synthetic poses. + +## Offline grip prerequisite — capitao-caveira only + +`characters/capitao-caveira/grip.json` pins the exact 0.2.0 mesh and donor hashes. +The existing client's `tools/finger-curl.mjs` establishes the longitudinal weight +ramp and positive local-X curl convention, but its world/local offset and IBM +calculations must not be copied onto the centimetre skeleton. This repair computes +the new inverse bind matrix from the complete actual joint hierarchy. + +Measured in Hand-local metres, the pilot's four non-thumb fingers separate into +four welded-position components past Y=0.185 (left) / 0.195 (right). The annotation +places their shared hinge at Y=0.17 / 0.18 and smoothly transfers only existing +Hand weight to the first corresponding Curl. Palm Y<=0.15 / 0.16 and thumb-side +X<=-0.075 / X>=0.075 remain untouched. No geometry, normals, UV, topology, +material, image, rights or animation bytes are regenerated. Duplicate Curl joints +remain in contract order, parented to Hand, with the unused copies unweighted. +This is one bend per finger, matching the existing meshy-28 mechanism, not a new +fully articulated finger rig. + +From this Studio worktree, with `BASE` pointing at the local character pack root +and `DONOR` at the client's existing `public/models/characters/mst.glb`: + +```sh +node tools/characters/repair-grip-pack.mjs \ + "$BASE/capitao-caveira/0.2.0" "$BASE/capitao-caveira/0.2.1" \ + characters/capitao-caveira/grip.json "$DONOR" \ + "$BASE/capitao-caveira/grip-0.2.1.json" +node tools/checks/character-grip-check.mjs \ + "$BASE/capitao-caveira/0.2.0/model/capitao-caveira.glb" \ + "$BASE/capitao-caveira/0.2.1/model/capitao-caveira.glb" \ + characters/capitao-caveira/grip.json --mutants +``` + +The builder refuses existing output/report paths, altered source/donor hashes, +unsupported skin encodings or missing weight slots. Before publication it runs +the causal numeric gate and validates the full original and new packs, including +the unchanged complete eleven-state clip file. It records exact commands, source, +tool and annotation hashes, output manifest/model hashes, donor influences and +per-finger measurements outside the pack. Local version 0.2.0 is immutable. + +The gate rejects zero finger influence, rotation of palm/thumb, wrong flexion +frame/sign, bind error above 0.1 mm, geometry/attribute/topology changes, unrelated +weight changes, or curl edge stretch above 2.5x. All four fingers must move inward +at both runtime endpoint curls (0.55 and 0.95 rad). `--mutants` includes the actual +zero-weight source, changed silhouette, palm-as-finger and reversed-frame defects. +Passing establishes only a real deformation prerequisite: the parent must render +the pilot with the actual AK and obtain independent visual acceptance. Do not +publish/integrate the remaining 29 or generalize an annotation across characters. + +The hand edge ceiling is shared with `POSE_THRESHOLDS.synthetic.handMaxEdge` in +`tools/lib/character-rig.mjs`, not a new aesthetic threshold. Its existing RM1 +provenance is documented there; the calibration table above records mst hand +L/R=1.68x/1.30x on shared clips, measured by `tools/characters/rig-pose-test.mjs`. +The grip production report records the additional synthetic Curl endpoints: +left 1.484x and right 1.747x maximum at 0.95 rad. None of these numbers approves +actual AK contact or replaces the parent browser/visual evaluation. + diff --git a/tools/characters/repair-grip-pack.mjs b/tools/characters/repair-grip-pack.mjs new file mode 100755 index 0000000..f518a20 --- /dev/null +++ b/tools/characters/repair-grip-pack.mjs @@ -0,0 +1,138 @@ +#!/usr/bin/env node +// Patch only pilot Hand→Curl influences and Curl bind frames. Never regenerate mesh data. +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { NodeIO } from '@gltf-transform/core'; +import { ALL_EXTENSIONS } from '@gltf-transform/extensions'; +import { cloneDocument } from '@gltf-transform/functions'; +import { assertGrip, handRegion } from '../checks/character-grip-check.mjs'; +import { loadRig, worldMatrices } from '../lib/character-rig.mjs'; +import { validatePack } from '../lib/pack.mjs'; +import { readGlb } from '../lib/glb-inspect.mjs'; + +const [sourcePack, targetPack, annotation, donorPath, reportPath] = process.argv.slice(2); +assert(sourcePack && targetPack && annotation && donorPath && reportPath, + 'usage: repair-grip-pack.mjs '); +const sha = bytes => createHash('sha256').update(bytes).digest('hex'); +const config = JSON.parse(readFileSync(annotation, 'utf8')); +assert(!existsSync(targetPack), 'immutable target pack already exists'); +assert(!existsSync(reportPath), 'immutable report already exists'); +const originalManifestBytes = readFileSync(path.join(sourcePack, 'manifest.json')); +const manifest = JSON.parse(originalManifestBytes); +assert.equal(manifest.id, config.id); assert.equal(manifest.version, '0.2.0'); +assert.equal(path.basename(targetPack), '0.2.1', 'pilot output must be a new 0.2.1 pack'); +const sourceBytes = readFileSync(path.join(sourcePack, manifest.model)); +assert.equal(sha(sourceBytes), config.sourceSha256, 'unsupported source geometry; author a new annotation'); +const donorBytes = readFileSync(donorPath); +assert.equal(sha(donorBytes), config.donorSha256, 'donor changed'); +const io = new NodeIO().registerExtensions(ALL_EXTENSIONS); +const original = await io.readBinary(sourceBytes), rig = loadRig(original); +const donor = loadRig(await io.readBinary(donorBytes)); +const donorInfluences = {}; +for (const h of config.hands) { + const slots = donor.names.flatMap((n, i) => n === h.curl ? [i] : []); + donorInfluences[h.curl] = donor.prims.reduce((total, p) => total + Array.from({ length: p.count }, (_, v) => + [0, 1, 2, 3].some(k => slots.includes(p.J[v * 4 + k]) && p.W[v * 4 + k] > 0.001) ? 1 : 0).reduce((a, b) => a + b, 0), 0); + assert(donorInfluences[h.curl] > 32, 'reference donor has no working Curl deformation'); + const hand = donor.joints[donor.names.indexOf(h.hand)], curl = donor.joints[slots[0]]; + assert(hand.listChildren().includes(curl), 'unsupported reference Curl hierarchy'); + assert(curl.getRotation().slice(0, 3).every(v => Math.abs(v) < 1e-6), 'unsupported reference flexion frame'); +} +assert.equal(rig.prims.length, 1); assert.equal(rig.joints.length, 28); +// Preserve the original GLB JSON and BIN verbatim except precisely allowed edits. Using the +// exporter here would needlessly rewrite geometry, UV, texture/material and clip bytes. +assert.equal(sourceBytes.readUInt32LE(0), 0x46546c67); assert.equal(sourceBytes.readUInt32LE(4), 2); +const jsonLength = sourceBytes.readUInt32LE(12), json = JSON.parse(sourceBytes.subarray(20, 20 + jsonLength)); +const binStart = 20 + jsonLength + 8, bin = Buffer.from(sourceBytes.subarray(binStart)); +assert.equal(sourceBytes.readUInt32LE(20 + jsonLength + 4), 0x004e4942); +assert(!json.extensionsRequired?.length, 'compressed/extended source requires a separate repair'); +const skin = json.skins[0], primitive = json.meshes[0].primitives[0]; +const allowedBytes = new Uint8Array(bin.length); +function writeElement(index, row, values) { + const a = json.accessors[index], view = json.bufferViews[a.bufferView]; + const size = { 5121: 1, 5123: 2, 5126: 4 }[a.componentType]; + assert(size && !a.normalized && !a.sparse, 'unsupported skin accessor encoding'); + const offset = (view.byteOffset || 0) + (a.byteOffset || 0) + row * (view.byteStride || values.length * size); + values.forEach((value, k) => { + const at = offset + k * size; + if (a.componentType === 5126) bin.writeFloatLE(value, at); + else if (a.componentType === 5123) bin.writeUInt16LE(value, at); + else bin.writeUInt8(value, at); + allowedBytes.fill(1, at, at + size); + }); +} +const working = cloneDocument(original), workRig = loadRig(working); +for (const h of config.hands) { + assert(h.palmY < h.knuckleY && h.knuckleY < h.fullY && h.branchY > h.knuckleY); + const region = handRegion(rig, h), { hi, ci, points, members, scale } = region; + assert(Math.abs(scale - 0.01) < 1e-9, 'annotation expects centimetre skeleton, metre mesh'); + for (const p of rig.prims) for (let v = 0; v < p.count; v++) for (let k = 0; k < 4; k++) { + assert(!(rig.names[p.J[v * 4 + k]].startsWith('Curl_') && p.W[v * 4 + k] > 0), 'source already has finger weights'); + } + const curl = workRig.joints[ci]; curl.setTranslation([0, h.knuckleY / scale, 0]).setRotation([0, 0, 0, 1]); + // Both duplicate Curl joints stay children of Hand; only the first becomes deforming. + // This preserves the meshy-28 joint order/hierarchy and the existing runtime discovery. + json.nodes[skin.joints[ci]].translation = curl.getTranslation(); + json.nodes[skin.joints[ci]].rotation = curl.getRotation(); + const p = rig.prims[0]; + for (let v = 0; v < p.count; v++) { + const q = points[v]; + if (!members[v] || q.y <= h.knuckleY || q.x * h.thumbSign >= h.thumbX) continue; + const js = Array.from(p.J.slice(v * 4, v * 4 + 4)), ws = Array.from(p.W.slice(v * 4, v * 4 + 4)); + const slot = js.findIndex((j, k) => j === hi && ws[k] > 0), free = ws.findIndex(w => w === 0); + assert(slot >= 0 && free >= 0, 'finger needs an available skin slot; never discard unrelated influences'); + const t = Math.min(1, (q.y - h.knuckleY) / (h.fullY - h.knuckleY)); + const moved = ws[slot] * t * t * (3 - 2 * t); + ws[slot] -= moved; js[free] = ci; ws[free] = moved; + writeElement(primitive.attributes.JOINTS_0, v, js); + writeElement(primitive.attributes.WEIGHTS_0, v, ws); + } + // Compute IBM from the complete parent chain; no world-space offsets in local space. + const updated = loadRig(working), inverse = worldMatrices(updated)(updated.joints[ci]).clone().invert(); + writeElement(skin.inverseBindMatrices, ci, inverse.elements); +} +// All payload bytes outside explicitly changed weight/IBM elements are identical. +const oldBin = sourceBytes.subarray(binStart); +for (let i = 0; i < bin.length; i++) if (!allowedBytes[i]) assert.equal(bin[i], oldBin[i], `unexpected binary change ${i}`); +const jsonBytes = Buffer.from(JSON.stringify(json)), pad = (4 - jsonBytes.length % 4) % 4; +const header = Buffer.alloc(20); header.writeUInt32LE(0x46546c67, 0); header.writeUInt32LE(2, 4); +header.writeUInt32LE(20 + jsonBytes.length + pad + 8 + bin.length, 8); +header.writeUInt32LE(jsonBytes.length + pad, 12); header.writeUInt32LE(0x4e4f534a, 16); +const binHeader = Buffer.alloc(8); binHeader.writeUInt32LE(bin.length, 0); binHeader.writeUInt32LE(0x004e4942, 4); +const result = Buffer.concat([header, jsonBytes, Buffer.alloc(pad, 32), binHeader, bin]); +const measurements = assertGrip(original, await io.readBinary(result), config); +// Validate the complete original before publication, not just the rewritten model. +await validatePack({ manifestPath: path.join(sourcePack, 'manifest.json') }); +const states = await readGlb(path.join(sourcePack, manifest.animations.idle), 'states', { allowMeshoptFallback: true }); +const clipNames = states.document.animations.map(a => a.name); +assert.equal(clipNames.length, 11, 'existing complete 11-state clip pack required'); +manifest.version = '0.2.1'; +manifest.source.provenance.push(`Offline pilot Curl repair: ${config.id}/grip.json; source model ${config.sourceSha256}; donor ${config.donorSha256}; palm/thumb and all non-skin payload bytes unchanged. Numeric prerequisite only; visual approval pending.`); +const entry = manifest.files.find(f => f.path === manifest.model); entry.sha256 = sha(result); entry.bytes = result.length; +mkdirSync(path.dirname(targetPack), { recursive: true }); +const temporary = mkdtempSync(path.join(path.dirname(targetPack), '.grip-pack-')); +try { + cpSync(sourcePack, temporary, { recursive: true }); + writeFileSync(path.join(temporary, manifest.model), result); + const manifestBytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`); + writeFileSync(path.join(temporary, 'manifest.json'), manifestBytes); + await validatePack({ manifestPath: path.join(temporary, 'manifest.json') }); + for (const f of manifest.files) if (f.path !== manifest.model) { + assert.equal(sha(readFileSync(path.join(temporary, f.path))), sha(readFileSync(path.join(sourcePack, f.path))), 'non-model pack payload changed'); + } + assert(!existsSync(targetPack), 'immutable target appeared during repair'); + renameSync(temporary, targetPack); + const report = { + status: 'numeric-prerequisite-only-visual-review-required', command: [process.execPath, ...process.argv.slice(1)], + toolSha256: sha(readFileSync(fileURLToPath(import.meta.url))), annotationSha256: sha(readFileSync(annotation)), + sourcePack, sourceManifestSha256: sha(originalManifestBytes), outputPack: targetPack, + manifestSha256: sha(manifestBytes), modelSha256: sha(result), donorInfluences, clipNames, + preserved: ['geometry', 'topology', 'UV', 'normals', 'materials', 'images', 'rights', 'all animation files', 'joint hierarchy/order'], + measurements, + }; + writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, { flag: 'wx' }); + console.log(JSON.stringify(report, null, 2)); +} finally { rmSync(temporary, { recursive: true, force: true }); } diff --git a/tools/checks/character-grip-check.mjs b/tools/checks/character-grip-check.mjs new file mode 100755 index 0000000..aa88300 --- /dev/null +++ b/tools/checks/character-grip-check.mjs @@ -0,0 +1,168 @@ +#!/usr/bin/env node +// Offline prerequisite only. This is not a visual/weapon-contact approval. +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { NodeIO } from '@gltf-transform/core'; +import { ALL_EXTENSIONS } from '@gltf-transform/extensions'; +import { cloneDocument } from '@gltf-transform/functions'; +import * as THREE from 'three'; +import { loadRig, POSE_THRESHOLDS, skinPositions, worldMatrices } from '../lib/character-rig.mjs'; + +// Inherit, do not invent, the existing hand-edge ceiling from character-rig.mjs:384-390. +// Calibration: docs/character-rig.md:97-104 records mst hand L/R 1.68x/1.30x, +// measured by rig-pose-test.mjs and compared with the original client RM1 hand gate. +const handEdgeLimit = POSE_THRESHOLDS.synthetic.handMaxEdge; +const same = (a, b, message) => assert.deepEqual(Array.from(a), Array.from(b), message); +const distance = (a, b, v) => Math.hypot(...[0, 1, 2].map(k => a[v * 3 + k] - b[v * 3 + k])); +export function handRegion(rig, config) { + const hi = rig.names.indexOf(config.hand), ci = rig.names.indexOf(config.curl); + assert(hi >= 0 && ci >= 0, 'missing Hand/Curl'); + const inverse = worldMatrices(rig)(rig.joints[hi]).clone().invert(); + const scale = new THREE.Vector3().setFromMatrixScale(worldMatrices(rig)(rig.joints[hi])).x; + const p = rig.prims[0]; + const points = [], members = []; + for (let v = 0; v < p.count; v++) { + points.push(new THREE.Vector3().fromArray(p.pos, v * 3).applyMatrix4(inverse).multiplyScalar(scale)); + members.push([0, 1, 2, 3].reduce((sum, k) => sum + (p.J[v * 4 + k] === hi ? p.W[v * 4 + k] : 0), 0) > 0.5); + } + return { hi, ci, points, members, scale }; +} +function branches(rig, region, config) { + // Weld position duplicates only for the measurement; never change exported topology. + const p = rig.prims[0], keys = new Map(), weld = []; + for (let v = 0; v < p.count; v++) { + const key = Array.from(p.pos.slice(v * 3, v * 3 + 3), x => x.toFixed(6)).join(','); + if (!keys.has(key)) keys.set(key, keys.size); + weld.push(keys.get(key)); + } + const selected = region.points.map((q, v) => region.members[v] && q.y > config.branchY && q.x * config.thumbSign < config.thumbX); + const adj = new Map(); + assert(p.idx, 'finger topology requires indexed triangles'); + for (let t = 0; t < p.idx.length; t += 3) for (let e = 0; e < 3; e++) { + const a = p.idx[t + e], b = p.idx[t + (e + 1) % 3]; + if (!selected[a] || !selected[b]) continue; + if (!adj.has(weld[a])) adj.set(weld[a], new Set()); + if (!adj.has(weld[b])) adj.set(weld[b], new Set()); + adj.get(weld[a]).add(weld[b]); adj.get(weld[b]).add(weld[a]); + } + const seen = new Set(), components = []; + for (const start of adj.keys()) { + if (seen.has(start)) continue; + const stack = [start], ids = new Set([start]); seen.add(start); + while (stack.length) for (const next of adj.get(stack.pop())) { + if (!seen.has(next)) { seen.add(next); ids.add(next); stack.push(next); } + } + components.push(weld.flatMap((w, v) => ids.has(w) ? [v] : [])); + } + assert.equal(components.length, 4, `${config.hand}: annotation must isolate four fingers (not the thumb)`); + assert(components.every(c => c.length >= 8), 'finger component too small'); + return components; +} +export function assertGrip(before, after, config) { + const a = loadRig(before), b = loadRig(after); + assert.equal(a.prims.length, 1, 'pilot annotation requires one primitive'); + assert.equal(b.prims.length, 1, 'primitive count changed'); + same(a.prims[0].pos, b.prims[0].pos, 'base shape changed'); + same(a.prims[0].idx, b.prims[0].idx, 'topology changed'); + assert.deepEqual(a.names, b.names, 'joint order/names changed'); + const ma = before.getRoot().listMeshes()[0].listPrimitives()[0], mb = after.getRoot().listMeshes()[0].listPrimitives()[0]; + assert.deepEqual(ma.listSemantics(), mb.listSemantics(), 'attribute semantics changed'); + for (const semantic of ma.listSemantics()) if (!['JOINTS_0', 'WEIGHTS_0'].includes(semantic)) { + same(ma.getAttribute(semantic).getArray(), mb.getAttribute(semantic).getArray(), `${semantic} changed`); + } + const bindA = skinPositions(a)[0], bindB = skinPositions(b)[0], p = b.prims[0]; + let bindError = 0; + for (let v = 0; v < p.count; v++) { + bindError = Math.max(bindError, distance(bindA, bindB, v)); + const sum = [0, 1, 2, 3].reduce((s, k) => s + p.W[v * 4 + k], 0); + assert(Math.abs(sum - 1) < 1e-5, 'weight mass lost'); + } + assert(bindError < 0.0001, `bind shape error ${bindError}`); + const result = { bindError, hands: [] }, allowed = new Set(); + for (const h of config.hands) { + const region = handRegion(a, h), { hi, ci, points, members } = region; + const fingers = branches(a, region, h); + let influenced = 0; + const weight = (rig, v, j) => [0, 1, 2, 3].reduce((s, k) => s + (rig.prims[0].J[v * 4 + k] === j ? rig.prims[0].W[v * 4 + k] : 0), 0); + for (let v = 0; v < p.count; v++) { + const q = points[v], protectedVertex = !members[v] || q.y <= h.palmY || q.x * h.thumbSign >= h.thumbX; + const cw = weight(b, v, ci); + if (cw > 1e-5) { + influenced++; allowed.add(v); + assert(!protectedVertex, `${h.hand}: palm/thumb acquired Curl influence`); + } + assert(Math.abs(weight(a, v, hi) - weight(b, v, hi) - cw) < 1e-5, 'Curl mass must come only from Hand'); + } + assert(influenced > 32, `${h.hand}: zero/insufficient finger influence`); + const bends = []; + for (const angle of [0.55, 0.95]) { + const node = b.joints[ci], trs = b.trs.get(node); + const euler = new THREE.Euler().setFromQuaternion(new THREE.Quaternion(...trs.r), 'XYZ'); euler.x += angle; + const overrides = new Map([[node, { ...trs, r: new THREE.Quaternion().setFromEuler(euler).toArray() }]]); + const bent = skinPositions(b, overrides)[0]; + const inv = worldMatrices(b)(b.joints[hi]).clone().invert(); + const moving = fingers.map(group => { + const deltas = group.map(v => { + const rest = new THREE.Vector3().fromArray(bindB, v * 3).applyMatrix4(inv).multiplyScalar(region.scale); + const curl = new THREE.Vector3().fromArray(bent, v * 3).applyMatrix4(inv).multiplyScalar(region.scale); + return { displacement: curl.distanceTo(rest), inward: curl.z - rest.z, shortening: rest.y - curl.y }; + }); + const mean = field => deltas.reduce((s, d) => s + d[field], 0) / deltas.length; + assert(mean('displacement') > 0.005, `${h.hand}: inert finger`); + assert(mean('inward') > 0.003 && mean('shortening') > 0.001, `${h.hand}: wrong flexion frame/sign`); + return { vertices: group.length, meanDisplacement: mean('displacement'), inward: mean('inward') }; + }); + let protectedMotion = 0, maxEdge = 1; + for (let v = 0; v < p.count; v++) if (!members[v] || points[v].y <= h.palmY || points[v].x * h.thumbSign >= h.thumbX) { + protectedMotion = Math.max(protectedMotion, distance(bindB, bent, v)); + } + assert(protectedMotion < 0.0001, `${h.hand}: curl rotates palm/thumb/body`); + for (let t = 0; t < p.idx.length; t += 3) for (let e = 0; e < 3; e++) { + const i = p.idx[t + e], j = p.idx[t + (e + 1) % 3]; + const len = data => Math.hypot(...[0, 1, 2].map(k => data[i * 3 + k] - data[j * 3 + k])); + if (len(bindB) > 0.0001) maxEdge = Math.max(maxEdge, len(bent) / len(bindB)); + } + assert(maxEdge <= handEdgeLimit, `${h.hand}: curl tears topology ${maxEdge}x (existing hand ceiling ${handEdgeLimit}x)`); + bends.push({ angle, moving, protectedMotion, maxEdge }); + } + result.hands.push({ hand: h.hand, influenced, bends }); + } + // Outside the authored finger region every original influence must remain intact. + for (let v = 0; v < p.count; v++) { + const weights = rig => { + const out = new Map(); + for (let k = 0; k < 4; k++) { const w = rig.prims[0].W[v * 4 + k], j = rig.prims[0].J[v * 4 + k]; if (w) out.set(j, (out.get(j) || 0) + w); } + return out; + }; + const wa = weights(a), wb = weights(b); + const handIndices = config.hands.flatMap(h => [a.names.indexOf(h.hand), a.names.indexOf(h.curl)]); + for (const j of new Set([...wa.keys(), ...wb.keys()])) if (!allowed.has(v) || !handIndices.includes(j)) { + assert(Math.abs((wa.get(j) || 0) - (wb.get(j) || 0)) < 1e-5, 'unrelated skin weight changed'); + } + } + return result; +} + +if (process.argv[1]?.endsWith('/character-grip-check.mjs')) { + const [source, repaired, annotation, flag] = process.argv.slice(2); + assert(source && repaired && annotation, 'usage: character-grip-check.mjs [--mutants]'); + const io = new NodeIO().registerExtensions(ALL_EXTENSIONS), config = JSON.parse(readFileSync(annotation, 'utf8')); + const before = await io.read(source), after = await io.read(repaired); + console.log(JSON.stringify(assertGrip(before, after, config), null, 2)); + if (flag === '--mutants') { + const reject = (name, doc, pattern) => { + assert.throws(() => assertGrip(before, doc, config), pattern, `mutant survived: ${name}`); + console.log(`KILLED ${name}`); + }; + reject('original-zero-finger-influence', before, /zero\/insufficient finger influence/); + const geometry = cloneDocument(after); geometry.getRoot().listMeshes()[0].listPrimitives()[0].getAttribute('POSITION').getArray()[0] += 0.01; + reject('changed-base-silhouette', geometry, /base shape changed/); + const wholeHand = cloneDocument(after), rig = loadRig(wholeHand), h = config.hands[0], region = handRegion(loadRig(before), h); + const v = region.members.findIndex((m, i) => m && region.points[i].y < h.palmY); + const j = rig.prims[0].J, w = rig.prims[0].W; + for (let k = 0; k < 4; k++) if (j[v * 4 + k] === region.hi && w[v * 4 + k] > 0) j[v * 4 + k] = region.ci; + reject('whole-palm-as-fingers', wholeHand, /palm\/thumb acquired Curl influence/); + const wrongFrame = cloneDocument(after); wrongFrame.getRoot().listNodes().find(n => n.getName() === h.curl).setRotation(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI).toArray()); + reject('reversed-flexion-frame', wrongFrame, /bind shape error|wrong flexion frame/); + } +} From 9af4360b165dd93e054d745fd5ad31f08032d3a1 Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Tue, 10 Nov 2026 03:11:38 +0000 Subject: [PATCH 09/10] Run public grip fixtures and causal mutants in Studio CI Generate synthetic anatomy in memory, share all four production gate mutants, and compare every vertex with a Three.js SkinnedMesh using the runtime Euler operation. No private payload is required. Agent: Claude Code Signed-off-by: rubenmarcus --- docs/character-rig.md | 21 +++- package.json | 1 + tools/checks/character-grip-check.mjs | 39 ++++--- tools/checks/character-grip-public-check.mjs | 107 +++++++++++++++++++ tools/studio-check.mjs | 3 +- 5 files changed, 152 insertions(+), 19 deletions(-) create mode 100755 tools/checks/character-grip-public-check.mjs diff --git a/docs/character-rig.md b/docs/character-rig.md index 74d34e6..c9c6b30 100644 --- a/docs/character-rig.md +++ b/docs/character-rig.md @@ -143,8 +143,10 @@ remain in contract order, parented to Hand, with the unused copies unweighted. This is one bend per finger, matching the existing meshy-28 mechanism, not a new fully articulated finger rig. -From this Studio worktree, with `BASE` pointing at the local character pack root -and `DONOR` at the client's existing `public/models/characters/mst.glb`: +Requires Node >=22.12 (the default system Node may be older; use `asdf exec node` +where applicable). From this Studio worktree, with `BASE` pointing at the local +character pack root and `DONOR` at the client's existing +`public/models/characters/mst.glb`: ```sh node tools/characters/repair-grip-pack.mjs \ @@ -181,3 +183,18 @@ The grip production report records the additional synthetic Curl endpoints: left 1.484x and right 1.747x maximum at 0.95 rad. None of these numbers approves actual AK contact or replaces the parent browser/visual evaluation. +### Public CI proof + +`npm run check:character-grip` generates a synthetic skinned hand pair in memory, +with four distal branches, a separate shorter thumb and a protected palm. It runs +the same nominal gate and four causal mutants as the private pilot: zero finger +influence, changed rest shape, palm-as-finger and reversed frame. The fixture also +constructs an actual Three.js `SkinnedMesh` and compares every vertex against the +offline skinning at the two runtime endpoint curls using Euler XYZ addition. +No GLB, texture, clip, private directory, paid service or browser is needed. + +`npm run check` runs this proof through `tools/studio-check.mjs`, so the existing +Studio CI executes the nominal case and mutants, not merely a syntax check. +Private-pack validation and the actual-client visual review remain separate +required evidence; no synthetic result means that a hand visibly grips a weapon. + diff --git a/package.json b/package.json index 5601df9..6ea8df6 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "check": "node tools/studio-check.mjs", "check:asset-gen": "node tools/checks/gen-asset-pbr-check.mjs", "check:pistol-source": "node tools/checks/pistol-hires-pilot-check.mjs", + "check:character-grip": "node tools/checks/character-grip-public-check.mjs", "smoke:pack": "node tools/smoke-pack.mjs", "pack:build-lajes": "node tools/build-lajes-pack.mjs", "pack:validate": "node tools/validate-pack.mjs", diff --git a/tools/checks/character-grip-check.mjs b/tools/checks/character-grip-check.mjs index aa88300..a0a3c1d 100755 --- a/tools/checks/character-grip-check.mjs +++ b/tools/checks/character-grip-check.mjs @@ -143,26 +143,33 @@ export function assertGrip(before, after, config) { return result; } +export function assertGripMutants(before, after, config) { + const reject = (name, doc, pattern) => { + assert.throws(() => assertGrip(before, doc, config), pattern, `mutant survived: ${name}`); + console.log(`KILLED ${name}`); + }; + reject('original-zero-finger-influence', before, /zero\/insufficient finger influence/); + const geometry = cloneDocument(after); geometry.getRoot().listMeshes()[0].listPrimitives()[0].getAttribute('POSITION').getArray()[0] += 0.01; + reject('changed-base-silhouette', geometry, /base shape changed/); + const wholeHand = cloneDocument(after), rig = loadRig(wholeHand), h = config.hands[0], region = handRegion(loadRig(before), h); + const v = region.members.findIndex((m, i) => m && region.points[i].y < h.palmY); + assert(v >= 0, 'palm mutant did not find a protected vertex'); + const j = rig.prims[0].J, w = rig.prims[0].W; + let changed = false; + for (let k = 0; k < 4; k++) if (j[v * 4 + k] === region.hi && w[v * 4 + k] > 0) { + j[v * 4 + k] = region.ci; changed = true; + } + assert(changed, 'palm mutant did not change an influence'); + reject('whole-palm-as-fingers', wholeHand, /palm\/thumb acquired Curl influence/); + const wrongFrame = cloneDocument(after); wrongFrame.getRoot().listNodes().find(n => n.getName() === h.curl).setRotation(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI).toArray()); + reject('reversed-flexion-frame', wrongFrame, /bind shape error|wrong flexion frame/); +} + if (process.argv[1]?.endsWith('/character-grip-check.mjs')) { const [source, repaired, annotation, flag] = process.argv.slice(2); assert(source && repaired && annotation, 'usage: character-grip-check.mjs [--mutants]'); const io = new NodeIO().registerExtensions(ALL_EXTENSIONS), config = JSON.parse(readFileSync(annotation, 'utf8')); const before = await io.read(source), after = await io.read(repaired); console.log(JSON.stringify(assertGrip(before, after, config), null, 2)); - if (flag === '--mutants') { - const reject = (name, doc, pattern) => { - assert.throws(() => assertGrip(before, doc, config), pattern, `mutant survived: ${name}`); - console.log(`KILLED ${name}`); - }; - reject('original-zero-finger-influence', before, /zero\/insufficient finger influence/); - const geometry = cloneDocument(after); geometry.getRoot().listMeshes()[0].listPrimitives()[0].getAttribute('POSITION').getArray()[0] += 0.01; - reject('changed-base-silhouette', geometry, /base shape changed/); - const wholeHand = cloneDocument(after), rig = loadRig(wholeHand), h = config.hands[0], region = handRegion(loadRig(before), h); - const v = region.members.findIndex((m, i) => m && region.points[i].y < h.palmY); - const j = rig.prims[0].J, w = rig.prims[0].W; - for (let k = 0; k < 4; k++) if (j[v * 4 + k] === region.hi && w[v * 4 + k] > 0) j[v * 4 + k] = region.ci; - reject('whole-palm-as-fingers', wholeHand, /palm\/thumb acquired Curl influence/); - const wrongFrame = cloneDocument(after); wrongFrame.getRoot().listNodes().find(n => n.getName() === h.curl).setRotation(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI).toArray()); - reject('reversed-flexion-frame', wrongFrame, /bind shape error|wrong flexion frame/); - } + if (flag === '--mutants') assertGripMutants(before, after, config); } diff --git a/tools/checks/character-grip-public-check.mjs b/tools/checks/character-grip-public-check.mjs new file mode 100755 index 0000000..a720ffe --- /dev/null +++ b/tools/checks/character-grip-public-check.mjs @@ -0,0 +1,107 @@ +#!/usr/bin/env node +// Public synthetic anatomy only: no private model, texture, animation, Blender or renderer. +// The gate proves a deformation prerequisite, never visual weapon-contact approval. +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { Document } from '@gltf-transform/core'; +import { cloneDocument } from '@gltf-transform/functions'; +import * as THREE from 'three'; +import { assertGrip, assertGripMutants, handRegion } from './character-grip-check.mjs'; +import { buildMeshy28Skeleton, loadRig, skinPositions, worldMatrices } from '../lib/character-rig.mjs'; + +const config = JSON.parse(readFileSync(new URL('../../characters/capitao-caveira/grip.json', import.meta.url), 'utf8')); +const points = { + Hips: [0, .83, -.02], LeftUpLeg: [.08, .75, -.01], LeftLeg: [.1, .42, .03], LeftFoot: [.11, .1, 0], LeftToeBase: [.13, .04, .11], + RightUpLeg: [-.08, .75, -.01], RightLeg: [-.1, .42, .03], RightFoot: [-.11, .1, 0], RightToeBase: [-.13, .04, .11], + Spine02: [0, .96, 0], Spine01: [0, 1.09, 0], Spine: [0, 1.22, 0], + LeftShoulder: [.035, 1.25, 0], LeftArm: [.17, 1.25, 0], LeftForeArm: [.4, 1.25, 0], LeftHand: [.62, 1.25, 0], + RightShoulder: [-.035, 1.25, 0], RightArm: [-.17, 1.25, 0], RightForeArm: [-.4, 1.25, 0], RightHand: [-.62, 1.25, 0], + neck: [0, 1.32, 0], Head: [0, 1.39, 0], head_end: [0, 1.7, 0], headfront: [0, 1.39, .12], + Curl_R: [-.62, 1.25, 0], Curl_L: [.62, 1.25, 0], +}; +const before = new Document(), buffer = before.createBuffer(); +const built = buildMeshy28Skeleton(before, points); +const skin = before.createSkin().setInverseBindMatrices(before.createAccessor().setType('MAT4').setArray(built.inverseBindMatrices).setBuffer(buffer)); +for (const joint of built.joints) skin.addJoint(joint); +const positions = [], joints = [], weights = [], indices = []; +for (const h of config.hands) { + const hi = built.joints.findIndex(j => j.getName() === h.hand); + const handWorld = new THREE.Matrix4().fromArray(built.joints[hi].getWorldMatrix()); + // Disconnected tubes are intentional: four distal branches plus a shorter thumb. + // No production geometry is approximated or copied by this fixture. + const tube = (x, ys, radius) => { + const start = positions.length / 3, sides = 8; + for (const y of ys) for (let k = 0; k < sides; k++) { + const angle = k / sides * Math.PI * 2; + const p = new THREE.Vector3(x + Math.cos(angle) * radius, y, Math.sin(angle) * radius).multiplyScalar(100).applyMatrix4(handWorld); + positions.push(...p.toArray()); joints.push(hi, 0, 0, 0); weights.push(1, 0, 0, 0); + } + for (let ring = 1; ring < ys.length; ring++) for (let k = 0; k < sides; k++) { + const a = start + (ring - 1) * sides + k, b = start + (ring - 1) * sides + (k + 1) % sides; + const c = start + ring * sides + k, d = start + ring * sides + (k + 1) % sides; + indices.push(a, c, b, b, c, d); + } + }; + for (const x of [-.05, -.02, .01, .04]) tube(x * -h.thumbSign, [.14, .17, .18, .19, .20, .22, .24, .26], .007); + tube(h.thumbSign * .09, [.10, .12, .14, .16, .17], .008); + tube(0, [.03, .06, .09, .12, .145], .04); +} +const accessor = (type, array) => before.createAccessor().setType(type).setArray(array).setBuffer(buffer); +const primitive = before.createPrimitive() + .setAttribute('POSITION', accessor('VEC3', new Float32Array(positions))) + .setAttribute('JOINTS_0', accessor('VEC4', new Uint16Array(joints))) + .setAttribute('WEIGHTS_0', accessor('VEC4', new Float32Array(weights))) + .setIndices(accessor('SCALAR', new Uint16Array(indices))); +const mesh = before.createMesh().addPrimitive(primitive); +before.createScene().addChild(built.armature).addChild(before.createNode('SyntheticHands').setMesh(mesh).setSkin(skin)); +const after = cloneDocument(before), baseline = loadRig(before); +for (const h of config.hands) { + const region = handRegion(baseline, h), rig = loadRig(after), { hi, ci, members, points: local } = region; + const node = rig.joints[ci]; node.setTranslation([0, h.knuckleY / region.scale, 0]).setRotation([0, 0, 0, 1]); + const changed = loadRig(after), inverse = worldMatrices(changed)(node).clone().invert(); + after.getRoot().listSkins()[0].getInverseBindMatrices().setElement(ci, inverse.elements); + for (let v = 0; v < rig.prims[0].count; v++) { + if (!members[v] || local[v].y <= h.knuckleY || local[v].x * h.thumbSign >= h.thumbX) continue; + const t = Math.min(1, (local[v].y - h.knuckleY) / (h.fullY - h.knuckleY)), w = t * t * (3 - 2 * t); + rig.prims[0].J[v * 4 + 1] = ci; rig.prims[0].W[v * 4] = 1 - w; rig.prims[0].W[v * 4 + 1] = w; + assert.equal(rig.prims[0].J[v * 4], hi); + } +} +const report = assertGrip(before, after, config); +console.log(`PASS public grip prerequisite: ${JSON.stringify(report)}`); +assertGripMutants(before, after, config); + +// Cross-check the offline implementation against an actual Three.js SkinnedMesh. +// Euler XYZ addition is exactly the runtime operation, including on nonidentity rest frames. +const rig = loadRig(after), isJoint = new Set(rig.joints), objects = new Map(); +for (const n of rig.nodes) { + const o = isJoint.has(n) ? new THREE.Bone() : new THREE.Object3D(), trs = rig.trs.get(n); + o.name = n.getName(); o.position.fromArray(trs.t); o.quaternion.fromArray(trs.r); o.scale.fromArray(trs.s); objects.set(n, o); +} +const root = new THREE.Group(); +for (const n of rig.nodes) (rig.parent.has(n) ? objects.get(rig.parent.get(n)) : root).add(objects.get(n)); +const geometry = new THREE.BufferGeometry(); +geometry.setAttribute('position', new THREE.BufferAttribute(rig.prims[0].pos, 3)); +geometry.setAttribute('skinIndex', new THREE.BufferAttribute(rig.prims[0].J, 4)); +geometry.setAttribute('skinWeight', new THREE.BufferAttribute(rig.prims[0].W, 4)); +const skinned = new THREE.SkinnedMesh(geometry, new THREE.MeshBasicMaterial()); +const skeleton = new THREE.Skeleton(rig.joints.map(n => objects.get(n)), rig.ibm.map(m => m.clone())); +root.add(skinned); root.updateMatrixWorld(true); skinned.bind(skeleton, new THREE.Matrix4()); +let maxEngineError = 0; +for (const angle of [.55, .95]) { + const overrides = new Map(); + for (const h of config.hands) { + const node = rig.joints[rig.names.indexOf(h.curl)], trs = rig.trs.get(node), o = objects.get(node); + o.quaternion.fromArray(trs.r); o.rotation.x += angle; + overrides.set(node, { ...trs, r: o.quaternion.toArray() }); + } + root.updateMatrixWorld(true); skeleton.update(); + const expected = skinPositions(rig, overrides)[0]; + for (let v = 0; v < rig.prims[0].count; v++) { + const actual = skinned.applyBoneTransform(v, new THREE.Vector3().fromArray(rig.prims[0].pos, v * 3)); + maxEngineError = Math.max(maxEngineError, actual.distanceTo(new THREE.Vector3().fromArray(expected, v * 3))); + } +} +assert(maxEngineError < 1e-6, `offline/runtime skinning mismatch ${maxEngineError}m`); +console.log(`PASS Three.js SkinnedMesh parity: ${maxEngineError}m maximum error`); +geometry.dispose(); skinned.material.dispose(); skeleton.dispose(); diff --git a/tools/studio-check.mjs b/tools/studio-check.mjs index 335f975..acd72c3 100755 --- a/tools/studio-check.mjs +++ b/tools/studio-check.mjs @@ -24,6 +24,7 @@ const requiredFiles = [ 'tools/checks/character-concept-prompt-check.mjs', 'tools/lib/character-rig.mjs', 'tools/checks/character-rig-check.mjs', + 'tools/checks/character-grip-public-check.mjs', 'docs/character-rig.md', 'maps/lajes/gauntlet/fixtures/scene-report.valid.json', ]; @@ -46,6 +47,6 @@ const scripts = walk(path.join(root, 'tools')).filter(file => file.endsWith('.mj for (const script of scripts) execFileSync(process.execPath, ['--check', script], { stdio: 'pipe' }); console.log(`PASS Studio structure, JSON, public asset boundary and ${scripts.length} Node tool syntax checks`); // Contract checks that use synthetic fixtures only; they never call paid generation APIs. -for (const check of ['tools/checks/character-pack-check.mjs', 'tools/checks/character-concept-prompt-check.mjs', 'tools/checks/character-rig-check.mjs']) { +for (const check of ['tools/checks/character-pack-check.mjs', 'tools/checks/character-concept-prompt-check.mjs', 'tools/checks/character-rig-check.mjs', 'tools/checks/character-grip-public-check.mjs']) { execFileSync(process.execPath, [path.join(root, check)], { stdio: 'inherit' }); } From 1c646370dbbdf49144c79d07b03ceac064c590cb Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Tue, 10 Nov 2026 03:22:30 +0000 Subject: [PATCH 10/10] Keep repair publication immutable and require causal safety invariants Materialize declared payloads, stage evidence before publishing and roll back on its commit failure. Require all eleven named states and finite nonnegative skin components. Prove the flexion-direction mutant independently of bind error and exercise the real CLI failure paths with generated public fixtures. Agent: Claude Code Signed-off-by: rubenmarcus --- docs/character-rig.md | 27 +++++-- tools/characters/repair-grip-pack.mjs | 39 ++++++--- tools/checks/character-grip-check.mjs | 20 ++++- tools/checks/character-grip-public-check.mjs | 85 +++++++++++++++++++- 4 files changed, 148 insertions(+), 23 deletions(-) diff --git a/docs/character-rig.md b/docs/character-rig.md index c9c6b30..1be9006 100644 --- a/docs/character-rig.md +++ b/docs/character-rig.md @@ -165,12 +165,19 @@ the causal numeric gate and validates the full original and new packs, including the unchanged complete eleven-state clip file. It records exact commands, source, tool and annotation hashes, output manifest/model hashes, donor influences and per-finger measurements outside the pack. Local version 0.2.0 is immutable. +The eleven canonical state names and all eleven manifest mappings are required, +not just an animation count. Internal source symlinks are materialized when +staging, so writing the repaired model cannot follow a link back into the source. +Evidence is prepared before publication; a failed evidence commit removes the +newly published candidate, allowing a safe retry without changing the source. The gate rejects zero finger influence, rotation of palm/thumb, wrong flexion frame/sign, bind error above 0.1 mm, geometry/attribute/topology changes, unrelated -weight changes, or curl edge stretch above 2.5x. All four fingers must move inward -at both runtime endpoint curls (0.55 and 0.95 rad). `--mutants` includes the actual -zero-weight source, changed silhouette, palm-as-finger and reversed-frame defects. +weight changes, negative/nonfinite weight components, or curl edge stretch above +2.5x. All four fingers must move inward at both runtime endpoint curls (0.55 and +0.95 rad). `--mutants` includes the actual zero-weight source, changed silhouette, +palm-as-finger, a reversed frame with corrected inverse bind, and cancelling +negative weights. The frame mutant must fail on flexion direction, not bind error. Passing establishes only a real deformation prerequisite: the parent must render the pilot with the actual AK and obtain independent visual acceptance. Do not publish/integrate the remaining 29 or generalize an annotation across characters. @@ -187,11 +194,15 @@ actual AK contact or replaces the parent browser/visual evaluation. `npm run check:character-grip` generates a synthetic skinned hand pair in memory, with four distal branches, a separate shorter thumb and a protected palm. It runs -the same nominal gate and four causal mutants as the private pilot: zero finger -influence, changed rest shape, palm-as-finger and reversed frame. The fixture also -constructs an actual Three.js `SkinnedMesh` and compares every vertex against the -offline skinning at the two runtime endpoint curls using Euler XYZ addition. -No GLB, texture, clip, private directory, paid service or browser is needed. +the same nominal gate and five causal mutants as the private pilot: zero finger +influence, changed rest shape, palm-as-finger, reversed frame and cancelling +negative weights. The fixture also constructs an actual Three.js `SkinnedMesh` +and compares every vertex against the offline skinning at the two runtime +endpoint curls using Euler XYZ addition. It generates temporary pack/clip bytes +to exercise the real repair CLI: successful symlink materialization, unchanged +source, missing report parent, injected evidence-link failure rollback, and +eleven animation names that omit required runtime states. No private GLB, texture, +clip, directory, paid service or browser is needed. `npm run check` runs this proof through `tools/studio-check.mjs`, so the existing Studio CI executes the nominal case and mutants, not merely a syntax check. diff --git a/tools/characters/repair-grip-pack.mjs b/tools/characters/repair-grip-pack.mjs index f518a20..ddcc642 100755 --- a/tools/characters/repair-grip-pack.mjs +++ b/tools/characters/repair-grip-pack.mjs @@ -2,14 +2,14 @@ // Patch only pilot Hand→Curl influences and Curl bind frames. Never regenerate mesh data. import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; -import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { NodeIO } from '@gltf-transform/core'; import { ALL_EXTENSIONS } from '@gltf-transform/extensions'; import { cloneDocument } from '@gltf-transform/functions'; import { assertGrip, handRegion } from '../checks/character-grip-check.mjs'; -import { loadRig, worldMatrices } from '../lib/character-rig.mjs'; +import { CLIP_STATES, loadRig, worldMatrices } from '../lib/character-rig.mjs'; import { validatePack } from '../lib/pack.mjs'; import { readGlb } from '../lib/glb-inspect.mjs'; @@ -108,23 +108,30 @@ const measurements = assertGrip(original, await io.readBinary(result), config); await validatePack({ manifestPath: path.join(sourcePack, 'manifest.json') }); const states = await readGlb(path.join(sourcePack, manifest.animations.idle), 'states', { allowMeshoptFallback: true }); const clipNames = states.document.animations.map(a => a.name); -assert.equal(clipNames.length, 11, 'existing complete 11-state clip pack required'); +assert(CLIP_STATES.every(state => manifest.animations[state] === manifest.animations.idle), + 'all eleven runtime states must map to the shared states pack'); +assert.deepEqual([...clipNames].sort(), [...CLIP_STATES].sort(), 'existing complete eleven named runtime states required'); manifest.version = '0.2.1'; manifest.source.provenance.push(`Offline pilot Curl repair: ${config.id}/grip.json; source model ${config.sourceSha256}; donor ${config.donorSha256}; palm/thumb and all non-skin payload bytes unchanged. Numeric prerequisite only; visual approval pending.`); const entry = manifest.files.find(f => f.path === manifest.model); entry.sha256 = sha(result); entry.bytes = result.length; mkdirSync(path.dirname(targetPack), { recursive: true }); const temporary = mkdtempSync(path.join(path.dirname(targetPack), '.grip-pack-')); +let reportTemporary = null, published = false, complete = false; try { - cpSync(sourcePack, temporary, { recursive: true }); - writeFileSync(path.join(temporary, manifest.model), result); + // Materialize only validated, declared payloads as fresh regular files. Copying a + // source tree can preserve symlinks or undeclared files and write back into it. + for (const file of manifest.files) { + const destination = path.join(temporary, file.path); + mkdirSync(path.dirname(destination), { recursive: true }); + const bytes = file.path === manifest.model ? result : readFileSync(path.join(sourcePack, file.path)); + writeFileSync(destination, bytes, { flag: 'wx' }); + } const manifestBytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`); - writeFileSync(path.join(temporary, 'manifest.json'), manifestBytes); + writeFileSync(path.join(temporary, 'manifest.json'), manifestBytes, { flag: 'wx' }); await validatePack({ manifestPath: path.join(temporary, 'manifest.json') }); for (const f of manifest.files) if (f.path !== manifest.model) { assert.equal(sha(readFileSync(path.join(temporary, f.path))), sha(readFileSync(path.join(sourcePack, f.path))), 'non-model pack payload changed'); } - assert(!existsSync(targetPack), 'immutable target appeared during repair'); - renameSync(temporary, targetPack); const report = { status: 'numeric-prerequisite-only-visual-review-required', command: [process.execPath, ...process.argv.slice(1)], toolSha256: sha(readFileSync(fileURLToPath(import.meta.url))), annotationSha256: sha(readFileSync(annotation)), @@ -133,6 +140,18 @@ try { preserved: ['geometry', 'topology', 'UV', 'normals', 'materials', 'images', 'rights', 'all animation files', 'joint hierarchy/order'], measurements, }; - writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, { flag: 'wx' }); + // Prepare evidence before making the pack visible. A report failure must not strand + // an immutable version that can neither be completed nor retried. + reportTemporary = mkdtempSync(path.join(path.dirname(reportPath), '.grip-report-')); + const stagedReport = path.join(reportTemporary, 'report.json'); + writeFileSync(stagedReport, `${JSON.stringify(report, null, 2)}\n`, { flag: 'wx' }); + assert(!existsSync(targetPack), 'immutable target appeared during repair'); + renameSync(temporary, targetPack); published = true; + // Hard-link publication is atomic and fails rather than replacing existing evidence. + linkSync(stagedReport, reportPath); complete = true; console.log(JSON.stringify(report, null, 2)); -} finally { rmSync(temporary, { recursive: true, force: true }); } +} finally { + if (published && !complete) rmSync(targetPack, { recursive: true, force: true }); + if (reportTemporary) rmSync(reportTemporary, { recursive: true, force: true }); + rmSync(temporary, { recursive: true, force: true }); +} diff --git a/tools/checks/character-grip-check.mjs b/tools/checks/character-grip-check.mjs index a0a3c1d..053e5e4 100755 --- a/tools/checks/character-grip-check.mjs +++ b/tools/checks/character-grip-check.mjs @@ -72,6 +72,9 @@ export function assertGrip(before, after, config) { } const bindA = skinPositions(a)[0], bindB = skinPositions(b)[0], p = b.prims[0]; let bindError = 0; + for (const rig of [a, b]) for (const primitive of rig.prims) for (const weight of primitive.W) { + assert(Number.isFinite(weight) && weight >= 0, 'skin components must be finite and nonnegative'); + } for (let v = 0; v < p.count; v++) { bindError = Math.max(bindError, distance(bindA, bindB, v)); const sum = [0, 1, 2, 3].reduce((s, k) => s + p.W[v * 4 + k], 0); @@ -161,8 +164,21 @@ export function assertGripMutants(before, after, config) { } assert(changed, 'palm mutant did not change an influence'); reject('whole-palm-as-fingers', wholeHand, /palm\/thumb acquired Curl influence/); - const wrongFrame = cloneDocument(after); wrongFrame.getRoot().listNodes().find(n => n.getName() === h.curl).setRotation(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI).toArray()); - reject('reversed-flexion-frame', wrongFrame, /bind shape error|wrong flexion frame/); + const wrongFrame = cloneDocument(after), reversed = loadRig(wrongFrame), ci = reversed.names.indexOf(h.curl); + // XYZ x-addition rotates about the parent X axis: changing only rest Y does + // not reverse it. Put the hinge beyond the fingertips so the same runtime + // operator bends outward, and refresh IBM so bind error cannot kill the mutant. + const fingertipY = region.points.reduce((max, q, i) => region.members[i] ? Math.max(max, q.y) : max, 0); + reversed.joints[ci].setTranslation([0, (fingertipY + 0.05) / region.scale, 0]); + const updated = loadRig(wrongFrame); + wrongFrame.getRoot().listSkins()[0].getInverseBindMatrices().setElement(ci, worldMatrices(updated)(updated.joints[ci]).clone().invert().elements); + reject('reversed-flexion-frame', wrongFrame, /wrong flexion frame\/sign/); + const negative = cloneDocument(after), invalid = loadRig(negative).prims[0]; + // Cancelling weights aggregate to zero but GLTFLoader's absolute-mass normalization + // changes them. Reject the individual invalid components, not just the signed sum. + invalid.J[v * 4 + 1] = region.ci; invalid.J[v * 4 + 2] = region.ci; + invalid.W[v * 4 + 1] = -0.25; invalid.W[v * 4 + 2] = 0.25; + reject('cancelling-negative-weights', negative, /finite and nonnegative/); } if (process.argv[1]?.endsWith('/character-grip-check.mjs')) { diff --git a/tools/checks/character-grip-public-check.mjs b/tools/checks/character-grip-public-check.mjs index a720ffe..2f36879 100755 --- a/tools/checks/character-grip-public-check.mjs +++ b/tools/checks/character-grip-public-check.mjs @@ -2,12 +2,17 @@ // Public synthetic anatomy only: no private model, texture, animation, Blender or renderer. // The gate proves a deformation prerequisite, never visual weapon-contact approval. import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import { Document } from '@gltf-transform/core'; +import { createHash } from 'node:crypto'; +import { spawnSync } from 'node:child_process'; +import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { Document, NodeIO } from '@gltf-transform/core'; import { cloneDocument } from '@gltf-transform/functions'; import * as THREE from 'three'; import { assertGrip, assertGripMutants, handRegion } from './character-grip-check.mjs'; -import { buildMeshy28Skeleton, loadRig, skinPositions, worldMatrices } from '../lib/character-rig.mjs'; +import { buildMeshy28Skeleton, CLIP_STATES, loadRig, skinPositions, worldMatrices } from '../lib/character-rig.mjs'; const config = JSON.parse(readFileSync(new URL('../../characters/capitao-caveira/grip.json', import.meta.url), 'utf8')); const points = { @@ -105,3 +110,77 @@ for (const angle of [.55, .95]) { assert(maxEngineError < 1e-6, `offline/runtime skinning mismatch ${maxEngineError}m`); console.log(`PASS Three.js SkinnedMesh parity: ${maxEngineError}m maximum error`); geometry.dispose(); skinned.material.dispose(); skeleton.dispose(); + +// Exercise the real repair CLI, not a mock, using only generated temporary bytes. +const work = mkdtempSync(path.join(os.tmpdir(), 'studio-grip-public-')); +try { + const io = new NodeIO(), sha = bytes => createHash('sha256').update(bytes).digest('hex'); + const modelBytes = Buffer.from(await io.writeBinary(before)), donorBytes = Buffer.from(await io.writeBinary(after)); + const sourcePack = path.join(work, 'source'), modelPath = 'model/pilot.glb', statesPath = 'animations/states.glb', previewPath = 'previews/front.png'; + for (const dir of ['model', 'animations', 'previews']) mkdirSync(path.join(sourcePack, dir), { recursive: true }); + writeFileSync(path.join(sourcePack, 'payload.glb'), modelBytes); + symlinkSync('../payload.glb', path.join(sourcePack, modelPath)); + const donorPath = path.join(work, 'donor.glb'), annotationPath = path.join(work, 'grip.json'); + writeFileSync(donorPath, donorBytes); + writeFileSync(annotationPath, JSON.stringify({ ...config, sourceSha256: sha(modelBytes), donorSha256: sha(donorBytes) })); + const preview = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64'); + writeFileSync(path.join(sourcePack, previewPath), preview); + const statesBytes = async names => { + const doc = new Document(), buf = doc.createBuffer(), hips = doc.createNode('Hips'); + doc.createScene().addChild(hips); + const time = doc.createAccessor().setType('SCALAR').setArray(new Float32Array([0, 1])).setBuffer(buf); + const values = doc.createAccessor().setType('VEC3').setArray(new Float32Array([0, 83, 0, 0, 83, 0])).setBuffer(buf); + for (const name of names) { + const sampler = doc.createAnimationSampler().setInput(time).setOutput(values).setInterpolation('LINEAR'); + doc.createAnimation(name).addSampler(sampler).addChannel(doc.createAnimationChannel().setTargetNode(hips).setTargetPath('translation').setSampler(sampler)); + } + return Buffer.from(await io.writeBinary(doc)); + }; + const setSourceManifest = async (names, declared) => { + const clips = await statesBytes(names); + writeFileSync(path.join(sourcePack, statesPath), clips); + const files = [[modelPath, modelBytes], [statesPath, clips], [previewPath, preview]].map(([p, bytes]) => ({ path: p, bytes: bytes.length, sha256: sha(bytes) })); + writeFileSync(path.join(sourcePack, 'manifest.json'), JSON.stringify({ + schemaVersion: 1, kind: 'character', id: config.id, version: '0.2.0', + source: { revision: 'synthetic-public-fixture', provenance: ['Generated mathematical fixture; no private source assets'] }, + files, model: modelPath, skeleton: 'meshy-28', animations: Object.fromEntries(declared.map(name => [name, statesPath])), + previews: [previewPath], rights: { status: 'original', basis: 'Programmatic public test geometry' }, + budgets: { triangles: 5000, bytes: 8388608 }, + })); + }; + await setSourceManifest(CLIP_STATES, CLIP_STATES); + const script = fileURLToPath(new URL('../characters/repair-grip-pack.mjs', import.meta.url)); + const run = (name, { reportParent = true, injectLinkFailure = false } = {}) => { + const directory = path.join(work, name); mkdirSync(directory); + const target = path.join(directory, '0.2.1'); + const evidence = reportParent ? path.join(directory, 'report.json') : path.join(directory, 'missing-parent/report.json'); + const hook = "import fs from 'node:fs';import {syncBuiltinESMExports} from 'node:module';fs.linkSync=()=>{throw new Error('injected evidence-link failure')};syncBuiltinESMExports();"; + const preload = injectLinkFailure ? ['--import', `data:text/javascript,${encodeURIComponent(hook)}`] : []; + const result = spawnSync(process.execPath, [...preload, script, sourcePack, target, annotationPath, donorPath, evidence], { encoding: 'utf8' }); + assert.equal(sha(readFileSync(path.join(sourcePack, modelPath))), sha(modelBytes), 'repair changed immutable source bytes'); + assert(lstatSync(path.join(sourcePack, modelPath)).isSymbolicLink(), 'repair replaced source symlink'); + return { result, target, evidence }; + }; + const valid = run('valid'); + assert.equal(valid.result.status, 0, valid.result.stderr); + assert(!lstatSync(path.join(valid.target, modelPath)).isSymbolicLink(), 'staged model must be materialized'); + assert(existsSync(valid.evidence), 'successful repair lacks evidence'); + assertGrip(before, await io.read(path.join(valid.target, modelPath)), config); + console.log('PASS real repair CLI materializes symlinks, preserves source and publishes a validated pack plus evidence'); + const absentParent = run('missing-evidence-parent', { reportParent: false }); + assert.notEqual(absentParent.result.status, 0, 'missing report parent unexpectedly accepted'); + assert(!existsSync(absentParent.target) && !existsSync(absentParent.evidence), 'report preparation failure published a partial version'); + console.log('PASS missing evidence parent leaves no immutable partial version'); + const linkFailure = run('evidence-link-failure', { injectLinkFailure: true }); + assert.notEqual(linkFailure.result.status, 0, 'injected report publication failure was not applied'); + assert.match(linkFailure.result.stderr, /injected evidence-link failure/); + assert(!existsSync(linkFailure.target) && !existsSync(linkFailure.evidence), 'evidence failure did not roll back the published version'); + console.log('PASS injected evidence publication failure rolls back the new pack'); + const requiredEight = CLIP_STATES.slice(0, 8); + await setSourceManifest([...requiredEight, 'unrelated_a', 'unrelated_b', 'unrelated_c'], requiredEight); + const incomplete = run('missing-optional-runtime-states'); + assert.notEqual(incomplete.result.status, 0, 'eleven unrelated clip names unexpectedly accepted'); + assert.match(incomplete.result.stderr, /all eleven runtime states/); + assert(!existsSync(incomplete.target), 'incomplete runtime states published a version'); + console.log('PASS eleven-clip count cannot substitute for all eleven named runtime states'); +} finally { rmSync(work, { recursive: true, force: true }); }