spine-parts 2.25.1 → 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.1",
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": {
@@ -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
+ }