spine-parts 2.25.0 → 2.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.ts CHANGED
@@ -16,7 +16,7 @@ import { applyDepth, prepareDepth } from './src/depthworkflow.ts';
16
16
  */
17
17
  import { spawnSync } from 'node:child_process';
18
18
  import { runBuildProcess, processRigcRunner as rigcRunner } from './tools/build-process.ts';
19
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
19
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
20
20
  import { tmpdir } from 'node:os';
21
21
  import { basename, dirname, extname, join, resolve } from 'node:path';
22
22
  import { DEFAULT_PROJECT_RULE, DEFAULT_SEAM_RULE, headGarmentOverlaps, headGarmentWarning, HOLES_LISTED, PROJECT_RULES, type ProjectRule, proposeFields, proposePlan, proposeSinglePlan, SEAM_RULES, type SeamRule } from './src/assemble.ts';
@@ -35,6 +35,7 @@ import { makeInputs } from './src/inputs.ts';
35
35
  import { idleKeysOf, isIdleKeys } from './src/rig.ts';
36
36
  import { bodyCoreBox, bodyOpaqueBox, CORE_ALPHA, depthSkipLine, exportLayers, figuresPhrase, hiddenLayerLine, implausibleRules, layerCoreBox, layerFigures, layerOpaqueBox, type LayerSet, layerSetDiff, type OpaqueBox, OPAQUE_ALPHA_ABOVE, pct, readLayers, readWrapperLayers, ruleSummary, templateLayerNames, templatePsdBytes, times } from './src/layers.ts';
37
37
  import { checkImageSize, choosePerson, KEYPOINTS_SPEC, loadKeypoints, type RigJoints, toRigJoints } from './src/keypoints.ts';
38
+ import { checkPartsStage } from './src/partscheck.ts';
38
39
  import { basisLines, branchSqueezeLine, checkProposal, compare, compareLines, DEFAULT_GRID_RULE, draftTurn, drawLandmarks, FIGURE_GRID_DIVISOR, FRINGE_STEP_PX, GRID_RULES, type GridRule, type BustDraft, HIP_MIN_FRACTION, type DraftLintFinding, lint, lintLine, type PartSet, PROPOSAL_CONFIG_SECTIONS, proposalAsConfig, proposeWithBasis, readBustLandmarks, readPartSet, serializeProposal, withTurn, WRIST_ON_PART_PX } from './src/propose.ts';
39
40
  import { BASIS_FILE, BASIS_SPEC, basisFile, basisLine, coverageLines, legChainChoice, serializeBasis } from './src/diagnostics.ts';
40
41
  import { BEND_DEGREES, BEND_WORST_SHARE, DUST_MAX_PX, DUST_MAX_SHARE, IDLE_BOUND_PX, MESH_DRAFT_REPORT, MESH_DRAFT_SPEC, meshDraftStage, MORE_TRIANGLES_FLAG, relativeConfigPaths, TOLERANCE_FIGURE_DIVISOR } from './src/meshdraft.ts';
@@ -565,6 +566,12 @@ usage:
565
566
  same input), refused as RETUNE_INPUT_CHECK_BOUND,
566
567
  RETUNE_INPUT_CHECK_FILE and RETUNE_INPUT_CHECK_MOVED.
567
568
 
569
+ rig-parts check-parts --parts <dir> --out <dir> [--json]
570
+ Read assemble outputs, bind their bytes and write parts-check.json.
571
+ --out is disjoint from --parts. No rig or renderer is required.
572
+ Exit 0 records input integrity; all six unmeasured quality classes print HOLE.
573
+ --json prints the completed report only, with the recorded exit code.
574
+
568
575
  rig-parts check --rig <dir> --out <dir> [--parts <dir>] [--source <painting.png>] [--no-extremes]
569
576
  [--page-edges pot|free] [--pack-shape rect|polygon]
570
577
  [--requirements <file.json>] [--seam-pairs] [--keep-stills]
