rig-review 0.19.0 → 0.20.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-review",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -1397,14 +1397,251 @@ export function applyAnimationOps(
1397
1397
  text: string,
1398
1398
  ops: readonly AnimationSourceOp[],
1399
1399
  ): AppliedAnimationOpsResult {
1400
- let current = text;
1400
+ const builder = new AnimationOpBuilder(text);
1401
1401
  const allSpans: { start: number; end: number }[] = [];
1402
1402
  for (const op of ops) {
1403
- const res = applyAnimationOp(current, op, text);
1404
- current = res.text;
1403
+ const res = builder.apply(op);
1405
1404
  allSpans.push(...res.changedSpans);
1406
1405
  }
1407
- return { text: current, changedSpans: allSpans };
1406
+ return { text: builder.text, changedSpans: builder.dirty ? allSpans : [] };
1407
+ }
1408
+
1409
+ /** Canonical serialized form of an `AnimationSourceOp[]` list for deterministic hashing. */
1410
+ export function animationOpsText(ops: readonly AnimationSourceOp[]): string {
1411
+ return JSON.stringify(ops);
1412
+ }
1413
+
1414
+ /** Validate and normalize one `AnimationSourceOp` from an untrusted request or applied record. */
1415
+ export function parseAnimationSourceOp(value: unknown, field = 'op'): AnimationSourceOp {
1416
+ if (!isRecord(value) || typeof value.op !== 'string') {
1417
+ throw new Error(`${field}: expected an animation op object`);
1418
+ }
1419
+ const checkBase = () => {
1420
+ if (typeof value.animation !== 'string' || !value.animation) {
1421
+ throw new Error(`${field}.animation: expected non-empty string`);
1422
+ }
1423
+ if (!Number.isSafeInteger(value.track) || (value.track as number) < 0) {
1424
+ throw new Error(`${field}.track: expected non-negative integer`);
1425
+ }
1426
+ };
1427
+ const checkKey = () => {
1428
+ if (!Number.isSafeInteger(value.key) || (value.key as number) < 0) {
1429
+ throw new Error(`${field}.key: expected non-negative integer`);
1430
+ }
1431
+ };
1432
+ const keys = Object.keys(value).sort().join(',');
1433
+
1434
+ if (value.op === 'set_key_time') {
1435
+ if (keys !== 'animation,key,op,time,track') {
1436
+ throw new Error(`${field}: set_key_time expects {op, animation, track, key, time}`);
1437
+ }
1438
+ checkBase();
1439
+ checkKey();
1440
+ if (typeof value.time !== 'number' || !Number.isFinite(value.time) || value.time < 0) {
1441
+ throw new Error(`${field}.time: expected finite number >= 0`);
1442
+ }
1443
+ return {
1444
+ op: 'set_key_time',
1445
+ animation: value.animation as string,
1446
+ track: value.track as number,
1447
+ key: value.key as number,
1448
+ time: value.time,
1449
+ };
1450
+ }
1451
+
1452
+ if (value.op === 'set_key_value') {
1453
+ if (keys !== 'animation,key,op,track,value' && keys !== 'animation,channel,key,op,track,value') {
1454
+ throw new Error(`${field}: set_key_value expects {op, animation, track, key, channel?, value}`);
1455
+ }
1456
+ checkBase();
1457
+ checkKey();
1458
+ if (value.channel !== undefined) {
1459
+ if (!Number.isSafeInteger(value.channel) || (value.channel as number) < 0) {
1460
+ throw new Error(`${field}.channel: expected non-negative integer`);
1461
+ }
1462
+ if (typeof value.value !== 'number' || !Number.isFinite(value.value)) {
1463
+ throw new Error(`${field}.value: expected finite number when channel is given`);
1464
+ }
1465
+ return {
1466
+ op: 'set_key_value',
1467
+ animation: value.animation as string,
1468
+ track: value.track as number,
1469
+ key: value.key as number,
1470
+ channel: value.channel as number,
1471
+ value: value.value,
1472
+ };
1473
+ }
1474
+ if (
1475
+ !Array.isArray(value.value) ||
1476
+ value.value.length === 0 ||
1477
+ !value.value.every((n) => typeof n === 'number' && Number.isFinite(n))
1478
+ ) {
1479
+ throw new Error(`${field}.value: expected non-empty array of finite numbers`);
1480
+ }
1481
+ return {
1482
+ op: 'set_key_value',
1483
+ animation: value.animation as string,
1484
+ track: value.track as number,
1485
+ key: value.key as number,
1486
+ value: [...(value.value as number[])],
1487
+ };
1488
+ }
1489
+
1490
+ if (value.op === 'set_key_curve') {
1491
+ if (keys !== 'animation,curve,key,op,track') {
1492
+ throw new Error(`${field}: set_key_curve expects {op, animation, track, key, curve}`);
1493
+ }
1494
+ checkBase();
1495
+ checkKey();
1496
+ const c = value.curve;
1497
+ if (
1498
+ c !== null &&
1499
+ c !== 'stepped' &&
1500
+ (!Array.isArray(c) || c.length === 0 || !c.every((n) => typeof n === 'number' && Number.isFinite(n)))
1501
+ ) {
1502
+ throw new Error(`${field}.curve: expected "stepped", null, or array of finite numbers`);
1503
+ }
1504
+ return {
1505
+ op: 'set_key_curve',
1506
+ animation: value.animation as string,
1507
+ track: value.track as number,
1508
+ key: value.key as number,
1509
+ curve: Array.isArray(c) ? [...(c as number[])] : (c as 'stepped' | null),
1510
+ };
1511
+ }
1512
+
1513
+ if (value.op === 'set_key_ease') {
1514
+ if (keys !== 'animation,ease,key,op,track') {
1515
+ throw new Error(`${field}: set_key_ease expects {op, animation, track, key, ease}`);
1516
+ }
1517
+ checkBase();
1518
+ checkKey();
1519
+ if (value.ease !== null && (typeof value.ease !== 'string' || !value.ease)) {
1520
+ throw new Error(`${field}.ease: expected non-empty string or null`);
1521
+ }
1522
+ return {
1523
+ op: 'set_key_ease',
1524
+ animation: value.animation as string,
1525
+ track: value.track as number,
1526
+ key: value.key as number,
1527
+ ease: value.ease as string | null,
1528
+ };
1529
+ }
1530
+
1531
+ if (value.op === 'insert_key') {
1532
+ const allowed = new Set(['op', 'animation', 'track', 'time', 'value', 'curve', 'ease']);
1533
+ if (
1534
+ !Object.keys(value).every((k) => allowed.has(k)) ||
1535
+ !Object.hasOwn(value, 'time') ||
1536
+ !Object.hasOwn(value, 'value')
1537
+ ) {
1538
+ throw new Error(`${field}: insert_key expects {op, animation, track, time, value, curve?, ease?}`);
1539
+ }
1540
+ checkBase();
1541
+ if (typeof value.time !== 'number' || !Number.isFinite(value.time) || value.time < 0) {
1542
+ throw new Error(`${field}.time: expected finite number >= 0`);
1543
+ }
1544
+ if (
1545
+ !Array.isArray(value.value) ||
1546
+ value.value.length === 0 ||
1547
+ !value.value.every((n) => typeof n === 'number' && Number.isFinite(n))
1548
+ ) {
1549
+ throw new Error(`${field}.value: expected non-empty array of finite numbers`);
1550
+ }
1551
+ if (value.curve !== undefined) {
1552
+ const c = value.curve;
1553
+ if (
1554
+ c !== 'stepped' &&
1555
+ (!Array.isArray(c) || c.length === 0 || !c.every((n) => typeof n === 'number' && Number.isFinite(n)))
1556
+ ) {
1557
+ throw new Error(`${field}.curve: expected "stepped" or array of finite numbers`);
1558
+ }
1559
+ }
1560
+ if (value.ease !== undefined && (typeof value.ease !== 'string' || !value.ease)) {
1561
+ throw new Error(`${field}.ease: expected non-empty string`);
1562
+ }
1563
+ return {
1564
+ op: 'insert_key',
1565
+ animation: value.animation as string,
1566
+ track: value.track as number,
1567
+ time: value.time,
1568
+ value: [...(value.value as number[])],
1569
+ ...(value.curve !== undefined
1570
+ ? { curve: Array.isArray(value.curve) ? [...(value.curve as number[])] : 'stepped' }
1571
+ : {}),
1572
+ ...(value.ease !== undefined ? { ease: value.ease as string } : {}),
1573
+ };
1574
+ }
1575
+
1576
+ if (value.op === 'delete_key') {
1577
+ if (keys !== 'animation,key,op,track') {
1578
+ throw new Error(`${field}: delete_key expects {op, animation, track, key}`);
1579
+ }
1580
+ checkBase();
1581
+ checkKey();
1582
+ return {
1583
+ op: 'delete_key',
1584
+ animation: value.animation as string,
1585
+ track: value.track as number,
1586
+ key: value.key as number,
1587
+ };
1588
+ }
1589
+
1590
+ throw new Error(`${field}.op: unknown operation "${String(value.op)}"`);
1591
+ }
1592
+
1593
+ function coalesceSetKeyValueOp(
1594
+ textBefore: string,
1595
+ prevOp: Extract<AnimationSourceOp, { op: 'set_key_value' }>,
1596
+ nextOp: Extract<AnimationSourceOp, { op: 'set_key_value' }>,
1597
+ ): Extract<AnimationSourceOp, { op: 'set_key_value' }> {
1598
+ if (nextOp.channel === undefined || prevOp.channel === nextOp.channel) {
1599
+ return nextOp;
1600
+ }
1601
+ const { classification, keys } = resolveEditableTrack(
1602
+ textBefore,
1603
+ nextOp.animation,
1604
+ nextOp.track,
1605
+ );
1606
+ const channels = classification.channels;
1607
+ const baseKey = keys[nextOp.key];
1608
+ if (!baseKey) return nextOp;
1609
+ const merged = [...baseKey.v];
1610
+ if (prevOp.channel !== undefined) {
1611
+ if (
1612
+ Number.isInteger(prevOp.channel) &&
1613
+ prevOp.channel >= 0 &&
1614
+ prevOp.channel < channels &&
1615
+ typeof prevOp.value === 'number' &&
1616
+ Number.isFinite(prevOp.value)
1617
+ ) {
1618
+ merged[prevOp.channel] = cleanMotionNumber(prevOp.value);
1619
+ }
1620
+ } else if (Array.isArray(prevOp.value) && prevOp.value.length === channels) {
1621
+ for (let c = 0; c < channels; c++) {
1622
+ const v = prevOp.value[c];
1623
+ if (typeof v === 'number' && Number.isFinite(v)) {
1624
+ merged[c] = cleanMotionNumber(v);
1625
+ }
1626
+ }
1627
+ }
1628
+ if (
1629
+ !Number.isInteger(nextOp.channel) ||
1630
+ nextOp.channel < 0 ||
1631
+ nextOp.channel >= channels ||
1632
+ typeof nextOp.value !== 'number' ||
1633
+ !Number.isFinite(nextOp.value)
1634
+ ) {
1635
+ return nextOp;
1636
+ }
1637
+ merged[nextOp.channel] = cleanMotionNumber(nextOp.value);
1638
+ return {
1639
+ op: 'set_key_value',
1640
+ animation: nextOp.animation,
1641
+ track: nextOp.track,
1642
+ key: nextOp.key,
1643
+ value: merged,
1644
+ };
1408
1645
  }
