@rig-c/parts 2.46.0 → 2.47.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.
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';
2
2
  import { readFileSync, statSync } from 'node:fs';
3
3
  import { dirname, resolve } from 'node:path';
4
4
  import { authoredUnitDepths } from './authoredunit.ts';
5
- import { isDoorKey, loadEarlyConfig, turnMovingPartPair, type AssembleConfig, type CharacterConfig, type Cut } from './config.ts';
5
+ import { controlSkeletonOf, isDoorKey, loadEarlyConfig, turnMovingPartPair, type AssembleConfig, type CharacterConfig, type Cut, type Limb } from './config.ts';
6
6
  import type { DepthRunConfig, UserDepthSheet } from './depthsheets.ts';
7
7
  import { PartsError, refuseIfAny } from './errors.ts';
8
8
  import { readWrapperLayers } from './layers.ts';
@@ -11,11 +11,40 @@ import type { AssemblyConfigRecord, PartsFile } from './parts.ts';
11
11
  import { PLATE_RECEIPT_FILE, verifyPlateReceipt } from './plate.ts';
12
12
  import { isSkeletonName } from './skeleton.ts';
13
13
  import { setupPaintingFilePath, type SetupPainting } from './setuppainting.ts';
14
- import { DEFAULT_GROUND, DEFAULT_PROJECT_RULE, type ProjectRule } from './projectrule.ts';
14
+ import { DEFAULT_GROUND, DEFAULT_PROJECT_RULE, type Ground, type ProjectRule } from './projectrule.ts';
15
15
  import { DEFAULT_SEAM_RULE, type SeamRule } from './seamrule.ts';
16
16
  import { readRequirements } from './requirements.ts';
17
17
 
18
- type AssemblySource = Omit<AssembleConfig, 'seethrough'> & Partial<Pick<AssembleConfig, 'seethrough'>> & Pick<CharacterConfig, 'generation'>;
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
+ }
19
48
 
