rig-review 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,11 +20,15 @@ import { parseBustSpec } from './chest-landmarks.ts';
20
20
  import { PRODUCER_DOCUMENTS, type ProducerDocument } from './producer-files.ts';
21
21
  import { MESH_EDIT_BASIS, MESH_EDIT_MAX_OPS, MESH_EDIT_SCHEMA } from './mesh-edit.ts';
22
22
  import { assertRetargetRecord, RETARGET_LINE_CODES, type MotionSummary, type RetargetLine, type RetargetRecord } from './retarget.ts';
23
+ import { parseAnimationSourceOp, type AnimationSourceOp } from './animation-ops.ts';
23
24
 
24
25
  export const APPLIED_REGIONS_SCHEMA = 'rig-review-applied/1';
25
26
  export const APPLIED_PATCH_SCHEMA = 'rig-review-applied/2';
26
27
  export const APPLIED_DELTA_SCHEMA = 'rig-review-applied/3';
27
28
  export const APPLIED_RETARGET_SCHEMA = 'rig-review-applied/4';
29
+ export const APPLIED_ANIMATION_SCHEMA = 'rig-review-applied/5';
30
+ /** At most this many animation source ops are kept in a record. */
31
+ export const MAX_ANIMATION_OPS = 200;
28
32
  /** At most this many retarget lines are kept in a record. */
29
33
  export const MAX_RETARGET_LINES = 200;
30
34
  export const CHECK_SUMMARY_SCHEMA = 'rig-review-check-summary/1';
@@ -130,6 +134,24 @@ export interface AppliedRetarget {
130
134
  readings: RetargetLine[];
131
135
  modelHash: string;
132
136
  }
137
+ /** #235: keyed animation edits applied to a scratch copy of `config.motion.animations_from`, rebuilt with `rig-parts rig` and `check`. */
138
+ export interface AppliedAnimation {
139
+ schema: typeof APPLIED_ANIMATION_SCHEMA;
140
+ buildId: string;
141
+ configHash: string;
142
+ animationsFrom: { path: string; beforeSha256: string; afterSha256: string };
143
+ ops: AnimationSourceOp[];
144
+ opsSha256: string;
145
+ /** The rig flags this Apply passed, empty when none; they are part of what rebuilds this state. */
146
+ args: string[];
147
+ producer: Tool; compiler: Tool;
148
+ line: string | null;
149
+ check: CheckSummary | null;
150
+ files: FilesDiff | null;
151
+ modelHash: string;
152
+ /** #112: the exported `rigc-environment/1` schedule Apply's check read, when "Use for readings" was on. */
153
+ environment?: { sha256: string; steps: number };
154
+ }
133
155
  /** One producer document against the inspected one: `count` differing JSON Pointers, the first `MAX_DIFF_PATHS` listed. */
134
156
  export interface DocumentDiff { file: ProducerDocument; count: number; paths: string[] }
135
157
  /** #125: the documents in `PRODUCER_DOCUMENTS` order (a document neither side has is left out) and the images by hash. */
@@ -272,7 +294,21 @@ export function parseAppliedContext(value: unknown): void {
272
294
  }
273
295
  return;
274
296
  }
275
- throw new Error(`${field}.schema: expected ${APPLIED_REGIONS_SCHEMA}, ${APPLIED_PATCH_SCHEMA} (patch ${CONFIG_PATCH_SCHEMA}), ${APPLIED_DELTA_SCHEMA} (mesh-edit delta) or ${APPLIED_RETARGET_SCHEMA} (retarget)`);
297
+ if (value.schema === APPLIED_ANIMATION_SCHEMA) {
298
+ const v = exact(value, `animationsFrom,args,buildId,check,compiler,configHash,${Object.hasOwn(value, 'environment') ? 'environment,' : ''}files,line,modelHash,ops,opsSha256,producer,schema`, field);
299
+ if (![v.buildId, v.configHash, v.opsSha256, v.modelHash].every(hex)) throw new Error(`${field}: buildId, configHash, opsSha256 and modelHash are SHA-256 hex`);
300
+ const af = exact(v.animationsFrom, 'afterSha256,beforeSha256,path', `${field}.animationsFrom`);
301
+ if (typeof af.path !== 'string' || !af.path || !hex(af.beforeSha256) || !hex(af.afterSha256)) throw new Error(`${field}.animationsFrom: {path, beforeSha256, afterSha256 (SHA-256 hex)}`);
302
+ if (!Array.isArray(v.ops) || v.ops.length < 1 || v.ops.length > MAX_ANIMATION_OPS) throw new Error(`${field}.ops: 1–${MAX_ANIMATION_OPS} animation ops`);
303
+ for (const [i, op] of v.ops.entries()) parseAnimationSourceOp(op, `${field}.ops[${i}]`);
304
+ if (!Array.isArray(v.args) || v.args.length > 16 || !v.args.every(a => typeof a === 'string')) throw new Error(`${field}.args: at most 16 strings`);
305
+ tool(v.producer, `${field}.producer`); tool(v.compiler, `${field}.compiler`); lineOrNull(v.line, `${field}.line`);
306
+ parseCheck(v.check, `${field}.check`);
307
+ parseFilesDiff(v.files, `${field}.files`);
308
+ if (Object.hasOwn(v, 'environment')) { const e = exact(v.environment, 'sha256,steps', `${field}.environment`); if (!hex(e.sha256) || !Number.isSafeInteger(e.steps) || (e.steps as number) < 1) throw new Error(`${field}.environment: {sha256 (SHA-256 hex), steps ≥ 1}`); }
309
+ return;
310
+ }
311
+ throw new Error(`${field}.schema: expected ${APPLIED_REGIONS_SCHEMA}, ${APPLIED_PATCH_SCHEMA} (patch ${CONFIG_PATCH_SCHEMA}), ${APPLIED_DELTA_SCHEMA} (mesh-edit delta), ${APPLIED_RETARGET_SCHEMA} (retarget) or ${APPLIED_ANIMATION_SCHEMA} (animation)`);
276
312
  }