1409
1646
 
1410
1647
  /**
@@ -1435,7 +1672,50 @@ export class AnimationOpBuilder {
1435
1672
  }
1436
1673
 
1437
1674
  apply(op: AnimationSourceOp): AppliedAnimationOpsResult {
1675
+ const last = this.history.at(-1);
1676
+ const sameKeyTarget =
1677
+ last !== undefined &&
1678
+ last.op.animation === op.animation &&
1679
+ last.op.track === op.track &&
1680
+ 'key' in last.op &&
1681
+ 'key' in op &&
1682
+ last.op.key === op.key;
1683
+
1684
+ if (
1685
+ sameKeyTarget &&
1686
+ ((op.op === 'set_key_time' && last.op.op === 'set_key_time') ||
1687
+ (op.op === 'set_key_value' && last.op.op === 'set_key_value'))
1688
+ ) {
1689
+ const replayFrom = last.textBefore;
1690
+ const coalescedOp =
1691
+ op.op === 'set_key_value' && last.op.op === 'set_key_value'
1692
+ ? coalesceSetKeyValueOp(replayFrom, last.op, op)
1693
+ : op;
1694
+ const res = applyAnimationOp(replayFrom, coalescedOp, this.baseText);
1695
+ this.history.pop();
1696
+ if (res.text === this.baseText) {
1697
+ this.history.length = 0;
1698
+ this.currentText = this.baseText;
1699
+ return { text: this.baseText, changedSpans: [] };
1700
+ }
1701
+ if (res.text === replayFrom) {
1702
+ this.currentText = replayFrom;
1703
+ return { text: replayFrom, changedSpans: [] };
1704
+ }
1705
+ this.history.push({ op: coalescedOp, textBefore: replayFrom });
1706
+ this.currentText = res.text;
1707
+ return res;
1708
+ }
1709
+
1438
1710
  const res = applyAnimationOp(this.currentText, op, this.baseText);
1711
+ if (res.text === this.baseText) {
1712
+ this.history.length = 0;
1713
+ this.currentText = this.baseText;
1714
+ return { text: this.baseText, changedSpans: [] };
1715
+ }
1716
+ if (res.text === this.currentText) {
1717
+ return { text: this.currentText, changedSpans: [] };
1718
+ }
1439
1719
  this.history.push({ op, textBefore: this.currentText });
1440
1720
  this.currentText = res.text;
1441
1721
  return res;
@@ -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,22 @@ 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
+ }
133
153
  /** One producer document against the inspected one: `count` differing JSON Pointers, the first `MAX_DIFF_PATHS` listed. */
