@rig-c/parts 1.54.0 → 1.55.1

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/src/remesh.ts CHANGED
@@ -50,6 +50,10 @@
50
50
  * through `check` beside the input; every bar the input measured is measured on the revision, and no bar the
51
51
  * input met is failed by it (`REMESH_CHECK_HELD`). `check`'s scope is the revision's scope, and the provenance
52
52
  * quotes check's own physics line ({@link checkScope}) rather than presenting a green check as more than it read.
53
+ * Under `--input-check <input-check.json>` (issue #617) the input's check is not run again: the record an earlier
54
+ * `--record-input-check` wrote is reused when every row binding it to what that check reads is this run's
55
+ * ({@link inputCheckBoundProblems}), and refused by name otherwise (`REMESH_INPUT_CHECK_FILE`,
56
+ * `REMESH_INPUT_CHECK_BOUND`) before anything is built.
53
57
  * 8. **The write**: `--out` receives the revision's files and {@link PROVENANCE_FILE} — spec {@link REMESH_SPEC}:
54
58
  * the request, both versions, every input file's SHA-256, the target before and after, and both checks — with no
55
59
  * path and no clock in it, so a second identical request writes the same bytes.
@@ -65,11 +69,14 @@ import { barsNotMet, type CheckReport, checkStatuses, type CheckStatus, checkSum
65
69
  import { loadConfigAndAnimations } from './config.ts';
66
70
  import { PartsError, type Problem, problemLine, refuseIfAny } from './errors.ts';
67
71
  import { jsonValueSpan, scratchConfig } from './meshdraft.ts';
68
- import { computeExactFrameTransforms } from './coords.ts';
72
+ import { type BoneTransform, computeExactFrameTransforms } from './coords.ts';
69
73
  import { type PartsFile } from './parts.ts';
70
74
  import { applyMeshEdit, type DeltaApplied, type DeltaPlant, deltaSourceProblems, type MeshEditDocument, readMeshEdit } from './remeshdelta.ts';
71
75
  import { DEFAULT_IDLE_KEYS, type IdleKeys, type MeshAttachment, meshBoundBones, rigJsonText, type RigSpec } from './rig.ts';
76
+ import { readRequirements } from './requirements.ts';
72
77
  import { pyRound } from './round.ts';
78
+ import { type RigSpec as RigcRigSpec } from 'rig-c/src/rig.ts';
79
+ import { expandStops } from 'rig-c/src/stop.ts';
73
80
 
74
81
  /** The provenance file's spec. */
75
82
  export const REMESH_SPEC = 'rig-parts-remesh/1';
@@ -107,6 +114,10 @@ export interface RemeshInput {
107
114
  pageEdges?: PageEdges;
108
115
  packShape?: PackShape;
109
116
  requirements?: string;
117
+ /** Issue #617: a {@link INPUT_CHECK_FILE} an earlier run wrote over this input; its check is reused when it is bound to this run's input. */
118
+ inputCheck?: string;
119
+ /** Issue #617: write {@link INPUT_CHECK_FILE} into `out` beside the provenance. Without it, and without `inputCheck`, nothing written moves. */
120
+ recordInputCheck?: boolean;
110
121
  }
111
122
 
112
123
  /**
@@ -119,6 +130,10 @@ export interface RemeshPlant {
119
130
  skipPreserve?: boolean;
120
131
  /** Issue #526's mutants, handed to the delta's replay (`src/remeshdelta.ts`). */
121
132
  delta?: DeltaPlant;
133
+ /** Issue #613's mutant: the setup frames read off `rig.json`'s bones as written, its `stops` not expanded. */
134
+ unexpandedStops?: boolean;
135
+ /** Issue #617's mutant: run just before check-input reads the input, after the first snapshot, to change a file under it. */
136
+ beforeInputCheck?: () => void;
122
137
  }
123
138
 
124
139
  /** The versions the provenance names: this package's and the rigc that gated the revision (its `--version` line). */
@@ -457,10 +472,234 @@ export function preservedProblems(input: FileTree, revision: FileTree, part: str
457
472
 
458
473
  /** The codes the shared readings below refuse with, by the revising command that runs them (`remesh`, `retune`). */
459
474
  export const REVISION_CODES = {
460
- remesh: { inputPresent: 'REMESH_INPUT_PRESENT', inputWritten: 'REMESH_INPUT_WRITTEN', checkHeld: 'REMESH_CHECK_HELD' },
461
- retune: { inputPresent: 'RETUNE_INPUT_PRESENT', inputWritten: 'RETUNE_INPUT_WRITTEN', checkHeld: 'RETUNE_CHECK_HELD' },
475
+ remesh: { inputPresent: 'REMESH_INPUT_PRESENT', inputWritten: 'REMESH_INPUT_WRITTEN', checkHeld: 'REMESH_CHECK_HELD', inputCheckFile: 'REMESH_INPUT_CHECK_FILE', inputCheckBound: 'REMESH_INPUT_CHECK_BOUND', inputCheckMoved: 'REMESH_INPUT_CHECK_MOVED', rigcGreen: 'REMESH_RIGC_GREEN' },
476
+ retune: { inputPresent: 'RETUNE_INPUT_PRESENT', inputWritten: 'RETUNE_INPUT_WRITTEN', checkHeld: 'RETUNE_CHECK_HELD', inputCheckFile: 'RETUNE_INPUT_CHECK_FILE', inputCheckBound: 'RETUNE_INPUT_CHECK_BOUND', inputCheckMoved: 'RETUNE_INPUT_CHECK_MOVED', rigcGreen: 'RETUNE_RIGC_GREEN' },
462
477
  } as const;
463
478
 
479
+ // ---------------------------------------------------------------------------
480
+ // the recorded input check (issue #617)
481
+ // ---------------------------------------------------------------------------
482
+
483
+ /** The recorded input check's spec. */
484
+ export const INPUT_CHECK_SPEC = 'rig-parts-input-check/1';
485
+
486
+ /** The recorded input check, written into `--out` under `--record-input-check`, read by `--input-check`. */
487
+ export const INPUT_CHECK_FILE = 'input-check.json';
488
+
489
+ /**
490
+ * Everything the input's `check` reads, as one record: the versions it ran under (this package's, and `rigc
491
+ * --version`'s whole output — the entry line and the Spine runtime beside it decide which validator gates), the pack
492
+ * mode and the requirements file it was given, and every file under the rig directory and the parts directory
493
+ * (`parts.json` and every file under `parts/`) by SHA-256. The directories are named as resolved because `check`'s
494
+ * own text can name them (a rig without an idle is skipped with `motion.json`'s path, `readCheckInputs`), so a check
495
+ * of the same bytes elsewhere is not the same record.
496
+ */
497
+ export interface InputCheckBinding {
498
+ versions: { parts: string; rigc: string };
499
+ options: { page_edges: PageEdges; pack_shape: PackShape; requirements: { path: string; sha256: string } | null };
500
+ rig: { dir: string; files: HashRow[] };
501
+ parts: { dir: string; files: HashRow[] };
502
+ }
503
+
504
+ /** {@link INPUT_CHECK_FILE} (spec {@link INPUT_CHECK_SPEC}): the binding, then the input's check side as the provenance carries it. */
505
+ export interface InputCheckRecord extends InputCheckBinding {
506
+ spec: typeof INPUT_CHECK_SPEC;
507
+ check: CheckSide;
508
+ }
509
+
510
+ /** `rigc --version`'s whole output, trimmed, or a refusal under `op`'s rigc code: the record binds the rigc that measured. */
511
+ export function rigcVersionText(rigc: RigcRunner, op: 'remesh' | 'retune'): string {
512
+ const v = rigc(['--version']);
513
+ const out = v.out.trim();
514
+ if (v.status !== 0 || out === '') throw new PartsError([{ code: REVISION_CODES[op].rigcGreen, object: 'rigc --version', detail: `exited ${v.status}${rigcRanClause(v)}; the recorded input check binds the rigc that measured it, so its version is required` }]);
515
+ return out;
516
+ }
517
+
518
+ /** The binding of this run's input: what the input's `check` would read now ({@link InputCheckBinding}). */
519
+ export function inputCheckBinding(rigAt: string, tree: FileTree, partsDir: string, requirements: string | undefined, pageEdges: PageEdges, packShape: PackShape, versions: { parts: string; rigc: string }): InputCheckBinding {
520
+ const partsAt = resolve(partsDir);
521
+ const partsTree: FileTree = new Map();
522
+ const json = join(partsAt, 'parts.json');
523
+ if (existsSync(json) && statSync(json).isFile()) partsTree.set('parts.json', new Uint8Array(readFileSync(json)));
524
+ const pngs = join(partsAt, 'parts');
525
+ if (existsSync(pngs) && statSync(pngs).isDirectory()) for (const [k, b] of readTree(pngs)) partsTree.set(`parts/${k}`, b);
526
+ let req: { path: string; sha256: string } | null = null;
527
+ if (requirements !== undefined) {
528
+ readRequirements(requirements);
529
+ const at = resolve(requirements);
530
+ req = { path: at, sha256: sha256(new Uint8Array(readFileSync(at))) };
531
+ }
532
+ return {
533
+ versions: { parts: versions.parts, rigc: versions.rigc },
534
+ options: { page_edges: pageEdges, pack_shape: packShape, requirements: req },
535
+ rig: { dir: resolve(rigAt), files: hashRows(tree) },
536
+ parts: { dir: partsAt, files: hashRows(new Map([...partsTree].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))) },
537
+ };
538
+ }
539
+
540
+ /** The number of SHA-256 rows a binding holds: every rig file, every parts file, and the requirements file when there is one. */
541
+ export function inputCheckHashes(b: InputCheckBinding): number {
542
+ return b.rig.files.length + b.parts.files.length + (b.options.requirements === null ? 0 : 1);
543
+ }
544
+
545
+ /** {@link INPUT_CHECK_FILE}'s text: the binding and the side, in the spec's key order. */
546
+ export function inputCheckText(b: InputCheckBinding, side: CheckSide): string {
547
+ const record: InputCheckRecord = { spec: INPUT_CHECK_SPEC, versions: b.versions, options: b.options, rig: b.rig, parts: b.parts, check: canonicalSide(side) };
548
+ return rigJsonText(record);
549
+ }
550
+
551
+ /** A check side with its keys in the provenance's order, so a side read back writes the bytes a measured one does. */
552
+ function canonicalSide(s: CheckSide): CheckSide {
553
+ return { pass: s.pass, measured: [...s.measured], not_met: [...s.not_met], skipped: s.skipped.map((x) => ({ bar: x.bar, reason: x.reason })), physics: s.physics, line: s.line, status: { ...s.status } };
554
+ }
555
+
556
+ const isStrings = (v: unknown): v is string[] => Array.isArray(v) && v.every((x) => typeof x === 'string');
557
+ const isRows = (v: unknown): v is HashRow[] => Array.isArray(v) && v.every((r) => isRecord(r) && typeof r.path === 'string' && typeof r.bytes === 'number' && typeof r.sha256 === 'string');
558
+
559
+ /**
560
+ * Read {@link INPUT_CHECK_FILE} and hold it to its spec's shape; every field that is not of it is named in one
561
+ * refusal under `op`'s file code. Nothing in it is trusted past its shape: its binding is {@link inputCheckBoundProblems}'s.
562
+ */
563
+ export function readInputCheck(path: string, op: 'remesh' | 'retune'): InputCheckRecord {
564
+ const code = REVISION_CODES[op].inputCheckFile;
565
+ const fail = (object: string, detail: string): Problem => ({ code, object, detail });
566
+ if (!existsSync(path) || !statSync(path).isFile()) throw new PartsError([fail(path, `no such file; --input-check takes the ${INPUT_CHECK_FILE} an earlier ${op} --record-input-check wrote over the same input`)]);
567
+ let raw: unknown;
568
+ try {
569
+ raw = JSON.parse(readFileSync(path, 'utf8'));
570
+ } catch (err) {
571
+ throw new PartsError([fail(path, `does not parse as JSON: ${(err as Error).message}`)]);
572
+ }
573
+ if (!isRecord(raw)) throw new PartsError([fail(path, `holds ${JSON.stringify(raw)?.slice(0, 40)}; one ${INPUT_CHECK_SPEC} object is required`)]);
574
+ if (raw.spec !== INPUT_CHECK_SPEC) throw new PartsError([fail(`${path} field "spec"`, `is ${JSON.stringify(raw.spec) ?? 'absent'}; "${INPUT_CHECK_SPEC}" is required`)]);
575
+ const out: Problem[] = [];
576
+ const field = (name: string, ok: boolean, want: string): void => {
577
+ if (!ok) out.push(fail(`${path} field "${name}"`, `is not ${want}`));
578
+ };
579
+ const v = raw.versions;
580
+ field('versions', isRecord(v) && typeof v.parts === 'string' && typeof v.rigc === 'string', '{ parts, rigc } as strings');
581
+ const o = raw.options;
582
+ const req = isRecord(o) ? o.requirements : undefined;
583
+ field('options', isRecord(o) && typeof o.page_edges === 'string' && typeof o.pack_shape === 'string' && (req === null || (isRecord(req) && typeof req.path === 'string' && typeof req.sha256 === 'string')), '{ page_edges, pack_shape, requirements: null or { path, sha256 } }');
584
+ for (const k of ['rig', 'parts'] as const) {
585
+ const t = raw[k];
586
+ field(k, isRecord(t) && typeof t.dir === 'string' && isRows(t.files), '{ dir, files: [{ path, bytes, sha256 }] }');
587
+ }
588
+ const c = raw.check;
589
+ const ok =
590
+ isRecord(c) &&
591
+ typeof c.pass === 'boolean' &&
592
+ isStrings(c.measured) &&
593
+ isStrings(c.not_met) &&
594
+ Array.isArray(c.skipped) &&
595
+ c.skipped.every((x) => isRecord(x) && typeof x.bar === 'string' && typeof x.reason === 'string') &&
596
+ (c.physics === null || typeof c.physics === 'string') &&
597
+ typeof c.line === 'string' &&
598
+ isRecord(c.status) &&
599
+ Object.values(c.status).every((x) => typeof x === 'string');
600
+ field('check', ok, 'a check side { pass, measured, not_met, skipped, physics, line, status } as remesh.json carries one');
601
+ refuseIfAny(out);
602
+ return raw as unknown as InputCheckRecord;
603
+ }
604
+
605
+ /**
606
+ * The binding (issue #617): every row of the record against this run's — each version, each option, each directory,
607
+ * and each file by path, size and SHA-256, a row on one side only included. Each difference is one problem naming
608
+ * the record's row, the value it holds and the value this run's input requires; none means the record's check was
609
+ * measured on exactly what this run's check would read.
610
+ */
611
+ export function inputCheckBoundProblems(recorded: InputCheckBinding, now: InputCheckBinding, path: string, op: 'remesh' | 'retune'): Problem[] {
612
+ const code = REVISION_CODES[op].inputCheckBound;
613
+ const out: Problem[] = [];
614
+ const moved = (row: string, found: unknown, required: unknown, why: string): void => {
615
+ out.push({ code, object: `${path} ${row}`, detail: `is ${JSON.stringify(found)}; this run's input requires ${JSON.stringify(required)} — ${why}, so the recorded check is not this input's and nothing was written` });
616
+ };
617
+ if (recorded.versions.parts !== now.versions.parts) moved('versions.parts', recorded.versions.parts, now.versions.parts, 'the check was measured by another version of this package');
618
+ if (recorded.versions.rigc !== now.versions.rigc) moved('versions.rigc', recorded.versions.rigc, now.versions.rigc, 'the check was measured under another rigc');
619
+ if (recorded.options.page_edges !== now.options.page_edges) moved('options.page_edges', recorded.options.page_edges, now.options.page_edges, 'the check packed its pages another way');
620
+ if (recorded.options.pack_shape !== now.options.pack_shape) moved('options.pack_shape', recorded.options.pack_shape, now.options.pack_shape, 'the check packed its pages another way');
621
+ const ra = recorded.options.requirements;
622
+ const rb = now.options.requirements;
623
+ if (ra === null || rb === null) {
624
+ if (ra !== rb) moved('options.requirements', ra, rb, 'the check measured another set of declared requirements');
625
+ } else {
626
+ if (ra.path !== rb.path) moved('options.requirements.path', ra.path, rb.path, 'the check read its requirements from another file');
627
+ if (ra.sha256 !== rb.sha256) moved('options.requirements.sha256', ra.sha256, rb.sha256, 'the check read other requirements bytes');
628
+ }
629
+ for (const k of ['rig', 'parts'] as const) {
630
+ if (recorded[k].dir !== now[k].dir) moved(`${k}.dir`, recorded[k].dir, now[k].dir, `the check read another ${k} directory`);
631
+ const a = new Map(recorded[k].files.map((r) => [r.path, r]));
632
+ const b = new Map(now[k].files.map((r) => [r.path, r]));
633
+ for (const p of [...new Set([...a.keys(), ...b.keys()])].sort()) {
634
+ const x = a.get(p);
635
+ const y = b.get(p);
636
+ const row = `${k}.files "${p}"`;
637
+ if (x === undefined) moved(row, 'absent', y?.sha256, `the input holds ${p} (${y?.bytes} bytes), which the check did not read`);
638
+ else if (y === undefined) moved(row, x.sha256, 'absent', `the check read ${p}, which the input no longer holds`);
639
+ else if (x.sha256 !== y.sha256 || x.bytes !== y.bytes) moved(row, `${x.bytes} bytes sha256 ${x.sha256}`, `${y.bytes} bytes sha256 ${y.sha256}`, `the input's ${p} is not the bytes the check read`);
640
+ }
641
+ }
642
+ return out;
643
+ }
644
+
645
+ /** The line a reused input check prints in place of check-input's lines. */
646
+ export function inputCheckReusedLine(path: string, b: InputCheckBinding): string {
647
+ const req = b.options.requirements === null ? 0 : 1;
648
+ return ` check-input: not run — ${path} (${INPUT_CHECK_SPEC}) is bound to this input by ${inputCheckHashes(b)} sha256 row(s) (rig ${b.rig.files.length}, parts ${b.parts.files.length}, requirements ${req}), parts ${b.versions.parts}, rigc ${b.versions.rigc.split('\n')[0]}, page edges ${b.options.page_edges}, pack shape ${b.options.pack_shape}; the input's check side is the recorded one`;
649
+ }
650
+
651
+ /**
652
+ * Steps 1's reading of `--input-check` and `--record-input-check` for both revising commands: the binding of this
653
+ * run's input when either is asked for (one `rigc --version`), and the recorded side when the record is bound to it.
654
+ * Neither asked for, nothing is read and null is returned for both.
655
+ */
656
+ export function inputCheckOf(
657
+ req: { inputCheck?: string; recordInputCheck?: boolean; requirements?: string; parts: string },
658
+ rigAt: string,
659
+ tree: FileTree,
660
+ pageEdges: PageEdges,
661
+ packShape: PackShape,
662
+ partsVersion: string,
663
+ rigc: RigcRunner,
664
+ op: 'remesh' | 'retune',
665
+ ): { binding: InputCheckBinding | null; reused: CheckSide | null } {
666
+ if (req.inputCheck === undefined && req.recordInputCheck !== true) return { binding: null, reused: null };
667
+ const recorded = req.inputCheck === undefined ? null : readInputCheck(req.inputCheck, op);
668
+ const binding = inputCheckBinding(rigAt, tree, req.parts, req.requirements, pageEdges, packShape, { parts: partsVersion, rigc: rigcVersionText(rigc, op) });
669
+ if (recorded === null) return { binding, reused: null };
670
+ refuseIfAny(inputCheckBoundProblems(recorded, binding, req.inputCheck as string, op));
671
+ return { binding, reused: canonicalSide(recorded.check) };
672
+ }
673
+
674
+ /**
675
+ * The second snapshot (issue #617): the input as the record's first snapshot read it, hashed again by
676
+ * {@link inputCheckBinding} right after check-input has read it. The two snapshots bracket the check, so a record is
677
+ * written only when the bytes the check measured are the bytes its rows name; a file that moved in between is named
678
+ * with both digests under `op`'s moved code.
679
+ */
680
+ export function inputCheckMovedProblems(first: InputCheckBinding, req: { requirements?: string; parts: string }, rigAt: string, op: 'remesh' | 'retune'): Problem[] {
681
+ const code = REVISION_CODES[op].inputCheckMoved;
682
+ const second = inputCheckBinding(rigAt, readTree(rigAt), req.parts, req.requirements, first.options.page_edges, first.options.pack_shape, first.versions);
683
+ const out: Problem[] = [];
684
+ const row = (r: HashRow | undefined): string => (r === undefined ? 'absent' : `${r.bytes} bytes sha256 ${r.sha256}`);
685
+ const moved = (object: string, before: string, after: string): void => {
686
+ out.push({ code, object, detail: `was ${before} when the input was first hashed and is ${after} after check-input read it; the check may have measured bytes the record's rows do not name, so neither the record nor the revision is written` });
687
+ };
688
+ const ra = first.options.requirements;
689
+ const rb = second.options.requirements;
690
+ if (ra !== null && rb !== null && ra.sha256 !== rb.sha256) moved(ra.path, `sha256 ${ra.sha256}`, `sha256 ${rb.sha256}`);
691
+ for (const k of ['rig', 'parts'] as const) {
692
+ const a = new Map(first[k].files.map((r) => [r.path, r]));
693
+ const b = new Map(second[k].files.map((r) => [r.path, r]));
694
+ for (const p of [...new Set([...a.keys(), ...b.keys()])].sort()) {
695
+ const x = a.get(p);
696
+ const y = b.get(p);
697
+ if (x === undefined || y === undefined || x.sha256 !== y.sha256 || x.bytes !== y.bytes) moved(join(first[k].dir, p), row(x), row(y));
698
+ }
699
+ }
700
+ return out;
701
+ }
702
+
464
703
  /** One side of the check block, read off a check report. */
465
704
  export function checkSide(r: CheckReport): CheckSide {
466
705
  return {
@@ -531,6 +770,53 @@ export function modelAttachmentHash(modelText: string, part: string): string | n
531
770
  return entry === undefined ? null : createHash('sha256').update(JSON.stringify(entry)).digest('hex');
532
771
  }
533
772
 
773
+ /**
774
+ * The setup frames a delta's crop px are read through (issue #613): the input's bones as rigc's rig reader reads them.
775
+ * That reader expands `stops` before it resolves a single parent (rig-c's `expandStops`, `src/stop.ts`), and the
776
+ * expansion generates a drawn link `<link>_d` per stopped link that `rig` hangs the next link, and every slot and
777
+ * weight on the link, from — so a rig with stops names parents its own `bones` array does not declare, and evaluating
778
+ * that array as written throws in rig-c's `evaluate`. Here the expansion is rig-c's own call, as `check` makes it for
779
+ * the loop (`withoutPhysics`); a rig without `stops` is the array as written, the same object, so its frames and
780
+ * every byte read through them are what they were. Nothing is reordered: rigc refuses a parent declared after its
781
+ * child (`CE_RIG_BONE_PARENT_ORDER`), so a parent this walk finds after its child, or nowhere, is refused by name
782
+ * (`REMESH_BONE_ORDER`) rather than sorted into an order rigc would not load; and any other throw from the
783
+ * expansion or the evaluation is named with rig-c's own sentence (`REMESH_BONES_POSED`). On the delta path both sit
784
+ * behind rigc's gate over the input, which refuses either first, so reaching one means rigc and its library read the
785
+ * same bones apart. `unexpanded` is the mutant: the bones as written.
786
+ */
787
+ export function deltaFrames(rig: Json, where: string, unexpanded = false): Map<string, BoneTransform> | Problem[] {
788
+ let bones: RigSpec['bones'];
789
+ try {
790
+ bones = (unexpanded || !Array.isArray(rig.stops) ? (rig as unknown as RigSpec) : (expandStops(rig as unknown as RigcRigSpec, where) as unknown as RigSpec)).bones;
791
+ } catch (err) {
792
+ if (!(err instanceof Error)) throw err;
793
+ return [{ code: 'REMESH_BONES_POSED', object: `${where} stops`, detail: `rig-c's expansion refuses them: ${err.message}; the delta's crop px are read through the setup frames of the bones the expansion lays out, so nothing was written` }];
794
+ }
795
+ const at = new Map<string, number>();
796
+ for (const [i, b] of bones.entries()) if (!at.has(b.name)) at.set(b.name, i);
797
+ const out: Problem[] = [];
798
+ const seen = new Set<string>();
799
+ for (const [i, b] of bones.entries()) {
800
+ const parent = b.parent;
801
+ if (parent !== undefined && parent !== '' && !seen.has(parent)) {
802
+ const later = at.get(parent);
803
+ out.push({
804
+ code: 'REMESH_BONE_ORDER',
805
+ object: `${where} bones[${i}] "${b.name}"`,
806
+ detail: `names parent "${parent}", which ${later === undefined ? `no bone declares${Array.isArray(rig.stops) && !unexpanded ? ' after rig-c expands the rig\'s stops' : ''}` : `is declared after it, at bones[${later}]`}; a parent declared before its child is required, as rigc's rig reader resolves it (CE_RIG_BONE_PARENT_ORDER), and nothing was written`,
807
+ });
808
+ }
809
+ seen.add(b.name);
810
+ }
811
+ if (out.length > 0) return out;
812
+ try {
813
+ return computeExactFrameTransforms(bones);
814
+ } catch (err) {
815
+ if (!(err instanceof Error)) throw err;
816
+ return [{ code: 'REMESH_BONES_POSED', object: `${where} bones`, detail: `rig-c cannot pose them at the setup pose: ${err.message}; the delta's crop px are read through those frames, so nothing was written` }];
817
+ }
818
+ }
819
+
534
820
  /**
535
821
  * Step 1's tree rules: the files `rig` writes are present, and the ones the splice rewrites (`spliced`) are this
536
822
  * writer's bytes. `op` names the revising command, whose codes these are (`retune` splices `rig.json` and `motion.json`).
@@ -605,6 +891,7 @@ export function remeshStage(input: RemeshInput, rigc: RigcRunner, checkBin: stri
605
891
  const tree = readTree(rigAt);
606
892
  refuseIfAny(inputTreeProblems(tree, input.rig));
607
893
  if ((input.mesh === undefined) === (input.delta === undefined)) throw new Error('remeshStage: exactly one of mesh, delta is required');
894
+ const recorded = inputCheckOf(input, rigAt, tree, pageEdges, packShape, versions.parts, rigc, 'remesh');
608
895
  const meshReq = input.mesh === undefined ? null : readMeshRequest(input.mesh);
609
896
  const deltaReq = input.delta === undefined ? null : readDeltaRequest(input.delta);
610
897
  const configText = readFileSync(input.config, 'utf8');
@@ -678,7 +965,8 @@ export function remeshStage(input: RemeshInput, rigc: RigcRunner, checkBin: stri
678
965
  const partsFile = JSON.parse(readFileSync(join(input.parts, 'parts.json'), 'utf8')) as PartsFile;
679
966
  const rec = partsFile.parts.find((p) => p.name === part);
680
967
  if (rec === undefined) throw new PartsError([{ code: 'REMESH_DELTA_SOURCE', object: `${input.parts}/parts.json`, detail: `names no part "${part}"; its box is where rig placed the image, which the delta's crop px are read against` }]);
681
- const world = computeExactFrameTransforms((inRig as unknown as RigSpec).bones);
968
+ const world = deltaFrames(inRig, `${input.rig}/rig.json`, plant.unexpandedStops === true);
969
+ if (Array.isArray(world)) throw new PartsError(world);
682
970
  const r = applyMeshEdit({ part, attachment: inAtt, box: [rec.x, rec.y], rigSize: [partsFile.rig_size[0], partsFile.rig_size[1]], world }, doc, deltaPath, plant.delta);
683
971
  if (Array.isArray(r)) throw new PartsError(r);
684
972
  const row = rowOf(inReport, part);
@@ -713,9 +1001,16 @@ export function remeshStage(input: RemeshInput, rigc: RigcRunner, checkBin: stri
713
1001
  }
714
1002
  const checkOf = (rig: string, name: string): CheckReport =>
715
1003
  checkStage({ rig, parts: input.parts, out: join(scratch, name), pageEdges, packShape, ...(input.requirements === undefined ? {} : { requirements: input.requirements }) }, rigc, checkBin, (l) => log(`[${name}] ${l}`));
716
- const inCheck = checkOf(rigAt, 'check-input');
1004
+ if (recorded.reused !== null) log(inputCheckReusedLine(input.inputCheck as string, recorded.binding as InputCheckBinding));
1005
+ let inSide: CheckSide;
1006
+ if (recorded.reused !== null) inSide = recorded.reused;
1007
+ else {
1008
+ plant.beforeInputCheck?.();
1009
+ inSide = checkSide(checkOf(rigAt, 'check-input'));
1010
+ if (recorded.binding !== null) refuseIfAny(inputCheckMovedProblems(recorded.binding, input, rigAt, 'remesh'));
1011
+ }
717
1012
  const revCheck = checkOf(staged, 'check-revision');
718
- const sides = { input: checkSide(inCheck), revision: checkSide(revCheck) };
1013
+ const sides = { input: inSide, revision: checkSide(revCheck) };
719
1014
  refuseIfAny(checkHeldProblems(sides.input, sides.revision, revCheck.problems));
720
1015
  const scope = checkScope(sides.revision.physics);
721
1016
  log(` check: input ${sides.input.pass ? 'PASS' : `FAIL (${sides.input.not_met.join(', ')})`}, revision ${sides.revision.pass ? 'PASS' : `FAIL (${sides.revision.not_met.join(', ')})`}, the same ${sides.revision.measured.length} bar(s) measured; ${scope}`);
@@ -743,6 +1038,11 @@ export function remeshStage(input: RemeshInput, rigc: RigcRunner, checkBin: stri
743
1038
  }
744
1039
  writeFileSync(join(outAt, PROVENANCE_FILE), rigJsonText(provenance));
745
1040
  written.push(PROVENANCE_FILE);
1041
+ if (input.recordInputCheck === true) {
1042
+ writeFileSync(join(outAt, INPUT_CHECK_FILE), inputCheckText(recorded.binding as InputCheckBinding, sides.input));
1043
+ written.push(INPUT_CHECK_FILE);
1044
+ log(` recorded: the input's check in ${INPUT_CHECK_FILE}, bound by ${inputCheckHashes(recorded.binding as InputCheckBinding)} sha256 row(s); pass it as --input-check to a later remesh or retune of ${input.rig}`);
1045
+ }
746
1046
  log(' file sha256 (input) sha256 (revision)');
747
1047
  const inHash = new Map(hashRows(tree).map((r) => [r.path, r.sha256]));
748
1048
  for (const r of provenance.revision) log(` ${r.path.padEnd(40)} ${(inHash.get(r.path) ?? 'absent').slice(0, 16)} ${r.sha256.slice(0, 16)}${inHash.get(r.path) === r.sha256 ? '' : ' (spliced)'}`);
package/src/retune.ts CHANGED
@@ -27,6 +27,9 @@
27
27
  * (`RETUNE_PRESERVED`, naming the first path that moved).
28
28
  * 6. **The gate and check**: the revision goes through rigc's build gate (`RETUNE_RIGC_GREEN`) and through `check`
29
29
  * beside the input; every bar the input measured is measured, none the input met is failed (`RETUNE_CHECK_HELD`).
30
+ * Under `--input-check` (issue #617) the input's check is the recorded one when the record is bound to this input
31
+ * (`src/remesh.ts` {@link inputCheckOf}), refused by name otherwise (`RETUNE_INPUT_CHECK_FILE`,
32
+ * `RETUNE_INPUT_CHECK_BOUND`) before the rebuild.
30
33
  * 7. **The write**: `--out` receives the revision's files and {@link RETUNE_FILE} — spec {@link RETUNE_SPEC} — with
31
34
  * no path and no clock in it, so a second identical request writes the same bytes.
32
35
  *
@@ -37,7 +40,7 @@ import { dirname, join, resolve, sep } from 'node:path';
37
40
  import { checkStage, gateThroughRigc, type Log, rigStage } from './build.ts';
38
41
  import { type CheckReport, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackShape, type PageEdges, rigcRanClause, type RigcRunner } from './check.ts';
39
42
  import { PartsError, type Problem, problemLine, refuseIfAny } from './errors.ts';
40
- import { type CheckSide, checkHeldProblems, checkSide, checkScope, type FileTree, firstDifference, type HashRow, hashRows, inputTreeProblems, perturbed, readTree, sha256 } from './remesh.ts';
43
+ import { type CheckSide, checkHeldProblems, checkSide, checkScope, type FileTree, firstDifference, type HashRow, hashRows, INPUT_CHECK_FILE, type InputCheckBinding, inputCheckHashes, inputCheckMovedProblems, inputCheckOf, inputCheckReusedLine, inputCheckText, inputTreeProblems, perturbed, readTree, sha256 } from './remesh.ts';
41
44
  import { DEFAULT_IDLE_KEYS, type IdleKeys, rigJsonText } from './rig.ts';
42
45
 
43
46
  /** The provenance file's spec. */
@@ -69,6 +72,10 @@ export interface RetuneInput {
69
72
  pageEdges?: PageEdges;
70
73
  packShape?: PackShape;
71
74
  requirements?: string;
75
+ /** Issue #617: a recorded input check (`input-check.json`, as `remesh` writes it) reused when it is bound to this run's input. */
76
+ inputCheck?: string;
77
+ /** Issue #617: write `input-check.json` into `out` beside the provenance. Without it, and without `inputCheck`, nothing written moves. */
78
+ recordInputCheck?: boolean;
72
79
  }
73
80
 
74
81
  /**
@@ -80,6 +87,8 @@ export interface RetunePlant {
80
87
  perturb?: string;
81
88
  skipPreserve?: boolean;
82
89
  skipHold?: boolean;
90
+ /** Issue #617's mutant: run just before check-input reads the input, after the first snapshot, to change a file under it. */
91
+ beforeInputCheck?: () => void;
83
92
  }
84
93
 
85
94
  /** One constraint the request changed: its name and type, and each field whose value moved, in the rebuild's order. */
@@ -340,6 +349,7 @@ export function retuneStage(input: RetuneInput, rigc: RigcRunner, checkBin: stri
340
349
  if (outAt.startsWith(`${rigAt}${sep}`)) throw new PartsError([{ code: 'RETUNE_OUT_FRESH', object: input.out, detail: `is inside the input ${input.rig}; a revision is written beside the input, never into it` }]);
341
350
  const tree = readTree(rigAt);
342
351
  refuseIfAny(inputTreeProblems(tree, input.rig, 'retune', RETUNE_SPLICED));
352
+ const recorded = inputCheckOf(input, rigAt, tree, pageEdges, packShape, versions.parts, rigc, 'retune');
343
353
  const inFiles = rigFiles(tree);
344
354
  // 2. The rebuild.
345
355
  log(`rig-parts retune: ${input.rig}, ${tree.size} file(s); the rebuild is the config as written`);
@@ -382,9 +392,16 @@ export function retuneStage(input: RetuneInput, rigc: RigcRunner, checkBin: stri
382
392
  }
383
393
  const checkOf = (rig: string, name: string): CheckReport =>
384
394
  checkStage({ rig, parts: input.parts, out: join(scratch, name), pageEdges, packShape, ...(input.requirements === undefined ? {} : { requirements: input.requirements }) }, rigc, checkBin, (l) => log(`[${name}] ${l}`));
385
- const inCheck = checkOf(rigAt, 'check-input');
395
+ if (recorded.reused !== null) log(inputCheckReusedLine(input.inputCheck as string, recorded.binding as InputCheckBinding));
396
+ let inSide: CheckSide;
397
+ if (recorded.reused !== null) inSide = recorded.reused;
398
+ else {
399
+ plant.beforeInputCheck?.();
400
+ inSide = checkSide(checkOf(rigAt, 'check-input'));
401
+ if (recorded.binding !== null) refuseIfAny(inputCheckMovedProblems(recorded.binding, input, rigAt, 'retune'));
402
+ }
386
403
  const revCheck = checkOf(staged, 'check-revision');
387
- const sides = { input: checkSide(inCheck), revision: checkSide(revCheck) };
404
+ const sides = { input: inSide, revision: checkSide(revCheck) };
388
405
  refuseIfAny(checkHeldProblems(sides.input, sides.revision, revCheck.problems, 'retune'));
389
406
  const scope = checkScope(sides.revision.physics);
390
407
  log(` check: input ${sides.input.pass ? 'PASS' : `FAIL (${sides.input.not_met.join(', ')})`}, revision ${sides.revision.pass ? 'PASS' : `FAIL (${sides.revision.not_met.join(', ')})`}, the same ${sides.revision.measured.length} bar(s) measured; ${scope}`);
@@ -409,6 +426,11 @@ export function retuneStage(input: RetuneInput, rigc: RigcRunner, checkBin: stri
409
426
  }
410
427
  writeFileSync(join(outAt, RETUNE_FILE), rigJsonText(provenance));
411
428
  written.push(RETUNE_FILE);
429
+ if (input.recordInputCheck === true) {
430
+ writeFileSync(join(outAt, INPUT_CHECK_FILE), inputCheckText(recorded.binding as InputCheckBinding, sides.input));
431
+ written.push(INPUT_CHECK_FILE);
432
+ log(` recorded: the input's check in ${INPUT_CHECK_FILE}, bound by ${inputCheckHashes(recorded.binding as InputCheckBinding)} sha256 row(s); pass it as --input-check to a later remesh or retune of ${input.rig}`);
433
+ }
412
434
  log(' file sha256 (input) sha256 (revision)');
413
435
  const inHash = new Map(hashRows(tree).map((r) => [r.path, r.sha256]));
414
436
  for (const r of provenance.revision) log(` ${r.path.padEnd(40)} ${(inHash.get(r.path) ?? 'absent').slice(0, 16)} ${r.sha256.slice(0, 16)}${inHash.get(r.path) === r.sha256 ? '' : ' (spliced)'}`);
package/src/rig.ts CHANGED
@@ -400,14 +400,20 @@ export function roundShares(list: readonly Influence[]): Influence[] {
400
400
  * trunk splits into branches and across adjacent trees' ruffled hem steps.
401
401
  * Four Laplacian passes (`FORK_SMOOTH_PASSES`, self share 0.5, floor 0.005, cap
402
402
  * 8 influences) diffuse each vertex's shares across its triangle neighbours
403
- * before rounding with {@link roundShares}.
403
+ * before rounding with {@link roundShares}. Every share is diffused alike —
404
+ * trunk, branch and fixed bones — none is held in place.
405
+ *
406
+ * Issue #615: an influence mesh that declares `influence.hold_tip: true` is
407
+ * smoothed by the same passes with `cap` its declared `influence.max`, so a
408
+ * vertex never binds more bones than the config states; the lattice's call
409
+ * passes no cap and keeps `FORK_SMOOTH_MAX_INFLUENCES`, byte for byte.
404
410
  */
405
411
  export const FORK_SMOOTH_PASSES = 4;
406
412
  export const FORK_SMOOTH_SELF = 0.5;
407
413
  export const FORK_SMOOTH_FLOOR = 0.005;
408
414
  export const FORK_SMOOTH_MAX_INFLUENCES = 8;
409
415
 
410
- export function smoothForkShares(raw: ReadonlyArray<readonly Influence[]>, triangles: readonly number[]): Influence[][] {
416
+ export function smoothForkShares(raw: ReadonlyArray<readonly Influence[]>, triangles: readonly number[], cap: number = FORK_SMOOTH_MAX_INFLUENCES): Influence[][] {
411
417
  const adj: number[][] = raw.map(() => []);
412
418
  const addEdge = (u: number, v: number): void => {
413
419
  if (!adj[u].includes(v)) adj[u].push(v);
@@ -435,7 +441,7 @@ export function smoothForkShares(raw: ReadonlyArray<readonly Influence[]>, trian
435
441
  const kept = [...m.entries()]
436
442
  .filter(([, w]) => w >= FORK_SMOOTH_FLOOR)
437
443
  .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
438
- .slice(0, FORK_SMOOTH_MAX_INFLUENCES);
444
+ .slice(0, cap);
439
445
  const sum = kept.reduce((s, [, w]) => s + w, 0);
440
446
  return roundShares(kept.map(([bone, w]) => ({ bone, weight: w / sum })));
441
447
  });
@@ -1912,6 +1918,7 @@ export function buildRig(
1912
1918
  let maxInfl = 0;
1913
1919
  let capped = 0;
1914
1920
  let widest = 0;
1921
+ const pulled: Influence[][] = [];
1915
1922
  for (const [vi, [x, y]] of lattice.points.entries()) {
1916
1923
  const r = influenceShares([x, y], local, spec.influence);
1917
1924
  if ('nearest' in r) {
@@ -1920,12 +1927,17 @@ export function buildRig(
1920
1927
  }
1921
1928
  if (r.inReach > spec.influence.max) capped++;
1922
1929
  widest = Math.max(widest, r.inReach);
1930
+ pulled.push(r.weights.map((e) => ({ bone: names[e.control ?? 0], weight: e.weight })));
1931
+ }
1932
+ // Issue #615: `hold_tip: true`, declared on the mesh (propose writes it from the recipe's `split.hold_tip`), smooths
1933
+ // the pulled shares by the lattice's held-fork passes, capped at the declared `max`; absent, the shares are rig-c's.
1934
+ const shares = spec.influence.hold_tip === true ? smoothForkShares(pulled, lattice.triangles, spec.influence.max) : pulled;
1935
+ for (const [vi, [x, y]] of lattice.points.entries()) {
1923
1936
  const wx = x + ox;
1924
1937
  const wy = y + oy;
1925
- const ent: WeightEntry[] = r.weights.map((e) => {
1926
- const bone = names[e.control ?? 0];
1938
+ const ent: WeightEntry[] = shares[vi].map(({ bone, weight }) => {
1927
1939
  const [bx, by] = toBoneLocal(world.get(bone) as BoneTransform, spineX(wx), spineY(wy));
1928
- return { bone, x: places(bx), y: places(by), weight: e.weight };
1940
+ return { bone, x: places(bx), y: places(by), weight };
1929
1941
  });
1930
1942
  weights.push(ent);
1931
1943
  infl += ent.length;