@rig-c/parts 2.45.0 → 2.47.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.
@@ -0,0 +1,493 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync, statSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { authoredUnitDepths } from './authoredunit.ts';
5
+ import { controlSkeletonOf, isDoorKey, loadEarlyConfig, turnMovingPartPair, type AssembleConfig, type CharacterConfig, type Cut, type Limb } from './config.ts';
6
+ import type { DepthRunConfig, UserDepthSheet } from './depthsheets.ts';
7
+ import { PartsError, refuseIfAny } from './errors.ts';
8
+ import { readWrapperLayers } from './layers.ts';
9
+ import { bonePlaces } from './limbs.ts';
10
+ import type { AssemblyConfigRecord, PartsFile } from './parts.ts';
11
+ import { PLATE_RECEIPT_FILE, verifyPlateReceipt } from './plate.ts';
12
+ import { isSkeletonName } from './skeleton.ts';
13
+ import { setupPaintingFilePath, type SetupPainting } from './setuppainting.ts';
14
+ import { DEFAULT_GROUND, DEFAULT_PROJECT_RULE, type Ground, type ProjectRule } from './projectrule.ts';
15
+ import { DEFAULT_SEAM_RULE, type SeamRule } from './seamrule.ts';
16
+ import { readRequirements } from './requirements.ts';
17
+
18
+ export type AssemblySource = Omit<AssembleConfig, 'seethrough'> & Partial<Pick<AssembleConfig, 'seethrough'>> & Pick<CharacterConfig, 'generation'>;
19
+
20
+ type ProjectionSource = Omit<AssemblySource, 'key' | 'proposed_rig_scale'>;
21
+
22
+ function assemblyLimb({ segments, split, front }: Limb) {
23
+ return {
24
+ segments,
25
+ ...(split === undefined ? {} : { split }),
26
+ ...(front === undefined ? {} : { front }),
27
+ };
28
+ }
29
+
30
+ export type AssemblyLimb = ReturnType<typeof assemblyLimb>;
31
+
32
+ function assemblyPhysics(constraints: ProjectionSource['constraints']) {
33
+ if (!Array.isArray(constraints)) return undefined;
34
+ return constraints.flatMap(constraint =>
35
+ constraint !== null && typeof constraint === 'object' && !Array.isArray(constraint) &&
36
+ constraint.type === 'physics' && typeof constraint.bone === 'string'
37
+ ? [{ type: 'physics' as const, bone: constraint.bone }]
38
+ : []);
39
+ }
40
+
41
+ function assemblyMotion(motion: ProjectionSource['motion']) {
42
+ const still = motion?.blink?.still;
43
+ if (still == null) return undefined;
44
+ const carriers = Object.fromEntries(Object.entries(still)
45
+ .map(([part, carrier]) => [part, carrier == null ? carrier : { bone: carrier.bone }] as const));
46
+ return { blink: { still: carriers } };
47
+ }
48
+
49
+ export interface AssemblyRules {
50
+ seam?: SeamRule;
51
+ project?: ProjectRule;
52
+ }
53
+
54
+ export function effectiveAssemblyRules(config: AssemblyRules, overrides: AssemblyRules = {}): Required<AssemblyRules> {
55
+ return { seam: overrides.seam ?? config.seam ?? DEFAULT_SEAM_RULE, project: overrides.project ?? config.project ?? DEFAULT_PROJECT_RULE };
56
+ }
57
+
58
+ const sha256 = (text: string | Uint8Array): string => createHash('sha256').update(text).digest('hex');
59
+
60
+ function fileBytes(path: string, field: string): Buffer {
61
+ try {
62
+ if (statSync(path).isFile()) return readFileSync(path);
63
+ } catch {
64
+ // Give callers the same named refusal for missing and unreadable files.
65
+ }
66
+ throw new PartsError([{ code: 'CONFIG_FILE_PRESENT', object: `config.${field}`, detail: `names ${path}; a readable file is required` }]);
67
+ }
68
+
69
+ function layerRunDigest(path: string, field: string): unknown {
70
+ if (/\.psd$/i.test(path)) return sha256(fileBytes(path, field));
71
+ const run = readWrapperLayers(path);
72
+ return {
73
+ manifest: sha256(fileBytes(run.source, field)),
74
+ // Wrapper layers always retain a file. PSD files are handled above.
75
+ layers: [...run.layers, ...run.hidden].map(layer => sha256(fileBytes(layer.file!, field))),
76
+ };
77
+ }
78
+
79
+ function plateDigest(path: string, field: string): string {
80
+ const receipt = resolve(path, PLATE_RECEIPT_FILE);
81
+ const bytes = fileBytes(receipt, field);
82
+ refuseIfAny(verifyPlateReceipt(receipt));
83
+ return sha256(bytes);
84
+ }
85
+
86
+ // These maps use authored part, bone or layer names as keys, independently
87
+ // of the loader's metadata spelling for structural fields.
88
+ const authoredKeyMaps = new Set(['layers', 'tips', 'drawn', 'base_anchor']);
89
+
90
+ function canonical(value: unknown, authoredKeys = false): unknown {
91
+ if (Array.isArray(value)) return value.map(entry => canonical(entry));
92
+ if (value !== null && typeof value === 'object') {
93
+ const fields = value as Record<string, unknown>;
94
+ const keys = Object.keys(fields).filter(key => authoredKeys || !isDoorKey(key)).sort();
95
+ return Object.fromEntries(keys.map(key => [key, canonical(fields[key], !authoredKeys && authoredKeyMaps.has(key))]));
96
+ }
97
+ return value;
98
+ }
99
+
100
+ // Each value below is exposed to assembly through the same entry that declares
101
+ // its digest. A shared binding names digest fields produced by another entry.
102
+ interface ReadingContext extends ReturnType<typeof digestFiles>, Required<AssemblyRules> {
103
+ ground: Ground;
104
+ hasHeadRun: boolean;
105
+ bones: unknown;
106
+ basePairs: Array<[string, string]>;
107
+ physicsPairs: Array<[string, string]>;
108
+ limbs: unknown[];
109
+ hybridWidths: ReadonlyMap<string, Array<{ set: string | null; width?: number }>>;
110
+ setup: SetupPainting | undefined;
111
+ setupImage: (declaration: SetupPainting['figure_mask'] | SetupPainting['backdrop'], field: string) => unknown;
112
+ authoredDepths: () => unknown;
113
+ }
114
+
115
+ type ReadDigest = (ctx: ReadingContext) => unknown;
116
+ type DigestBindings = Readonly<Record<string, ReadDigest>>;
117
+ type Exemption = { readonly issue: number; readonly reason: string };
118
+ type ProjectionEntry<T> =
119
+ | { value: T; bindings: DigestBindings; shared?: never; exemption?: never }
120
+ | { value: T; bindings?: never; shared: readonly string[]; exemption?: never }
121
+ | { value: T; bindings?: never; shared?: never; exemption: Exemption };
122
+
123
+ function bound<T>(value: T, read: (value: T, ctx: ReadingContext) => unknown = value => value): ProjectionEntry<T> {
124
+ return { value, bindings: { '': ctx => read(value, ctx) } };
125
+ }
126
+
127
+ function named<T>(value: T, bindings: DigestBindings): ProjectionEntry<T> {
128
+ return { value, bindings };
129
+ }
130
+
131
+ function shared<T>(value: T, ...fields: string[]): ProjectionEntry<T> {
132
+ return { value, shared: fields };
133
+ }
134
+
135
+ function exempt<T>(value: T, issue: number, reason: string): ProjectionEntry<T> {
136
+ return { value, exemption: { issue, reason } };
137
+ }
138
+
139
+ type EntryGroup = Readonly<Record<string, ProjectionEntry<unknown>>>;
140
+ type Projected<G extends EntryGroup> = { [K in keyof G]: G[K]['value'] };
141
+
142
+ function projected<G extends EntryGroup>(group: G): Projected<G> {
143
+ return Object.fromEntries(Object.entries(group).map(([key, entry]) => [key, entry.value])) as Projected<G>;
144
+ }
145
+
146
+ function nonempty<T>(value: T[] | undefined): T[] | undefined {
147
+ return value?.length ? value : undefined;
148
+ }
149
+
150
+ function projectionEntries(cfg: ProjectionSource) {
151
+ // Follow-up #1393 covers effective requirements/receipt inputs. CLI
152
+ // requirements values are read outside this config view. Only selected values
153
+ // can be exemptions in the projection, such as the editor receipt ledger below.
154
+ const a = cfg.assemble;
155
+ // These fields used to enter the digest through the enumerable assemble spread.
156
+ const authored = <K extends keyof typeof a>(key: K) => {
157
+ const enumerable = Object.prototype.propertyIsEnumerable.call(a, key);
158
+ return bound(a[key], value => enumerable ? value : undefined);
159
+ };
160
+ const assemble = {
161
+ seam: bound(a.seam, (_, ctx) => ctx.seam),
162
+ project: bound(a.project, (_, ctx) => ctx.project),
163
+ ground: bound(a.ground, (_, ctx) => ctx.ground),
164
+ rig_scale: authored('rig_scale'),
165
+ plan: authored('plan'),
166
+ extend_below_crop: bound(a.extend_below_crop, nonempty),
167
+ extend_painting: authored('extend_painting'),
168
+ edge_splits: authored('edge_splits'),
169
+ patches: bound(a.patches, nonempty),
170
+ cuts: bound(a.cuts, (value, ctx) => ctx.cuts(value, 'assemble.cuts')),
171
+ keep_under_occluders: bound(a.keep_under_occluders, nonempty),
172
+ require_hidden_extent: bound(a.require_hidden_extent, nonempty),
173
+ head_face_underfill: bound(a.head_face_underfill, (value, ctx) => ctx.hasHeadRun && value === true ? true : undefined),
174
+ yield_refused: bound(a.yield_refused, value => value === false ? undefined : value),
175
+ stage_map: exempt(a.stage_map, 1393, 'Selects a report sidecar without changing the assembly manifest.'),
176
+ editor_receipts: exempt(a.editor_receipts, 946, 'The legacy config digest omits the validation ledger and its receipt policy.'),
177
+ edited_parts: bound(a.edited_parts, (edited, { base, file }) => edited?.receipts.length ? {
178
+ receipts: edited.receipts.map((receipt, i) => ({
179
+ ...receipt,
180
+ file: file(resolve(base, edited.dir, receipt.file), `assemble.edited_parts.receipts[${i}].file`),
181
+ })),
182
+ } : undefined),
183
+ occluders: bound(a.occluders, (items, { file, plate }) => items?.length ? items.map((item, i) => ({
184
+ ...item,
185
+ image: file(item.image, `assemble.occluders[${i}].image`),
186
+ plate: plate(item.plate, `assemble.occluders[${i}].plate`),
187
+ grow: item.grow === 0 ? undefined : item.grow,
188
+ guard: item.guard === 0 ? undefined : item.guard,
189
+ })) : undefined),
190
+ take: named(a.take, {
191
+ '': ({ base, file, run }) => a.take?.length ? a.take.map((take, i) => {
192
+ const field = `assemble.take[${i}]`;
193
+ const reference = 'reference' in take ? take.reference : undefined;
194
+ return {
195
+ ...take,
196
+ run_dir: run(take.run_dir, `${field}.run_dir`),
197
+ st_input: file(take.st_input, `${field}.st_input`),
198
+ // Keep whole-layer metadata in the original take digest.
199
+ meta: 'tags' in take ? file(resolve(base, take.run_dir, 'meta.json'), `${field}.run_dir`) : undefined,
200
+ reference: reference !== undefined && 'painting' in reference
201
+ ? { ...reference, painting: file(reference.painting, `${field}.reference.painting`) } : reference,
202
+ };
203
+ }) : undefined,
204
+ ...Object.fromEntries((a.take ?? []).flatMap((take, i) => {
205
+ if (!('occluder' in take)) return [];
206
+ const field = `assemble.take[${i}].meta`;
207
+ const digest: ReadDigest = ({ base, file }) => file(resolve(base, take.run_dir, 'meta.json'), field);
208
+ return [[field, digest]];
209
+ })),
210
+ }),
211
+ alternates: bound(a.alternates, (items, { file, run, cuts }) => items?.length ? items.map((set, i) => ({
212
+ ...set,
213
+ source: file(set.source, `assemble.alternates[${i}].source`),
214
+ full: run(set.full, `assemble.alternates[${i}].full`),
215
+ head: run(set.head, `assemble.alternates[${i}].head`),
216
+ skeleton: file(set.skeleton, `assemble.alternates[${i}].skeleton`),
217
+ cuts: cuts(set.cuts, `assemble.alternates[${i}].cuts`),
218
+ layers: Object.keys(set.layers ?? {}).length === 0 ? undefined : set.layers,
219
+ })) : undefined),
220
+ };
221
+ const st = cfg.seethrough;
222
+ const seethrough = st == null ? undefined : {
223
+ resolution: bound(st.resolution),
224
+ head_box: bound(st.head_box, (value, ctx) => ctx.hasHeadRun ? value : undefined),
225
+ arm_split: bound(st.arm_split),
226
+ };
227
+ const skeleton = cfg.generation?.control?.skeleton;
228
+ const latent = cfg.generation?.latent;
229
+ // Look up the resolved pose on the original loader object before projecting.
230
+ const root = {
231
+ bones: bound(cfg.bones, (_, ctx) => ctx.bones),
232
+ constraints: named(assemblyPhysics(cfg.constraints), {
233
+ 'constraints.physics': ctx => nonempty(ctx.physicsPairs),
234
+ }),
235
+ depth: bound(cfg.depth, (value, ctx) => value === undefined ? undefined : ({
236
+ ...value,
237
+ full: ctx.depthRun(value.full, 'depth.full'),
238
+ head: ctx.depthRun(value.head, 'depth.head'),
239
+ })),
240
+ keySkeleton: named(controlSkeletonOf(cfg), {
241
+ 'generation.control.skeleton': ctx => skeleton === undefined ? undefined : {
242
+ latent,
243
+ ...(isSkeletonName(skeleton) ? { builtin: skeleton } : { file: ctx.file(skeleton, 'generation.control.skeleton') }),
244
+ },
245
+ }),
246
+ limbs: named(cfg.limbs == null ? undefined : Object.fromEntries(
247
+ Object.entries(cfg.limbs).map(([name, limb]) => [name, assemblyLimb(limb)] as const),
248
+ ), {
249
+ limbs: ctx => nonempty(ctx.limbs),
250
+ 'limbs.hybrid_width': ctx => ctx.hybridWidths.size === 0 ? undefined : [...ctx.hybridWidths],
251
+ }),
252
+ motion_seams: bound(cfg.motion_seams),
253
+ requirements: named(cfg.requirements, {
254
+ 'requirements.setup_painting': ctx => ctx.setup === undefined ? undefined : {
255
+ ...ctx.setup,
256
+ figure_mask: ctx.setupImage(ctx.setup.figure_mask, 'figure_mask'),
257
+ backdrop: ctx.setupImage(ctx.setup.backdrop, 'backdrop'),
258
+ },
259
+ }),
260
+ scene: bound(cfg.scene === undefined ? undefined : true),
261
+ // Turn, meshes and regions reach existing carrier helpers as aggregates.
262
+ // Their digest bindings cover the current derived effects. The guard
263
+ // cannot attribute a new read inside those aggregates to a digest.
264
+ turn: named(cfg.turn, {
265
+ turn: ctx => nonempty(ctx.basePairs),
266
+ 'depth.authored_units': ctx => ctx.authoredDepths(),
267
+ }),
268
+ meshes: shared(cfg.meshes, 'turn', 'constraints.physics', 'depth.authored_units'),
269
+ regions: shared(cfg.regions, 'turn', 'constraints.physics', 'depth.authored_units'),
270
+ motion: shared(assemblyMotion(cfg.motion), 'depth.authored_units'),
271
+ };
272
+ return { assemble, seethrough, root };
273
+ }
274
+
275
+ // Keep the validator's input permissive so it can name malformed entries at
276
+ // runtime, including entries planted in tests. The live entries use the union above.
277
+ type ProjectionRow = Readonly<Partial<{
278
+ value: unknown;
279
+ bindings: DigestBindings;
280
+ shared: readonly string[];
281
+ exemption: Exemption;
282
+ }>>;
283
+
284
+ function bindingName(path: string, name: string): string {
285
+ return name === '' ? path : name;
286
+ }
287
+
288
+ export function assemblyProjectionProblems(rows: Readonly<Record<string, ProjectionRow>>): string[] {
289
+ const problems: string[] = [];
290
+ const boundNames = new Set<string>();
291
+ for (const [path, entry] of Object.entries(rows)) {
292
+ for (const name of Object.keys(entry.bindings ?? {})) {
293
+ const field = bindingName(path, name);
294
+ if (boundNames.has(field)) problems.push(`config.${field} has duplicate assembly digest bindings`);
295
+ boundNames.add(field);
296
+ }
297
+ }
298
+ for (const [path, entry] of Object.entries(rows)) {
299
+ const field = `config.${path}`;
300
+ if (entry.exemption !== undefined) {
301
+ if (!Object.hasOwn(entry, 'value')) problems.push(`${field} has an exemption but is not projected`);
302
+ if (boundNames.has(path) || entry.shared?.length || Object.keys(entry.bindings ?? {}).length) {
303
+ problems.push(`${field} has an exemption and a digest binding`);
304
+ }
305
+ } else if (Object.keys(entry.bindings ?? {}).length === 0 && !entry.shared?.length) {
306
+ problems.push(`${field} is projected without a digest binding or exemption`);
307
+ }
308
+ for (const name of entry.shared ?? []) {
309
+ if (!boundNames.has(name)) problems.push(`${field} names missing digest binding config.${name}`);
310
+ }
311
+ }
312
+ return problems;
313
+ }
314
+
315
+ export function projectAssemblyConfig(source: ProjectionSource) {
316
+ const { assemble, seethrough, root } = projectionEntries(source);
317
+ const rows: Readonly<Record<string, ProjectionRow>> = {
318
+ ...Object.fromEntries(Object.entries(assemble).map(([key, entry]) => [`assemble.${key}`, entry])),
319
+ ...root,
320
+ ...Object.fromEntries(Object.entries(seethrough ?? {}).map(([key, entry]) => [`seethrough.${key}`, entry])),
321
+ };
322
+ const problems = assemblyProjectionProblems(rows);
323
+ if (problems.length > 0) throw new Error(problems.join('\n'));
324
+ return {
325
+ config: {
326
+ assemble: projected(assemble),
327
+ seethrough: seethrough === undefined ? undefined : projected(seethrough),
328
+ ...projected(root),
329
+ },
330
+ rows,
331
+ // The loader refuses unknown assemble keys. The public reader also accepts
332
+ // inline configs, whose extra enumerable fields were historically hashed.
333
+ legacyFields: Object.entries(source.assemble).filter(([key]) => !Object.hasOwn(assemble, key) && !isDoorKey(key)),
334
+ };
335
+ }
336
+
337
+ type AssemblyProjection = ReturnType<typeof projectAssemblyConfig>;
338
+ export type AssemblyView = AssemblyProjection['config'];
339
+
340
+ function movingPairs(cfg: AssemblyView, names: readonly string[]): Array<[string, string]> {
341
+ const moves = turnMovingPartPair(cfg);
342
+ if (moves === null) return [];
343
+ return names.flatMap((a, i) => names.slice(i + 1).filter(b => moves(a, b)).map((b): [string, string] => [a, b]));
344
+ }
345
+
346
+ function digestFiles(base: string) {
347
+ const file = (path: string | undefined, field: string): string | undefined =>
348
+ path === undefined ? undefined : sha256(fileBytes(resolve(base, path), field));
349
+ const run = (path: string | undefined, field: string): unknown =>
350
+ path === undefined ? undefined : layerRunDigest(resolve(base, path), field);
351
+ const plate = (path: string | undefined, field: string): string | undefined =>
352
+ path === undefined ? undefined : plateDigest(resolve(base, path), field);
353
+ const cuts = (entries: Cut[] | undefined, field: string): unknown => entries?.length
354
+ ? entries.map((cut, i) => ({
355
+ ...cut,
356
+ under: typeof cut.under === 'string' ? file(cut.under, `${field}[${i}].under`)
357
+ : cut.under === undefined ? undefined : { plate: plate(cut.under.plate, `${field}[${i}].under.plate`) },
358
+ }))
359
+ : undefined;
360
+ const sheet = (value: UserDepthSheet, field: string): unknown => ({ ...value, image: file(value.image, field) });
361
+ const depthRun = (value: DepthRunConfig | undefined, field: string): unknown => value === undefined ? undefined : ({
362
+ atlas: value.atlas === undefined ? undefined : sheet(value.atlas, `${field}.atlas.image`),
363
+ layers: value.layers === undefined ? undefined : Object.fromEntries(Object.entries(value.layers)
364
+ .map(([name, layer]) => [name, sheet(layer, `${field}.layers.${name}.image`)])),
365
+ });
366
+ return { base, file, run, plate, cuts, depthRun };
367
+ }
368
+
369
+ function readingContext(cfg: AssemblyView, parts: PartsFile, configPath: string, overrides?: AssemblyRules): ReadingContext {
370
+ const { seam, project } = effectiveAssemblyRules(cfg.assemble, overrides);
371
+ const ground = project === 'visible' ? cfg.assemble.ground ?? DEFAULT_GROUND : DEFAULT_GROUND;
372
+ const base = dirname(resolve(configPath));
373
+ const files = digestFiles(base);
374
+ const { file } = files;
375
+ const requirementsPath = ground === 'busy' && cfg.requirements !== undefined
376
+ ? resolve(base, cfg.requirements) : undefined;
377
+ const setup = requirementsPath === undefined ? undefined : readRequirements(requirementsPath).setup_painting;
378
+ const setupImage = (declaration: SetupPainting['figure_mask'] | SetupPainting['backdrop'], field: string) =>
379
+ declaration === undefined ? undefined : {
380
+ ...declaration,
381
+ path: sha256(fileBytes(setupPaintingFilePath(requirementsPath!, declaration.path), `requirements.setup_painting.${field}.path`)),
382
+ };
383
+ const names = [...new Set([
384
+ ...parts.parts.map(part => part.name),
385
+ ...(parts.alternates ?? []).flatMap(set => set.records.map(part => part.name)),
386
+ ...(cfg.assemble.cuts ?? []).map(cut => cut.into),
387
+ ...(cfg.assemble.patches ?? []).map(patch => patch.name),
388
+ ...cfg.assemble.plan.map(([name]) => name),
389
+ ])].sort();
390
+ const basePairs = movingPairs({ ...cfg, constraints: undefined }, names);
391
+ const baseSet = new Set(basePairs.map(pair => JSON.stringify(pair)));
392
+ const physicsPairs = movingPairs(cfg, names).filter(pair => !baseSet.has(JSON.stringify(pair)));
393
+ const hasHeadRun = Object.keys(parts.ghost_px).some(name => name.startsWith('head:'));
394
+ const frontParts = new Set((cfg.assemble.alternates ?? []).flatMap(set => set.front ?? []));
395
+ const bands = [
396
+ { name: null, records: parts.parts },
397
+ ...(parts.alternates ?? []).map(({ name, records }) => ({ name, records })),
398
+ ];
399
+ const hybridWidths = new Map<string, Array<{ set: string | null; width?: number }>>();
400
+ const limbs = Object.entries(cfg.limbs ?? {}).map(([name, { segments, split, front }]) => {
401
+ const activeFront = front?.parts.filter(part => frontParts.has(part)) ?? [];
402
+ const resolvedSegments = segments.map(({ hybrid, ...declared }, i) => {
403
+ const segment = { ...declared, cap: file(declared.cap, `limbs.${name}.segments[${i}].cap`) };
404
+ if (hybrid === undefined) return segment;
405
+ hybridWidths.set(hybrid.part, bands.flatMap(({ name: set, records }) => {
406
+ const band = records.find(record => record.name === hybrid.part)?.limb?.band;
407
+ return band === undefined ? [] : [{ set, width: hybrid.width ?? band.measured_width }];
408
+ }));
409
+ return { ...segment, hybrid: { part: hybrid.part } };
410
+ });
411
+ return [name, {
412
+ segments: resolvedSegments,
413
+ split,
414
+ front: front !== undefined && activeFront.length > 0 ? { parts: activeFront, after: front.after } : undefined,
415
+ }] as const;
416
+ });
417
+ const limbBones = new Set(limbs.flatMap(([, limb]) => limb.segments.map(segment => segment.bone)));
418
+ const alternateBones = new Set((cfg.assemble.alternates ?? []).flatMap(set => Object.keys(set.tips ?? {})));
419
+ const posesAlternate = limbs.length > 0 && cfg.assemble.alternates?.some(set => set.drawn !== undefined || set.skeleton !== undefined);
420
+ const geometry = limbBones.size === 0 && alternateBones.size === 0 ? [] : [...bonePlaces(cfg.bones ?? [])]
421
+ .filter(([name]) => limbBones.has(name) || alternateBones.has(name));
422
+ // Alternate skeleton and drawn registration also use the hierarchy.
423
+ const bones = posesAlternate ? cfg.bones : geometry.length === 0 ? undefined : geometry;
424
+ return {
425
+ ...files, seam, project, ground, setup, setupImage, hasHeadRun,
426
+ basePairs, physicsPairs, bones, limbs, hybridWidths,
427
+ authoredDepths: () => cfg.depth === undefined ? undefined
428
+ : [...authoredUnitDepths(cfg)].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0),
429
+ };
430
+ }
431
+
432
+ /** Config values consumed by assembly, evaluated against the assembled names and run shape. */
433
+ export function readAssemblyConfig(
434
+ cfg: AssemblySource, parts: PartsFile, configPath: string, overrides?: AssemblyRules,
435
+ ): AssemblyConfigRecord {
436
+ return readProjectedAssemblyConfig(projectAssemblyConfig(cfg), parts, configPath, overrides);
437
+ }
438
+
439
+ export function readProjectedAssemblyConfig(
440
+ projection: AssemblyProjection, parts: PartsFile, configPath: string, overrides?: AssemblyRules,
441
+ ): AssemblyConfigRecord {
442
+ const ctx = readingContext(projection.config, parts, configPath, overrides);
443
+ const inputs: Array<[string, unknown]> = projection.legacyFields.map(([key, value]) => [`assemble.${key}`, value]);
444
+ for (const [path, entry] of Object.entries(projection.rows)) {
445
+ for (const [name, read] of Object.entries(entry.bindings ?? {})) inputs.push([bindingName(path, name), read(ctx)]);
446
+ }
447
+ const fields = inputs.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
448
+ .flatMap(([name, value]) => value === undefined ? [] : [{ name, sha256: sha256(JSON.stringify(canonical(value))) }]);
449
+ return { sha256: assemblyFieldDigest(fields), fields };
450
+ }
451
+
452
+ export function assemblyFieldDigest(fields: AssemblyConfigRecord['fields']): string {
453
+ return sha256(JSON.stringify(fields.map(({ name, sha256 }) => [name, sha256])));
454
+ }
455
+
456
+ export function isSplitTakeMetadataField(name: string): boolean {
457
+ return /^assemble\.take\[(?:0|[1-9][0-9]*)\]\.meta$/.test(name);
458
+ }
459
+
460
+ export function assemblyConfigReading(configPath: string, parts: PartsFile): AssemblyConfigRecord {
461
+ return readAssemblyConfig(loadEarlyConfig(configPath, 'assemble'), parts, configPath);
462
+ }
463
+
464
+ export function changedAssemblyFields(previous: AssemblyConfigRecord, current: AssemblyConfigRecord): string[] {
465
+ if (previous.sha256 === current.sha256) return [];
466
+ const before = new Map(previous.fields.map(row => [row.name, row.sha256]));
467
+ const after = new Map(current.fields.map(row => [row.name, row.sha256]));
468
+ return [...new Set([...before.keys(), ...after.keys()])].sort().filter(name => before.get(name) !== after.get(name));
469
+ }
470
+
471
+ export function assemblyConfigChanges(configPath: string, parts: PartsFile): string[] {
472
+ if (parts.assembly_config === undefined) return [];
473
+ return changedAssemblyFields(parts.assembly_config, assemblyConfigReading(configPath, parts));
474
+ }
475
+
476
+ export function assemblyChangeDetail(changes: readonly string[]): string {
477
+ return `assembly config changed at ${changes.map(name => `config.${name}`).join(', ')}; re-run assemble from the current config`;
478
+ }
479
+
480
+ export function refuseStaleAssembly(configPath: string, parts: PartsFile, loaded?: AssemblySource, overrides?: AssemblyRules): void {
481
+ const previous = parts.assembly_config;
482
+ if (previous === undefined) return;
483
+ const cfg = loaded ?? loadEarlyConfig(configPath, 'assemble', overrides?.project);
484
+ const current = readAssemblyConfig(cfg, parts, configPath, overrides);
485
+ const changes = changedAssemblyFields(previous, current);
486
+ if (changes.length === 0) return;
487
+ const recorded = new Set(previous.fields.map(({ name }) => name));
488
+ const predatesSplitMetadata = changes.every(name => isSplitTakeMetadataField(name) && !recorded.has(name));
489
+ const detail = predatesSplitMetadata
490
+ ? `assembly reading changed at ${changes.map(name => `config.${name}`).join(', ')}; the recorded stamp predates split-take donor metadata binding. Re-run assemble once with the same config`
491
+ : assemblyChangeDetail(changes);
492
+ throw new PartsError([{ code: 'ASSEMBLY_CONFIG_STALE', object: configPath, detail }]);
493
+ }
@@ -1,5 +1,5 @@
1
1
  /** Fully explicit unit consumers may omit their unused scalar transport (#877). */
2
- import type { MeshSpec, Motion, RegionSpec, TurnSpec } from './config.ts';
2
+ import type { BlinkStill, MeshSpec, RegionSpec, TurnSpec } from './config.ts';
3
3
  import { turnUnitBone } from './turn.ts';
4
4
 
5
5
  export interface AuthoredUnitDepth {
@@ -12,7 +12,7 @@ export function authoredUnitDepths(cfg: {
12
12
  turn?: TurnSpec;
13
13
  regions?: Record<string, RegionSpec>;
14
14
  meshes?: Record<string, MeshSpec>;
15
- motion?: Pick<Motion, 'blink'>;
15
+ motion?: { blink?: { still?: Record<string, Pick<BlinkStill, 'bone'>> } };
16
16
  }): ReadonlyMap<string, AuthoredUnitDepth> {
17
17
  const out = new Map<string, AuthoredUnitDepth>();
18
18
  const turn = cfg.turn;