@@ -1126,6 +1133,7 @@ function printLayerTable(set: LayerSet): void {
1126
1133
  * no row; `layers` takes one positional path beside its flags (issue #359).
1127
1134
  */
1128
1135
  const TAKES = {
1136
+ 'check-parts': { valued: ['--parts', '--out'], switches: ['--json'] },
1129
1137
  'diff-components': { valued: ['--stack', '--painting', '--parts', '--figure', '--floor', '--threshold', '--out', '--verify'], switches: [] },
1130
1138
  'depth-prepare': { valued: ['--parts', '--config', '--out'], switches: [] },
1131
1139
  'depth-apply': { valued: ['--parts', '--manifest', '--config', '--rig-config', '--out'], switches: [] },
@@ -1376,6 +1384,23 @@ function flags(args: string[], command: Command, required: readonly string[]): M
1376
1384
  return got;
1377
1385
  }
1378
1386
 
1387
+ function cmdCheckParts(args: string[]): number {
1388
+ const json = args.filter(arg => arg === '--json').length;
1389
+ if (json > 1) return usage('--json is given twice');
1390
+ const values = flags(args.filter(arg => arg !== '--json'), 'check-parts', ['--parts', '--out']);
1391
+ if (typeof values === 'string') return usage(values);
1392
+ try {
1393
+ const input = values.get('--parts') as string;
1394
+ const parts = existsSync(input) ? realpathSync(input) : input;
1395
+ const report = checkPartsStage(parts, values.get('--out') as string, json === 1 ? () => {} : console.log);
1396
+ if (json === 1) process.stdout.write(JSON.stringify(report, null, 2) + '\n');
1397
+ return report.exit_code;
1398
+ } catch (error) {
1399
+ if (error instanceof PartsError) return printRefusal(error);
1400
+ return printRefusal(new PartsError([{ code: 'PARTS_CHECK_INTERNAL', object: 'check-parts', detail: 'unexpected internal exception; no report was published' }]));
1401
+ }
1402
+ }
1403
+
1379
1404
  function cmdCheck(args: string[]): number {
1380
1405
  // The switches check takes (issues #202, #209, #454): they carry no value, so they are taken out before the valued flags are read.
1381
1406
  const json = args.filter((a) => a === '--json').length;
@@ -2333,6 +2358,7 @@ function main(argv: string[]): number | Promise<number> {
2333
2358
  if (command === 'head-crop-preflight') return cmdHeadCropPreflight(rest);
2334
2359
  if (command === 'compare') return cmdCompare(rest);
2335
2360
  if (command === 'check') return cmdCheck(rest);
2361
+ if (command === 'check-parts') return cmdCheckParts(rest);
2336
2362
  if (command === 'loop') return cmdLoop(rest);
2337
2363
  if (command === 'assemble') return cmdAssemble(rest);
2338
2364
  if (command === 'inputs') return cmdInputs(rest);
package/docs/AUTHORING.md CHANGED
@@ -5735,6 +5735,31 @@ documents do not ship). Each is an input this package built; none is an author's
5735
5735
  | <a id="COMPARE_WARMUP_UNSUPPORTED"></a>`COMPARE_WARMUP_UNSUPPORTED` | a physics warm-up other than 0 was asked of the comparison; physics resets at time 0 and steps from there | an input this package built, not an author's: report it with the line |
5736
5736
  | <a id="SKINNING_RANGE_UNSUPPORTED"></a>`SKINNING_RANGE_UNSUPPORTED` | `skinningEnvelopeBone` was handed a bone range not declared by the bone's own keys (a physics swing, a range read off a posed schedule), or a bone whose setup scale is not uniform; the bound is not proven, so it is refused | nothing to change for the build: inside the residual clause it means the residual veto was not applied to that bone, and the motion comparison decides |
5737
5737
 
5738
+ ### check-parts
5739
+
5740
+ Run `rig-parts check-parts --parts <assembled-dir> --out <disjoint-report-dir>`
5741
+ before parts review. Add `--json` for the completed report alone. The command
5742
+ writes `parts-check.json` and reads no rig, motion or plate. Exit 0 records input
5743
+ integrity while the six #945/#884 quality classes remain named HOLEs.
5744
+ [STABILITY](STABILITY.md#parts-stage-integrity-report) defines the binding and
5745
+ closed diagnostic vocabulary. Base and alternate `scene.figure_mask` remain
5746
+ outside the consumed inputs pending [#1177](https://github.com/rig-c/parts/issues/1177).
5747
+
5748
+ | rule | means | change |
5749
+ | --- | --- | --- |
5750
+ | <a id="PARTS_CHECK_INPUT_READ"></a>`PARTS_CHECK_INPUT_READ` | an input cannot be inventoried, is a link/special file, or references an asset outside the input root | supply a readable regular-file assemble output |
5751
+ | <a id="PARTS_CHECK_PNG_READ"></a>`PARTS_CHECK_PNG_READ` | the named part or auxiliary depth PNG is missing or undecodable | restore the declared PNG or re-run assemble |
5752
+ | <a id="PARTS_CHECK_REPORT"></a>`PARTS_CHECK_REPORT` | a present source-cover/allocation report has invalid JSON, spec, grid, membership or counted spans | regenerate the named producer report with the assemble output |
5753
+ | <a id="PARTS_CHECK_OUTPUT"></a>`PARTS_CHECK_OUTPUT` | output and input roots overlap | choose a disjoint report directory |
5754
+ | <a id="PARTS_CHECK_INPUT_CHANGED"></a>`PARTS_CHECK_INPUT_CHANGED` | bytes or inventory membership changed while reading | freeze the input and run again |
5755
+ | <a id="PARTS_CHECK_PUBLISH"></a>`PARTS_CHECK_PUBLISH` | the report could not be atomically published | supply a writable output root and resolve any existing temporary file |
5756
+ | <a id="PARTS_CHECK_INTERNAL"></a>`PARTS_CHECK_INTERNAL` | an unexpected exception or undeclared diagnostic occurred | report the tool failure |
5757
+ | <a id="PARTS_UNPLANNED_SOURCE_COVER"></a>`PARTS_UNPLANNED_SOURCE_COVER` | REPORTED direct input support under an unplanned front owner, with part/source/count/spans | review its provenance; no quality threshold is applied |
5758
+ | <a id="PARTS_SOURCE_COVER"></a>`PARTS_SOURCE_COVER` | HOLE when source_cover.json is absent | re-run assemble when a cover inventory is required |
5759
+ | <a id="PARTS_PAINTING_ALLOCATION"></a>`PARTS_PAINTING_ALLOCATION` | HOLE when painting_allocation.json is absent | retain the missing transfer observation in review |
5760
+ | <a id="PARTS_PLATE_GHOST"></a><a id="PARTS_PLATE_STRUCTURE"></a><a id="PARTS_PLATE_SMEAR"></a><a id="PARTS_PLATE_STEPS"></a>`PARTS_PLATE_GHOST`, `PARTS_PLATE_STRUCTURE`, `PARTS_PLATE_SMEAR`, `PARTS_PLATE_STEPS` | HOLE; no adopted plate discriminator is available | carry these unmeasured classes to parts review |
5761
+ | <a id="PARTS_INVENTED_MATERIAL"></a><a id="PARTS_INVENTED_EXPOSURE"></a>`PARTS_INVENTED_MATERIAL`, `PARTS_INVENTED_EXPOSURE` | HOLE; validated producer material truth and posed exposure are unavailable | retain the producer-provenance and frame-measurement gaps in review |
5762
+
5738
5763
  ### check and build
5739
5764
 
5740
5765
  | rule | means | change |
package/docs/STABILITY.md CHANGED
@@ -29,6 +29,105 @@ below). A build's bytes are not promised across versions. A later version may mo
29
29
  them, and when it does, the change that moves them declares which bytes and why (the
30
30
  winding change of #133 is the example: [MIGRATION.md](MIGRATION.md)).
31
31
 
32
+ ## Parts-stage integrity report
33
+
34
+ `rig-parts check-parts --parts <assembled-dir> --out <disjoint-report-dir>
35
+ [--json]` writes `parts-check.json`, spec `rig-parts-parts-check/1`.
36
+ Exit 0 is not a quality pass. No #945/#884 defect class is measured yet.
37
+ The six quality HOLEs are always present. They name plate ghost, plate structure,
38
+ plate smear, stepped fill, invented material and invented-material exposure.
39
+
40
+ The top-level key order is `spec`, `stage`, `inputs`, `parts`, `refusals`,
41
+ `reported`, `holes`, `exit_code`. `stage` is `parts`. `inputs` is sorted by
42
+ relative POSIX path. Each row has `path`, `status`, `sha256`, in that order.
43
+ Status is `read`, `missing`, `unreadable` or optional `absent`; SHA-256 is null
44
+ unless the file was read. The inventory binds regular files under `--parts`,
45
+ including primary and alternate PNGs, declared depth images, `parts.json`,
46
+ `painting_in_rig.png` and present source-cover/allocation reports. Missing
47
+ required references are explicit inventory rows. Symlinks and special files
48
+ are refused. Inputs are hashed again before atomic publication.
49
+
50
+ Base and alternate `scene.figure_mask` are declared but not consumed, read,
51
+ hashed or bound by this command. Their standalone-assemble location is tracked
52
+ in [#1177](https://github.com/rig-c/parts/issues/1177). The plate is outside this
53
+ command's inputs. `painting_in_rig` is written beside `parts.json` in both
54
+ standalone assemble and build layouts and is consumed and hash-checked.
55
+
56
+ `parts` preserves primary names, alternate records, the source-cover inventory
57
+ and allocation reports. Embedded object keys are sorted, and producer array
58
+ order is retained. `refusals` rows have `code`, `object`, `found`, `required`,
59
+ `detail`; reused metadata-reader diagnostics retain their code and detail with
60
+ null structured values when the reader supplies none. A refused input produces
61
+ a report and exit 1. `reported` rows have `code`, `set`, `part`, `source`, `count`,
62
+ `spans`; unplanned direct cover is reported without a refusal. `holes` rows have
63
+ `code`, `object`, `reason`, `line`. Absent source cover or allocation adds its
64
+ own HOLE; malformed present reports are refused. A HOLE carries no measured zero.
65
+
66
+ Bad arguments (exit 2), overlapping output, changing inputs, internal exceptions
67
+ and publication failures (exit 1) produce no new report. After parsing `--out`
68
+ and checking overlap, the command removes exactly `parts-check.json` and
69
+ `parts-check.json.tmp` there before reading inputs. Failed input reads cannot
70
+ leave an earlier success report. Bad arguments that prevent resolving `--out`
71
+ cannot remove a prior report. The CLI resolves an existing `--parts` root to its
72
+ real path before reading, including a symlinked root. Consumers bind the report
73
+ and current input hashes and read its `exit_code`. A sibling temporary file is
74
+ exclusively created, cleaned up after a failed write, then renamed into place.
75
+ Identical inputs produce identical report bytes on repeat
76
+ runs and under output roots with different parents.
77
+
78
+ The diagnostic code vocabulary below is closed for `rig-parts-parts-check/1`,
79
+ including reused reader and invocation codes. Adding a code requires a new spec
80
+ version. The generated controls derive literals from `src/parts.ts`,
81
+ `src/takesource.ts`, `src/depthsheets.ts`, `src/setfocus.ts` and `src/partscheck.ts`,
82
+ compare this list with the command's allowlist, and plant an undeclared code.
83
+
84
+ <!-- parts-check:codes -->
85
+ - `CONFIG_SET_FOCUS`
86
+ - `PARTS_ALT_BASE_ANCHOR`
87
+ - `PARTS_ALT_TIPS`
88
+ - `PARTS_ALT_TIPS_SOURCE`
89
+ - `PARTS_BOX_INSIDE_RIG`
90
+ - `PARTS_CHECK_INPUT_CHANGED`
91
+ - `PARTS_CHECK_INPUT_READ`
92
+ - `PARTS_CHECK_INTERNAL`
93
+ - `PARTS_CHECK_OUTPUT`
94
+ - `PARTS_CHECK_PNG_READ`
95
+ - `PARTS_CHECK_PUBLISH`
96
+ - `PARTS_CHECK_REPORT`
97
+ - `PARTS_COUNTS_ADD_UP`
98
+ - `PARTS_CUT_FROM_KNOWN`
99
+ - `PARTS_DEPTH_REFERENCE`
100
+ - `PARTS_FIELD_PRESENT`
101
+ - `PARTS_FIELD_TYPE`
102
+ - `PARTS_FILE_PRESENT`
103
+ - `PARTS_FROM_KNOWN`
104
+ - `PARTS_HOLES_LARGEST_FIRST`
105
+ - `PARTS_HOLE_PART_KNOWN`
106
+ - `PARTS_HYBRID_PAIR`
107
+ - `PARTS_INVENTED_EXPOSURE`
108
+ - `PARTS_INVENTED_MATERIAL`
109
+ - `PARTS_IS_JSON`
110
+ - `PARTS_KEY_KNOWN`
111
+ - `PARTS_MOTION_SEAM`
112
+ - `PARTS_NAME_UNIQUE`
113
+ - `PARTS_PAINTING_ALLOCATION`
114
+ - `PARTS_PAINTING_OPAQUE`
115
+ - `PARTS_PAINTING_PNG`
116
+ - `PARTS_PAINTING_PRESENT`
117
+ - `PARTS_PAINTING_SHA256`
118
+ - `PARTS_PAINTING_SIZE`
119
+ - `PARTS_PLATE_GHOST`
120
+ - `PARTS_PLATE_SMEAR`
121
+ - `PARTS_PLATE_STEPS`
122
+ - `PARTS_PLATE_STRUCTURE`
123
+ - `PARTS_SINGLE_RUN_PAD`
124
+ - `PARTS_SOURCE_COVER`
125
+ - `PARTS_TAKEN_LAYERS`
126
+ - `PARTS_UNPLANNED_SOURCE_COVER`
127
+ - `PROPOSE_PNG_MATCHES_BOX`
128
+ - `USAGE`
129
+ <!-- /parts-check:codes -->
130
+
32
131
  ## Programmatic config file references
33
132
 
34
133
  `@rig-c/parts/src/config.ts` exports `configFileReferences(raw: unknown):
@@ -122,6 +221,7 @@ defaults are the help's too, and none is guessed from the art.
122
221
  | `propose` | `--parts`, `--source`, `--out`, `--full`, `--head`, `--write-config` together: the [neck draft](AUTHORING.md#a-neck-that-moves-on-its-own) for an existing config with `turn.body` and one neck plan row; reassembles under `<out>/rig`, preserves the sampled turn and drafts a rigid neck unit (issue #826) |
123
222
  | `compare` | `--left`, `--right`; optional `--map` |
124
223
  | `rig` | `--config`, `--parts`, `--out`; optional `--idle-keys` (ctl, direct), `--page-edges` (pot, free), `--pack-shape` (rect, polygon) |
224
+ | `check-parts` | `--parts`, `--out`; optional `--json` |
125
225
  | `check` | `--rig`, `--out`; optional `--parts`, `--source`, `--page-edges`, `--pack-shape`, `--requirements`, `--seam-pairs`, `--keep-stills`, `--no-extremes` (issue #829), `--set` or `--all-sets` (issue #454), `--environment` (issue #538, additive), `--wind-band` (issue #590, additive), `--json` (issue #904) |
126
226
  | `loop` | `--frames`, `--out`; optional `--palette` |
127
227
  | `build` | `--config`, `--source`, `--full`, `--out`; optional `--head` (as for `assemble`), `--seam`, `--project`, `--page-edges`, `--pack-shape`, `--loop`, `--lead-in`, `--requirements`, `--idle-keys`, `--seam-pairs`, `--keep-stills`, `--no-extremes` (issue #829), `--alt` (as for `assemble`, issue #454), `--set` or `--all-sets` (as for `check`, issue #454), `--environment` (as for `check`, issue #538, additive), `--wind-band` (as for `check`, issue #590, additive) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spine-parts",
3
- "version": "2.25.0",
3
+ "version": "2.26.0",
4
4
  "description": "AI-authored 2D character parts from one anime painting and its See-through layer decomposition: measured parts, weighted-mesh rig specs, verified through rig-c before anything is written. A CLI for agents that cannot see the image.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/assemble.ts CHANGED
@@ -6049,8 +6049,8 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6049
6049
  });
6050
6050
  refuseIfAny(empty);
6051
6051
  const placed: PlacedPart[] = order.map((d) => ('plan' in d ? planned[d.plan] : 'cut' in d ? cutPlaced[d.cut] : 'limb' in d ? limbPlaced[d.limb] : cut[d.patch]) as PlacedPart);
6052
- const artFiles = new Set(placed.map(p => `${p.record.name}.png`));
6053
- for (const p of placed) if (p.record.depth !== undefined && artFiles.has(p.record.depth.image)) refuseIfAny([{ code: 'DEPTH_SHEET_UNAMBIGUOUS', object: p.record.depth.image, detail: 'collides with a part artwork filename; choose noncolliding part names before sheet emission' }]);
6052
+ const artFiles = new Map<string, string>(); for (const p of placed) { const k = `${p.record.name}.png`.toLowerCase(), prev = artFiles.get(k); if (prev !== undefined) refuseIfAny([{ code: 'DEPTH_SHEET_UNAMBIGUOUS', object: `${p.record.name}.png`, detail: `part "${prev}" ("${prev}.png") and part "${p.record.name}" ("${p.record.name}.png") collides with a part artwork filename; choose noncolliding part names before sheet emission` }]); artFiles.set(k, p.record.name); }
6053
+ for (const p of placed) if (p.record.depth !== undefined && artFiles.has(p.record.depth.image.toLowerCase())) refuseIfAny([{ code: 'DEPTH_SHEET_UNAMBIGUOUS', object: p.record.depth.image, detail: `part "${p.record.name}" sheet "${p.record.depth.image}" and part "${artFiles.get(p.record.depth.image.toLowerCase())}" ("${artFiles.get(p.record.depth.image.toLowerCase())}.png") collides with a part artwork filename; choose noncolliding part names before sheet emission` }]);
6054
6054
 
6055
6055
 
6056
6056
  const regionSupport = new Map<string, Mask>();
package/src/build.ts CHANGED
@@ -866,15 +866,15 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
866
866
  ];
867
867
  const assetIndices = new Map<string, number>();
868
868
  emittedAssets.forEach((file, index) => {
869
- const previous = assetIndices.get(file);
869
+ const previous = assetIndices.get(file.toLowerCase());
870
870
  if (previous !== undefined) {
871
871
  altProblems.push({
872
872
  code: 'DEPTH_SHEET_UNAMBIGUOUS',
873
873
  object: file,
874
- detail: `output assets[${previous}] and [${index}] require the same filename; choose distinct base, alternate and sheet names`,
874
+ detail: `output assets[${previous}] ("${emittedAssets[previous]}") and [${index}] ("${file}") require the same filename; choose distinct base, alternate and sheet names`,
875
875
  });
876
876
  } else {
877
- assetIndices.set(file, index);
877
+ assetIndices.set(file.toLowerCase(), index);
878
878
  }
879
879
  });
880
880
  const outputFiles = new Set([
package/src/check.ts CHANGED
@@ -145,7 +145,7 @@ import {
145
145
  type ChainEdge,
146
146
  type WorldBox,
147
147
  } from './instruments.ts';
148
- import { type AlternatePartsRecord, FRONT_SUFFIX, type LimbRecord, type PartRecord, type PartsFile, readParts } from './parts.ts';
148
+ import { type AlternatePartsRecord, FRONT_SUFFIX, type LimbRecord, partImageReference, type PartRecord, type PartsFile, readParts } from './parts.ts';
149
149
  import { ARM_SPLIT_MIGRATION, poseRigBonesForDrawn, type RigBone, SETS_FILE, writtenShares } from './rig.ts';
150
150
  import { TURN_BONE, turnConstraintName, turnTwin } from './turn.ts';
151
151
  import { ROOT_BONE, loadConfigWithBytes, type Point } from './config.ts';
@@ -706,7 +706,7 @@ export function readCheckInputs(rigDir: string, partsHome?: string, sourcePath?:
706
706
  }
707
707
  if (parts !== null) {
708
708
  for (const p of parts.parts) {
709
- const png = join(partsDir, `${p.name}.png`);
709
+ const png = join(home, partImageReference(p).path);
710
710
  if (!existsSync(png)) {
711
711
  problems.push({ code: 'CHECK_PART_PNG_PRESENT', object: `part "${p.name}"`, detail: `${png} does not exist; parts.json lists it` });
712
712
  continue;
@@ -718,7 +718,7 @@ export function readCheckInputs(rigDir: string, partsHome?: string, sourcePath?:
718
718
  }
719
719
  for (const alt of parts.alternates ?? []) {
720
720
  for (const r of alt.records) {
721
- const png = join(partsDir, `${alt.name}_${r.name}.png`);
721
+ const png = join(home, partImageReference(r, alt.name).path);
722
722
  if (!existsSync(png)) {
723
723
  problems.push({ code: 'CHECK_PART_PNG_PRESENT', object: `set "${alt.name}" part "${r.name}"`, detail: `${png} does not exist; parts.json lists it` });
724
724
  continue;
@@ -1382,7 +1382,7 @@ export function resolvePlacedAlpha(placements: readonly ReferencePlacement[], pa
1382
1382
  const readRaw = (png: string): Raster => {
1383
1383
  const hit = rawCache.get(png);
1384
1384
  if (hit !== undefined) return hit;
1385
- const img = readPng(join(partsDir, `${png}.png`));
1385
+ const img = readPng(join(dirname(partsDir), png));
1386
1386
  rawCache.set(png, img);
1387
1387
  return img;
1388
1388
  };
@@ -1512,7 +1512,7 @@ export function setPlacements(parts: PartsFile, alt: AlternatePartsRecord, slotO
1512
1512
  }
1513
1513
  }
1514
1514
  }
1515
- const entry: PlacedIslandEntry = { name: islSlot, png: p.name, box: p, islandIndex: k, islandCount: islandSlots.length, at };
1515
+ const entry: PlacedIslandEntry = { name: islSlot, png: partImageReference(p).path, box: p, islandIndex: k, islandCount: islandSlots.length, at };
1516
1516
  if (!reordered) {
1517
1517
  const list = inlineIslands.get(p.name) ?? [];
1518
1518
  list.push(entry);
@@ -1543,11 +1543,11 @@ export function setPlacements(parts: PartsFile, alt: AlternatePartsRecord, slotO
1543
1543
  const rec = byName.get(name);
1544
1544
  const islandSlots = rec === undefined ? partIslandSlots(name, slotOrder) : [name];
1545
1545
  if (islandSlots.length > 1) {
1546
- out.push({ name, png: name, box: base, islandIndex: 0, islandCount: islandSlots.length });
1546
+ out.push({ name, png: partImageReference(base).path, box: base, islandIndex: 0, islandCount: islandSlots.length });
1547
1547
  for (const isl of inlineIslands.get(name) ?? []) pushIsland(isl);
1548
1548
  return;
1549
1549
  }
1550
- out.push({ name, png: rec === undefined ? name : `${alt.name}_${rec.name}`, box: rec ?? base });
1550
+ out.push({ name, png: rec === undefined ? partImageReference(base).path : partImageReference(rec, alt.name).path, box: rec ?? base });
1551
1551
  };
1552
1552
  const baseOf = new Map(parts.parts.map((p) => [p.name, p]));
1553
1553
  for (const p of parts.parts) {
@@ -1861,7 +1861,7 @@ export function seamDrawingSignature(input: {
1861
1861
  /** File-only rig-image padding checks after the parts loader has validated each PNG against its record. */
1862
1862
  export function boundaryColourSizeProblems(inp: CheckInputs): Problem[] {
1863
1863
  if (inp.parts === null) return [];
1864
- const records = new Set(inp.parts.parts.map(p => p.name));
1864
+ const records = new Map(inp.parts.parts.map(p => [p.name, p]));
1865
1865
  const imagesDir = typeof inp.rig.images === 'string' ? resolve(inp.rigDir, inp.rig.images) : join(inp.rigDir, 'images');
1866
1866
  const problems: Problem[] = [];
1867
1867
  const seen = new Set<string>();
@@ -1874,9 +1874,9 @@ export function boundaryColourSizeProblems(inp: CheckInputs): Problem[] {
1874
1874
  if (!seamImageSource(source) || seen.has(source.image)) continue;
1875
1875
  const image = source.image;
1876
1876
  seen.add(image);
1877
- const name = image.replace(/\.png$/, '');
1878
- const partPng = join(inp.partsDir, `${name}.png`), rigPng = join(imagesDir, image);
1879
- if (!records.has(name) || !existsSync(partPng) || !existsSync(rigPng)) continue;
1877
+ const name = image.replace(/\.png$/, ''), record = records.get(name);
1878
+ const partPng = record === undefined ? '' : join(dirname(inp.partsDir), partImageReference(record).path), rigPng = join(imagesDir, image);
1879
+ if (record === undefined || !existsSync(partPng) || !existsSync(rigPng)) continue;
1880
1880
  let src: Raster, rigImg: Raster;
1881
1881
  try { src = readPng(partPng); rigImg = readPng(rigPng); }
1882
1882
  catch { continue; }
@@ -6664,7 +6664,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6664
6664
  const parts = ready.parts;
6665
6665
  seams = take(() => resolveSeams(file, parts === null ? null : parts.parts.map((p) => p.name), ready.noParts, (n) => {
6666
6666
  const rec = (parts as PartsFile).parts.find((p) => p.name === n) as PartRecord;
6667
- return placedArt(rec.x, rec.y, readPng(join(ready.partsDir, `${n}.png`)));
6667
+ return placedArt(rec.x, rec.y, readPng(join(dirname(ready.partsDir), partImageReference(rec).path)));
6668
6668
  }));
6669
6669
  }
6670
6670
  if (wb !== null) take(() => resolveWindBand(wb, ready));
@@ -6678,7 +6678,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6678
6678
  // Read source support before rendering; no output/sidecar for undeclared builds.
6679
6679
  if (reqFile?.cut_material !== undefined && (set !== undefined || allSets)) refuseIfAny([{code: 'CHECK_CUT_MATERIAL_MEASURED', object: 'cut_material', detail: 'source evidence binds base assembly only; run check on its base parts without --set/--all-sets; alternate-set coverage requires its own original source instrument'}]);
6680
6680
  const cutMaterialProblems: Problem[] = [];
6681
- const cutMaterial = reqFile?.cut_material === undefined ? null : checkJointMaterial(reqFile.cut_material, inp.parts, name => readPng(join(inp.partsDir, `${name}.png`)), cutMaterialProblems, inp.parts === null ? undefined : readMaterialSources(dirname(inp.partsDir), inp.parts));
6681
+ const cutMaterial = reqFile?.cut_material === undefined ? null : checkJointMaterial(reqFile.cut_material, inp.parts, name => readPng(join(dirname(inp.partsDir), partImageReference((inp.parts as PartsFile).parts.find(p => p.name === name) as PartRecord).path)), cutMaterialProblems, inp.parts === null ? undefined : readMaterialSources(dirname(inp.partsDir), inp.parts));
6682
6682
  // A measured material failure is a check bar; unavailable data is a refusal.
6683
6683
  const rigcEntry = readRigcEntry(requireRigcVersion(rigc));
6684
6684
  /**
@@ -7035,7 +7035,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7035
7035
  const png = (name: string): Raster => {
7036
7036
  const hit = pngs.get(name);
7037
7037
  if (hit !== undefined) return hit;
7038
- const r = readPng(join(inp.partsDir, `${name}.png`));
7038
+ const r = readPng(join(dirname(inp.partsDir), partImageReference(parts.parts.find((p) => p.name === name) as PartRecord).path));
7039
7039
  pngs.set(name, r);
7040
7040
  return r;
7041
7041
  };
@@ -8333,7 +8333,7 @@ function tipLine(inp: FullInputs, geometryPath: string, frames: number, problems
8333
8333
  const rises = excepted.rises.includes(p.name);
8334
8334
  const rests = excepted.rests.includes(p.name);
8335
8335
  const [rootHalf, tipHalf] = rises ? ['lower', 'upper'] : ['upper', 'lower'];
8336
- const art = placedArt(p.x, p.y, readPng(join(inp.partsDir, `${p.name}.png`)));
8336
+ const art = placedArt(p.x, p.y, readPng(join(dirname(inp.partsDir), partImageReference(p).path)));
8337
8337
  const shown = poses.map((f) => f.get(p.name) ?? null);
8338
8338
  const w = halfTravels(art, p, inp.stage, shown, rises ? 'up' : 'down');
8339
8339
  // Issue #987: the halves are read in the frame of the bone the part hangs from; the world reading rides beside them.
@@ -8862,7 +8862,7 @@ export function stillLine(inp: FullInputs, idle: FrameSet, geo: IdleGeometry | n
8862
8862
  const H = inp.parts.rig_size[1];
8863
8863
  const W = inp.parts.rig_size[0];
8864
8864
  const poses = attachmentPoses(geometryPath, idle.written);
8865
- const top = topmostIndex(inp.parts, (i) => readPng(join(inp.partsDir, `${inp.parts.parts[i].name}.png`)));
8865
+ const top = topmostIndex(inp.parts, (i) => readPng(join(dirname(inp.partsDir), partImageReference(inp.parts.parts[i]).path)));
8866
8866
  const index = new Map(inp.parts.parts.map((p, i) => [p.name, i]));
8867
8867
  const record = new Map(inp.parts.parts.map((p) => [p.name, p]));
8868
8868
  const slots = (Array.isArray(inp.rig.slots) ? inp.rig.slots : []).filter(isRecord).map((sl) => ({ name: String(sl.name), bone: typeof sl.bone === 'string' ? sl.bone : undefined }));
@@ -8872,7 +8872,7 @@ export function stillLine(inp: FullInputs, idle: FrameSet, geo: IdleGeometry | n
8872
8872
  let a = arts.get(name);
8873
8873
  if (a === undefined) {
8874
8874
  const p = record.get(name) as PartRecord;
8875
- a = placedArt(p.x, p.y, readPng(join(inp.partsDir, `${name}.png`)));
8875
+ a = placedArt(p.x, p.y, readPng(join(dirname(inp.partsDir), partImageReference(p).path)));
8876
8876
  arts.set(name, a);
8877
8877
  }
8878
8878
  return a;
@@ -4,7 +4,7 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
4
4
  import { dirname, join } from 'node:path';
5
5
  import { edgeLength } from './length.ts';
6
6
  import { canonicalInward, CUT_MATERIAL_SOURCES, CUT_MATERIAL_SPEC, type MaterialSource, type Point } from './cutmaterial.ts';
7
- import type { PartsFile } from './parts.ts';
7
+ import { partImageReference, type PartsFile } from './parts.ts';
8
8
  import { refuseIfAny } from './errors.ts';
9
9
  const sha=(data:Uint8Array|string):string=>createHash('sha256').update(data).digest('hex');
10
10
  const hash=(path:string):string=>sha(readFileSync(path));
@@ -15,7 +15,7 @@ export function writeMaterialSources(partsPath:string,partsDir:string,parts:Part
15
15
  const emitted=sources.filter(s=>parts.parts.some(p=>p.name===s.part));
16
16
  writeFileSync(join(dirname(partsPath),CUT_MATERIAL_SOURCES),JSON.stringify({
17
17
  spec:CUT_MATERIAL_SPEC,parts_sha256:hash(partsPath),
18
- images:parts.parts.map(p=>({part:p.name,sha256:hash(join(partsDir,`${p.name}.png`))})),
18
+ images:parts.parts.map(p=>({part:p.name,sha256:hash(join(dirname(partsDir),partImageReference(p).path))})),
19
19
  sources_sha256:sha(JSON.stringify(emitted)),sources:emitted,
20
20
  },null,2)+'\n');
21
21
  }
@@ -32,10 +32,11 @@ export function readMaterialSources(home:string,parts:PartsFile):MaterialSource[
32
32
  if(raw.images.length!==parts.parts.length)return fail('image bindings do not cover every emitted base part');
33
33
  const seen=new Set<string>();
34
34
  for(const binding of raw.images){
35
- if(!record(binding)||typeof binding.part!=='string'||!digest(binding.sha256)||seen.has(binding.part)||!parts.parts.some(p=>p.name===binding.part))return fail('image bindings require each named base part exactly once and its SHA-256');
35
+ const part=record(binding)&&typeof binding.part==='string'?parts.parts.find(p=>p.name===binding.part):undefined;
36
+ if(!record(binding)||typeof binding.part!=='string'||!digest(binding.sha256)||seen.has(binding.part)||part===undefined)return fail('image bindings require each named base part exactly once and its SHA-256');
36
37
  if(Object.keys(binding).some(k=>!['part','sha256'].includes(k)))return fail('image binding has an unknown field');
37
38
  seen.add(binding.part);
38
- const file=join(home,'parts',`${binding.part}.png`);
39
+ const file=join(home,partImageReference(part).path);
39
40
  if(!existsSync(file)||hash(file)!==binding.sha256)return fail(`source-edge binding for part "${binding.part}" differs from its emitted PNG`);
40
41
  }
41
42
  const sources=new Set<string>();
@@ -8,7 +8,7 @@ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
8
8
  import { loadConfigAndAnimations, parseConfig } from './config.ts';
9
9
  import { depthReading, readSourceDepth } from './depthsheets.ts';
10
10
  import { alphaSupport, depthMapFail as fail, floatBox, integrateNormals, mapToSheet, readNumericMap, type NumericMap } from './depthmaps.ts';
11
- import { readParts } from './parts.ts';
11
+ import { depthImageReference, partImageReference, readParts } from './parts.ts';
12
12
  import { readPartSet } from './propose.ts';
13
13
  import { decodePngBytes, encodePngBytes } from './raster/png.ts';
14
14
  import { resize } from './raster/resize.ts';
@@ -98,7 +98,7 @@ function preparedParts(partsDir: string, recipe: DepthRecipe): { manifest: Prepa
98
98
  }
99
99
  if (!alphaSupport(art).some(Boolean)) fail('DEPTH_MAP_SUPPORT', part.name, 'has no alpha>=128 pixels; a supported part is required');
100
100
  const bytes = encodePngBytes(input), file = `${part.name}.png`; images.set(file, bytes);
101
- parts.push({ part: part.name, crop: [part.x, part.y, part.w, part.h], sourceSha256: hash(readFileSync(join(partsDir, 'parts', file))), input: file, inputSha256: hash(bytes), size: [art.width, art.height], upscaled: [w, h], upscale, padding: pad, inputSize: [input.width, input.height] });
101
+ parts.push({ part: part.name, crop: [part.x, part.y, part.w, part.h], sourceSha256: hash(readFileSync(join(partsDir, partImageReference(part).path))), input: file, inputSha256: hash(bytes), size: [art.width, art.height], upscaled: [w, h], upscale, padding: pad, inputSize: [input.width, input.height] });
102
102
  }
103
103
  return { manifest: { spec: 'rig-parts-depth-inputs/1', partsSha256: hash(readFileSync(join(partsDir, 'parts.json'))), recipeSha256: hash(text(recipe)), background: 128, alpha: 128, parts }, images };
104
104
  }
@@ -185,12 +185,12 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
185
185
  };
186
186
  collect(input.parts, '');
187
187
  for (const p of file.parts) {
188
- const name = p.name, bytes = readFileSync(join(input.parts, 'parts', `${name}.png`)), art = decodePngBytes(bytes, name), rec = recs.find(r => r.name === name) as Obj;
188
+ const name = p.name, bytes = readFileSync(join(input.parts, partImageReference(p).path)), art = decodePngBytes(bytes, name), rec = recs.find(r => r.name === name) as Obj;
189
189
  writes.set(`${name}.png`, bytes);
190
190
  const declaration = Object.hasOwn(recipe.parts, name) ? recipe.parts[name] : undefined;
191
191
  if (declaration === undefined) {
192
- if (recipe.clear.includes(name)) { if (p.depth !== undefined) retained.delete(`parts/${p.depth.image}`); delete rec.depth; }
193
- else if (p.depth !== undefined) { readSourceDepth(join(input.parts, 'parts', p.depth.image), art, null); writes.set(p.depth.image, readFileSync(join(input.parts, 'parts', p.depth.image))); }
192
+ if (recipe.clear.includes(name)) { if (p.depth !== undefined) retained.delete(depthImageReference(p.depth).path); delete rec.depth; }
193
+ else if (p.depth !== undefined) { const depthPath = join(input.parts, depthImageReference(p.depth).path); readSourceDepth(depthPath, art, null); writes.set(p.depth.image, readFileSync(depthPath)); }
194
194
  continue;
195
195
  }
196
196
  const g = recipe.groups[declaration.group], target = declaration.group === 'head' ? turn : object(turn.body, 'config.turn.body');
@@ -213,7 +213,7 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
213
213
  const { sheet, reading } = mapToSheet(values, art, declaration.median, declaration.relief, g.near, g.zScale, name), image = `${name}_depth.png`, sheetBytes = encodePngBytes(sheet);
214
214
  if (file.parts.some(p => `${p.name}.png` === image)) fail('DEPTH_GROUP_BINDING', name, `sheet filename ${image} collides with artwork; use noncolliding part names`);
215
215
  writes.set(image, sheetBytes);
216
- if (p.depth !== undefined) retained.delete(`parts/${p.depth.image}`);
216
+ if (p.depth !== undefined) retained.delete(depthImageReference(p.depth).path);
217
217
  rec.depth = { image, near: g.near, zScale: g.zScale, sources: [{ from: p.from, image: basename(declaration.map), sha256: hash(mapBytes), crop: [0, 0, art.width, art.height], reading: depthReading(sheet, art, null) }] };
218
218
  rows.push({ part: name, group: declaration.group, source: declaration.source, frame: declaration.frame, sourceSha256: prepared.sourceSha256, mapSha256: hash(mapBytes), inputSha256: prepared.inputSha256, sheetSha256: hash(sheetBytes), median: declaration.median, relief: declaration.relief, near: g.near, zScale: g.zScale, pivot: g.pivot, ...reading, sign: normal?.sign ?? 1, ...(normal === undefined ? {} : { integration: { stride: 2, iterations: normal.iterations, residual: normal.residual, coreMinusRim: normal.coreMinusRim, maxIterations: 3000, atol: 1e-6, btol: 1e-6 } }) });
219
219
  }
@@ -4,7 +4,7 @@ import { readFileSync, writeFileSync } from 'node:fs';
4
4
  import { dirname, join } from 'node:path';
5
5
  import { COVERED_ALPHA, ERROR_LIMIT, coveredMask, errorMask, holeBorders, type PlacedPart } from './assemble.ts';
6
6
  import { PartsError, type Problem } from './errors.ts';
7
- import { readParts } from './parts.ts';
7
+ import { partImageReference, readParts } from './parts.ts';
8
8
  import { connectedComponents } from './raster/components.ts';
9
9
  import { decodePngBytes } from './raster/png.ts';
10
10
  import { newMask, type Raster } from './raster/types.ts';
@@ -184,7 +184,7 @@ export function diffComponentsCommand(args: string[]): void {
184
184
  };
185
185
  const partsPath = flags.get('--parts')!;
186
186
  const parts = readParts(partsPath);
187
- const placed = parts.parts.map(record => ({ record, image: diffPng(bytes(join(dirname(partsPath), 'parts', `${record.name}.png`)).bytes, record.name) }));
187
+ const placed = parts.parts.map(record => ({ record, image: diffPng(bytes(join(dirname(partsPath), partImageReference(record).path)).bytes, record.name) }));
188
188
  const stack = bytes(flags.get('--stack')!), painting = bytes(flags.get('--painting')!);
189
189
  const reference = diffPng(painting.bytes, painting.path);
190
190
  if (parts.rig_size[0] !== reference.width || parts.rig_size[1] !== reference.height) inputFailure('parts.rig_size', `is ${parts.rig_size[0]}x${parts.rig_size[1]}; painting ${reference.width}x${reference.height} is required, with no resampling`);
package/src/meshdraft.ts CHANGED
@@ -72,7 +72,7 @@ import { PartsError, type Problem, problemLine } from './errors.ts';
72
72
  import { IDLE_FPS } from './motion.ts';
73
73
  import { type ContourBridges, FAINT_ALPHA } from './contour.ts';
74
74
  import { ART_ALPHA, DUST_MAX_PX, DUST_MAX_SHARE, isDust, dustOf, type DustReading } from './mesh.ts';
75
- import { type PartsFile, readParts } from './parts.ts';
75
+ import { partImageReference, type PartsFile, readParts } from './parts.ts';
76
76
  import { readPng } from './raster/png.ts';
77
77
  import type { Raster } from './raster/types.ts';
78
78
  import { buildRig, type IdleKeys, type MeshAttachment, rigJsonText, type RigSpec } from './rig.ts';
@@ -852,7 +852,7 @@ export function meshDraftStage(input: MeshDraftInput, rigc: RigcRunner, checkBin
852
852
  if ('code' in rules) throw new PartsError([rules]);
853
853
  const images = new Map<string, Raster>();
854
854
  for (const p of parts.parts) {
855
- const png = join(input.parts, 'parts', `${p.name}.png`);
855
+ const png = join(input.parts, partImageReference(p).path);
856
856
  if (existsSync(png)) images.set(p.name, readPng(png));
857
857
  }
858
858
  log(`rig-parts mesh-draft: ${cfg.key}, figure ${rules.height} px (rows ${rules.top}..${rules.bottom}): tolerance and margin T = max(1, round(${rules.height} / ${TOLERANCE_FIGURE_DIVISOR})) = ${rules.tolerance}, spacing and longest outline edge S = round(${rules.height} / ${FIGURE_GRID_DIVISOR}) = ${rules.spacing}`);
package/src/parts.ts CHANGED
@@ -777,7 +777,7 @@ function checkParts(raw: unknown, path: string): PartsFile {
777
777
  }
778
778
  if ('parts' in o && !(Array.isArray(o.parts) && o.parts.length > 0)) fail('PARTS_FIELD_TYPE', `${path} field "parts"`, `is ${show(o.parts)}; a non-empty array is required`);
779
779
  if (Array.isArray(o.parts)) {
780
- const seen = new Map<string, number>();
780
+ const seen = new Map<string, { index: number; name: string }>();
781
781
  o.parts.forEach((p, i) => {
782
782
  const at = `${path} parts[${i}]`;
783
783
  if (typeof p !== 'object' || p === null || Array.isArray(p)) {
@@ -796,8 +796,8 @@ function checkParts(raw: unknown, path: string): PartsFile {
796
796
  }
797
797
  if (!isPartName(r.name)) {
798
798
  fail('PARTS_FIELD_TYPE', `${label} field "name"`, `is ${show(r.name)}; a file-name-safe part name is required`);
799
- } else if (seen.has(r.name)) fail('PARTS_NAME_UNIQUE', label, `appears at parts[${seen.get(r.name)}] and parts[${i}]`);
800
- else seen.set(r.name, i);
799
+ } else if (seen.has(r.name.toLowerCase())) fail('PARTS_NAME_UNIQUE', label, `appears at parts[${seen.get(r.name.toLowerCase())!.index}] ("${seen.get(r.name.toLowerCase())!.name}") and parts[${i}] ("${r.name}")`);
800
+ else seen.set(r.name.toLowerCase(), { index: i, name: r.name });
801
801
  const from = typeof r.from === 'string' ? readFrom(r.from) : null;
802
802
  if (from === null) fail('PARTS_FROM_KNOWN', `${label} field "from"`, `is ${show(r.from)}; "<full|head>:<v3 tag>", "<full|head>:author:<label>" for a layer the author made, or "painting:<the part's own name>" for a patch, is required`);
803
803
  else if (from.run === 'painting' && from.patch !== r.name) {
@@ -0,0 +1,421 @@
1
+ /** Assemble-output integrity and explicit unmeasured quality classes. No rig or renderer. */
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { failLine, PartsError, type Problem } from './errors.ts';
6
+ import { FIGURE_MASK_FILE, partImageReference, partsFileReferences, readParts, type PartsFile } from './parts.ts';
7
+ import { readPng } from './raster/png.ts';
8
+ import { RasterError } from './raster/types.ts';
9
+ import { NotAPngError } from '@rig-c/core/png';
10
+ import { SOURCE_COVER_SPEC, sourceCoverReport } from './sourcecover.ts';
11
+
12
+ export const PARTS_CHECK_SPEC = 'rig-parts-parts-check/1';
13
+ export const PARTS_CHECK_FILE = 'parts-check.json';
14
+
15
+ /** Closed diagnostic vocabulary for this spec, including reused metadata readers. */
16
+ export const PARTS_CHECK_CODES: readonly string[] = [
17
+ 'CONFIG_SET_FOCUS',
18
+ 'PARTS_ALT_BASE_ANCHOR',
19
+ 'PARTS_ALT_TIPS',
20
+ 'PARTS_ALT_TIPS_SOURCE',
21
+ 'PARTS_BOX_INSIDE_RIG',
22
+ 'PARTS_CHECK_INPUT_CHANGED',
23
+ 'PARTS_CHECK_INPUT_READ',
24
+ 'PARTS_CHECK_INTERNAL',
25
+ 'PARTS_CHECK_OUTPUT',
26
+ 'PARTS_CHECK_PNG_READ',
27
+ 'PARTS_CHECK_PUBLISH',
28
+ 'PARTS_CHECK_REPORT',
29
+ 'PARTS_COUNTS_ADD_UP',
30
+ 'PARTS_CUT_FROM_KNOWN',
31
+ 'PARTS_DEPTH_REFERENCE',
32
+ 'PARTS_FIELD_PRESENT',
33
+ 'PARTS_FIELD_TYPE',
34
+ 'PARTS_FILE_PRESENT',
35
+ 'PARTS_FROM_KNOWN',
36
+ 'PARTS_HOLES_LARGEST_FIRST',
37
+ 'PARTS_HOLE_PART_KNOWN',
38
+ 'PARTS_HYBRID_PAIR',
39
+ 'PARTS_INVENTED_EXPOSURE',
40
+ 'PARTS_INVENTED_MATERIAL',
41
+ 'PARTS_IS_JSON',
42
+ 'PARTS_KEY_KNOWN',
43
+ 'PARTS_MOTION_SEAM',
44
+ 'PARTS_NAME_UNIQUE',
45
+ 'PARTS_PAINTING_ALLOCATION',
46
+ 'PARTS_PAINTING_OPAQUE',
47
+ 'PARTS_PAINTING_PNG',
48
+ 'PARTS_PAINTING_PRESENT',
49
+ 'PARTS_PAINTING_SHA256',
50
+ 'PARTS_PAINTING_SIZE',
51
+ 'PARTS_PLATE_GHOST',
52
+ 'PARTS_PLATE_SMEAR',
53
+ 'PARTS_PLATE_STEPS',
54
+ 'PARTS_PLATE_STRUCTURE',
55
+ 'PARTS_SINGLE_RUN_PAD',
56
+ 'PARTS_SOURCE_COVER',
57
+ 'PARTS_TAKEN_LAYERS',
58
+ 'PARTS_UNPLANNED_SOURCE_COVER',
59
+ 'PROPOSE_PNG_MATCHES_BOX',
60
+ 'USAGE',
61
+ ];
62
+
63
+ export const PARTS_QUALITY_HOLES = [
64
+ ['PARTS_PLATE_GHOST', 'no adopted plate-ghost discriminator; assemble outputs do not bind a background plate or composed figure outline'],
65
+ ['PARTS_PLATE_STRUCTURE', 'no adopted background-structure continuation measure or reference'],
66
+ ['PARTS_PLATE_SMEAR', 'no adopted plate-smear discriminator'],
67
+ ['PARTS_PLATE_STEPS', 'no adopted plate-fill continuity measure'],
68
+ ['PARTS_INVENTED_MATERIAL', 'no validated producer-bound per-pixel painted-versus-invented record'],
69
+ ['PARTS_INVENTED_EXPOSURE', 'invented-material identity and posed-frame observations are unavailable at the parts stage'],
70
+ ] as const;
71
+
72
+ export interface PartsCheckInput {
73
+ path: string;
74
+ status: 'read' | 'missing' | 'unreadable' | 'absent';
75
+ sha256: string | null;
76
+ }
77
+ interface Refusal extends Problem { found: unknown; required: unknown }
78
+ interface Hole { code: string; object: string; reason: string; line: string }
79
+ interface CoverRow { code: string; set: string | null; part: string; source: string; count: number; spans: unknown[] }
80
+ export interface PartsCheckReport {
81
+ spec: typeof PARTS_CHECK_SPEC;
82
+ stage: 'parts';
83
+ inputs: PartsCheckInput[];
84
+ parts: { primary: string[]; alternates: unknown[]; source_cover: unknown; painting_allocation: unknown[] };
85
+ refusals: Refusal[];
86
+ reported: CoverRow[];
87
+ holes: Hole[];
88
+ exit_code: number;
89
+ }
90
+
91
+ function object(value: unknown): value is Record<string, unknown> {
92
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
93
+ }
94
+ function count(value: unknown): value is number { return Number.isSafeInteger(value) && Number(value) >= 0; }
95
+ function strings(value: unknown): value is string[] { return Array.isArray(value) && value.every(v => typeof v === 'string'); }
96
+ function hash(value: unknown): boolean { return typeof value === 'string' && /^[a-f0-9]{64}$/.test(value); }
97
+ function unique(value: unknown[]): boolean { return new Set(value).size === value.length; }
98
+ function grid(value: unknown): value is [number, number] {
99
+ return Array.isArray(value) && value.length === 2 && value.every(v => count(v) && v > 0);
100
+ }
101
+ function pixels(value: unknown, size: [number, number]): boolean {
102
+ if (!object(value) || !count(value.count) || !Array.isArray(value.spans)) return false;
103
+ let total = 0;
104
+ let previousY = -1;
105
+ let previousRight = -1;
106
+ for (const span of value.spans) {
107
+ if (!Array.isArray(span) || span.length !== 3 || !span.every(count)) return false;
108
+ const [y, left, right] = span as number[];
109
+ if (y >= size[1] || right > size[0] || left >= right || y < previousY || (y === previousY && left < previousRight)) return false;
110
+ previousY = y;
111
+ previousRight = right;
112
+ total += right - left;
113
+ }
114
+ return total === value.count;
115
+ }
116
+
117
+ /** Preserve array order, but make embedded producer objects independent of JSON key order. */
118
+ function canonical(value: unknown): unknown {
119
+ if (Array.isArray(value)) return value.map(canonical);
120
+ if (object(value)) return Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])]));
121
+ return value;
122
+ }
123
+
124
+ function physical(path: string): string {
125
+ const absolute = resolve(path);
126
+ if (existsSync(absolute)) return realpathSync(absolute);
127
+ const parent = dirname(absolute);
128
+ return parent === absolute ? absolute : join(physical(parent), relative(parent, absolute));
129
+ }
130
+ function within(parent: string, path: string): boolean {
131
+ const rel = relative(parent, path);
132
+ return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`));
133
+ }
134
+ function fatal(code: string, object: string, detail: string): never {
135
+ throw new PartsError([{ code, object, detail }]);
136
+ }
137
+ function ioError(error: unknown): error is Error & { code: string } {
138
+ return error instanceof Error && 'code' in error && typeof error.code === 'string' && /^E[A-Z]+$/.test(error.code);
139
+ }
140
+
141
+ /** No source writes. A disjoint output root is required even for a refused input. */
142
+ export function checkPartsStage(input: string, output: string, log: (line: string) => void = console.log): PartsCheckReport {
143
+ const home = resolve(input);
144
+ const out = resolve(output);
145
+ const realHome = physical(home);
146
+ const realOut = physical(out);
147
+ if (within(realHome, realOut) || within(realOut, realHome)) {
148
+ fatal('PARTS_CHECK_OUTPUT', '--out', 'overlaps --parts; a disjoint report directory is required');
149
+ }
150
+ const destination = join(out, PARTS_CHECK_FILE);
151
+ const temporary = `${destination}.tmp`;
152
+ try {
153
+ rmSync(destination, { force: true });
154
+ rmSync(temporary, { force: true });
155
+ } catch {
156
+ fatal('PARTS_CHECK_PUBLISH', '--out', 'could not remove the previous report or its temporary file before reading inputs');
157
+ }
158
+ const clean = (value: string): string => value.replaceAll(home, '.').replaceAll(realHome, '.');
159
+ const refusals: Refusal[] = [];
160
+ const refuse = (code: string, at: string, found: unknown, required: unknown, detail: string): void => {
161
+ if (!PARTS_CHECK_CODES.includes(code)) fatal('PARTS_CHECK_INTERNAL', 'check-parts', 'reader emitted a code outside the signed spec');
162
+ refusals.push({ code, object: clean(at), found, required, detail: clean(detail) });
163
+ };
164
+ const readerError = (error: unknown): void => {
165
+ if (!(error instanceof PartsError)) throw error;
166
+ for (const problem of error.problems) refuse(problem.code, problem.object, null, null, problem.detail);
167
+ };
168
+ const requiredPaths = new Set(['parts.json']);
169
+ const optionalPaths = new Set(['source_cover.json', 'painting_allocation.json']);
170
+ const ignoredPaths = new Set<string>();
171
+ let initialManifestHash: string | undefined;
172
+ // Only metadata is read here. Figure masks have a layout-dependent location (#1177).
173
+ try {
174
+ const manifestPath = join(home, 'parts.json');
175
+ if (lstatSync(manifestPath).isFile()) {
176
+ const bytes = readFileSync(manifestPath);
177
+ initialManifestHash = createHash('sha256').update(bytes).digest('hex');
178
+ const raw: unknown = JSON.parse(bytes.toString('utf8'));
179
+ if (object(raw)) {
180
+ const scenes = [raw.scene, ...(Array.isArray(raw.alternates) ? raw.alternates.filter(object).map(set => set.scene) : [])];
181
+ for (const scene of scenes) if (object(scene) && scene.figure_mask === FIGURE_MASK_FILE) {
182
+ ignoredPaths.add(FIGURE_MASK_FILE);
183
+ }
184
+ }
185
+ }
186
+ } catch (error) {
187
+ if (!(error instanceof SyntaxError) && !ioError(error)) throw error;
188
+ // The regular metadata reader below owns the named refusal.
189
+ }
190
+ const inventory = (reportErrors: boolean): PartsCheckInput[] => {
191
+ const rows = new Map<string, PartsCheckInput>();
192
+ const visit = (name: string): void => {
193
+ if (ignoredPaths.has(name)) return;
194
+ const path = join(home, name);
195
+ try {
196
+ const stat = lstatSync(path);
197
+ if (stat.isSymbolicLink() || (!stat.isDirectory() && !stat.isFile())) {
198
+ rows.set(name, { path: name, status: 'unreadable', sha256: null });
199
+ if (reportErrors) refuse('PARTS_CHECK_INPUT_READ', name, 'non-regular input', 'regular file or directory', 'input links and special files require a regular-file scratch copy');
200
+ } else if (stat.isDirectory()) {
201
+ for (const entry of readdirSync(path).sort()) visit(name === '.' ? entry : `${name}/${entry}`);
202
+ } else {
203
+ rows.set(name, { path: name, status: 'read', sha256: createHash('sha256').update(readFileSync(path)).digest('hex') });
204
+ }
205
+ } catch (error) {
206
+ if (!ioError(error)) throw error;
207
+ const missing = 'code' in error && error.code === 'ENOENT';
208
+ rows.set(name, { path: name, status: missing ? 'missing' : 'unreadable', sha256: null });
209
+ if (reportErrors) refuse('PARTS_CHECK_INPUT_READ', name, clean(error.message), 'readable regular input', 'input inventory could not read this object');
210
+ }
211
+ };
212
+ visit('.');
213
+ for (const name of [...requiredPaths, ...optionalPaths]) if (!rows.has(name)) {
214
+ rows.set(name, { path: name, status: optionalPaths.has(name) ? 'absent' : 'missing', sha256: null });
215
+ }
216
+ return [...rows.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
217
+ };
218
+ // Inventory first, then discover references through the existing metadata reader.
219
+ const before = inventory(true);
220
+ if (initialManifestHash !== undefined && before.find(row => row.path === 'parts.json')?.sha256 !== initialManifestHash) {
221
+ fatal('PARTS_CHECK_INPUT_CHANGED', 'parts.json', 'manifest changed while reading references; no report was published');
222
+ }
223
+ let file: PartsFile | undefined;
224
+ let references: ReturnType<typeof partsFileReferences> = [];
225
+ try {
226
+ references = partsFileReferences(home).filter(reference => reference.role !== 'figure_mask');
227
+ for (const reference of references) requiredPaths.add(reference.path);
228
+ const unsafe = references.filter(reference => !within(realHome, physical(join(home, reference.path))));
229
+ for (const reference of unsafe) refuse('PARTS_CHECK_INPUT_READ', reference.path, 'reference outside --parts', 'input inside --parts', 'copy declared assets into the assemble directory');
230
+ if (unsafe.length === 0 && !before.some(row => row.status === 'unreadable')) file = readParts(join(home, 'parts.json'));
231
+ } catch (error) {
232
+ if (ioError(error)) refuse('PARTS_CHECK_INPUT_READ', 'parts.json', clean(error.message), 'readable input', 'the manifest or its declared painting could not be read');
233
+ else readerError(error);
234
+ }
235
+ // Add missing declared references to the initial inventory, without re-reading bytes.
236
+ for (const name of requiredPaths) if (!before.some(row => row.path === name)) before.push({ path: name, status: 'missing', sha256: null });
237
+ before.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
238
+ const holes: Hole[] = [];
239
+ const hole = (code: string, at: string, reason: string): void => { holes.push({ code, object: at, reason, line: `${code}: HOLE — ${reason}` }); };
240
+ for (const [code, reason] of PARTS_QUALITY_HOLES) hole(code, 'parts', reason);
241
+ if (file !== undefined) {
242
+ const partRows = [
243
+ ...file.parts.map(part => ({ part, path: partImageReference(part).path })),
244
+ ...(file.alternates ?? []).flatMap(set => set.records.map(part => ({ part, path: partImageReference(part, set.name).path }))),
245
+ ];
246
+ for (const { part, path } of partRows) {
247
+ try {
248
+ const image = readPng(join(home, path));
249
+ if (image.width !== part.w || image.height !== part.h) {
250
+ refuse('PROPOSE_PNG_MATCHES_BOX', `part "${part.name}"`, [image.width, image.height], [part.w, part.h], `${path} is ${image.width}x${image.height}; parts.json requires ${part.w}x${part.h}`);
251
+ }
252
+ } catch (error) {
253
+ if (!ioError(error) && !(error instanceof RasterError) && !(error instanceof NotAPngError)) throw error;
254
+ refuse('PARTS_CHECK_PNG_READ', `part "${part.name}"`, clean(error.message), 'decodable PNG', `${path} is not a readable PNG`);
255
+ }
256
+ }
257
+ for (const reference of references.filter(row => row.role !== 'part' && row.role !== 'alternate' && row.role !== 'painting')) {
258
+ try { readPng(join(home, reference.path)); }
259
+ catch (error) {
260
+ if (!ioError(error) && !(error instanceof RasterError) && !(error instanceof NotAPngError)) throw error;
261
+ refuse('PARTS_CHECK_PNG_READ', reference.path, clean(error.message), 'decodable PNG', 'declared auxiliary PNG is not readable');
262
+ }
263
+ }
264
+ }
265
+ const readReport = (name: string, spec: string): Record<string, unknown> | null => {
266
+ const row = before.find(entry => entry.path === name);
267
+ if (row?.status === 'absent') return null;
268
+ if (row?.status === 'unreadable') {
269
+ refuse('PARTS_CHECK_REPORT', name, 'unreadable input', spec, 'present report must be a readable regular file');
270
+ return null;
271
+ }
272
+ try {
273
+ const value: unknown = JSON.parse(readFileSync(join(home, name), 'utf8'));
274
+ if (!object(value) || value.spec !== spec) {
275
+ refuse('PARTS_CHECK_REPORT', name, object(value) ? value.spec ?? null : value, spec, 'report requires its declared producer spec');
276
+ return null;
277
+ }
278
+ return value;
279
+ } catch (error) {
280
+ if (!(error instanceof SyntaxError) && !ioError(error)) throw error;
281
+ refuse('PARTS_CHECK_REPORT', name, clean(error.message), spec, 'present report must be readable JSON');
282
+ return null;
283
+ }
284
+ };
285
+ const cover = readReport('source_cover.json', SOURCE_COVER_SPEC);
286
+ const reported: CoverRow[] = [];
287
+ if (before.find(row => row.path === 'source_cover.json')?.status === 'absent') {
288
+ hole('PARTS_SOURCE_COVER', 'source_cover.json', 'source_cover.json is absent; direct unplanned source cover is unavailable');
289
+ }
290
+ if (cover !== null) {
291
+ const valid = cover.stage === 'source-projection-input' &&
292
+ JSON.stringify(canonical(cover.predicate)) === JSON.stringify(canonical(sourceCoverReport([]).predicate)) &&
293
+ Array.isArray(cover.sets) && cover.sets.length > 0;
294
+ if (!valid) refuse('PARTS_CHECK_REPORT', 'source_cover.json', canonical(cover), 'source-projection-input predicate and nonempty sets', 'source cover header is malformed');
295
+ else for (const set of cover.sets as unknown[]) {
296
+ if (!object(set) || !(set.set === null || typeof set.set === 'string') || !grid(set.grid) ||
297
+ !Array.isArray(set.sources) || !Array.isArray(set.parts) || !Array.isArray(set.inputs) ||
298
+ !strings(set.hidden_parts) || !Array.isArray(set.inherited_parts) || !Array.isArray(set.output_assets)) {
299
+ refuse('PARTS_CHECK_REPORT', 'source_cover.json set', canonical(set), 'complete source-cover set', 'set membership or grid is malformed');
300
+ continue;
301
+ }
302
+ const validSources = set.sources.every(source => object(source) && typeof source.source === 'string' &&
303
+ (source.run === 'full' || source.run === 'head') && typeof source.layer === 'string' &&
304
+ source.source === `${source.run}:${source.layer}` && (source.depth_median === null || typeof source.depth_median === 'number') &&
305
+ count(source.draw_order) && Number.isSafeInteger(source.plan_rank) && Number(source.plan_rank) >= -1 &&
306
+ strings(source.planned_parts) && strings(source.extend_parts) && (source.input_layer === null || typeof source.input_layer === 'string') &&
307
+ typeof source.prepared === 'boolean' && Array.isArray(source.taken_layers));
308
+ const validInputs = hash(set.painting_sha256) && set.inputs.every(row => object(row) &&
309
+ (row.run === 'full' || row.run === 'head') && typeof row.file === 'string' && hash(row.sha256) &&
310
+ Array.isArray(row.layers) && row.layers.every(layer => object(layer) && typeof layer.layer === 'string' &&
311
+ (layer.image === null || typeof layer.image === 'string')));
312
+ const validAssets = set.output_assets.every(row => object(row) && typeof row.part === 'string' &&
313
+ (row.image === null || typeof row.image === 'string')) && set.inherited_parts.every(row => object(row) && typeof row.part === 'string' && row.set === null);
314
+ const sources = new Set(set.sources.filter(object).map(source => source.source));
315
+ const expectedSets = [null, ...(file?.alternates ?? []).map(alternate => alternate.name)];
316
+ if (!validSources || sources.size !== set.sources.length || !validInputs || !validAssets ||
317
+ (file !== undefined && (!expectedSets.includes(set.set as string | null) || JSON.stringify(set.grid) !== JSON.stringify(file.rig_size)))) {
318
+ refuse('PARTS_CHECK_REPORT', 'source_cover.json set', canonical(set), 'unique complete source identities, inputs, assets and matching rig grid', 'source-cover bindings are malformed');
319
+ continue;
320
+ }
321
+ if (!unique(set.parts.filter(object).map(part => part.part))) {
322
+ refuse('PARTS_CHECK_REPORT', 'source_cover.json set', set.parts.filter(object).map(part => part.part), 'unique part membership', 'source-cover part names repeat');
323
+ }
324
+ if (file !== undefined && set.set === null && JSON.stringify(canonical(set.output_assets)) !==
325
+ JSON.stringify(canonical(file.parts.map(part => ({ part: part.name, image: `${part.name}.png` }))))) {
326
+ refuse('PARTS_CHECK_REPORT', 'source_cover.json output_assets', canonical(set.output_assets), file.parts.map(part => part.name), 'primary asset membership disagrees with parts.json');
327
+ }
328
+ for (const part of set.parts) {
329
+ if (!object(part) || typeof part.part !== 'string' || !sources.has(part.source) || !count(part.support_px) ||
330
+ !count(part.held_under_cover_px) || part.held_under_cover_px > part.support_px || !Array.isArray(part.covered_by)) {
331
+ refuse('PARTS_CHECK_REPORT', 'source_cover.json part', canonical(part), 'named part with source and support counts', 'part membership is malformed');
332
+ continue;
333
+ }
334
+ let covered = 0;
335
+ for (const owner of part.covered_by) {
336
+ const identity = object(owner) ? set.sources.filter(object).find(source => source.source === owner.source) : undefined;
337
+ if (!object(owner) || typeof owner.source !== 'string' || !sources.has(owner.source) || typeof owner.planned !== 'boolean' ||
338
+ owner.planned !== (Number(identity?.plan_rank) >= 0) || !pixels(owner.pixels, set.grid)) {
339
+ refuse('PARTS_CHECK_REPORT', `part "${part.part}"`, canonical(owner), 'known owner, boolean planned, counted in-grid spans', 'source-cover owner is malformed');
340
+ } else if (!owner.planned && object(owner.pixels)) {
341
+ covered += owner.pixels.count as number;
342
+ reported.push({ code: 'PARTS_UNPLANNED_SOURCE_COVER', set: set.set as string | null, part: part.part,
343
+ source: owner.source, count: owner.pixels.count as number, spans: owner.pixels.spans as unknown[] });
344
+ } else if (object(owner.pixels)) {
345
+ covered += owner.pixels.count as number;
346
+ }
347
+ }
348
+ if (covered + part.held_under_cover_px > part.support_px) {
349
+ refuse('PARTS_CHECK_REPORT', `part "${part.part}"`, covered + part.held_under_cover_px, part.support_px, 'covered and held support exceeds own support');
350
+ }
351
+ }
352
+ }
353
+ if (Array.isArray(cover.sets) && file !== undefined) {
354
+ const sets = cover.sets.filter(object).map(set => set.set);
355
+ const expected = [null, ...(file.alternates ?? []).map(set => set.name)];
356
+ if (!unique(sets) || JSON.stringify(sets) !== JSON.stringify(expected)) {
357
+ refuse('PARTS_CHECK_REPORT', 'source_cover.json', sets, expected, 'source-cover sets must match assembled set order and membership');
358
+ }
359
+ }
360
+ }
361
+ const allocation = readReport('painting_allocation.json', 'rig-parts-painting-allocation/1');
362
+ const allocations: unknown[] = [];
363
+ if (before.find(row => row.path === 'painting_allocation.json')?.status === 'absent') {
364
+ hole('PARTS_PAINTING_ALLOCATION', 'painting_allocation.json', 'painting_allocation.json is absent; painting-edge transfer membership is unavailable');
365
+ }
366
+ const validateAllocation = (name: string, value: Record<string, unknown>): void => {
367
+ if (value.code !== 'PAINTING_EDGE_COVERAGE_TRANSFER' || value.stage !== 'paintingEdges after piece guarding and restoration' ||
368
+ typeof value.supplier !== 'string' || !object(value.refused) || !Object.values(value.refused).every(count) ||
369
+ !Array.isArray(value.lineage) || !count(value.fallbackHeld) || !grid(value.grid) ||
370
+ (file !== undefined && JSON.stringify(value.grid) !== JSON.stringify(file.rig_size)) ||
371
+ !Array.isArray(value.coverageTransfers) || value.coverageTransfers.some(row =>
372
+ !object(row) || typeof row.front !== 'string' || typeof row.receiver !== 'string' || typeof row.owner !== 'string' || !pixels(row.pixels, value.grid as [number, number]))) {
373
+ refuse('PARTS_CHECK_REPORT', name, canonical(value), 'grid and named coverageTransfers with counted spans', 'allocation membership is malformed');
374
+ } else allocations.push({ path: name, report: canonical(value) });
375
+ };
376
+ if (allocation !== null) {
377
+ validateAllocation('painting_allocation.json', allocation);
378
+ if (!strings(allocation.written_reports) || !unique(allocation.written_reports) || allocation.written_reports.some(name =>
379
+ !/^painting_allocation\.[^/\\]+\.json$/.test(name) || (file !== undefined && !(file.alternates ?? []).some(set => name === `painting_allocation.${encodeURIComponent(set.name)}.json`)))) {
380
+ refuse('PARTS_CHECK_REPORT', 'painting_allocation.json', allocation.written_reports ?? null, 'written_reports containing sibling allocation filenames', 'alternate report inventory is malformed');
381
+ } else for (const name of allocation.written_reports) {
382
+ requiredPaths.add(name);
383
+ if (!before.some(row => row.path === name)) before.push({ path: name, status: 'missing', sha256: null });
384
+ const value = readReport(name, 'rig-parts-painting-allocation/1');
385
+ if (value !== null) {
386
+ if (typeof value.set !== 'string' || name !== `painting_allocation.${encodeURIComponent(value.set)}.json`) {
387
+ refuse('PARTS_CHECK_REPORT', name, value.set ?? null, 'matching alternate-set identity', 'alternate report set disagrees with its inventory filename');
388
+ }
389
+ validateAllocation(name, value);
390
+ }
391
+ }
392
+ }
393
+ before.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
394
+ const report: PartsCheckReport = {
395
+ spec: PARTS_CHECK_SPEC, stage: 'parts', inputs: before,
396
+ parts: { primary: file?.parts.map(part => part.name) ?? [], alternates: canonical(file?.alternates ?? []) as unknown[],
397
+ source_cover: canonical(cover), painting_allocation: allocations },
398
+ refusals, reported, holes, exit_code: refusals.length === 0 ? 0 : 1,
399
+ };
400
+ if (JSON.stringify(before) !== JSON.stringify(inventory(false))) {
401
+ fatal('PARTS_CHECK_INPUT_CHANGED', '--parts', 'input inventory changed during the read; no report was published');
402
+ }
403
+ let created = false;
404
+ try {
405
+ mkdirSync(out, { recursive: true });
406
+ created = true;
407
+ writeFileSync(temporary, JSON.stringify(report, null, 2) + '\n', { flag: 'wx' });
408
+ if (JSON.stringify(before) !== JSON.stringify(inventory(false))) {
409
+ fatal('PARTS_CHECK_INPUT_CHANGED', '--parts', 'input inventory changed before publication; no report was published');
410
+ }
411
+ renameSync(temporary, destination);
412
+ } catch (error) {
413
+ if (created && existsSync(temporary)) rmSync(temporary);
414
+ if (error instanceof PartsError) throw error;
415
+ fatal('PARTS_CHECK_PUBLISH', '--out', `could not publish ${PARTS_CHECK_FILE}; ${error instanceof Error ? error.message.replaceAll(out, '--out') : String(error)}`);
416
+ }
417
+ for (const refusal of refusals) log(failLine(refusal));
418
+ for (const row of reported) log(`${row.code}: REPORTED part "${row.part}" — ${row.source}, ${row.count} px`);
419
+ for (const row of holes) log(row.line);
420
+ return report;
421
+ }