134
154
  export interface DocumentDiff { file: ProducerDocument; count: number; paths: string[] }
135
155
  /** #125: the documents in `PRODUCER_DOCUMENTS` order (a document neither side has is left out) and the images by hash. */
@@ -272,7 +292,20 @@ export function parseAppliedContext(value: unknown): void {
272
292
  }
273
293
  return;
274
294
  }
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)`);
295
+ if (value.schema === APPLIED_ANIMATION_SCHEMA) {
296
+ const v = exact(value, 'animationsFrom,args,buildId,check,compiler,configHash,files,line,modelHash,ops,opsSha256,producer,schema', field);
297
+ if (![v.buildId, v.configHash, v.opsSha256, v.modelHash].every(hex)) throw new Error(`${field}: buildId, configHash, opsSha256 and modelHash are SHA-256 hex`);
298
+ const af = exact(v.animationsFrom, 'afterSha256,beforeSha256,path', `${field}.animationsFrom`);
299
+ if (typeof af.path !== 'string' || !af.path || !hex(af.beforeSha256) || !hex(af.afterSha256)) throw new Error(`${field}.animationsFrom: {path, beforeSha256, afterSha256 (SHA-256 hex)}`);
300
+ 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`);
301
+ for (const [i, op] of v.ops.entries()) parseAnimationSourceOp(op, `${field}.ops[${i}]`);
302
+ 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`);
303
+ tool(v.producer, `${field}.producer`); tool(v.compiler, `${field}.compiler`); lineOrNull(v.line, `${field}.line`);
304
+ parseCheck(v.check, `${field}.check`);
305
+ parseFilesDiff(v.files, `${field}.files`);
306
+ return;
307
+ }
308
+ 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
309
  }
277
310
 
278
311
  /** The export's one readable line for a valid applied record; the raw context still follows it. */
@@ -291,6 +324,13 @@ export function appliedSummary(value: unknown): string | null {
291
324
  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
325
  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
326
  }
327
+ if (v.schema === APPLIED_ANIMATION_SCHEMA) {
328
+ const a = value as AppliedAnimation;
329
+ const anims = [...new Set(a.ops.map(o => o.animation))];
330
+ const check = a.check ? `check ${a.check.pass === null ? 'not read' : a.check.pass ? 'PASS' : 'FAIL'}` : 'check not run';
331
+ const diff = a.files ? ` · ${filesDiffText(a.files)}` : '';
332
+ 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}${diff} · model ${model}…`;
333
+ }
294
334
  const a = value as AppliedPatch, paths = a.patch.ops.map(o => `${o.op} ${o.path}`);
295
335
  const check = a.check ? `check ${a.check.pass === null ? 'not read' : a.check.pass ? 'PASS' : 'FAIL'}` : 'check not run';
296
336
  const diff = a.files ? ` · ${filesDiffText(a.files)}` : a.diff ? ` · rig.json differs at ${a.diff.count} path(s)` : '';
@@ -306,7 +346,7 @@ export function appliedSummary(value: unknown): string | null {
306
346
  * else the first bar check.json marks FAIL — verbatim. Null when the record is not a patch or its check did not FAIL.
307
347
  */
308
348
  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;
349
+ if (!isObject(value) || (value.schema !== APPLIED_PATCH_SCHEMA && value.schema !== APPLIED_ANIMATION_SCHEMA) || !isObject(value.check) || value.check.pass !== false) return null;
310
350
  const check = value.check as unknown as CheckSummary;
311
351
  const bar = Object.entries(check.bars ?? {}).find(([, status]) => status === 'FAIL')?.[0];
312
352
  const line = typeof check.line === 'string' && /\bFAIL\b/.test(check.line) ? check.line : bar ? `${bar}: FAIL` : `check exited ${check.exitCode}`;
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,53 @@ 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) return bad(`ops must hold at most ${MAX_ANIMATION_OPS} entries`);
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 and any non-default rig flags. No clock. */
413
+ export function animationId(input: { sourceHash: string; configHash: string; animationsFromHash: string; opsText: string; producer: string; compiler: string; args?: readonly 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] : [])]));
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
+ }
378
426
  /**
379
427
  * Deterministic: the package, the config bytes, the patch's own bytes and both tool versions. No clock. A retune-routed
380
428
  * 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 +629,7 @@ async function hashBuild(build: string, id: string, assetPrefix = '/rebuild'): P
581
629
  /** One rebuild at a time per review instance; finished jobs stay readable by id. */
582
630
  export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
583
631
  const assetPrefix = options.assetPrefix ?? '/rebuild', stripPrefix = options.stripPrefix ?? '/density-strip';
584
- const jobs = new Map<string, RebuildJob | PatchJob | DeltaJob | RetargetJob>();
632
+ const jobs = new Map<string, RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob>();
585
633
  let running: string | null = null;
586
634
  /** #173: the density strip on screen (at most one per review): its candidates run beside each other, none of them applied. */
587
635
  interface StripCandidate { value: number; id: string; entry: JsonValue; dir: string; job: PatchJob; applied: boolean }
@@ -604,7 +652,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
604
652
  const bodies = new Map<string, unknown>();
605
653
  /** #166: an undo re-running an evicted predecessor: its id and the build files it must reproduce. */
606
654
  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] });
655
+ const snapshot = <J extends RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob>(job: J): J => ({ ...job, lines: [...job.lines] });
608
656
 
609
657
  /** The state directory may not sit inside the package or the handoff's root (the parent of an opened out/). */