20
49
  export interface AssemblyRules {
21
50
  seam?: SeamRule;
@@ -68,19 +97,253 @@ function canonical(value: unknown, authoredKeys = false): unknown {
68
97
  return value;
69
98
  }
70
99
 
71
- function movingPairs(cfg: AssemblySource, names: readonly string[]): Array<[string, string]> {
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]> {
72
341
  const moves = turnMovingPartPair(cfg);
73
342
  if (moves === null) return [];
74
343
  return names.flatMap((a, i) => names.slice(i + 1).filter(b => moves(a, b)).map((b): [string, string] => [a, b]));
75
344
  }
76
345
 
77
- /** Config values consumed by assembly, evaluated against the assembled names and run shape. */
78
- export function readAssemblyConfig(
79
- cfg: AssemblySource, parts: PartsFile, configPath: string, overrides?: AssemblyRules,
80
- ): AssemblyConfigRecord {
81
- const { seam, project } = effectiveAssemblyRules(cfg.assemble, overrides);
82
- const ground = project === 'visible' ? cfg.assemble.ground ?? DEFAULT_GROUND : DEFAULT_GROUND;
83
- const base = dirname(resolve(configPath));
346
+ function digestFiles(base: string) {
84
347
  const file = (path: string | undefined, field: string): string | undefined =>
85
348
  path === undefined ? undefined : sha256(fileBytes(resolve(base, path), field));
86
349
  const run = (path: string | undefined, field: string): unknown =>
@@ -100,7 +363,15 @@ export function readAssemblyConfig(
100
363
  layers: value.layers === undefined ? undefined : Object.fromEntries(Object.entries(value.layers)
101
364
  .map(([name, layer]) => [name, sheet(layer, `${field}.layers.${name}.image`)])),
102
365
  });
103
- const skeleton = cfg.generation?.control?.skeleton;
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;
104
375
  const requirementsPath = ground === 'busy' && cfg.requirements !== undefined
105
376
  ? resolve(base, cfg.requirements) : undefined;
106
377
  const setup = requirementsPath === undefined ? undefined : readRequirements(requirementsPath).setup_painting;
@@ -109,7 +380,6 @@ export function readAssemblyConfig(
109
380
  ...declaration,
110
381
  path: sha256(fileBytes(setupPaintingFilePath(requirementsPath!, declaration.path), `requirements.setup_painting.${field}.path`)),
111
382
  };
112
- const edited = cfg.assemble.edited_parts;
113
383
  const names = [...new Set([
114
384
  ...parts.parts.map(part => part.name),
115
385
  ...(parts.alternates ?? []).flatMap(set => set.records.map(part => part.name)),
@@ -120,7 +390,6 @@ export function readAssemblyConfig(
120
390
  const basePairs = movingPairs({ ...cfg, constraints: undefined }, names);
121
391
  const baseSet = new Set(basePairs.map(pair => JSON.stringify(pair)));
122
392
  const physicsPairs = movingPairs(cfg, names).filter(pair => !baseSet.has(JSON.stringify(pair)));
123
- const { resolution, head_box, arm_split } = cfg.seethrough ?? {};
124
393
  const hasHeadRun = Object.keys(parts.ghost_px).some(name => name.startsWith('head:'));
125
394
  const frontParts = new Set((cfg.assemble.alternates ?? []).flatMap(set => set.front ?? []));
126
395
  const bands = [
@@ -152,84 +421,30 @@ export function readAssemblyConfig(
152
421
  .filter(([name]) => limbBones.has(name) || alternateBones.has(name));
153
422
  // Alternate skeleton and drawn registration also use the hierarchy.
154
423
  const bones = posesAlternate ? cfg.bones : geometry.length === 0 ? undefined : geometry;
155
- const assemble = {
156
- ...cfg.assemble,
157
- ground,
158
- project,
159
- seam,
160
- extend_below_crop: cfg.assemble.extend_below_crop?.length ? cfg.assemble.extend_below_crop : undefined,
161
- patches: cfg.assemble.patches?.length ? cfg.assemble.patches : undefined,
162
- cuts: cuts(cfg.assemble.cuts, 'assemble.cuts'),
163
- keep_under_occluders: cfg.assemble.keep_under_occluders?.length ? cfg.assemble.keep_under_occluders : undefined,
164
- require_hidden_extent: cfg.assemble.require_hidden_extent?.length ? cfg.assemble.require_hidden_extent : undefined,
165
- head_face_underfill: hasHeadRun && cfg.assemble.head_face_underfill === true ? true : undefined,
166
- yield_refused: cfg.assemble.yield_refused === true ? true : undefined,
167
- stage_map: undefined,
168
- editor_receipts: undefined,
169
- edited_parts: edited?.receipts.length ? {
170
- receipts: edited.receipts.map((receipt, i) => ({
171
- ...receipt,
172
- file: file(resolve(base, edited.dir, receipt.file), `assemble.edited_parts.receipts[${i}].file`),
173
- })),
174
- } : undefined,
175
- occluders: cfg.assemble.occluders?.length ? cfg.assemble.occluders.map((item, i) => ({
176
- ...item,
177
- image: file(item.image, `assemble.occluders[${i}].image`),
178
- plate: plate(item.plate, `assemble.occluders[${i}].plate`),
179
- grow: item.grow === 0 ? undefined : item.grow,
180
- guard: item.guard === 0 ? undefined : item.guard,
181
- })) : undefined,
182
- take: cfg.assemble.take?.length ? cfg.assemble.take.map((take, i) => {
183
- const field = `assemble.take[${i}]`;
184
- const reference = 'reference' in take ? take.reference : undefined;
185
- return {
186
- ...take,
187
- run_dir: run(take.run_dir, `${field}.run_dir`),
188
- st_input: file(take.st_input, `${field}.st_input`),
189
- meta: 'tags' in take ? file(resolve(base, take.run_dir, 'meta.json'), `${field}.run_dir`) : undefined,
190
- reference: reference !== undefined && 'painting' in reference
191
- ? { ...reference, painting: file(reference.painting, `${field}.reference.painting`) } : reference,
192
- };
193
- }) : undefined,
194
- alternates: cfg.assemble.alternates?.length ? cfg.assemble.alternates.map((set, i) => ({
195
- ...set,
196
- source: file(set.source, `assemble.alternates[${i}].source`),
197
- full: run(set.full, `assemble.alternates[${i}].full`),
198
- head: run(set.head, `assemble.alternates[${i}].head`),
199
- skeleton: file(set.skeleton, `assemble.alternates[${i}].skeleton`),
200
- cuts: cuts(set.cuts, `assemble.alternates[${i}].cuts`),
201
- layers: Object.keys(set.layers ?? {}).length === 0 ? undefined : set.layers,
202
- })) : undefined,
203
- };
204
- const inputs = {
205
- ...Object.fromEntries(Object.entries(assemble).filter(([key]) => !isDoorKey(key)).map(([key, value]) => [`assemble.${key}`, value])),
206
- bones,
207
- 'constraints.physics': physicsPairs.length === 0 ? undefined : physicsPairs,
208
- 'depth.authored_units': cfg.depth === undefined ? undefined : [...authoredUnitDepths(cfg)].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0),
209
- depth: cfg.depth === undefined ? undefined : {
210
- ...cfg.depth,
211
- full: depthRun(cfg.depth.full, 'depth.full'),
212
- head: depthRun(cfg.depth.head, 'depth.head'),
213
- },
214
- 'generation.control.skeleton': skeleton === undefined ? undefined : {
215
- latent: cfg.generation?.latent,
216
- ...(isSkeletonName(skeleton) ? { builtin: skeleton } : { file: file(skeleton, 'generation.control.skeleton') }),
217
- },
218
- limbs: limbs.length === 0 ? undefined : limbs,
219
- 'limbs.hybrid_width': hybridWidths.size === 0 ? undefined : [...hybridWidths],
220
- motion_seams: cfg.motion_seams,
221
- 'requirements.setup_painting': setup === undefined ? undefined : {
222
- ...setup,
223
- figure_mask: setupImage(setup.figure_mask, 'figure_mask'),
224
- backdrop: setupImage(setup.backdrop, 'backdrop'),
225
- },
226
- scene: cfg.scene === undefined ? undefined : true,
227
- 'seethrough.resolution': resolution,
228
- 'seethrough.head_box': hasHeadRun ? head_box : undefined,
229
- 'seethrough.arm_split': arm_split,
230
- turn: basePairs.length === 0 ? undefined : basePairs,
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),
231
429
  };
232
- const fields = Object.entries(inputs).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
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)
233
448
  .flatMap(([name, value]) => value === undefined ? [] : [{ name, sha256: sha256(JSON.stringify(canonical(value))) }]);
234
449
  return { sha256: assemblyFieldDigest(fields), fields };
235
450
  }
@@ -238,6 +453,10 @@ export function assemblyFieldDigest(fields: AssemblyConfigRecord['fields']): str
238
453
  return sha256(JSON.stringify(fields.map(({ name, sha256 }) => [name, sha256])));
239
454
  }
240
455
 
456
+ export function isSplitTakeMetadataField(name: string): boolean {
457
+ return /^assemble\.take\[(?:0|[1-9][0-9]*)\]\.meta$/.test(name);
458
+ }
459
+
241
460
  export function assemblyConfigReading(configPath: string, parts: PartsFile): AssemblyConfigRecord {
242
461
  return readAssemblyConfig(loadEarlyConfig(configPath, 'assemble'), parts, configPath);
243
462
  }
@@ -259,9 +478,16 @@ export function assemblyChangeDetail(changes: readonly string[]): string {
259
478
  }
260
479
 
261
480
  export function refuseStaleAssembly(configPath: string, parts: PartsFile, loaded?: AssemblySource, overrides?: AssemblyRules): void {
262
- if (parts.assembly_config === undefined) return;
481
+ const previous = parts.assembly_config;
482
+ if (previous === undefined) return;
263
483
  const cfg = loaded ?? loadEarlyConfig(configPath, 'assemble', overrides?.project);
264
484
  const current = readAssemblyConfig(cfg, parts, configPath, overrides);
265
- const changes = changedAssemblyFields(parts.assembly_config, current);
266
- if (changes.length > 0) throw new PartsError([{ code: 'ASSEMBLY_CONFIG_STALE', object: configPath, detail: assemblyChangeDetail(changes) }]);
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 }]);
267
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;
@@ -39,6 +39,8 @@ export interface BehindSeamsFramesInput {
39
39
  stock: readonly BehindSeamsStockPair[] | null;
40
40
  fps: number;
41
41
  turn?: BehindSeamsTurnInput;
42
+ /** Issue #1403 plant only: the samples[] cap; production never sets it ({@link BEHIND_SAMPLE_CAP}). */
43
+ sampleCap?: number;
42
44
  }
43
45
  export interface BehindSeamsTurnPose {
44
46
  name: string;
@@ -93,6 +95,8 @@ export interface BehindSeamsCount {
93
95
  box: [number, number, number, number] | null;
94
96
  max_spatial_run_cells: number;
95
97
  samples: BehindSeamsSample[];
98
+ /** Issue #1403: present only when the list held more than {@link BEHIND_SAMPLE_CAP} rows; the rows left out. */
99
+ samples_omitted?: number;
96
100
  }
97
101
  export type BehindSeamsEndpoint = [grid_x: number, grid_y: number, world_x: number, world_y: number, owner: number];
98
102
  export interface BehindSeamsUnreadCorridor {
@@ -215,6 +219,60 @@ export function behindSeamsProblems(value: unknown, at: string): Problem[] {
215
219
  return problems;
216
220
  }
217
221
 
222
+ /**
223
+ * Issue #1403: the most `samples[]` rows one count writes. Per-cell samples are
224
+ * a bounded diagnostic sample; the counts are the measurement. Every count,
225
+ * `px`, `box`, hit, span, run and status is computed from all cells before the
226
+ * list is cut, and a list at or under the cap is written as it was.
227
+ */
228
+ export const BEHIND_SAMPLE_CAP = 64;
229
+
230
+ /** One standing candidate: its measured ordinal, cell, chosen distances, whether it qualified, and the smaller distance. */
231
+ interface StandingCandidate { ord: number; k: number; d: [number, number]; q: boolean; m: number }
232
+
233
+ /**
234
+ * Whether standing candidate `a` ranks worse than `b`. The gate counts a cell
235
+ * when both rear-to-front distances exceed the threshold (`qualifies`), so the
236
+ * smaller of the two is the margin the threshold is compared against: a counted
237
+ * cell ranks first, then the larger smaller-distance, then the earlier measured
238
+ * ordinal. No two candidates tie, so the kept set is one set.
239
+ */
240
+ export function standingWorse(a: Pick<StandingCandidate, 'ord' | 'q' | 'm'>, b: Pick<StandingCandidate, 'ord' | 'q' | 'm'>): boolean {
241
+ if (a.q !== b.q) return a.q;
242
+ if (a.m !== b.m) return a.m > b.m;
243
+ return a.ord < b.ord;
244
+ }
245
+
246
+ /**
247
+ * The {@link BEHIND_SAMPLE_CAP} worst standing candidates seen so far, without
248
+ * keeping the others: at most `cap` entries live at once.
249
+ */
250
+ export class WorstStanding {
251
+ readonly kept: StandingCandidate[] = [];
252
+ seen = 0;
253
+ constructor(readonly cap: number = BEHIND_SAMPLE_CAP) {}
254
+ offer(k: number, d: [number, number], q: boolean): void {
255
+ const c: StandingCandidate = { ord: this.seen++, k, d, q, m: d[0] < d[1] ? d[0] : d[1] };
256
+ if (this.kept.length < this.cap) { this.kept.push(c); return; }
257
+ let weakest = 0;
258
+ for (let i = 1; i < this.kept.length; i++) if (standingWorse(this.kept[weakest], this.kept[i])) weakest = i;
259
+ if (standingWorse(c, this.kept[weakest])) this.kept[weakest] = c;
260
+ }
261
+ /** The kept candidates in measured order. */
262
+ inOrder(): StandingCandidate[] { return [...this.kept].sort((x, y) => x.ord - y.ord); }
263
+ }
264
+
265
+ /**
266
+ * The positions kept from a list of `n` rows that carry no magnitude: all of
267
+ * them at or under `cap`, otherwise floor(j · n / cap) for j = 0 … cap − 1 —
268
+ * `cap` distinct, increasing positions spread across the list, the first row
269
+ * always among them.
270
+ */
271
+ export function evenlySpaced(n: number, cap: number = BEHIND_SAMPLE_CAP): number[] {
272
+ if (n <= cap) return Array.from({ length: n }, (_, i) => i);
273
+ return Array.from({ length: cap }, (_, j) => Math.floor((j * n) / cap));
274
+ }
275
+
218
276
  const emptyCount = (status: BehindSeamsCount['status'] = 'SKIP'): BehindSeamsCount => ({ status, boundary_cells: 0, geometric_px: 0, raw_px: 0, px: 0, box: null, max_spatial_run_cells: 0, samples: [] });
219
277
  type RGB = [number, number, number];
220
278
  interface Material { alpha: Float64Array; base: Float64Array; delta: Float64Array }
@@ -397,6 +455,7 @@ function readBehindFrame(api: BehindSeamsApi, input: BehindSeamsFramesInput, pai
397
455
  };
398
456
  const standingHits = new Set<number>(), motionHits = new Set<number>();
399
457
  let standingUnderflow = false;
458
+ const cap = input.sampleCap ?? BEHIND_SAMPLE_CAP, worstStanding = new WorstStanding(cap);
400
459
  for (const [k, corridor] of corridors) {
401
460
  if (!surviving.has(k)) continue;
402
461
  if (rear.alpha[k] <= 0 || underflow.has(k)) { unread(label, 'positive symbolic rear contribution underflowed its numeric colour weight'); standingUnderflow = true; continue; }
@@ -410,8 +469,10 @@ function readBehindFrame(api: BehindSeamsApi, input: BehindSeamsFramesInput, pai
410
469
  }
411
470
  if (raw) row.standing.raw_px++;
412
471
  if (qualifies) standingHits.add(k);
413
- row.standing.samples.push(sample(k, chosen, qualifies));
472
+ worstStanding.offer(k, chosen as [number, number], qualifies);
414
473
  }
474
+ row.standing.samples = worstStanding.inOrder().map(c => sample(c.k, c.d, c.q));
475
+ if (worstStanding.seen > cap) row.standing.samples_omitted = worstStanding.seen - cap;
415
476
  counted(row.standing, standingHits, grid, allowance);
416
477
  // Incomplete coverage cannot certify PASS, but cannot hide a measured failure.
417
478
  if (support.size === 0 || unreadCorridors.length > 0 || standingUnderflow) {
@@ -435,8 +496,12 @@ function readBehindFrame(api: BehindSeamsApi, input: BehindSeamsFramesInput, pai
435
496
  motionReadable = false; unread(label, 'stock transported setup-overlap support cannot be bound to the actually drawn setup pair strictly in front of the complete rear set'); continue;
436
497
  }
437
498
  if (rear.alpha[k] <= 0 || underflow.has(k)) { motionReadable = false; unread(label, 'positive symbolic rear contribution underflowed its numeric colour weight'); continue; }
438
- motionHits.add(k); row.motion_opened.samples.push(sample(k, null, true));
499
+ motionHits.add(k);
439
500
  }
501
+ // Motion-opened rows carry no distance; keep evenly spaced rows, built only for what is kept.
502
+ const hitCells = [...motionHits];
503
+ row.motion_opened.samples = evenlySpaced(hitCells.length, cap).map(i => sample(hitCells[i], null, true));
504
+ if (hitCells.length > cap) row.motion_opened.samples_omitted = hitCells.length - cap;
440
505
  row.motion_opened.boundary_cells = motionCells.size;
441
506
  row.motion_opened.geometric_px = motionHits.size; row.motion_opened.raw_px = motionHits.size;
442
507
  counted(row.motion_opened, motionHits, grid, allowance);