diff --git a/docs/INTEGRATION.md b/docs/INTEGRATION.md index 53c3ed7..5f2027e 100644 --- a/docs/INTEGRATION.md +++ b/docs/INTEGRATION.md @@ -19,7 +19,7 @@ Local candidate packaging and validation are implemented for the Lajes vertical - Every release records provenance and licensing. - Map packs declare geometry, textures, LODs, collision, navigation, spawns, regions and previews. Every payload path has exactly one role and exactly one `files` entry; undeclared or missing files are rejected. - All payload paths are canonical package-relative paths. Absolute paths, traversal segments, backslashes and executable JavaScript are rejected. -- Character packs declare one rigged meshy-28 model, per-state animation clips, previews, rights and budgets, one pack per character (see [character-pack.md](character-pack.md)). Every payload path has exactly one role and exactly one `files` entry. +- Character packs declare one rigged meshy-28 model, per-state animation clips, previews, rights and budgets, one pack per character (see [character-pack.md](character-pack.md)). Every payload path has exactly one role and exactly one `files` entry. Characters reach a pack through the standard pipeline only ([character-pipeline.md](character-pipeline.md)). - `low` is a required output profile for map packs. - The client may reject a Studio-valid release if it violates runtime contracts. diff --git a/docs/character-pipeline.md b/docs/character-pipeline.md new file mode 100644 index 0000000..0471b71 --- /dev/null +++ b/docs/character-pipeline.md @@ -0,0 +1,169 @@ +# Character pipeline (the standard process) + +Every new third-person character of CORO SOLTO follows this one route, end to end. The +output is an immutable Studio character pack ([character-pack.md](character-pack.md)) +pinned by a client release — never a new GLB under the client's `public/`, never a Mint or +proximity auto-rig, never clips that skipped the QA gate. + +Stage docs live on their branches until the program merges: the pack contract +(`feat/character-pack-contract-20261108` + `feat/pack-optional-clips-20261109`), the +Blender rig (`docs/character-rig.md`, `feat/blender-character-rig-20261109` + +`fix/character-rig-robustness-20261109`) and the animation conversion +(`docs/animation-conversion.md`, `feat/animation-conversion-20261109`). This document is +the map that ties them together; the builder (`tools/characters/build-character-pack.mjs`) +is the only promotion step. + +``` +concept ──> Mint model ──> Blender rig ──> animation bake ──> pack build ──> client verify ──> release pin + (rights) (owner) + pose gate + clip QA + validate + install (own PR) +``` + +## 1. Concept and rights (studio-assets, private) + +A character starts as a ficha in the private `corosolto/studio-assets` repository +(`characters//`): ficha, concept, references and `PROVENANCE.md`. The `## Rights` +section is the contract the builder reads later: `original`, `public-domain` (with +citations) or `political-satire`. Photos of real people never enter either repository; +the concept prompt carries the ORIGINAL CHARACTER or PUBLIC-DOMAIN FIGURE clause +(`tools/gen-character-concept-openrouter.mjs --dry-run` composes it without calling any +paid API). + +## 2. Mint model (owner-generated) + +The unrigged final GLB comes from the owner's Mint run (agents make no paid generation +calls). It lands with the ficha (for the 2026-11 lot: `csbrasil/local/mint-raw/lote30/`). +This is the last time the model has no skeleton: everything after this stage works on the +shared **meshy-28** skeleton. + +## 3. Blender rig + pose gate + +```bash +node tools/characters/rig-character.mjs \ + --config=characters//rig.json --work=/ \ + --source= --clips-from=/public/models/anims/mixamo \ + --retarget=/tools/retarget-glb.mjs +``` + +Clean → parts → joints → armature → weights → assemble → pose, in Blender 5.2, described +in `docs/character-rig.md` (branch `feat/blender-character-rig-20261109`). The gate is the +numeric pose test (`pose-test.json`): the build refuses to continue unless it has **0 +failures**. Work in gauntlet rounds — measure, fix (a `joints.json` override, a +`parts.extras` selector, a weights lever), re-measure, at most 3 rounds; keep the best +round. Gate thresholds: body/upper back ≤ 3.5×, hands ≤ 2.5×, seams ≤ 5 mm, bind ≤ 2 mm; +the pilot quality reference is stricter (worst clip edge ≈ 2.6–2.8×, hands ≤ 1.4×, +synthetic poses ≤ 3.0×). A character whose rig never passes the gate gets **no pack** (7 +of the 37-character lot stayed out for exactly this reason). + +Always look at `joints-review.png` and `parts-review.png` before trusting the numbers. + +## 4. Animation bake + clip QA + +```bash +node tools/animations/build-library.mjs --catalog=/animations/catalog.json --out=/reference +node tools/animations/bake-character.mjs --model=.blender.glb --clips=/reference --out=/ +node tools/animations/clip-qa.mjs --model=.blender.glb --clips=/ --out=/qa-.json --strict --pack=states,loco,combat,ceremony +``` + +`docs/animation-conversion.md` (branch `feat/animation-conversion-20261109`) covers the +conversion of the private Mixamo/Quaternius catalog onto meshy-28, the bake (ground +contact, foot IK, floor clamp, two-hand grip) and the QA gates (foot slide, floor +penetration, floating, hips height, loop seam, grip, skin stretch). The output this +builder consumes is the **character-clips@2** pack: `states.glb` (the 11 runtime states), +`loco.glb`, `combat.glb`, `ceremony.glb`, one GLB per emote and a `manifest.json` that +records each clip's duration, loop flag and catalog provenance. + +QA failures tagged `[rig: …]` are rig-weight defects (tracked by the rig stage, not the +pack); every other failure is a conversion defect and blocks step 5 unless the reviewer +allows it explicitly. + +## 5. Previews + +Render the portraits from the **same GLB the pack ships** (for the 2026-11 lot: +`render_poses.py` from the rig pipeline, orthographic front + three-quarters, framing per +the rig pipeline's height rules). Previews prove identity: they are hashed into the +manifest next to the model. + +## 6. Pack build + validate + +```bash +node tools/characters/build-character-pack.mjs \ + --id= --version=0.2.0 \ + --model=/.blender.glb --pose-test=/pose-test.json \ + --clips=/ --qa=/qa-.json \ + --assets=/characters/ --revision= \ + --preview= --preview=<34.png> \ + --out= +``` + +The builder (`npm run pack:build-character`) is deterministic — same inputs, same pack +bytes — and fails closed. It refuses to build when: + +| Refusal | Meaning | +| --- | --- | +| `pose_gate_failed` | the rig pose test has failures; back to step 3 | +| `qa_failure_not_allowed` | a non-rig clip QA failure is not covered by an explicit `--allow-qa=:` | +| `converter_schema` / `converter_id_mismatch` / `model_sha_mismatch` | the clips were not baked for this model (SHA-256 chain) | +| `state_missing` / `state_layout_unsupported` / `extra_name_not_in_vocabulary` / `pack_file_missing` | the clip set does not match the contract vocabulary or layout | +| `rights_*` | PROVENANCE rights missing, unknown status, no basis, or public-domain without citations | +| `triangles_over_budget` / `bytes_over_budget` | over the declared budgets (triangles cap 15000, bytes 8388608; schema caps 15000/16 MiB) | +| `preview_signature` / `preview_missing` | previews absent or not a real PNG/JPEG/WebP | +| `pack_version_exists` | that version was already published with different content — packs are immutable, bump the version | +| `pack_validation_failed` | the freshly built pack failed the shared contract validator | +| `omit_extra_state` / `omit_extra_invalid` / `omit_extra_absent` / `omit_reason_missing` | an `--omit-extra` names a state, a key outside the vocabulary or twice, a clip the converter never baked, or has neither a reason nor a QA failure to cite | + +The built pack ends in `/character///` and is validated in place +(`tools/validate-pack.mjs` runs inside the build; `npm run pack:validate` re-runs it +standalone). Families in the manifest come from the contract's own `clipFamily`, so the +manifest can never disagree with the validator mirror. The 2026-11 pilot measured the full +layout at 4.4–6.7 MB per pack (worst `bebe-reborn` 6671250 bytes = 80% of the 8 MiB +declared budget; 30 packs, 155.5 MiB total, 85 clips each). + +An optional extra that fails clip QA on one character can leave that character's pack by +owner decision instead of an allowance: `--omit-extra=[:]` (repeatable). The +builder rewrites the clip's family pack without it (same encoding; the other clips decode +identically), drops it from `animations.extra`, stops gating on its QA results and adds one +`source.provenance` line per omission with the reason and every QA failure of that clip, for +example `omitted extra crouchwalk_back (dropped from animations/loco.glb; ...): clip QA: skin +stretch 3.666× @0.6364s > 3.5 [clip: Hips+RightUpLeg]`. The runtime falls back when an +optional extra is missing; states are its floor, so they can never be omitted. + +## 7. Client verify + install + +```bash +node scripts/studio-pack.mjs install /character// # into the local tree +node scripts/studio-pack.mjs verify @ +STUDIO_PACK_ROOT= npm run dev # serves /packs/ +STUDIO_PACK_ROOT= npm run eval:studiochar:browser # real-renderer gate +``` + +The client verifier (client PR #1225) re-checks the installed tree: schema, hashes, +immutable install (versions live side by side), and the runtime resolver's fail-closed +order (`docs/studio-character-release.md`, client PR #1244). Nothing is copied into +`public/`: the dev server and the CDN both serve packs read-only from the pack root. + +## 8. Release pin (own PR, owner's call) + +A character reaches players only when a client release pins the pack +(`public/js/data/content-releases.js`: kind, id, version, `manifestSha256`, +`manifestUrl`, `minRuntime`) — and joining the roster (characters.js, art, backend +allowlist, multiplayer identity) is a separate PR each, per +`docs/studio-character-release.md`. Publishing the pack files to the public Studio pack +root and bumping a pin are owner decisions. + +## Where artifacts live + +| Place | Content | Visibility | +| --- | --- | --- | +| `corosolto/studio-assets` | fichas, concepts, references, Mint finals, `PROVENANCE.md`, raw Mixamo FBX (LFS) + `animations/catalog.json` | private | +| `csbrasil/local/…` (rig work, bake, QA, packs, previews) | every private byte produced by steps 3–6 | private, not committed | +| `corosolto/studio` (this repo) | pipeline tools, contract, docs, synthetic checks — no GLB/FBX/blend/images ever | public | +| `corosolto/client` `public/` | the legacy character tree stays until cutover; **no new character GLBs land here** | public | + +## Checks + +`npm run check` includes `tools/checks/character-pack-builder-check.mjs`: a synthetic +pipeline output (skinned meshy-28 GLB, family packs, pose test, QA report, PROVENANCE, +preview) is built, validated against the contract, rebuilt byte-identical, and every gate +mutant above is rejected with its own error code — including the immutable-version rule +and the QA allowlist. An omitted extra is proven gone from its rewritten family pack and +recorded with its QA number. No real asset bytes are committed anywhere. diff --git a/package.json b/package.json index 5601df9..c3b8281 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "check:pistol-source": "node tools/checks/pistol-hires-pilot-check.mjs", "smoke:pack": "node tools/smoke-pack.mjs", "pack:build-lajes": "node tools/build-lajes-pack.mjs", + "pack:build-character": "node tools/characters/build-character-pack.mjs", "pack:validate": "node tools/validate-pack.mjs", "gauntlet:lajes": "node tools/validate-lajes-gauntlet.mjs" }, diff --git a/tools/characters/build-character-pack.mjs b/tools/characters/build-character-pack.mjs new file mode 100755 index 0000000..5e62296 --- /dev/null +++ b/tools/characters/build-character-pack.mjs @@ -0,0 +1,447 @@ +#!/usr/bin/env node +// Builds one character pack (kind: "character") from the standard pipeline outputs. +// Deterministic promotion step: same inputs always produce the same pack bytes, so a +// rebuilt version is byte-identical and an already-published version can never change. +// +// Inputs (all produced by earlier pipeline stages, see docs/character-pipeline.md): +// --id character id (must equal the converter manifest id) +// --version pack semver, e.g. 0.2.0 +// --model rigged meshy-28 GLB from the Blender rig pipeline (.blender.glb) +// --pose-test pose-test.json from the same rig run (the rig gate; must have 0 failures) +// --clips baked clip dir in character-clips@2 layout (states/loco/combat/ceremony.glb +// + emotes/.glb + manifest.json, from the animation converter) +// --qa clip QA report for those packs (tools/animations/clip-qa.mjs); non-rig +// failures refuse the build unless explicitly allowlisted +// --assets studio-assets character dir (reads PROVENANCE.md ## Rights) +// --revision studio-assets commit the PROVENANCE.md was read at (recorded in the manifest) +// --preview preview image file (png/jpg/jpeg/webp); repeat for more portraits +// --out pack root; the pack lands in /character/// +// --allow-qa explicit allowance ":" for a non-rig QA failure; repeatable +// --rights-reference citation line for a public-domain character; repeatable, >= 1 required +// --omit-extra "[:]": drop that optional extra clip from the pack (its +// family GLB is rewritten without it), skip its QA results and record the +// omission with its reason and QA failures in the manifest provenance; +// repeatable; states can never be omitted +// +// The pack is validated with the shared contract validator (tools/lib/pack.mjs) after it +// is written; a pack that does not validate is not built. No file here is ever committed +// to this repository: model, clips, previews and manifests carry private character bytes. +import { createHash } from 'node:crypto'; +import { copyFileSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { Logger, NodeIO, PropertyType } from '@gltf-transform/core'; +import { ALL_EXTENSIONS } from '@gltf-transform/extensions'; +import { prune } from '@gltf-transform/functions'; +import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { clipFamily, isExtraClipName, optionalCharacterStates, requiredCharacterStates } from '../lib/character-pack.mjs'; +import { validatePack } from '../lib/pack.mjs'; + +export const CONVERTER_SCHEMA = 'coro-solto/character-clips@2'; +const RIGHTS_STATUSES = ['original', 'public-domain', 'political-satire']; +const PREVIEW_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp']); +const FAMILIES = ['loco', 'combat', 'ceremony']; +const TRIANGLE_BUDGET_STEP = 500; +const TRIANGLE_CAP = 15000; +const BYTES_BUDGET = 8388608; // declared byte budget (schema cap is 16 MiB; stay stricter) +const STATE_NAMES = [...requiredCharacterStates, ...optionalCharacterStates]; + +export class BuildCharacterPackError extends Error { + constructor(code, message) { + super(`[${code}] ${message}`); + this.code = code; + } +} + +const sha256 = (file) => createHash('sha256').update(readFileSync(file)).digest('hex'); + +function requiredFile(file, code, what) { + const info = statSync(file, { throwIfNoEntry: false }); + if (!info?.isFile()) throw new BuildCharacterPackError(code, `missing ${what}: ${file}`); + return file; +} + +function readJson(file, code, what) { + let parsed; + try { + parsed = JSON.parse(readFileSync(file, 'utf8')); + } catch (error) { + throw new BuildCharacterPackError(code, `${what} is not valid JSON (${file}): ${error.message}`); + } + return parsed; +} + +function hasPreviewSignature(bytes, extension) { + if (extension === '.png') return bytes.length > 8 && bytes[0] === 0x89 && bytes.subarray(1, 4).toString('ascii') === 'PNG'; + if (extension === '.jpg' || extension === '.jpeg') return bytes.length > 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff; + return bytes.length > 12 && bytes.subarray(0, 4).toString('ascii') === 'RIFF' && bytes.subarray(8, 12).toString('ascii') === 'WEBP'; +} + +// Verifies the rig pose gate: the shipped model must be a rig whose own pose test passed. +function readPoseGate(poseTestPath, id) { + const pose = readJson(requiredFile(poseTestPath, 'pose_test_missing', 'pose test report'), 'pose_test_invalid', 'pose test report'); + const failures = pose.failures ?? []; + if (!Array.isArray(failures)) throw new BuildCharacterPackError('pose_test_invalid', 'pose test failures is not an array'); + if (failures.length) { + throw new BuildCharacterPackError('pose_gate_failed', `${id}: rig pose gate failed with ${failures.length} failures (${poseTestPath}); re-rig the character before packing`); + } + if (!Number.isFinite(pose.triangles) || pose.triangles <= 0) { + throw new BuildCharacterPackError('pose_test_invalid', `${id}: pose test has no triangle count`); + } + return pose; +} + +// Clip QA gate: failures tagged `[rig: ...]` point at rig weights (repair work tracked by +// the rig stage, not the pack); every other failure must be covered by the allowlist. +// Omitted extras leave the pack, so their results no longer gate it. +function checkClipQa(qaPath, allow, omissions, id) { + const qa = readJson(requiredFile(qaPath, 'qa_report_missing', 'clip QA report'), 'qa_report_invalid', 'clip QA report'); + const results = qa.results; + if (!Array.isArray(results)) throw new BuildCharacterPackError('qa_report_invalid', 'clip QA report has no results array'); + const disallowed = []; + for (const result of results) { + if (omissions.has(result.name)) continue; + for (const failure of result.failures ?? []) { + if (String(failure).includes('[rig:')) continue; + const covered = allow.some(({ clip, needle }) => (clip === '*' || clip === result.name) && String(failure).includes(needle)); + if (!covered) disallowed.push(`${result.name}: ${failure}`); + } + } + if (disallowed.length) { + throw new BuildCharacterPackError('qa_failure_not_allowed', `${id}: clip QA has ${disallowed.length} non-rig failure(s) not on the allowlist:\n ${disallowed.join('\n ')}\nfix the conversion or pass --allow-qa=: for a reviewed exception`); + } + return results; +} + +// Omitted extras are an owner decision (for example a clip whose QA fails on this +// character): the runtime falls back when an optional extra is missing, but the states are +// its floor, so only contract extras can be omitted. +function planOmissions(omitExtra, id) { + const omissions = new Map(); + for (const { name, reason } of omitExtra) { + if (STATE_NAMES.includes(name)) { + throw new BuildCharacterPackError('omit_extra_state', `${id}: ${name} is a state; only optional extra clips can be omitted`); + } + if (!isExtraClipName(name)) throw new BuildCharacterPackError('omit_extra_invalid', `${id}: --omit-extra ${JSON.stringify(name)} is not a contract extra name`); + if (omissions.has(name)) throw new BuildCharacterPackError('omit_extra_invalid', `${id}: --omit-extra ${name} given twice`); + omissions.set(name, reason?.trim() ?? ''); + } + return omissions; +} + +// The recorded reason of each omission: the explicit reason plus every QA failure of that +// clip, so the manifest carries the measured numbers that justified dropping it. +function omissionRecords(omissions, results, id) { + return [...omissions].sort(([a], [b]) => a.localeCompare(b)).map(([name, reason]) => { + const failures = results.filter((result) => result.name === name).flatMap((result) => result.failures ?? []).map(String); + const why = [reason, failures.length ? `clip QA: ${failures.join('; ')}` : ''].filter(Boolean).join('; '); + if (!why) { + throw new BuildCharacterPackError('omit_reason_missing', `${id}: omitted extra ${name} has no QA failure to cite; pass --omit-extra=${name}:`); + } + return { name, reason: why }; + }); +} + +// Rewrites a converter family pack without the omitted clips. The document keeps whatever +// encoding it was read with (the converter's EXT_meshopt_compression included), only the +// dropped clips' channels, samplers and now-unused accessors leave; skeleton nodes stay. +async function dropClips(source, names, id) { + await Promise.all([MeshoptDecoder.ready, MeshoptEncoder.ready]); + const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'meshopt.decoder': MeshoptDecoder, 'meshopt.encoder': MeshoptEncoder }); + const document = (await io.read(source)).setLogger(new Logger(Logger.Verbosity.WARN)); + for (const name of names) { + const animation = document.getRoot().listAnimations().find((candidate) => candidate.getName() === name); + if (!animation) throw new BuildCharacterPackError('omit_extra_absent', `${id}: omitted extra ${name} is not in ${source}`); + for (const channel of animation.listChannels()) channel.dispose(); + for (const sampler of animation.listSamplers()) sampler.dispose(); + animation.dispose(); + } + await document.transform(prune({ propertyTypes: [PropertyType.ACCESSOR], keepLeaves: true })); + return Buffer.from(await io.writeBinary(document)); +} + +// Rights come verbatim from the studio-assets PROVENANCE.md ## Rights section. +function parseRights(assetsDir, references, id) { + const provenance = requiredFile(path.join(assetsDir, 'PROVENANCE.md'), 'provenance_missing', 'PROVENANCE.md'); + const markdown = readFileSync(provenance, 'utf8'); + const section = markdown.split(/^## Rights$/m)[1]?.split(/^## /m)[0] ?? ''; + const status = /\*\*([\w-]+)\*\*/.exec(section)?.[1]; + const basis = /^- Basis: (.+)$/m.exec(section)?.[1]?.trim(); + if (!RIGHTS_STATUSES.includes(status ?? '')) { + throw new BuildCharacterPackError('rights_status_invalid', `${id}: rights status ${JSON.stringify(status)} is not one of ${RIGHTS_STATUSES.join(', ')} in ${provenance}`); + } + if (!basis) throw new BuildCharacterPackError('rights_basis_missing', `${id}: no "- Basis:" line in ## Rights of ${provenance}`); + const rights = { status, basis }; + if (status === 'public-domain') { + if (!references.length) { + throw new BuildCharacterPackError('rights_references_missing', `${id}: public-domain requires at least one --rights-reference citation`); + } + rights.references = [...references]; + } + return rights; +} + +// Layout of the converter output (character-clips@2): states share states.glb, extras share +// one family pack per non-emote family, emotes keep one file each. The builder reproduces +// that layout inside the pack and derives every family from the contract's own clipFamily, +// so the manifest can never disagree with the validator mirror. Omitted extras are left out +// of the manifest; a family pack that loses clips is listed in droppedByFamily for rewriting. +function planClips(clipsDir, id, omissions) { + const converter = readJson(requiredFile(path.join(clipsDir, 'manifest.json'), 'converter_manifest_missing', 'converter manifest'), 'converter_manifest_invalid', 'converter manifest'); + if (converter.schema !== CONVERTER_SCHEMA) { + throw new BuildCharacterPackError('converter_schema', `${id}: converter manifest schema is ${JSON.stringify(converter.schema)}, expected ${CONVERTER_SCHEMA}`); + } + if (converter.id !== undefined && converter.id !== id) { + throw new BuildCharacterPackError('converter_id_mismatch', `${id}: converter manifest id is ${converter.id}`); + } + if (!converter.model || typeof converter.model.sha256 !== 'string') { + throw new BuildCharacterPackError('converter_manifest_invalid', `${id}: converter manifest has no model.sha256`); + } + const clips = converter.clips; + if (!clips || typeof clips !== 'object' || Array.isArray(clips)) { + throw new BuildCharacterPackError('converter_manifest_invalid', `${id}: converter manifest has no clips object`); + } + const animations = {}; + const stateFiles = new Set(); + for (const state of STATE_NAMES) { + const clip = clips[state]; + if (!clip) { + if (requiredCharacterStates.includes(state)) throw new BuildCharacterPackError('state_missing', `${id}: state ${state} missing from the converter clips`); + continue; + } + if (clip.file !== 'states.glb') { + throw new BuildCharacterPackError('state_layout_unsupported', `${id}: state ${state} lives in ${clip.file}; this builder consumes the shared states.glb layout`); + } + stateFiles.add(clip.file); + animations[state] = `animations/${clip.file}`; + } + const extra = {}; + const familyCounts = { loco: 0, combat: 0, ceremony: 0, emote: 0 }; + const familyFiles = new Map(); + const emoteFiles = []; + const catalogRoots = new Set(); + const droppedByFamily = new Map(); + for (const [name, clip] of Object.entries(clips)) { + if (STATE_NAMES.includes(name)) continue; + if (!isExtraClipName(name)) { + throw new BuildCharacterPackError('extra_name_not_in_vocabulary', `${id}: clip ${name} is neither a state nor a contract extra name`); + } + const family = clipFamily(name); + if (family === 'states') throw new BuildCharacterPackError('extra_family_invalid', `${id}: clip ${name} classified as a state`); + if (omissions.has(name)) { + if (family !== 'emote') droppedByFamily.set(family, [...(droppedByFamily.get(family) ?? []), name]); + continue; + } + const relative = family === 'emote' ? `animations/emotes/${name}.glb` : `animations/${family}.glb`; + if (family === 'emote') emoteFiles.push([name, relative]); + else familyFiles.set(family, `animations/${family}.glb`); + if (!(Number(clip.duration) > 0)) { + throw new BuildCharacterPackError('clip_metadata_invalid', `${id}: clip ${name} duration ${clip.duration}`); + } + if (typeof clip.provenance !== 'string' || !clip.provenance) { + throw new BuildCharacterPackError('clip_metadata_invalid', `${id}: clip ${name} has no provenance`); + } + extra[name] = { + file: relative, + duration: clip.duration, + loop: !!clip.loop, + rootMotion: false, // clips are baked in place; the converter manifest carries the velocity metadata + source: `${clip.provenance} retargeted to meshy-28 (${CONVERTER_SCHEMA})`, + family, + }; + familyCounts[family] += 1; + catalogRoots.add(clip.provenance.split('/').slice(0, 2).join('/')); + } + animations.extra = extra; + for (const name of omissions.keys()) { + if (!clips[name]) throw new BuildCharacterPackError('omit_extra_absent', `${id}: omitted extra ${name} is not in the converter clips`); + } + // Every referenced source file must exist in the converter output before anything is copied. + const requiredSources = [['states.glb', stateFiles.size > 0], ...FAMILIES.map((family) => [`${family}.glb`, familyFiles.has(family)]), ...emoteFiles.map(([name]) => [`emotes/${name}.glb`, true])]; + for (const [file, needed] of requiredSources) { + if (needed) requiredFile(path.join(clipsDir, file), 'pack_file_missing', `converter pack file ${file}`); + } + return { converter, animations, familyCounts, familyFiles, emoteFiles, droppedByFamily, catalogRoots: [...catalogRoots].sort(), stateCount: STATE_NAMES.filter((state) => animations[state]).length }; +} + +function planPreviews(previews, id) { + if (!previews.length) throw new BuildCharacterPackError('preview_missing', `${id}: at least one --preview is required`); + const seen = new Set(); + return previews.map((preview) => { + const extension = path.extname(preview).toLowerCase(); + if (!PREVIEW_EXTENSIONS.has(extension)) { + throw new BuildCharacterPackError('preview_signature', `${id}: preview ${preview} is not a png/jpg/jpeg/webp`); + } + const name = path.basename(preview); + if (seen.has(name)) throw new BuildCharacterPackError('preview_signature', `${id}: duplicate preview name ${name}`); + seen.add(name); + const bytes = readFileSync(requiredFile(preview, 'preview_missing', 'preview')); + if (!hasPreviewSignature(bytes, extension)) { + throw new BuildCharacterPackError('preview_signature', `${id}: preview ${preview} does not start with the ${extension} signature`); + } + return { source: preview, relative: `previews/${name}` }; + }); +} + +export async function buildCharacterPack({ id, version, model, poseTest, clips, qa, assets, revision, previews = [], allowQa = [], rightsReferences = [], omitExtra = [], out }) { + if (!/^[a-z][a-z0-9-]{0,63}$/.test(id ?? '')) throw new BuildCharacterPackError('id_invalid', `id ${JSON.stringify(id)} must match ^[a-z][a-z0-9-]{0,63}$`); + if (!/^\d+\.\d+\.\d+$/.test(version ?? '')) throw new BuildCharacterPackError('version_invalid', `version ${JSON.stringify(version)} must be semver x.y.z`); + if (!/^[0-9a-f]{7,40}$/.test(revision ?? '')) throw new BuildCharacterPackError('revision_invalid', `revision ${JSON.stringify(revision)} must be a git sha`); + + const modelFile = requiredFile(model, 'model_missing', 'rigged GLB'); + const pose = readPoseGate(poseTest, id); + const omissions = planOmissions(omitExtra, id); + const qaResults = checkClipQa(qa, allowQa, omissions, id); + const omitted = omissionRecords(omissions, qaResults, id); + const rights = parseRights(assets, rightsReferences, id); + const plannedPreviews = planPreviews(previews, id); + const plan = planClips(clips, id, omissions); + + const modelSha = sha256(modelFile); + if (plan.converter.model.sha256 !== modelSha) { + throw new BuildCharacterPackError('model_sha_mismatch', `${id}: converter model sha256 ${plan.converter.model.sha256} != rigged GLB sha256 ${modelSha}; the clips were baked for a different model`); + } + + const budgetTriangles = Math.ceil(pose.triangles / TRIANGLE_BUDGET_STEP) * TRIANGLE_BUDGET_STEP; + if (budgetTriangles > TRIANGLE_CAP) { + throw new BuildCharacterPackError('triangles_over_budget', `${id}: ${pose.triangles} triangles (budget ${budgetTriangles}) over the ${TRIANGLE_CAP} cap`); + } + const counts = plan.familyCounts; + const manifest = { + schemaVersion: 1, + kind: 'character', + id, + version, + source: { + revision, + provenance: [ + `studio-assets characters/${id} @ ${revision.slice(0, 8)}: ficha, concept, rights; rigged model sha256 ${modelSha}`, + `Blender character rig pipeline${pose.label ? ` (${pose.label})` : ''}: clean+parts+joints+weights, meshy-28, pose gate PASS (0 failures)`, + `${CONVERTER_SCHEMA}: ${plan.stateCount} states + ${counts.loco} loco + ${counts.combat} combat + ${counts.ceremony} ceremony + ${counts.emote} emotes; catalog: ${plan.catalogRoots.join(', ')}`, + ...omitted.map(({ name, reason }) => { + const family = clipFamily(name); + const where = family === 'emote' ? 'emote file not packed' : `dropped from animations/${family}.glb`; + return `omitted extra ${name} (${where}; the runtime falls back for a missing optional extra): ${reason}`; + }), + ], + }, + files: [], + model: `model/${id}.glb`, + skeleton: 'meshy-28', + animations: plan.animations, + previews: plannedPreviews.map(({ relative }) => relative), + rights, + budgets: { triangles: budgetTriangles, bytes: BYTES_BUDGET }, + }; + + // Assemble into a staging name first: a version directory that already exists must stay + // byte-identical, so an existing differing manifest refuses the build before any copy. + const directory = path.join(path.resolve(out), 'character', id, version); + const staging = `${directory}.building`; + const manifestPath = path.join(directory, 'manifest.json'); + const entries = []; + const putStaged = (source, relative) => { + const staged = path.join(staging, relative); + mkdirSync(path.dirname(staged), { recursive: true }); + copyFileSync(source, staged); + entries.push({ path: relative, sha256: sha256(staged), bytes: statSync(staged).size }); + }; + const putStagedBytes = (bytes, relative) => { + const staged = path.join(staging, relative); + mkdirSync(path.dirname(staged), { recursive: true }); + writeFileSync(staged, bytes); + entries.push({ path: relative, sha256: sha256(staged), bytes: bytes.length }); + }; + try { + putStaged(modelFile, `model/${id}.glb`); + if (plan.stateCount > 0) putStaged(path.join(clips, 'states.glb'), 'animations/states.glb'); + for (const family of FAMILIES) { + if (!plan.familyFiles.has(family)) continue; + const source = path.join(clips, `${family}.glb`); + const dropped = plan.droppedByFamily.get(family); + if (dropped) putStagedBytes(await dropClips(source, dropped, id), `animations/${family}.glb`); + else putStaged(source, `animations/${family}.glb`); + } + for (const [name] of plan.emoteFiles) putStaged(path.join(clips, 'emotes', `${name}.glb`), `animations/emotes/${name}.glb`); + for (const { source, relative } of plannedPreviews) putStaged(source, relative); + + const totalBytes = entries.reduce((sum, file) => sum + file.bytes, 0); + if (totalBytes > BYTES_BUDGET) { + throw new BuildCharacterPackError('bytes_over_budget', `${id}: ${totalBytes} bytes over the declared ${BYTES_BUDGET} byte budget`); + } + manifest.files = [...entries].sort((a, b) => a.path.localeCompare(b.path)); + const manifestBytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`); + if (statSync(manifestPath, { throwIfNoEntry: false })?.isFile()) { + if (!readFileSync(manifestPath).equals(manifestBytes)) { + throw new BuildCharacterPackError('pack_version_exists', `${manifestPath} already exists with different content; packs are immutable, publish a new version instead`); + } + } else { + mkdirSync(directory, { recursive: true }); + writeFileSync(manifestPath, manifestBytes); + for (const entry of entries) { + const destination = path.join(directory, entry.path); + mkdirSync(path.dirname(destination), { recursive: true }); + copyFileSync(path.join(staging, entry.path), destination); + } + } + + let validation; + try { + validation = await validatePack({ manifestPath, packageRoot: directory }); + } catch (error) { + throw new BuildCharacterPackError('pack_validation_failed', `${id}@${version}: the built pack failed the contract validator: ${error.message}`); + } + return { + id, + version, + directory, + manifestSha256: sha256(manifestPath), + totalBytes, + triangles: pose.triangles, + budgetTriangles, + files: validation.manifest.files.length, + omitted: omitted.map(({ name }) => name), + manifest, + }; + } finally { + rmSync(staging, { recursive: true, force: true }); + } +} + +function repeatable(argv, name) { + return argv.filter((argument) => argument.startsWith(`--${name}=`)).map((argument) => argument.slice(name.length + 3)); +} + +const isInvocation = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url); +if (isInvocation) { + const argv = process.argv.slice(2); + const value = (name) => { + const match = argv.find((argument) => argument.startsWith(`--${name}=`)); + if (match === undefined) throw new BuildCharacterPackError('argument_missing', `--${name} is required`); + return match.slice(name.length + 3); + }; + const summary = await buildCharacterPack({ + id: value('id'), + version: value('version'), + model: value('model'), + poseTest: value('pose-test'), + clips: value('clips'), + qa: value('qa'), + assets: value('assets'), + revision: value('revision'), + out: value('out'), + previews: repeatable(argv, 'preview'), + allowQa: repeatable(argv, 'allow-qa').map((entry) => { + const separator = entry.indexOf(':'); + if (separator <= 0) throw new BuildCharacterPackError('argument_invalid', `--allow-qa expects ":", got ${JSON.stringify(entry)}`); + return { clip: entry.slice(0, separator), needle: entry.slice(separator + 1) }; + }), + rightsReferences: repeatable(argv, 'rights-reference'), + omitExtra: repeatable(argv, 'omit-extra').map((entry) => { + const separator = entry.indexOf(':'); + return separator < 0 ? { name: entry } : { name: entry.slice(0, separator), reason: entry.slice(separator + 1) }; + }), + }); + const omittedNote = summary.omitted.length ? `, omitted ${summary.omitted.join(', ')}` : ''; + console.log(`PASS character/${summary.id}@${summary.version}: built ${summary.files} files, ${summary.totalBytes}/${BYTES_BUDGET} bytes, ${summary.triangles}/${summary.budgetTriangles} triangles${omittedNote}, manifest sha256 ${summary.manifestSha256}`); +} diff --git a/tools/checks/character-pack-builder-check.mjs b/tools/checks/character-pack-builder-check.mjs new file mode 100755 index 0000000..8590b3c --- /dev/null +++ b/tools/checks/character-pack-builder-check.mjs @@ -0,0 +1,384 @@ +#!/usr/bin/env node +// Proves tools/characters/build-character-pack.mjs end to end on a synthetic pipeline +// output (programmatic skinned GLB, converter-layout clip packs, synthetic pose-test, QA +// report, PROVENANCE and preview — no real asset bytes, nothing committed): a healthy +// build validates against the contract, is byte-deterministic, and every gate mutant is +// rejected with its own error code. +import { createHash } from 'node:crypto'; +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import { isExtraClipName, meshy28Joints, optionalCharacterStates, requiredCharacterStates } from '../lib/character-pack.mjs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { buildCharacterPack, BuildCharacterPackError, CONVERTER_SCHEMA } from '../characters/build-character-pack.mjs'; +import { readGlb } from '../lib/glb-inspect.mjs'; +import { validatePack } from '../lib/pack.mjs'; + +const root = fileURLToPath(new URL('../../', import.meta.url)); +const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64'); +const sha256 = bytes => createHash('sha256').update(bytes).digest('hex'); +const pad4 = bytes => Buffer.concat([bytes, Buffer.alloc((4 - (bytes.length % 4)) % 4)]); +const ID = 'fixture-builder-character'; +const REVISION = '7b4b30d4b0b0fc56a58da3686ac987dfc5d36376'; + +let caseNumber = 0; +let passed = 0; +const fixtureDirectories = []; + +function glb(document, chunks) { + const views = []; + const parts = []; + let offset = 0; + for (const chunk of chunks) { + const padded = pad4(chunk.bytes); + views.push({ buffer: 0, byteOffset: offset, byteLength: chunk.bytes.length }); + parts.push(padded); + offset += padded.length; + } + const bin = Buffer.concat(parts); + const json = Buffer.from(JSON.stringify({ asset: { version: '2.0', generator: 'coro-solto-studio builder-check' }, ...document, buffers: [{ byteLength: bin.length }], 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); + header.writeUInt32LE(2, 4); + header.writeUInt32LE(28 + paddedJson.length + bin.length, 8); + header.writeUInt32LE(paddedJson.length, 12); + header.writeUInt32LE(0x4e4f534a, 16); + const binHeader = Buffer.alloc(8); + binHeader.writeUInt32LE(bin.length, 0); + binHeader.writeUInt32LE(0x004e4942, 4); + return Buffer.concat([header, paddedJson, binHeader, bin]); +} + +function skeletonNodes() { + const nodes = [{ name: 'Armature', children: [] }]; + const firstIndex = new Map(); + for (const [name] of meshy28Joints) { + firstIndex.set(name, firstIndex.get(name) ?? nodes.length); + nodes.push({ name }); + } + meshy28Joints.forEach(([, parent], offset) => { + const owner = parent === null ? nodes[0] : nodes[firstIndex.get(parent)]; + owner.children = [...(owner.children || []), offset + 1]; + }); + return nodes; +} + +function floats(values) { + const bytes = Buffer.alloc(values.length * 4); + values.forEach((value, index) => bytes.writeFloatLE(value, index * 4)); + return bytes; +} + +function modelGlb() { + const nodes = skeletonNodes(); + const vertexCount = 12 * 3; + const positions = floats(Array.from({ length: vertexCount * 3 }, (_, index) => ((index * 7) % 11) * 0.01)); + const jointIndices = Buffer.alloc(vertexCount * 4); + const jointWeights = floats(Array.from({ length: vertexCount * 4 }, (_, index) => (index % 4 === 0 ? 1 : 0))); + const indices = Buffer.alloc(vertexCount * 2); + for (let index = 0; index < vertexCount; index += 1) indices.writeUInt16LE(index, index * 2); + const inverseBind = floats(meshy28Joints.flatMap(() => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])); + nodes.push({ name: 'Body', mesh: 0, skin: 0 }); + return glb({ + scene: 0, + scenes: [{ nodes: [0, nodes.length - 1] }], + nodes, + meshes: [{ name: 'Body', primitives: [{ attributes: { POSITION: 0, JOINTS_0: 1, WEIGHTS_0: 2 }, indices: 3, mode: 4 }] }], + accessors: [ + { bufferView: 0, componentType: 5126, count: vertexCount, type: 'VEC3', min: [0, 0, 0], max: [0.1, 0.1, 0.1] }, + { bufferView: 1, componentType: 5121, count: vertexCount, type: 'VEC4' }, + { bufferView: 2, componentType: 5126, count: vertexCount, type: 'VEC4' }, + { bufferView: 3, componentType: 5123, count: vertexCount, type: 'SCALAR' }, + { bufferView: 4, componentType: 5126, count: meshy28Joints.length, type: 'MAT4' }, + ], + skins: [{ name: 'Armature', skeleton: 1, joints: meshy28Joints.map((_, offset) => offset + 1), inverseBindMatrices: 4 }], + }, [ + { bytes: positions }, + { bytes: jointIndices }, + { bytes: jointWeights }, + { bytes: indices }, + { bytes: inverseBind }, + ]); +} + +// One GLB holding several named clips (the converter's states/family pack layout). +function clipsGlb(names) { + const nodes = skeletonNodes(); + 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 STATES = [...requiredCharacterStates, ...optionalCharacterStates]; +const LOCO_CLIPS = ['strafe_left', 'walk_back']; +const COMBAT_CLIPS = ['reload_rifle']; +const CEREMONY_CLIPS = ['victory']; +const EMOTE_CLIPS = ['emote_danca']; +for (const name of [...LOCO_CLIPS, ...COMBAT_CLIPS, ...CEREMONY_CLIPS, ...EMOTE_CLIPS]) { + if (!isExtraClipName(name)) throw new Error(`fixture clip ${name} is not in the contract vocabulary`); +} + +function converterClips() { + const clips = {}; + for (const state of STATES) clips[state] = { file: 'states.glb', duration: 1.2, loop: true, provenance: 'mixamo/fixture/state' }; + for (const name of LOCO_CLIPS) clips[name] = { file: 'loco.glb', duration: 0.9, loop: true, provenance: 'mixamo/fixture/loco' }; + for (const name of COMBAT_CLIPS) clips[name] = { file: 'combat.glb', duration: 2.4, loop: false, provenance: 'mixamo/fixture/combat' }; + for (const name of CEREMONY_CLIPS) clips[name] = { file: 'ceremony.glb', duration: 3.1, loop: false, provenance: 'quaternius/fixture/ceremony' }; + for (const name of EMOTE_CLIPS) clips[name] = { file: 'emotes/emote_danca.glb', duration: 2.0, loop: true, provenance: 'mixamo/fixture/emote' }; + return clips; +} + +// Writes one synthetic pipeline output; every mutant below overrides a piece of it. +function writeFixture(overrides = {}) { + const directory = path.join(os.tmpdir(), `studio-builder-${process.pid}-${caseNumber += 1}`); + fixtureDirectories.push(directory); + const modelBytes = overrides.modelBytes ?? modelGlb(); + const clips = overrides.clips ?? converterClips(); + const files = { + 'model.glb': modelBytes, + 'pose-test.json': JSON.stringify({ model: 'model.glb', label: 'v4-fixture', triangles: overrides.triangles ?? 12, failures: overrides.poseFailures ?? [] }, null, 2), + 'clips/manifest.json': JSON.stringify({ + schema: overrides.schema ?? CONVERTER_SCHEMA, + id: overrides.converterId ?? ID, + skeleton: 'meshy-28', + model: { file: 'model.glb', sha256: overrides.modelSha ?? sha256(modelBytes) }, + files: {}, + clips, + }, null, 2), + 'clips/states.glb': clipsGlb(STATES.filter(state => clips[state])), + 'clips/emotes/emote_danca.glb': clipsGlb(['emote_danca']), + 'assets/PROVENANCE.md': overrides.provenance ?? '## Ficha\n\n## Rights\n\n- Status: **original**.\n- Basis: Invented synthetic character; no likeness, no third-party design.\n\n## Notes\n', + 'qa.json': JSON.stringify({ model: 'model.glb', clipCount: 2, failing: [], results: overrides.qaResults ?? [ + { name: 'idle', failures: [] }, + { name: 'death', failures: ['skin stretch 4.16\u00d7 @1.3818s > 3.5 [rig: RightShoulder+Head]'] }, + ] }, null, 2), + 'previews/portrait-front.png': overrides.previewBytes ?? png, + }; + if (clips.strafe_left || clips.walk_back) files['clips/loco.glb'] = clipsGlb(LOCO_CLIPS.filter(name => clips[name])); + if (clips.reload_rifle) files['clips/combat.glb'] = clipsGlb(COMBAT_CLIPS.filter(name => clips[name])); + if (clips.victory) files['clips/ceremony.glb'] = clipsGlb(CEREMONY_CLIPS.filter(name => clips[name])); + for (const [name, bytes] of Object.entries(overrides.extraFiles ?? {})) files[name] = bytes; + for (const name of overrides.removeFiles ?? []) delete files[name]; + for (const [name, bytes] of Object.entries(files)) { + fs.mkdirSync(path.dirname(path.join(directory, name)), { recursive: true }); + fs.writeFileSync(path.join(directory, name), bytes); + } + const defaultOptions = { + id: ID, + version: '0.2.0', + model: path.join(directory, 'model.glb'), + poseTest: path.join(directory, 'pose-test.json'), + clips: path.join(directory, 'clips'), + qa: path.join(directory, 'qa.json'), + assets: path.join(directory, 'assets'), + revision: REVISION, + previews: [path.join(directory, 'previews/portrait-front.png')], + allowQa: overrides.allowQa ?? [], + rightsReferences: overrides.rightsReferences ?? [], + omitExtra: overrides.omitExtra ?? [], + out: overrides.out ?? path.join(directory, 'out'), + }; + return { directory, options: overrides.options ? overrides.options(defaultOptions) : defaultOptions }; +} + +function expectFailure(label, code, overrides) { + const { options } = writeFixture(overrides); + return buildCharacterPack(options).then(() => { + throw new Error(`${label} was not rejected`); + }, error => { + if (!(error instanceof BuildCharacterPackError) || error.code !== code) { + throw new Error(`${label} was rejected for the wrong reason (want [${code}]): ${error.message}`); + } + console.log(`PASS ${label} rejected`); + passed += 1; + }); +} + +async function expectSuccess(label, overrides, verify) { + const { options } = writeFixture(overrides); + const summary = await buildCharacterPack(options); + if (!/^[0-9a-f]{64}$/.test(summary.manifestSha256)) throw new Error(`${label}: manifest sha256 missing`); + if (verify) await verify(summary); + console.log(`PASS ${label}`); + passed += 1; + return summary; +} + +const packRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'studio-builder-pack-')); +try { + // The healthy build: validates against the shared contract, states share states.glb, + // extras carry converter metadata and the family derived by the contract's own mirror. + const healthy = await expectSuccess('healthy build', {}, summary => { + if (summary.files !== 7) throw new Error(`healthy build packed ${summary.files} files, expected 7`); + for (const state of STATES) { + if (summary.manifest.animations[state] !== 'animations/states.glb') throw new Error(`state ${state} does not share states.glb`); + } + const strafe = summary.manifest.animations.extra.strafe_left; + if (strafe.family !== 'loco' || strafe.file !== 'animations/loco.glb' || strafe.loop !== true || strafe.duration !== 0.9) throw new Error('strafe_left extra metadata is wrong'); + if (summary.manifest.animations.extra.emote_danca.file !== 'animations/emotes/emote_danca.glb') throw new Error('emote does not keep its own file'); + if (summary.manifest.rights.status !== 'original' || !summary.manifest.rights.basis.includes('Invented')) throw new Error('rights not copied verbatim'); + if (summary.manifest.source.revision !== REVISION) throw new Error('studio-assets revision not recorded'); + if (summary.manifest.files.at(-1).path !== 'previews/portrait-front.png') throw new Error('files are not sorted by path'); + if (summary.manifest.budgets.triangles !== 500 || summary.manifest.budgets.bytes !== 8388608) throw new Error('budgets not derived from the pose test'); + if (!summary.manifest.source.provenance[2].includes('11 states + 2 loco + 1 combat + 1 ceremony + 1 emote')) throw new Error('converter provenance line is wrong'); + }); + + // The CLI wrapper parses the same arguments and prints the same PASS summary. + { + const { options } = writeFixture({ out: path.join(packRoot, 'cli') }); + const output = execFileSync(process.execPath, [ + path.join(root, 'tools/characters/build-character-pack.mjs'), + `--id=${options.id}`, `--version=${options.version}`, `--model=${options.model}`, `--pose-test=${options.poseTest}`, + `--clips=${options.clips}`, `--qa=${options.qa}`, `--assets=${options.assets}`, `--revision=${options.revision}`, + `--preview=${options.previews[0]}`, `--out=${options.out}`, + ], { encoding: 'utf8' }); + if (!output.startsWith(`PASS character/${ID}@0.2.0: built 7 files`)) throw new Error(`CLI output is not the PASS summary: ${output.trim()}`); + console.log('PASS CLI invocation builds the same pack'); + passed += 1; + } + + // Determinism: the same inputs produce byte-identical manifests wherever they land. + await expectSuccess('deterministic rebuild elsewhere', { out: path.join(packRoot, 'det-b') }, summary => { + if (summary.manifestSha256 !== healthy.manifestSha256) throw new Error('rebuild in another root changed the manifest sha'); + }); + await expectSuccess('immutable version rebuild is a no-op', { out: path.join(packRoot, 'det-b') }, summary => { + }); + + // The built pack also passes the shared validator on its own (defense in depth). + { + const manifestPath = path.join(packRoot, 'det-b', 'character', ID, '0.2.0', 'manifest.json'); + const { character } = await validatePack({ manifestPath, packageRoot: path.dirname(manifestPath) }); + if (character.animations !== STATES.length) throw new Error(`validator counted ${character.animations} state clips`); + console.log('PASS built pack validates against the contract'); + passed += 1; + } + + // An already-published version must never change: identical rebuild is fine, a + // different input under the same version is refused. + { + const immutableRoot = path.join(packRoot, 'immutable'); + await expectSuccess('immutable version first build', { out: immutableRoot }); + await expectFailure('immutable version refuses to change', 'pack_version_exists', { + out: immutableRoot, + previewBytes: Buffer.concat([png, Buffer.from('different bytes')]), + }); + } + + await expectFailure('pose gate failure', 'pose_gate_failed', { poseFailures: ['walk: clip worst edge 12.3\u00d7 > 3.5'] }); + await expectFailure('missing pose test', 'pose_test_missing', { removeFiles: ['pose-test.json'] }); + await expectFailure('missing QA report', 'qa_report_missing', { removeFiles: ['qa.json'] }); + await expectFailure('QA report without results', 'qa_report_invalid', { qaResults: 'nope' }); + await expectFailure('non-rig QA failure', 'qa_failure_not_allowed', { qaResults: [{ name: 'run_back', failures: ['foot slide 5.2 cm > 4 cm'] }] }); + await expectFailure('non-rig QA failure on another clip', 'qa_failure_not_allowed', { qaResults: [{ name: 'idle', failures: [] }, { name: 'jump', failures: ['floating 4.1 cm > 3 cm'] }] }); + await expectSuccess('non-rig QA failure allowlisted by clip', { + qaResults: [{ name: 'run_back', failures: ['foot slide 5.2 cm > 4 cm'] }], + allowQa: [{ clip: 'run_back', needle: 'foot slide 5.2' }], + }); + await expectSuccess('non-rig QA failure allowlisted by wildcard', { + qaResults: [{ name: 'victory', failures: ['floating 4.1 cm > 3 cm'] }], + allowQa: [{ clip: '*', needle: 'floating' }], + }); + await expectFailure('allowlist for the wrong clip does not cover', 'qa_failure_not_allowed', { + qaResults: [{ name: 'run_back', failures: ['foot slide 5.2 cm > 4 cm'] }], + allowQa: [{ clip: 'idle', needle: 'foot slide' }], + }); + await expectFailure('converter schema mismatch', 'converter_schema', { schema: 'coro-solto/character-clips@1' }); + await expectFailure('converter id mismatch', 'converter_id_mismatch', { converterId: 'another-character' }); + await expectFailure('model sha mismatch', 'model_sha_mismatch', { modelSha: '0'.repeat(64) }); + await expectFailure('missing converter manifest', 'converter_manifest_missing', { removeFiles: ['clips/manifest.json'] }); + await expectFailure('required state missing', 'state_missing', { clips: (() => { const clips = converterClips(); delete clips.jump; return clips; })() }); + await expectFailure('state outside states.glb', 'state_layout_unsupported', { clips: (() => { const clips = converterClips(); clips.idle.file = 'idle.glb'; return clips; })() }); + await expectFailure('extra name outside the vocabulary', 'extra_name_not_in_vocabulary', { clips: { ...converterClips(), teleport: { file: 'loco.glb', duration: 1, loop: false, provenance: 'mixamo/fixture/teleport' } } }); + await expectFailure('zero duration clip', 'clip_metadata_invalid', { clips: { ...converterClips(), strafe_left: { ...converterClips().strafe_left, duration: 0 } } }); + await expectFailure('clip without provenance', 'clip_metadata_invalid', { clips: { ...converterClips(), victory: { file: 'ceremony.glb', duration: 3, loop: false, provenance: '' } } }); + await expectFailure('missing family pack file', 'pack_file_missing', { removeFiles: ['clips/loco.glb'] }); + await expectFailure('missing ceremony pack file', 'pack_file_missing', { removeFiles: ['clips/ceremony.glb'] }); + await expectFailure('missing emote file', 'pack_file_missing', { removeFiles: ['clips/emotes/emote_danca.glb'] }); + await expectFailure('missing PROVENANCE', 'provenance_missing', { removeFiles: ['assets/PROVENANCE.md'] }); + await expectFailure('unknown rights status', 'rights_status_invalid', { provenance: '## Rights\n\n- Status: **fan-art**.\n- Basis: Someone else\u2019s character.\n' }); + await expectFailure('rights without basis', 'rights_basis_missing', { provenance: '## Rights\n\n- Status: **original**.\n' }); + await expectFailure('public-domain without citations', 'rights_references_missing', { provenance: '## Rights\n\n- Status: **public-domain**.\n- Basis: Bram Stoker, Dracula, 1897 (author died 1912).\n' }); + await expectSuccess('public-domain with citation', { + provenance: '## Rights\n\n- Status: **public-domain**.\n- Basis: Bram Stoker, Dracula, 1897 (author died 1912).\n', + rightsReferences: ['Bram Stoker, Dracula, 1897 (author died 1912)'], + }, summary => { + if (summary.manifest.rights.references?.[0] !== 'Bram Stoker, Dracula, 1897 (author died 1912)') throw new Error('citation not recorded'); + }); + await expectFailure('triangles over the cap', 'triangles_over_budget', { triangles: 16000 }); + await expectFailure('bytes over the budget', 'bytes_over_budget', { previewBytes: Buffer.concat([png, Buffer.alloc(8388608)]) }); + await expectFailure('preview with wrong signature', 'preview_signature', { previewBytes: Buffer.from('not a png at all') }); + await expectFailure('no preview', 'preview_missing', { options: defaults => ({ ...defaults, previews: [] }) }); + await expectFailure('bad revision', 'revision_invalid', { options: defaults => ({ ...defaults, revision: 'not-a-sha' }) }); + await expectFailure('bad version', 'version_invalid', { options: defaults => ({ ...defaults, version: '0.2' }) }); + + // Omitted extras (owner decision): the clip leaves its family pack and the manifest, its QA + // failure stops gating the build, and the provenance records the reason with the number. + const stretch = 'skin stretch 3.666\u00d7 @0.6364s > 3.5 [clip: Hips+RightUpLeg]'; + await expectFailure('QA failure on a kept extra still refuses', 'qa_failure_not_allowed', { + qaResults: [{ name: 'walk_back', failures: [stretch] }], + }); + await expectSuccess('omitted extra leaves its family pack', { + qaResults: [{ name: 'idle', failures: [] }, { name: 'walk_back', failures: [stretch] }], + omitExtra: [{ name: 'walk_back' }], + }, summary => { + const extra = summary.manifest.animations.extra; + if (extra.walk_back || extra.strafe_left?.file !== 'animations/loco.glb') throw new Error('walk_back still declared or strafe_left lost'); + if (summary.files !== 7) throw new Error(`omitted build packed ${summary.files} files, expected 7`); + const line = summary.manifest.source.provenance.find(entry => entry.startsWith('omitted extra walk_back')); + if (!line?.includes('3.666\u00d7') || !line.includes('animations/loco.glb')) throw new Error(`omission not recorded with its QA number: ${line}`); + if (!summary.manifest.source.provenance[2].includes('11 states + 1 loco')) throw new Error('converter provenance still counts the omitted clip'); + return readGlb(path.join(summary.directory, 'animations/loco.glb'), 'loco.glb', { allowMeshoptFallback: true }).then(({ document }) => { + const names = document.animations.map(animation => animation.name); + if (names.join() !== 'strafe_left') throw new Error(`rewritten loco.glb holds ${names.join(', ')}`); + }); + }); + await expectSuccess('omitted emote with an explicit reason drops its file', { + omitExtra: [{ name: 'emote_danca', reason: 'owner decision: lobby emote cut' }], + }, summary => { + if (summary.files !== 6 || summary.manifest.files.some(file => file.path.includes('emote_danca'))) throw new Error('omitted emote file still packed'); + if (!summary.manifest.source.provenance.some(entry => entry.includes('omitted extra emote_danca') && entry.includes('owner decision: lobby emote cut'))) throw new Error('emote omission reason not recorded'); + }); + { + const { options } = writeFixture({ out: path.join(packRoot, 'cli-omit'), qaResults: [{ name: 'walk_back', failures: [stretch] }] }); + const output = execFileSync(process.execPath, [ + path.join(root, 'tools/characters/build-character-pack.mjs'), + `--id=${options.id}`, `--version=${options.version}`, `--model=${options.model}`, `--pose-test=${options.poseTest}`, + `--clips=${options.clips}`, `--qa=${options.qa}`, `--assets=${options.assets}`, `--revision=${options.revision}`, + `--preview=${options.previews[0]}`, `--out=${options.out}`, '--omit-extra=walk_back', + ], { encoding: 'utf8' }); + if (!output.includes('triangles, omitted walk_back, manifest sha256')) throw new Error(`CLI did not report the omission: ${output.trim()}`); + console.log('PASS CLI --omit-extra builds without the clip'); + passed += 1; + } + await expectFailure('omitting a required state', 'omit_extra_state', { omitExtra: [{ name: 'jump', reason: 'owner decision' }] }); + await expectFailure('omitting an optional state', 'omit_extra_state', { omitExtra: [{ name: 'walkfire', reason: 'owner decision' }] }); + await expectFailure('omitting a name outside the vocabulary', 'omit_extra_invalid', { omitExtra: [{ name: 'teleport', reason: 'owner decision' }] }); + await expectFailure('omitting the same extra twice', 'omit_extra_invalid', { omitExtra: [{ name: 'victory', reason: 'a' }, { name: 'victory', reason: 'b' }] }); + await expectFailure('omitting an extra the converter never baked', 'omit_extra_absent', { + clips: (() => { const clips = converterClips(); delete clips.walk_back; return clips; })(), + omitExtra: [{ name: 'walk_back', reason: 'owner decision' }], + }); + await expectFailure('omission without a reason or QA failure', 'omit_reason_missing', { omitExtra: [{ name: 'strafe_left' }] }); + + console.log(`PASS character pack builder check (${passed} cases)`); +} finally { + fs.rmSync(packRoot, { recursive: true, force: true }); + for (const directory of fixtureDirectories) fs.rmSync(directory, { recursive: true, force: true }); +} diff --git a/tools/studio-check.mjs b/tools/studio-check.mjs index 0eb868f..6002d9f 100755 --- a/tools/studio-check.mjs +++ b/tools/studio-check.mjs @@ -21,6 +21,7 @@ const requiredFiles = [ 'tools/lib/character-pack.mjs', 'tools/lib/character-concept-prompt.mjs', 'tools/checks/character-pack-check.mjs', + 'tools/checks/character-pack-builder-check.mjs', 'tools/checks/character-concept-prompt-check.mjs', 'maps/lajes/gauntlet/fixtures/scene-report.valid.json', ]; @@ -43,6 +44,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']) { +for (const check of ['tools/checks/character-pack-check.mjs', 'tools/checks/character-pack-builder-check.mjs', 'tools/checks/character-concept-prompt-check.mjs']) { execFileSync(process.execPath, [path.join(root, check)], { stdio: 'inherit' }); }