610
658
  function assertStateOutside(): void {
@@ -732,7 +780,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
732
780
  * record leaves it — and the scratch tree is arranged: the stage's build in the scratch root, the other records' most
733
781
  * recent `MAX_KEPT_BUILDS - 1` builds in keptRoot, every other build removed.
734
782
  */
735
- async function landed(job: RebuildJob | PatchJob | DeltaJob | RetargetJob): Promise<void> {
783
+ async function landed(job: RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob): Promise<void> {
736
784
  if (restoring?.id === job.id) { stack.pop(); restoring = null; }
737
785
  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
786
  latestId = stack.at(-1)?.id ?? null;
@@ -761,7 +809,9 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
761
809
  const kind = !('kind' in job) ? 'regions' as const : job.kind;
762
810
  const what = !('kind' in job) ? `${job.request.bust ? 'contour.bust landmarks' : `${job.request.regions.length} region(s)`} on ${job.request.part}`
763
811
  : 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}"`;
812
+ : job.kind === 'delta' ? `mesh edit on ${job.request.part}`
813
+ : job.kind === 'animation' ? `${job.request.ops.length} op(s) on ${[...new Set(job.request.ops.map(o => o.animation))].join(', ')}`
814
+ : `retarget "${job.request.record.flags.animation}"`;
765
815
  const kept = await exists(join(last ? rebuildRoot(options.stateDir, p.sourceHash) : keptRoot(options.stateDir, p.sourceHash), e.id));
766
816
  records.push({ id: e.id, kind, op: 'op' in job ? job.op : 'remesh', what, modelHash: e.modelHash, kept });
767
817
  }
@@ -788,7 +838,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
788
838
  // (i) the kept build: back into the scratch root, re-hashed against result.json and against the record.
789
839
  await unkeep(pred.id);
790
840
  const dir = rebuildDir(options.stateDir, p.sourceHash, pred.id);
791
- const kept = await reuse<RebuildJob | PatchJob | DeltaJob | RetargetJob>(dir, pred.id);
841
+ const kept = await reuse<RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob>(dir, pred.id);
792
842
  if (kept && JSON.stringify(kept.build!.files) === JSON.stringify(pred.files)) {
793
843
  jobs.set(pred.id, kept); stack.pop(); latestId = pred.id; await arrange();
794
844
  return { status: 200, body: { status: 'built', undone: top.id, job: snapshot(kept), history: await history() } };
@@ -818,7 +868,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
818
868
  /** The baseline once it settles (tests, and the whole-rig ops of #102/#103 through assertWholeRigBaseline). */
819
869
  async function settledBaseline(): Promise<BaselineResult | null> { if (!baselineRun) ensureBaseline(resolveProducer(options.starts)); return baselineRun ? await baselineRun : baseline; }
820
870
 
821
- async function reuse<J extends RebuildJob | PatchJob | DeltaJob | RetargetJob>(dir: string, id: string): Promise<J | null> {
871
+ async function reuse<J extends RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob>(dir: string, id: string): Promise<J | null> {
822
872
  const resultFile = join(dir, 'result.json');
823
873
  if (!(await exists(resultFile))) return null;
824
874
  try {
@@ -844,7 +894,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
844
894
  * beside the scratch root for undo); anything but a built job leaves nothing behind.
845
895
  * Each runner passes only its producer op and the optional steps it records.
846
896
  */
847
- async function apply(job: RebuildJob | PatchJob | DeltaJob | RetargetJob, dir: string, inputs: ProducerInputs, resolved: Resolved, op: ProducerOp, steps: ApplySteps = {}): Promise<void> {
897
+ async function apply(job: RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob, dir: string, inputs: ProducerInputs, resolved: Resolved, op: ProducerOp, steps: ApplySteps = {}): Promise<void> {
848
898
  const push = (line: string) => { if (job.lines.length < MAX_LINES) job.lines.push(line); };
849
899
  const producer = resolved.producer;
850
900
  // #180: a refusal or failure is published only after its scratch is removed (as "built" is published last, #146),
@@ -859,7 +909,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
859
909
  job.producerLine = firstRefusal(run.lines) ?? `${op.tool ?? 'rig-parts'} ${op.cmd} exited ${run.exitCode} without a named refusal`;
860
910
  // #148: the producer's line stays as printed; review adds what it means here, when it knows.
861
911
  const hint = producerHint(job.producerLine);
862
- if (hint && !('refusals' in job)) { (job as RebuildJob | PatchJob | DeltaJob).hint = hint; push(`review: ${hint}`); }
912
+ if (hint && !('refusals' in job)) { (job as RebuildJob | PatchJob | DeltaJob | AnimationJob).hint = hint; push(`review: ${hint}`); }
863
913
  outcome = 'refused'; return;
864
914
  }
865
915
  job.producerLine = run.stdout.filter(l => l.trim()).at(-1)?.trim() ?? null;
@@ -1472,8 +1522,149 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1472
1522
  });
1473
1523
  }
1474
1524
 
1525
+ /** #235: spliced `animations_from` → `<dir>/animations.json`, `<dir>/config.json` pointing at it → `rig-parts rig` → compile → `rig-parts check`. */
1526
+ function executeAnimation(job: AnimationJob, dir: string, inputs: ProducerInputs, resolved: Resolved, scratchConfig: string, splicedAnimations: string): Promise<void> {
1527
+ const args = job.request.args ?? [], producer = resolved.producer;
1528
+ return apply(job, dir, inputs, resolved, {
1529
+ cmd: 'rig', spec: 'rig',
1530
+ async run(push) {
1531
+ await writeFile(join(dir, 'animations.json'), splicedAnimations, { mode: 0o600 });
1532
+ await writeFile(join(dir, 'config.json'), scratchConfig, { mode: 0o600 });
1533
+ const anims = [...new Set(job.request.ops.map(o => o.animation))];
1534
+ 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`);
1535
+ return runTool(producer.bin, ['rig', '--config', 'config.json', '--parts', inputs.parts, '--out', 'rig', ...args], { cwd: dir, onLine: push });
1536
+ },
1537
+ wallMs: ms => { job.wallMs.op = ms; },
1538
+ async flags() {
1539
+ return { pageEdges: flagValue(args, '--page-edges', 'free') as PageEdges, packShape: flagValue(args, '--pack-shape', 'polygon') as PackShape, note: '' };
1540
+ },
1541
+ }, {
1542
+ diff: files => { job.files = files; },
1543
+ check: (summary: CheckSummary, wallMs: number | null) => { job.wallMs.check = wallMs; job.check = summary; },
1544
+ });
1545
+ }
1546
+
1547
+ /**
1548
+ * `POST /api/rebuild` with `{animation: {configHash, animationsFromHash, ops, args?}}` (#235): applies the cumulative
1549
+ * span-preserving ops directly to the handoff's `motion.animations_from` text (`REBUILD_ANIMATIONS_STALE` when
1550
+ * `animationsFromHash` does not match the handoff file), writes `<dir>/animations.json` and `<dir>/config.json` in
1551
+ * scratch, and runs `rig-parts rig` + `rigc build` + `check`. Empty or no-op ops (leaving `animations_from` equal to
1552
+ * the handoff text) are refused before anything is written or run; producer refusals return by name with nothing landed.
1553
+ */
1554
+ async function startAnimation(input: unknown): Promise<{ status: number; body: unknown }> {
1555
+ const request = parseAnimationRequest(input);
1556
+ assertStateOutside();
1557
+ await options.unchanged();
1558
+ const inputs = await producerInputs(p.handoff, p.handoffReason);
1559
+ if (inputs.configHash !== request.configHash) throw new RebuildError('REBUILD_CONFIG_STALE', 'the producer config changed since the editor read it; reload');
1560
+ const configDoc = object(JSON.parse(inputs.configText), 'config');
1561
+ const motion = configDoc.motion && typeof configDoc.motion === 'object' && !Array.isArray(configDoc.motion) ? configDoc.motion as Record<string, unknown> : null;
1562
+ const relFrom = typeof motion?.animations_from === 'string' && motion.animations_from ? motion.animations_from : null;
1563
+ if (!relFrom) throw new RebuildError('ANIMATION_SOURCE_MISSING', 'the handoff config declares no motion.animations_from');
1564
+ // The handoff records a named file's canonical path, so an alias inside the package reads as the file it names.
1565
+ let absFrom: string;
1566
+ try { absFrom = await realpath(resolve(dirname(inputs.config), relFrom)); }
1567
+ catch { throw new RebuildError('ANIMATION_SOURCE_MISSING', `config motion.animations_from (${relFrom}) does not exist`); }
1568
+ const showFrom = relative(await realpath(p.root), absFrom).split(sep).join('/') || '.';
1569
+ const handoffFile = inputs.handoff.files.find(f => f.path === showFrom);
1570
+ if (!handoffFile) throw new RebuildError('ANIMATION_SOURCE_MISSING', `config motion.animations_from (${showFrom}) is missing from the handoff`);
1571
+ const baseAnimText = await readFile(absFrom, 'utf8'), baseAnimHash = sha256(baseAnimText);
1572
+ if (baseAnimHash !== handoffFile.sha256) throw new RebuildError('REBUILD_INPUTS_CHANGED', `${showFrom} changed since the review was opened; restart review`);
1573
+ if (request.animationsFromHash !== baseAnimHash) {
1574
+ throw new RebuildError('REBUILD_ANIMATIONS_STALE', 'the animations_from file changed since the editor read it; reload');
1575
+ }
1576
+
1577
+ const builder = new AnimationOpBuilder(baseAnimText);
1578
+ try {
1579
+ for (const op of request.ops) builder.apply(op);
1580
+ } catch (e) {
1581
+ const msg = e instanceof Error ? e.message : String(e);
1582
+ const colon = msg.indexOf(': ');
1583
+ if (colon > 0 && /^[A-Z][A-Z0-9_]+$/.test(msg.slice(0, colon))) {
1584
+ throw new RebuildError(msg.slice(0, colon), msg.slice(colon + 2));
1585
+ }
1586
+ throw new RebuildError('ANIMATION_OP_FAILED', msg);
1587
+ }
1588
+
1589
+ const splicedAnimText = builder.text;
1590
+ const effectiveOps = [...builder.ops];
1591
+ if (!builder.dirty || splicedAnimText === baseAnimText || effectiveOps.length === 0) {
1592
+ throw new RebuildError('ANIMATION_OPS_NOOP', 'the animation operations leave animations_from byte-identical; nothing to apply');
1593
+ }
1594
+
1595
+ const resolved = resolveProducer(options.starts);
1596
+ if (!resolved.ok) return { status: 200, body: { status: 'refused', error: resolved.error, producerLine: resolved.error } };
1597
+ try { assertWholeRigBaseline(await settledBaseline()); } catch (e) { if (e instanceof BaselineError) throw new RebuildError(e.code, e.message.slice(e.code.length + 2)); throw e; }
1598
+
1599
+ const opsText = animationOpsText(effectiveOps), opsSha256 = sha256(opsText), afterSha256 = sha256(splicedAnimText);
1600
+ const id = animationId({
1601
+ sourceHash: p.sourceHash,
1602
+ configHash: inputs.configHash,
1603
+ animationsFromHash: baseAnimHash,
1604
+ opsText,
1605
+ producer: `${resolved.producer.package}@${resolved.producer.version}`,
1606
+ compiler: `${resolved.compiler.package}@${resolved.compiler.version}`,
1607
+ args: request.args,
1608
+ });
1609
+ const current = jobs.get(id);
1610
+ if (current?.status === 'running') return { status: 202, body: snapshot(current) };
1611
+ if (busy()) return { status: 200, body: { status: 'refused', error: busy(), producerLine: null } };
1612
+
1613
+ const scratchDoc = JSON.parse(scratchConfigText(inputs.config, configDoc as unknown as JsonValue)) as Record<string, unknown>;
1614
+ (scratchDoc.motion as Record<string, unknown>).animations_from = 'animations.json';
1615
+ const scratchCfgText = JSON.stringify(scratchDoc, null, 2) + '\n';
1616
+ const recordedBody = {
1617
+ animation: {
1618
+ configHash: inputs.configHash,
1619
+ animationsFromHash: baseAnimHash,
1620
+ ops: effectiveOps,
1621
+ ...(request.args.length ? { args: request.args } : {}),
1622
+ },
1623
+ };
1624
+
1625
+ return reserve(`REBUILD_BUSY: rebuild ${id} is still running`, async () => {
1626
+ guardRestore(id);
1627
+ const dir = rebuildDir(options.stateDir, p.sourceHash, id);
1628
+ await adopt(id);
1629
+ await unkeep(id);
1630
+ const reused = await reuse<AnimationJob>(dir, id);
1631
+ if (reused) { jobs.set(id, reused); latestId = id; bodies.set(id, recordedBody); await landed(reused); return { status: 200, body: snapshot(reused) }; }
1632
+ const job: AnimationJob = {
1633
+ schema: REBUILD_SCHEMA,
1634
+ kind: 'animation',
1635
+ id,
1636
+ status: 'running',
1637
+ reused: false,
1638
+ op: 'rig',
1639
+ request: {
1640
+ configHash: inputs.configHash,
1641
+ animationsFrom: { path: showFrom, beforeSha256: baseAnimHash, afterSha256 },
1642
+ ops: effectiveOps,
1643
+ opsSha256,
1644
+ ...(request.args.length ? { args: [...request.args] } : {}),
1645
+ },
1646
+ producer: tool(resolved.producer),
1647
+ compiler: tool(resolved.compiler),
1648
+ lines: [],
1649
+ producerLine: null,
1650
+ exitCode: null,
1651
+ wallMs: { op: null, compile: null, check: null },
1652
+ check: null,
1653
+ files: null,
1654
+ build: null,
1655
+ };
1656
+ jobs.set(id, job); running = id; bodies.set(id, recordedBody);
1657
+ void executeAnimation(job, dir, inputs, resolved, scratchCfgText, splicedAnimText).finally(() => { if (running === id) running = null; });
1658
+ return { status: 202, body: snapshot(job) };
1659
+ });
1660
+ }
1661
+
1475
1662
  /** `POST /api/rebuild`: refusals are returned before anything is written or run. */
1476
1663
  async function start(input: unknown): Promise<{ status: number; body: unknown }> {
1664
+ if (input && typeof input === 'object' && !Array.isArray(input) && Object.hasOwn(input, 'animation')) {
1665
+ if (Object.keys(input).length !== 1) bad('expected exactly {animation}');
1666
+ return startAnimation((input as { animation: unknown }).animation);
1667
+ }
1477
1668
  if (input && typeof input === 'object' && !Array.isArray(input) && Object.hasOwn(input, 'retarget')) {
1478
1669
  if (Object.keys(input).length !== 1) bad('expected exactly {retarget}');
1479
1670
  return startRetarget((input as { retarget: unknown }).retarget, input);
@@ -1512,7 +1703,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1512
1703
  });
1513
1704
  }
1514
1705
 
1515
- function read(id: string): RebuildJob | PatchJob | DeltaJob | RetargetJob {
1706
+ function read(id: string): RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob {
1516
1707
  const job = jobs.get(id);
1517
1708
  if (!job) throw new RebuildError('REBUILD_NOT_FOUND', id);
1518
1709
  return snapshot(job);
@@ -44,7 +44,7 @@ import {
44
44
  appliedRecord, deltaAppliedRecord, deltaOutcomeLine, designatedRegions, handoffText,
45
45
  landmarksRequest, seedLandmarks, makePatch, outcomeLine, patchAppliedRecord, patchOutcomeLine,
46
46
  pickPart, runRebuild, seedFields, stageModel, retargetAppliedRecord, retargetOutcomeLine, stripPendingAfter,
47
- type AppliedHistoryView, type UndoView, type AnyJobView, type AppliedDelta, type AppliedPatch,
47
+ type AppliedHistoryView, type UndoView, type AnyJobView, type AppliedAnimation, type AppliedDelta, type AppliedPatch,
48
48
  type AppliedRecord, type AppliedRetarget, type DeltaJobView, type DeltaRequestBody, type ConfigPatch,
49
49
  type PatchJobView, type RebuildJobView, type RebuildRefusal, type RebuildRequestBody, type RebuildStatusView,
50
50
  type RetargetJobView, type RetargetRequestBody, type StageChange,
@@ -79,8 +79,8 @@ interface SideBuildState {
79
79
  inspectedDocument: unknown | null;
80
80
  inspectedDocumentReason: string | null;
81
81
  rebuildStatus: RebuildStatusView | null;
82
- appliedOnStage: AppliedRecord | AppliedPatch | AppliedDelta | AppliedRetarget | null;
83
- readoutStage: AppliedRecord | AppliedPatch | AppliedDelta | AppliedRetarget | null;
82
+ appliedOnStage: AppliedRecord | AppliedPatch | AppliedDelta | AppliedRetarget | AppliedAnimation | null;
83
+ readoutStage: AppliedRecord | AppliedPatch | AppliedDelta | AppliedRetarget | AppliedAnimation | null;
84
84
  appliedHistory: AppliedHistoryView | null;
85
85
  stageCheck: { lines: string[]; check: CheckSummary | null } | null;
86
86
  chestInputs: Record<string, string> | null;
@@ -94,7 +94,7 @@ interface SideBuildState {
94
94
  url: string;
95
95
  prefix: string;
96
96
  hash: string;
97
- applied: AppliedRecord | AppliedPatch | AppliedDelta | AppliedRetarget | null;
97
+ applied: AppliedRecord | AppliedPatch | AppliedDelta | AppliedRetarget | AppliedAnimation | null;
98
98
  check: { lines: string[]; check: CheckSummary | null } | null;
99
99
  };
100
100
  } | null;
@@ -178,7 +178,7 @@ export interface ComparePickedTools {
178
178
  commentRefusal: () => string | null;
179
179
  shortcutBlocked: () => boolean;
180
180
  busy: () => boolean;
181
- appliedFor: (side: Side) => AppliedRecord | AppliedPatch | AppliedDelta | AppliedRetarget | null;
181
+ appliedFor: (side: Side) => AppliedRecord | AppliedPatch | AppliedDelta | AppliedRetarget | AppliedAnimation | null;
182
182
  modelHashFor: (side: Side) => string | null;
183
183
  seekMode: (target: number, continuing: boolean) => 'settle' | 'seek';
184
184
  stepSide: (mode: 'present' | 'settle' | 'seek', side: Side, target: number) => void;
package/web/main.ts CHANGED
@@ -23,7 +23,7 @@ import {readSetupPose} from './setup-pose.ts';
23
23
  import {bindBonesPanel,type BonesPanel,type BonesCheckView} from './bones-panel.ts';
24
24
  import {bindCutsPanel,type CutsPanel} from './cuts-panel.ts';
25
25
  import {bindClothPanel,type ClothPanel} from './cloth-panel.ts';
26
- import {retargetAppliedRecord,retargetOutcomeLine,stripPendingAfter,type StageChange,type AppliedRetarget,type RetargetJobView,type RetargetRequestBody} from './rebuild-client.ts';
26
+ import {retargetAppliedRecord,retargetOutcomeLine,stripPendingAfter,type StageChange,type AppliedAnimation,type AppliedRetarget,type RetargetJobView,type RetargetRequestBody} from './rebuild-client.ts';
27
27
  import {bindRetargetPanel,type PoseMap,type RetargetPanel} from './retarget-panel.ts';
28
28
  import type {RetargetFlags} from '../src/retarget.ts';
29
29
  import {historyRow,isPatchJob,recordFor,refusedText,retargetStage,undoControl,type AppliedHistoryView,type UndoView,type AnyJobView,appliedRecord,deltaAppliedRecord,deltaOutcomeLine,designatedRegions,handoffText,landmarksRequest,seedLandmarks,makePatch,outcomeLine,patchAppliedRecord,patchOutcomeLine,pickPart,runRebuild,seedFields,stageModel,type AppliedDelta,type AppliedPatch,type AppliedRecord,type DeltaJobView,type DeltaRequestBody,type ConfigPatch,type PatchJobView,type RebuildJobView,type RebuildRefusal,type RebuildRequestBody,type RebuildStatusView} from './rebuild-client.ts';
@@ -130,7 +130,7 @@ let clothPanel:ClothPanel|null=null;
130
130
  /** The hash-verified compiled model document the parts catalog was read from (mesh edit reads attachments from it). */
131
131
  let partModel:unknown=null;
132
132
  /** Apply · Rebuild (#99): the inspected model's URL, the producer status, and the applied record while its scratch build is on the stage. */
133
- let inspectedModel:{url:string;prefix:string;sha256:string}|null=null,rebuildStatus:RebuildStatusView|null=null,appliedOnStage:AppliedRecord|AppliedPatch|AppliedDelta|AppliedRetarget|null=null,rebuildBusy=false,stageModelHash:string|null=null;
133
+ let inspectedModel:{url:string;prefix:string;sha256:string}|null=null,rebuildStatus:RebuildStatusView|null=null,appliedOnStage:AppliedRecord|AppliedPatch|AppliedDelta|AppliedRetarget|AppliedAnimation|null=null,rebuildBusy=false,stageModelHash:string|null=null;
134
134
  let appearance:ReturnType<typeof bindAppearance>|null=null;
135
135
  let workspace:WorkspaceUI|null=null;
136
136
  let inspectorBlocks:InspectorBlocks|null=null;
@@ -1495,7 +1495,7 @@ async function refreshApplied():Promise<void> {
1495
1495
  renderApplied();
1496
1496
  }
1497
1497
  /** #172: the Cuts and Cloth blocks mark as applied only the ops the stage's applied record holds (none on the inspected build). */
1498
- let readoutStage:AppliedRecord|AppliedPatch|AppliedDelta|AppliedRetarget|null=null;
1498
+ let readoutStage:AppliedRecord|AppliedPatch|AppliedDelta|AppliedRetarget|AppliedAnimation|null=null;
1499
1499
  function renderAppliedBlocks():void {
1500
1500
  const on=appliedBlockOps(appliedOnStage);cutsPanel?.applied(on.cuts);clothPanel?.applied(on.cloth);
1501
1501
  // #186: when the stage record changes, a Cuts / Cloth readout the new record is not that block's names an older build.
@@ -2032,7 +2032,7 @@ async function resetMeshBuild():Promise<void> {
2032
2032
  * the strip's scratch.
2033
2033
  */
2034
2034
  let stripView:DensityStripViewLike|null=null,densityBusy=false;
2035
- let stripPending:{index:number;id:string;candidate:string;back:{url:string;prefix:string;hash:string;applied:AppliedRecord|AppliedPatch|AppliedDelta|AppliedRetarget|null;check:{lines:string[];check:CheckSummary|null}|null}}|null=null;
2035
+ let stripPending:{index:number;id:string;candidate:string;back:{url:string;prefix:string;hash:string;applied:AppliedRecord|AppliedPatch|AppliedDelta|AppliedRetarget|AppliedAnimation|null;check:{lines:string[];check:CheckSummary|null}|null}}|null=null;
2036
2036
  /** #183: after every landed Apply, Reset or Undo the pending row and Back go (`stripPendingAfter`); the strip re-reads (a row Applied is marked). */
2037
2037
  function stageChanged(change:StageChange<NonNullable<typeof stripPending>>):void {const next=stripPendingAfter(stripPending,change);if(next===stripPending)return;stripPending=next;void refreshDensityStrip();}
2038
2038
  const densityLine=(text:string,error=false)=>{densityStrip?.status(text,error);if(error)message(text,true);};
@@ -6,9 +6,10 @@
6
6
  import {ellipsePolygon} from '../src/chest-regions.ts';
7
7
  import type {BustSpec} from '../src/chest-landmarks.ts';
8
8
  import {CONFIG_PATCH_SCHEMA,type ConfigPatch,type PatchCmd,type PatchOp} from '../src/config-patch.ts';
9
- import {APPLIED_DELTA_SCHEMA,APPLIED_PATCH_SCHEMA,APPLIED_RETARGET_SCHEMA,filesDiffText,type AppliedAssembled,type AppliedDelta,type AppliedPatch,type AppliedRetarget,type CheckSummary,type FilesDiff} from '../src/applied-context.ts';
9
+ import {APPLIED_ANIMATION_SCHEMA,APPLIED_DELTA_SCHEMA,APPLIED_PATCH_SCHEMA,APPLIED_RETARGET_SCHEMA,filesDiffText,type AppliedAnimation,type AppliedAssembled,type AppliedDelta,type AppliedPatch,type AppliedRetarget,type CheckSummary,type FilesDiff} from '../src/applied-context.ts';
10
+ import type {AnimationSourceOp} from '../src/animation-ops.ts';
10
11
  import type {MotionSummary,RetargetFlags,RetargetLine,RetargetRecord} from '../src/retarget.ts';
11
- export type {ConfigPatch,PatchOp,AppliedPatch,AppliedDelta,AppliedRetarget,CheckSummary,BustSpec};
12
+ export type {ConfigPatch,PatchOp,AppliedPatch,AppliedDelta,AppliedRetarget,AppliedAnimation,AnimationSourceOp,CheckSummary,BustSpec};
12
13
  import {chestContourFields,chestRegionRows,chestRowId,type ChestFieldReader} from './chest-regions-tool.ts';
13
14
  import type {InspectedCheckView} from '../src/physics-tuning.ts';
14
15
  import {samplesClock,type StageClock} from '../src/frame-clock.ts';
@@ -114,7 +115,7 @@ export function seedLandmarks(status:Pick<RebuildStatusView,'parts'|'contour'>,r
114
115
  }
115
116
 
116
117
  export const appliedRecord=(job:RebuildJobView):AppliedRecord=>({schema:'rig-review-applied/1',buildId:job.id,part:job.request.part,regions:job.request.regions,...(job.request.bust?{bust:job.request.bust}:{}),configHash:job.request.configHash,entrySha256:job.request.entrySha256,producer:job.producer,compiler:job.compiler,line:job.producerLine,modelHash:job.build!.modelHash});
117
- export function parseApplied(text:string):AppliedRecord|AppliedPatch|AppliedDelta|AppliedRetarget|null {try{const value=JSON.parse(text);return value?.schema==='rig-review-applied/1'||value?.schema===APPLIED_PATCH_SCHEMA||value?.schema===APPLIED_DELTA_SCHEMA||value?.schema===APPLIED_RETARGET_SCHEMA?value as AppliedRecord|AppliedPatch|AppliedDelta|AppliedRetarget:null;}catch{return null;}}
118
+ export function parseApplied(text:string):AppliedRecord|AppliedPatch|AppliedDelta|AppliedRetarget|AppliedAnimation|null {try{const value=JSON.parse(text);return value?.schema==='rig-review-applied/1'||value?.schema===APPLIED_PATCH_SCHEMA||value?.schema===APPLIED_DELTA_SCHEMA||value?.schema===APPLIED_RETARGET_SCHEMA||value?.schema===APPLIED_ANIMATION_SCHEMA?value as AppliedRecord|AppliedPatch|AppliedDelta|AppliedRetarget|AppliedAnimation:null;}catch{return null;}}
118
119
 
119
120
  /** A patch Apply's job (#102): the patch and its hash, the op/compile/check wall clocks, check's summary and the rig.json diff. */
120
121
  /** #115: a build job's assemble readout (`AssembledView` in src/rebuild.ts). */
@@ -140,7 +141,19 @@ export function retargetOutcomeLine(result:RetargetJobView|RebuildRefusal):{text
140
141
  const kept=result.motion?(result.motion.kept?'the rig\'s own animations unchanged':`changed: ${result.motion.changed.join(', ')}`):'';
141
142
  return {text:`Retargeted "${r.flags.animation}" from ${r.sequence.reference} with ${result.producer.package} ${result.producer.version} · ${wall} · ${kept} · ${result.files?filesDiffText(result.files):'no diff'} · Reset returns to the inspected build`,error:!!result.motion&&!result.motion.kept};
142
143
  }
143
- export type AnyJobView=RebuildJobView|PatchJobView|DeltaJobView|RetargetJobView;
144
+ /** A keyed animation Apply's job (#235): spliced animations_from, `rig-parts rig`, compile, `rig-parts check`, per-file diff. */
145
+ export interface AnimationJobView {id:string;kind:'animation';op:'rig';status:'running'|'built'|'refused'|'failed';reused:boolean;lines:string[];producerLine:string|null;hint?:string;exitCode:number|null;wallMs:{op:number|null;compile:number|null;check:number|null};check:CheckSummary|null;files:FilesDiff|null;build:{modelUrl:string;modelHash:string;files:Record<string,string>}|null;request:{configHash:string;animationsFrom:{path:string;beforeSha256:string;afterSha256:string};ops:AnimationSourceOp[];opsSha256:string;args?:string[]};producer:{package:string;version:string};compiler:{package:string;version:string}}
146
+ export interface AnimationRequestBody {animation:{configHash:string;animationsFromHash:string;ops:AnimationSourceOp[];args?:string[]}}
147
+ export const animationAppliedRecord=(job:AnimationJobView):AppliedAnimation=>({schema:APPLIED_ANIMATION_SCHEMA,buildId:job.id,configHash:job.request.configHash,animationsFrom:{...job.request.animationsFrom},ops:JSON.parse(JSON.stringify(job.request.ops)),opsSha256:job.request.opsSha256,args:[...(job.request.args??[])],producer:job.producer,compiler:job.compiler,line:job.producerLine,check:job.check,files:job.files,modelHash:job.build!.modelHash});
148
+ export function animationOutcomeLine(result:AnimationJobView|RebuildRefusal):{text:string;error:boolean} {
149
+ if(!('id' in result))return {text:result.producerLine??result.error,error:true};
150
+ if(result.status!=='built')return {text:refusedText(result),error:true};
151
+ const check=result.check?(result.check.pass===null?`check refused: ${result.check.line??`exit ${result.check.exitCode}`}`:`check ${result.check.pass?'PASS':'FAIL'}`):'check not run';
152
+ const wall=result.reused?'reused the scratch build of this exact animation edit':`rig ${seconds(result.wallMs.op)} + compile ${seconds(result.wallMs.compile)} + check ${seconds(result.wallMs.check)}`;
153
+ const anims=[...new Set(result.request.ops.map(o=>o.animation))];
154
+ return {text:`Applied animation ${result.request.opsSha256.slice(0,12)}… (${result.request.ops.length} op(s) on ${anims.join(', ')}) with ${result.producer.package} ${result.producer.version} · ${wall} · ${check} · ${result.files?filesDiffText(result.files):'no diff'} · Reset returns to the inspected build`,error:!!result.check&&result.check.pass!==true};
155
+ }
156
+ export type AnyJobView=RebuildJobView|PatchJobView|DeltaJobView|RetargetJobView|AnimationJobView;
144
157
  export const isPatchJob=(job:AnyJobView):job is PatchJobView=>(job as PatchJobView).kind==='patch';
145
158
 
146
159
  export interface RebuildDeps<B=RebuildRequestBody|PatchRequestBody,J extends AnyJobView=AnyJobView> {post:(body:B)=>Promise<J|RebuildRefusal>;get:(id:string)=>Promise<J>;onLine:(line:string,index:number)=>void;sleep:(ms:number)=>Promise<void>;intervalMs?:number}
@@ -224,7 +237,7 @@ export function handoffText(status:Pick<RebuildStatusView,'handoff'|'baseline'|'
224
237
  }
225
238
 
226
239
  /** #166: `GET /api/rebuild/history` — the session's applied records in order; the last is on the stage; `kept`: its build is on disk. */
227
- export interface AppliedHistoryView {schema:'rig-review-applied-history/1';depth:number;records:{id:string;kind:'regions'|'patch'|'delta'|'retarget';op:string;what:string;modelHash:string;kept:boolean}[]}
240
+ export interface AppliedHistoryView {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}[]}
228
241
  /** #166: `POST /api/rebuild/undo {from}` — the predecessor's build (kept, or re-run and still running), the inspected build, or a refusal. */
229
242
  export type UndoView=
230
243
  |{status:'inspected';undone:string;history:AppliedHistoryView}
@@ -232,9 +245,9 @@ export type UndoView=
232
245
  |{status:'running';undone:string;job:AnyJobView}
233
246
  |RebuildRefusal;
234
247
  /** #166: the applied record a job carries into `context.applied` (the same shapes each Apply records). */
235
- export function recordFor(job:AnyJobView):AppliedRecord|AppliedPatch|AppliedDelta|AppliedRetarget {
248
+ export function recordFor(job:AnyJobView):AppliedRecord|AppliedPatch|AppliedDelta|AppliedRetarget|AppliedAnimation {
236
249
  const kind=(job as {kind?:string}).kind;
237
- return kind==='patch'?patchAppliedRecord(job as PatchJobView):kind==='delta'?deltaAppliedRecord(job as DeltaJobView):kind==='retarget'?retargetAppliedRecord(job as RetargetJobView):appliedRecord(job as RebuildJobView);
250
+ return kind==='patch'?patchAppliedRecord(job as PatchJobView):kind==='delta'?deltaAppliedRecord(job as DeltaJobView):kind==='retarget'?retargetAppliedRecord(job as RetargetJobView):kind==='animation'?animationAppliedRecord(job as AnimationJobView):appliedRecord(job as RebuildJobView);
238
251
  }
239
252
  /**
240
253
  * What a retarget build on the stage sets beside its model (#164, #186): its new animation, to select, and that
@@ -268,7 +281,7 @@ export function undoControl(history:AppliedHistoryView|null,stageId:string|null,
268
281
  * were; only Load puts a row on the stage.
269
282
  */
270
283
  export type StageChange<P>=
271
- |{kind:'apply';via:'regions'|'mesh'|'physics'|'idle'|'cuts'|'cloth'|'rig-fields'|'bones'|'patch'|'delta'|'retarget'}
284
+ |{kind:'apply';via:'regions'|'mesh'|'physics'|'idle'|'cuts'|'cloth'|'rig-fields'|'bones'|'patch'|'delta'|'retarget'|'animation'}
272
285
  |{kind:'reset'}|{kind:'undo'}|{kind:'refused'}
273
286
  |{kind:'load';row:P};
274
287
  export function stripPendingAfter<P>(pending:P|null,change:StageChange<P>):P|null {