277
313
 
278
314
  /** The export's one readable line for a valid applied record; the raw context still follows it. */
@@ -291,6 +327,14 @@ export function appliedSummary(value: unknown): string | null {
291
327
  const mesh = d.mesh ? ` · ${d.mesh.part} v ${d.mesh.before.vertices} t ${d.mesh.before.triangles} → v ${d.mesh.after.vertices} t ${d.mesh.after.triangles}` : '';
292
328
  return `mesh edit ${d.deltaSha256.slice(0, 12)}… (remesh --delta; ${ops} op(s) on ${d.part}) with ${producer.package} ${producer.version}${d.files ? ` · ${filesDiffText(d.files)}` : ''}${mesh} · model ${model}…`;
293
329
  }
330
+ if (v.schema === APPLIED_ANIMATION_SCHEMA) {
331
+ const a = value as AppliedAnimation;
332
+ const anims = [...new Set(a.ops.map(o => o.animation))];
333
+ const check = a.check ? `check ${a.check.pass === null ? 'not read' : a.check.pass ? 'PASS' : 'FAIL'}` : 'check not run';
334
+ const env = a.environment ? ` under the exported world (${a.environment.steps} step(s), sha256 ${a.environment.sha256.slice(0, 16)})` : '';
335
+ const diff = a.files ? ` · ${filesDiffText(a.files)}` : '';
336
+ return `animation ${a.opsSha256.slice(0, 12)}… (${a.ops.length} op(s) on ${anims.join(', ')}; ${a.animationsFrom.path} ${a.animationsFrom.beforeSha256.slice(0, 12)}… → ${a.animationsFrom.afterSha256.slice(0, 12)}…) with ${producer.package} ${producer.version} · ${check}${env}${diff} · model ${model}…`;
337
+ }
294
338
  const a = value as AppliedPatch, paths = a.patch.ops.map(o => `${o.op} ${o.path}`);
295
339
  const check = a.check ? `check ${a.check.pass === null ? 'not read' : a.check.pass ? 'PASS' : 'FAIL'}` : 'check not run';
296
340
  const diff = a.files ? ` · ${filesDiffText(a.files)}` : a.diff ? ` · rig.json differs at ${a.diff.count} path(s)` : '';
@@ -306,7 +350,7 @@ export function appliedSummary(value: unknown): string | null {
306
350
  * else the first bar check.json marks FAIL — verbatim. Null when the record is not a patch or its check did not FAIL.
307
351
  */
308
352
  export function appliedCheckRefusal(value: unknown): string | null {
309
- if (!isObject(value) || value.schema !== APPLIED_PATCH_SCHEMA || !isObject(value.check) || value.check.pass !== false) return null;
353
+ if (!isObject(value) || (value.schema !== APPLIED_PATCH_SCHEMA && value.schema !== APPLIED_ANIMATION_SCHEMA) || !isObject(value.check) || value.check.pass !== false) return null;
310
354
  const check = value.check as unknown as CheckSummary;
311
355
  const bar = Object.entries(check.bars ?? {}).find(([, status]) => status === 'FAIL')?.[0];
312
356
  const line = typeof check.line === 'string' && /\bFAIL\b/.test(check.line) ? check.line : bar ? `${bar}: FAIL` : `check exited ${check.exitCode}`;
@@ -71,22 +71,22 @@ const REGIONS: readonly {
71
71
  key: 'animateBlockRow',
72
72
  placeholder: '<!-- shared:animate-block-row -->',
73
73
  start: '<nav class="block-row" aria-label="Animate blocks">',
74
- end: '<section id="transport"',
75
- compareEnd: '<section id="transport"',
74
+ end: '<section id="motion-tools">',
75
+ compareEnd: '<div class="compare-info">',
76
76
  },
77
77
  {
78
78
  key: 'transportStrips',
79
79
  placeholder: '<!-- shared:transport-strips -->',
80
80
  start: '<div id="reading-ticks"',
81
81
  end: '</section><section id="frame-controls"',
82
- compareEnd: '</section><div class="compare-info">',
82
+ compareEnd: '</section><section id="animation-inspection"',
83
83
  },
84
84
  {
85
85
  key: 'animatePanels',
86
86
  placeholder: '<!-- shared:animate-panels -->',
87
87
  start: '<section id="motion-tools">',
88
- end: '</section></div></section></main>',
89
- compareEnd: '</section><section id="inspector-feedback"',
88
+ end: '</div></section></div></section></main>',
89
+ compareEnd: '</div></section><section id="inspector-feedback"',
90
90
  },
91
91
  ];
92
92
 
package/src/rebuild.ts CHANGED
@@ -17,8 +17,9 @@ import { compileArgs, firstRefusal, modelingProducerTooOld, REMESH_DELTA_SINCE,
17
17
  import { meshEditText } from './mesh-edit.ts';
18
18
  import { CONFIG_NAMED_FILES, HANDOFF_DECLARATION, type Handoff, type HandoffRecord } from './handoff.ts';
19
19
  import { assertWholeRigBaseline, BaselineError, baselineKey, producerDiff, runBaseline, runInspectedCheck, runningInspectedCheck, type BaselineResult, type InspectedCheck } from './baseline.ts';
20
- import { applyConfigPatch, assertOpNames, assertPatchFresh, ConfigPatchError, parseConfigPatch, patchSha256, patchText, remeshPart, type ConfigPatch, type JsonValue } from './config-patch.ts';
21
- import { checkSummary, filesDiffText, MAX_RETARGET_LINES, type CheckSummary, type FilesDiff } from './applied-context.ts';
20
+ import { applyConfigPatch, assertOpNames, assertPatchFresh, ConfigPatchError, parseConfigPatch, PATCH_FLAGS, patchSha256, patchText, remeshPart, type ConfigPatch, type JsonValue } from './config-patch.ts';
21
+ import { checkSummary, filesDiffText, MAX_ANIMATION_OPS, MAX_RETARGET_LINES, type CheckSummary, type FilesDiff } from './applied-context.ts';
22
+ import { AnimationOpBuilder, animationOpsText, parseAnimationSourceOp, type AnimationSourceOp } from './animation-ops.ts';
22
23
  import { idleKeying, idleSource, type IdleStatus } from './idle-tracks.ts';
23
24
  import { CHEST_REGIONS_MAX } from './chest-regions.ts';
24
25
  import { bustMeshEntry, deriveBust, parseBustSpec, BustSpecError, type BustSpec } from './chest-landmarks.ts';
@@ -222,10 +223,10 @@ export interface AppliedEntry {
222
223
  producer: { package: string; version: string }; compiler: { package: string; version: string };
223
224
  files: Record<string, string>; modelHash: string;
224
225
  /** The job as it settled, served back on undo. */
225
- job: RebuildJob | PatchJob | DeltaJob | RetargetJob;
226
+ job: RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob;
226
227
  }
227
228
  /** `GET /api/rebuild/history`: the applied records in order, the last one on the stage; `kept`: its build is still on disk. */
228
- export interface AppliedHistory { schema: 'rig-review-applied-history/1'; depth: number; records: { id: string; kind: 'regions' | 'patch' | 'delta' | 'retarget'; op: string; what: string; modelHash: string; kept: boolean }[] }
229
+ export interface AppliedHistory { schema: 'rig-review-applied-history/1'; depth: number; records: { id: string; kind: 'regions' | 'patch' | 'delta' | 'retarget' | 'animation'; op: string; what: string; modelHash: string; kept: boolean }[] }
229
230
 
230
231
  export type RebuildStatus = 'running' | 'built' | 'refused' | 'failed';
231
232
  export interface RebuildBuild { model: string; modelUrl: string; modelHash: string; files: Record<string, string> }
@@ -375,6 +376,62 @@ export interface DeltaJob {
375
376
  remesh: (RemeshCounts & { modelTriangles: number | null }) | null;
376
377
  build: RebuildBuild | null;
377
378
  }
379
+
380
+ /** #235: keyed animation Apply — `{animation: {configHash, animationsFromHash, ops, args?}}`, spliced onto a scratch copy of `animations_from` and built with `rig-parts rig` + `check`. */
381
+ export interface AnimationRequest { configHash: string; animationsFromHash: string; ops: AnimationSourceOp[]; args: string[] }
382
+ function parseAnimationArgs(args: unknown): string[] {
383
+ if (args === undefined) return [];
384
+ if (!Array.isArray(args) || args.length > 16 || !args.every(a => typeof a === 'string')) bad('args must be an array of at most 16 strings');
385
+ const list = args as string[], seen = new Set<string>();
386
+ for (let i = 0; i < list.length; i += 2) {
387
+ const flag = list[i]!, value = list[i + 1];
388
+ if (seen.has(flag)) bad(`args: ${flag} given twice`);
389
+ seen.add(flag);
390
+ if (value === undefined) bad(`args: ${flag} has no value`);
391
+ const allowed = PATCH_FLAGS[flag];
392
+ if (!allowed) bad(`args: ${flag} is not a flag an animation Apply may pass to rig (allowed: ${Object.keys(PATCH_FLAGS).join(', ')})`);
393
+ if (!allowed.includes(value)) bad(`args: ${flag} ${value} (allowed: ${allowed.join(' | ')})`);
394
+ }
395
+ return [...list];
396
+ }
397
+ export function parseAnimationRequest(input: unknown): AnimationRequest {
398
+ const v = object(input, 'animation'), keys = Object.keys(v).sort().join(',');
399
+ if (keys !== 'animationsFromHash,configHash,ops' && keys !== 'animationsFromHash,args,configHash,ops') bad('expected {configHash, animationsFromHash, ops, args?}');
400
+ if (typeof v.configHash !== 'string' || !/^[a-f0-9]{64}$/.test(v.configHash)) bad('configHash');
401
+ if (typeof v.animationsFromHash !== 'string' || !/^[a-f0-9]{64}$/.test(v.animationsFromHash)) bad('animationsFromHash');
402
+ const args = parseAnimationArgs(v.args);
403
+ if (!Array.isArray(v.ops)) return bad('ops must be an array');
404
+ if (v.ops.length > MAX_ANIMATION_OPS) throw new RebuildError('ANIMATION_OPS_TOO_MANY', `ops must hold at most ${MAX_ANIMATION_OPS} entries (got ${v.ops.length})`);
405
+ if (v.ops.length === 0) throw new RebuildError('ANIMATION_OPS_EMPTY', 'ops must hold at least 1 operation; nothing to apply');
406
+ const ops = v.ops.map((op, i) => {
407
+ try { return parseAnimationSourceOp(op, `ops[${i}]`); }
408
+ catch (e) { return bad(e instanceof Error ? e.message : String(e)); }
409
+ });
410
+ return { configHash: v.configHash as string, animationsFromHash: v.animationsFromHash as string, ops, args };
411
+ }
412
+ /** Deterministic: the package, the config bytes, the handoff animations_from bytes, the canonical ops bytes, both tool versions, any non-default rig flags, and any exported environment schedule. No clock. */
413
+ export function animationId(input: { sourceHash: string; configHash: string; animationsFromHash: string; opsText: string; producer: string; compiler: string; args?: readonly string[]; environment?: string }): string {
414
+ return sha256(JSON.stringify([REBUILD_SCHEMA, 'animation', input.sourceHash, input.configHash, input.animationsFromHash, input.opsText, input.producer, input.compiler, ...(input.args?.length ? [input.args] : []), ...(input.environment ? ['environment', input.environment] : [])]));
415
+ }
416
+ export interface AnimationJob {
417
+ schema: typeof REBUILD_SCHEMA; kind: 'animation'; id: string; status: RebuildStatus; reused: boolean; op: 'rig';
418
+ request: { configHash: string; animationsFrom: { path: string; beforeSha256: string; afterSha256: string }; ops: AnimationSourceOp[]; opsSha256: string; args?: string[] };
419
+ producer: { package: string; version: string }; compiler: { package: string; version: string };
420
+ lines: string[]; producerLine: string | null; exitCode: number | null; wallMs: { op: number | null; compile: number | null; check: number | null };
421
+ hint?: string;
422
+ check: CheckSummary | null;
423
+ files: FilesDiff | null;
424
+ build: RebuildBuild | null;
425
+ environment?: ApplyWorld['record'];
426
+ }
427
+ export interface AnimationSourceStatus {
428
+ available: boolean;
429
+ reason: string | null;
430
+ path: string | null;
431
+ sha256: string | null;
432
+ text: string | null;
433
+ easings: Record<string, [number, number, number, number]> | null;
434
+ }
378
435
  /**
379
436
  * Deterministic: the package, the config bytes, the patch's own bytes and both tool versions. No clock. A retune-routed
380
437
  * patch adds its op (#136), so a scratch build the whole-rig path left for the same patch is never reused as retune's.
@@ -581,7 +638,7 @@ async function hashBuild(build: string, id: string, assetPrefix = '/rebuild'): P
581
638
  /** One rebuild at a time per review instance; finished jobs stay readable by id. */
582
639
  export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
583
640
  const assetPrefix = options.assetPrefix ?? '/rebuild', stripPrefix = options.stripPrefix ?? '/density-strip';
584
- const jobs = new Map<string, RebuildJob | PatchJob | DeltaJob | RetargetJob>();
641
+ const jobs = new Map<string, RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob>();
585
642
  let running: string | null = null;
586
643
  /** #173: the density strip on screen (at most one per review): its candidates run beside each other, none of them applied. */
587
644
  interface StripCandidate { value: number; id: string; entry: JsonValue; dir: string; job: PatchJob; applied: boolean }
@@ -604,7 +661,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
604
661
  const bodies = new Map<string, unknown>();
605
662
  /** #166: an undo re-running an evicted predecessor: its id and the build files it must reproduce. */
606
663
  let restoring: { id: string; files: Record<string, string> } | null = null;
607
- const snapshot = <J extends RebuildJob | PatchJob | DeltaJob | RetargetJob>(job: J): J => ({ ...job, lines: [...job.lines] });
664
+ const snapshot = <J extends RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob>(job: J): J => ({ ...job, lines: [...job.lines] });
608
665
 
609
666
  /** The state directory may not sit inside the package or the handoff's root (the parent of an opened out/). */
610
667
  function assertStateOutside(): void {
@@ -673,10 +730,81 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
673
730
  producer: resolved.ok ? tool(resolved.producer) : null, compiler: resolved.ok ? tool(resolved.compiler) : null,
674
731
  // #114: what the retarget editor offers — the pose producer, the declared sequences, the rig's bones and animations.
675
732
  retarget: await retargetStatus(inputs),
733
+ // #235: the handoff's motion.animations_from file (path, sha256, text) and the rig's easings table for the timeline editor.
734
+ animations: await animationsStatus(inputs),
676
735
  reason,
677
736
  running,
678
737
  };
679
738
  }
739
+ /** #235: what the keyed animation editor starts from. */
740
+ async function animationsStatus(inputs: ProducerInputs | null): Promise<AnimationSourceStatus> {
741
+ if (!inputs) {
742
+ return {
743
+ available: false,
744
+ reason: p.handoff ? handoffGap(p.handoff) : (p.handoffReason ?? modelingHandoffMissing(null)),
745
+ path: null,
746
+ sha256: null,
747
+ text: null,
748
+ easings: null,
749
+ };
750
+ }
751
+ let easings: Record<string, [number, number, number, number]> | null = null;
752
+ try {
753
+ const rigMotion = JSON.parse(await readFile(join(inputs.rig, 'motion.json'), 'utf8')) as { easings?: unknown };
754
+ if (rigMotion.easings && typeof rigMotion.easings === 'object' && !Array.isArray(rigMotion.easings)) {
755
+ easings = rigMotion.easings as Record<string, [number, number, number, number]>;
756
+ }
757
+ } catch { /* optional */ }
758
+ const configDoc = object(JSON.parse(inputs.configText), 'config');
759
+ const motion = configDoc.motion && typeof configDoc.motion === 'object' && !Array.isArray(configDoc.motion) ? configDoc.motion as Record<string, unknown> : null;
760
+ const relFrom = typeof motion?.animations_from === 'string' && motion.animations_from.trim() ? motion.animations_from : null;
761
+ if (!relFrom) {
762
+ return {
763
+ available: false,
764
+ reason: 'ANIMATION_SOURCE_MISSING: config.json does not declare an "animations_from" motion spec file.',
765
+ path: null,
766
+ sha256: null,
767
+ text: null,
768
+ easings,
769
+ };
770
+ }
771
+ let absFrom: string;
772
+ try { absFrom = await realpath(resolve(dirname(inputs.config), relFrom)); }
773
+ catch {
774
+ return {
775
+ available: false,
776
+ reason: `ANIMATION_SOURCE_MISSING: config motion.animations_from (${relFrom}) does not exist`,
777
+ path: relFrom,
778
+ sha256: null,
779
+ text: null,
780
+ easings,
781
+ };
782
+ }
783
+ const showFrom = relative(await realpath(p.root), absFrom).split(sep).join('/') || '.';
784
+ const handoffFile = inputs.handoff.files.find(f => f.path === showFrom);
785
+ if (!handoffFile) {
786
+ return {
787
+ available: false,
788
+ reason: `ANIMATION_SOURCE_MISSING: config motion.animations_from (${showFrom}) is missing from the handoff`,
789
+ path: showFrom,
790
+ sha256: null,
791
+ text: null,
792
+ easings,
793
+ };
794
+ }
795
+ const text = await readFile(absFrom, 'utf8'), hash = sha256(text);
796
+ if (hash !== handoffFile.sha256) {
797
+ return {
798
+ available: false,
799
+ reason: `REBUILD_INPUTS_CHANGED: ${showFrom} changed since the review was opened; restart review`,
800
+ path: showFrom,
801
+ sha256: hash,
802
+ text: null,
803
+ easings,
804
+ };
805
+ }
806
+ return { available: true, reason: null, path: showFrom, sha256: hash, text, easings };
807
+ }
680
808
  /** #111: what the cloth recipe form starts from. */
681
809
  async function clothStatus(handoff: Handoff, inputs: ProducerInputs, resolved: ReturnType<typeof resolveProducer>) {
682
810
  const config = object(JSON.parse(inputs.configText), 'config');
@@ -732,7 +860,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
732
860
  * record leaves it — and the scratch tree is arranged: the stage's build in the scratch root, the other records' most
733
861
  * recent `MAX_KEPT_BUILDS - 1` builds in keptRoot, every other build removed.
734
862
  */
735
- async function landed(job: RebuildJob | PatchJob | DeltaJob | RetargetJob): Promise<void> {
863
+ async function landed(job: RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob): Promise<void> {
736
864
  if (restoring?.id === job.id) { stack.pop(); restoring = null; }
737
865
  else if (stack.at(-1)?.id !== job.id && job.build) stack.push({ id: job.id, body: bodies.get(job.id) ?? null, configHash: job.request.configHash, producer: { ...job.producer }, compiler: { ...job.compiler }, files: { ...job.build.files }, modelHash: job.build.modelHash, job: snapshot(job) });
738
866
  latestId = stack.at(-1)?.id ?? null;
@@ -761,7 +889,9 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
761
889
  const kind = !('kind' in job) ? 'regions' as const : job.kind;
762
890
  const what = !('kind' in job) ? `${job.request.bust ? 'contour.bust landmarks' : `${job.request.regions.length} region(s)`} on ${job.request.part}`
763
891
  : job.kind === 'patch' ? job.request.patch.ops.map(o => `${o.op} ${o.path}`).slice(0, 3).join(', ') + (job.request.patch.ops.length > 3 ? `, +${job.request.patch.ops.length - 3}` : '')
764
- : job.kind === 'delta' ? `mesh edit on ${job.request.part}` : `retarget "${job.request.record.flags.animation}"`;
892
+ : job.kind === 'delta' ? `mesh edit on ${job.request.part}`
893
+ : job.kind === 'animation' ? `${job.request.ops.length} op(s) on ${[...new Set(job.request.ops.map(o => o.animation))].join(', ')}`
894
+ : `retarget "${job.request.record.flags.animation}"`;
765
895
  const kept = await exists(join(last ? rebuildRoot(options.stateDir, p.sourceHash) : keptRoot(options.stateDir, p.sourceHash), e.id));
766
896
  records.push({ id: e.id, kind, op: 'op' in job ? job.op : 'remesh', what, modelHash: e.modelHash, kept });
767
897
  }
@@ -788,7 +918,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
788
918
  // (i) the kept build: back into the scratch root, re-hashed against result.json and against the record.
789
919
  await unkeep(pred.id);
790
920
  const dir = rebuildDir(options.stateDir, p.sourceHash, pred.id);
791
- const kept = await reuse<RebuildJob | PatchJob | DeltaJob | RetargetJob>(dir, pred.id);
921
+ const kept = await reuse<RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob>(dir, pred.id);
792
922
  if (kept && JSON.stringify(kept.build!.files) === JSON.stringify(pred.files)) {
793
923
  jobs.set(pred.id, kept); stack.pop(); latestId = pred.id; await arrange();
794
924
  return { status: 200, body: { status: 'built', undone: top.id, job: snapshot(kept), history: await history() } };
@@ -818,7 +948,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
818
948
  /** The baseline once it settles (tests, and the whole-rig ops of #102/#103 through assertWholeRigBaseline). */
819
949
  async function settledBaseline(): Promise<BaselineResult | null> { if (!baselineRun) ensureBaseline(resolveProducer(options.starts)); return baselineRun ? await baselineRun : baseline; }
820
950
 
821
- async function reuse<J extends RebuildJob | PatchJob | DeltaJob | RetargetJob>(dir: string, id: string): Promise<J | null> {
951
+ async function reuse<J extends RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob>(dir: string, id: string): Promise<J | null> {
822
952
  const resultFile = join(dir, 'result.json');
823
953
  if (!(await exists(resultFile))) return null;
824
954
  try {
@@ -844,7 +974,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
844
974
  * beside the scratch root for undo); anything but a built job leaves nothing behind.
845
975
  * Each runner passes only its producer op and the optional steps it records.
846
976
  */
847
- async function apply(job: RebuildJob | PatchJob | DeltaJob | RetargetJob, dir: string, inputs: ProducerInputs, resolved: Resolved, op: ProducerOp, steps: ApplySteps = {}): Promise<void> {
977
+ async function apply(job: RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob, dir: string, inputs: ProducerInputs, resolved: Resolved, op: ProducerOp, steps: ApplySteps = {}): Promise<void> {
848
978
  const push = (line: string) => { if (job.lines.length < MAX_LINES) job.lines.push(line); };
849
979
  const producer = resolved.producer;
850
980
  // #180: a refusal or failure is published only after its scratch is removed (as "built" is published last, #146),
@@ -859,7 +989,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
859
989
  job.producerLine = firstRefusal(run.lines) ?? `${op.tool ?? 'rig-parts'} ${op.cmd} exited ${run.exitCode} without a named refusal`;
860
990
  // #148: the producer's line stays as printed; review adds what it means here, when it knows.
861
991
  const hint = producerHint(job.producerLine);
862
- if (hint && !('refusals' in job)) { (job as RebuildJob | PatchJob | DeltaJob).hint = hint; push(`review: ${hint}`); }
992
+ if (hint && !('refusals' in job)) { (job as RebuildJob | PatchJob | DeltaJob | AnimationJob).hint = hint; push(`review: ${hint}`); }
863
993
  outcome = 'refused'; return;
864
994
  }
865
995
  job.producerLine = run.stdout.filter(l => l.trim()).at(-1)?.trim() ?? null;
@@ -1472,8 +1602,168 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1472
1602
  });
1473
1603
  }
1474
1604
 
1605
+ /** #235: spliced `animations_from` → `<dir>/animations.json`, `<dir>/config.json` pointing at it → `rig-parts rig` → compile → `rig-parts check`. */
1606
+ function executeAnimation(job: AnimationJob, dir: string, inputs: ProducerInputs, resolved: Resolved, scratchConfig: string, splicedAnimations: string, world: ApplyWorld | null = null): Promise<void> {
1607
+ const args = job.request.args ?? [], producer = resolved.producer;
1608
+ return apply(job, dir, inputs, resolved, {
1609
+ cmd: 'rig', spec: 'rig',
1610
+ async run(push) {
1611
+ await writeFile(join(dir, 'animations.json'), splicedAnimations, { mode: 0o600 });
1612
+ await writeFile(join(dir, 'config.json'), scratchConfig, { mode: 0o600 });
1613
+ const anims = [...new Set(job.request.ops.map(o => o.animation))];
1614
+ push(`review: ${producer.package} ${producer.version} rig --config config.json (${job.request.ops.length} animation op(s) on ${anims.join(', ')}; ${job.request.animationsFrom.path} ${job.request.animationsFrom.beforeSha256.slice(0, 12)}… → ${job.request.animationsFrom.afterSha256.slice(0, 12)}…) → scratch rig`);
1615
+ return runTool(producer.bin, ['rig', '--config', 'config.json', '--parts', inputs.parts, '--out', 'rig', ...args], { cwd: dir, onLine: push });
1616
+ },
1617
+ wallMs: ms => { job.wallMs.op = ms; },
1618
+ async flags() {
1619
+ return { pageEdges: flagValue(args, '--page-edges', 'free') as PageEdges, packShape: flagValue(args, '--pack-shape', 'polygon') as PackShape, note: '' };
1620
+ },
1621
+ }, {
1622
+ diff: files => { job.files = files; },
1623
+ check: (summary: CheckSummary, wallMs: number | null) => { job.wallMs.check = wallMs; job.check = summary; },
1624
+ world,
1625
+ });
1626
+ }
1627
+
1628
+ /**
1629
+ * `POST /api/rebuild` with `{animation: {configHash, animationsFromHash, ops, args?}, environment?}` (#235): applies the cumulative
1630
+ * span-preserving ops directly to the handoff's `motion.animations_from` text (`REBUILD_ANIMATIONS_STALE` when
1631
+ * `animationsFromHash` does not match the handoff file), writes `<dir>/animations.json` and `<dir>/config.json` in
1632
+ * scratch, and runs `rig-parts rig` + `rigc build` + `check`. Empty or no-op ops (leaving `animations_from` equal to
1633
+ * the handoff text) are refused before anything is written or run; producer refusals return by name with nothing landed.
1634
+ */
1635
+ async function startAnimation(input: unknown, world: ApplyWorld | null = null, rawEnvironment?: unknown): Promise<{ status: number; body: unknown }> {
1636
+ const request = parseAnimationRequest(input);
1637
+ assertStateOutside();
1638
+ await options.unchanged();
1639
+ const inputs = await producerInputs(p.handoff, p.handoffReason);
1640
+ if (inputs.configHash !== request.configHash) throw new RebuildError('REBUILD_CONFIG_STALE', 'the producer config changed since the editor read it; reload');
1641
+ const configDoc = object(JSON.parse(inputs.configText), 'config');
1642
+ const motion = configDoc.motion && typeof configDoc.motion === 'object' && !Array.isArray(configDoc.motion) ? configDoc.motion as Record<string, unknown> : null;
1643
+ const relFrom = typeof motion?.animations_from === 'string' && motion.animations_from ? motion.animations_from : null;
1644
+ if (!relFrom) throw new RebuildError('ANIMATION_SOURCE_MISSING', 'the handoff config declares no motion.animations_from');
1645
+ // The handoff records a named file's canonical path, so an alias inside the package reads as the file it names.
1646
+ let absFrom: string;
1647
+ try { absFrom = await realpath(resolve(dirname(inputs.config), relFrom)); }
1648
+ catch { throw new RebuildError('ANIMATION_SOURCE_MISSING', `config motion.animations_from (${relFrom}) does not exist`); }
1649
+ const showFrom = relative(await realpath(p.root), absFrom).split(sep).join('/') || '.';
1650
+ const handoffFile = inputs.handoff.files.find(f => f.path === showFrom);
1651
+ if (!handoffFile) throw new RebuildError('ANIMATION_SOURCE_MISSING', `config motion.animations_from (${showFrom}) is missing from the handoff`);
1652
+ const baseAnimText = await readFile(absFrom, 'utf8'), baseAnimHash = sha256(baseAnimText);
1653
+ if (baseAnimHash !== handoffFile.sha256) throw new RebuildError('REBUILD_INPUTS_CHANGED', `${showFrom} changed since the review was opened; restart review`);
1654
+ if (request.animationsFromHash !== baseAnimHash) {
1655
+ throw new RebuildError('REBUILD_ANIMATIONS_STALE', 'the animations_from file changed since the editor read it; reload');
1656
+ }
1657
+
1658
+ let fallbackEasings: Record<string, [number, number, number, number]> | undefined;
1659
+ try {
1660
+ const rigMotion = JSON.parse(await readFile(join(inputs.rig, 'motion.json'), 'utf8')) as { easings?: unknown };
1661
+ if (rigMotion.easings && typeof rigMotion.easings === 'object' && !Array.isArray(rigMotion.easings)) {
1662
+ fallbackEasings = rigMotion.easings as Record<string, [number, number, number, number]>;
1663
+ }
1664
+ } catch { /* optional */ }
1665
+
1666
+ const builder = new AnimationOpBuilder(baseAnimText, fallbackEasings);
1667
+ try {
1668
+ for (const op of request.ops) builder.apply(op);
1669
+ } catch (e) {
1670
+ const msg = e instanceof Error ? e.message : String(e);
1671
+ const colon = msg.indexOf(': ');
1672
+ if (colon > 0 && /^[A-Z][A-Z0-9_]+$/.test(msg.slice(0, colon))) {
1673
+ throw new RebuildError(msg.slice(0, colon), msg.slice(colon + 2));
1674
+ }
1675
+ throw new RebuildError('ANIMATION_OP_FAILED', msg);
1676
+ }
1677
+
1678
+ const splicedAnimText = builder.text;
1679
+ const effectiveOps = [...builder.ops];
1680
+ if (!builder.dirty || splicedAnimText === baseAnimText || effectiveOps.length === 0) {
1681
+ throw new RebuildError('ANIMATION_OPS_NOOP', 'the animation operations leave animations_from byte-identical; nothing to apply');
1682
+ }
1683
+
1684
+ const resolved = resolveProducer(options.starts);
1685
+ if (!resolved.ok) return { status: 200, body: { status: 'refused', error: resolved.error, producerLine: resolved.error } };
1686
+ if (world && !versionAtLeast(resolved.producer.version, CHECK_ENVIRONMENT_SINCE)) {
1687
+ const error = modelingProducerTooOld(resolved.producer.version || 'unknown', CHECK_ENVIRONMENT_SINCE, 'rig-parts check --environment');
1688
+ return { status: 200, body: { status: 'refused', error, producerLine: error } };
1689
+ }
1690
+ try { assertWholeRigBaseline(await settledBaseline()); } catch (e) { if (e instanceof BaselineError) throw new RebuildError(e.code, e.message.slice(e.code.length + 2)); throw e; }
1691
+
1692
+ const opsText = animationOpsText(effectiveOps), opsSha256 = sha256(opsText), afterSha256 = sha256(splicedAnimText);
1693
+ const id = animationId({
1694
+ sourceHash: p.sourceHash,
1695
+ configHash: inputs.configHash,
1696
+ animationsFromHash: baseAnimHash,
1697
+ opsText,
1698
+ producer: `${resolved.producer.package}@${resolved.producer.version}`,
1699
+ compiler: `${resolved.compiler.package}@${resolved.compiler.version}`,
1700
+ args: request.args,
1701
+ ...(world ? { environment: world.record.sha256 } : {}),
1702
+ });
1703
+ const current = jobs.get(id);
1704
+ if (current?.status === 'running') return { status: 202, body: snapshot(current) };
1705
+ if (busy()) return { status: 200, body: { status: 'refused', error: busy(), producerLine: null } };
1706
+
1707
+ const scratchDoc = JSON.parse(scratchConfigText(inputs.config, configDoc as unknown as JsonValue)) as Record<string, unknown>;
1708
+ (scratchDoc.motion as Record<string, unknown>).animations_from = 'animations.json';
1709
+ const scratchCfgText = JSON.stringify(scratchDoc, null, 2) + '\n';
1710
+ const recordedBody = {
1711
+ animation: {
1712
+ configHash: inputs.configHash,
1713
+ animationsFromHash: baseAnimHash,
1714
+ ops: effectiveOps,
1715
+ ...(request.args.length ? { args: request.args } : {}),
1716
+ },
1717
+ ...(world && rawEnvironment !== undefined ? { environment: rawEnvironment } : {}),
1718
+ };
1719
+
1720
+ return reserve(`REBUILD_BUSY: rebuild ${id} is still running`, async () => {
1721
+ guardRestore(id);
1722
+ const dir = rebuildDir(options.stateDir, p.sourceHash, id);
1723
+ await adopt(id);
1724
+ await unkeep(id);
1725
+ const reused = await reuse<AnimationJob>(dir, id);
1726
+ if (reused) { jobs.set(id, reused); latestId = id; bodies.set(id, recordedBody); await landed(reused); return { status: 200, body: snapshot(reused) }; }
1727
+ const job: AnimationJob = {
1728
+ schema: REBUILD_SCHEMA,
1729
+ kind: 'animation',
1730
+ id,
1731
+ status: 'running',
1732
+ reused: false,
1733
+ op: 'rig',
1734
+ request: {
1735
+ configHash: inputs.configHash,
1736
+ animationsFrom: { path: showFrom, beforeSha256: baseAnimHash, afterSha256 },
1737
+ ops: effectiveOps,
1738
+ opsSha256,
1739
+ ...(request.args.length ? { args: [...request.args] } : {}),
1740
+ },
1741
+ producer: tool(resolved.producer),
1742
+ compiler: tool(resolved.compiler),
1743
+ lines: [],
1744
+ producerLine: null,
1745
+ exitCode: null,
1746
+ wallMs: { op: null, compile: null, check: null },
1747
+ check: null,
1748
+ files: null,
1749
+ build: null,
1750
+ ...(world ? { environment: world.record } : {}),
1751
+ };
1752
+ jobs.set(id, job); running = id; bodies.set(id, recordedBody);
1753
+ void executeAnimation(job, dir, inputs, resolved, scratchCfgText, splicedAnimText, world).finally(() => { if (running === id) running = null; });
1754
+ return { status: 202, body: snapshot(job) };
1755
+ });
1756
+ }
1757
+
1475
1758
  /** `POST /api/rebuild`: refusals are returned before anything is written or run. */
1476
1759
  async function start(input: unknown): Promise<{ status: number; body: unknown }> {
1760
+ if (input && typeof input === 'object' && !Array.isArray(input) && Object.hasOwn(input, 'animation')) {
1761
+ const keys = Object.keys(input).sort().join(',');
1762
+ if (keys !== 'animation' && keys !== 'animation,environment') bad('expected exactly {animation} or {animation, environment}');
1763
+ const rawEnv = Object.hasOwn(input, 'environment') ? (input as { environment: unknown }).environment : undefined;
1764
+ const world = rawEnv !== undefined ? parseApplyWorld(rawEnv) : null;
1765
+ return startAnimation((input as { animation: unknown }).animation, world, rawEnv);
1766
+ }
1477
1767
  if (input && typeof input === 'object' && !Array.isArray(input) && Object.hasOwn(input, 'retarget')) {
1478
1768
  if (Object.keys(input).length !== 1) bad('expected exactly {retarget}');
1479
1769
  return startRetarget((input as { retarget: unknown }).retarget, input);
@@ -1512,7 +1802,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1512
1802
  });
1513
1803
  }
1514
1804
 
1515
- function read(id: string): RebuildJob | PatchJob | DeltaJob | RetargetJob {
1805
+ function read(id: string): RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob {
1516
1806
  const job = jobs.get(id);
1517
1807
  if (!job) throw new RebuildError('REBUILD_NOT_FOUND', id);
1518
1808
  return snapshot(job);