rig-parts 2.67.0 → 2.69.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/src/parts.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { assemblyFieldDigest, isSplitTakeMetadataField } from './assembly-reading.ts';
2
- import { compareRemovedRegions, orderedEditedPartReceipt, type EditedPartReceipt, type EditedPartRemovedRegion } from './editedparts.ts';
3
- import { parseReceiptProducer, receiptText } from './receiptproducer.ts';
2
+ import { compareRemovedRegions, editedPartReceiptProblem, orderedEditedPartReceipt, type EditedPartRemovedRegion } from './editedparts.ts';
4
3
  import { takenSourceProblems, type TakenLayerSource } from './takesource.ts';
5
4
  import { AUTOMATIC_WRITERS, provenanceAddsUp, type PixelProvenance, type CutOwnership } from './provenance.ts';
6
5
  import { baseAnchorProblems, orderedBaseAnchor, type BaseAnchor } from './baseanchor.ts';
6
+ import { REPLACEMENT_RECORD_PATH } from './replacementrecord.ts';
7
7
  import { partDepthProblems, type PartDepthReference } from './depthsheets.ts';
8
8
  /**
9
9
  * The output contract of the assemble stage: `parts.json`, one record per
@@ -155,6 +155,8 @@ export interface PartRecord {
155
155
  w: number;
156
156
  h: number;
157
157
  opaque_px: number;
158
+ /** On a post-assembly replacement, the original scope of the mandatory assembly counters and authored-unit provenance. */
159
+ assembly_opaque_px?: number;
158
160
  source_visibility?: PartSourceVisibility;
159
161
  source_state_map?: PartSourceStateMap;
160
162
  /** With `source_visibility` only: every later part this one overlaps, in draw order (issue #1474). */
@@ -464,6 +466,8 @@ export interface AssemblyConfigRecord {
464
466
 
465
467
  export interface PartsFile {
466
468
  assembly_config?: AssemblyConfigRecord;
469
+ /** Current derivation attestation, relative to the directory holding parts.json. */
470
+ replacement_record?: string;
467
471
  /** Optional on legacy packages; binds the opaque RGB raster assemble actually read. */
468
472
  painting_in_rig?: PaintingInRig;
469
473
  /** Structural moves, independent of per-pixel value equality. */
@@ -522,8 +526,8 @@ export interface SceneRecord {
522
526
  figure_mask: string;
523
527
  }
524
528
 
525
- const TOP_KEYS = ['assembly_config', 'painting_in_rig', 'rig_size', 'scale_rig_per_source', 'parts', 'ghost_px', 'recomposite', 'scene', 'occluder_plates', 'occluder_grow', 'occluder_guard', 'single_run_pad', 'alternates', 'motion_seams', 'cut_ownership'] as const;
526
- const REQUIRED_TOP_KEYS = TOP_KEYS.filter((k) => k !== 'assembly_config' && k !== 'painting_in_rig' && k !== 'recomposite' && k !== 'scene' && k !== 'single_run_pad' && k !== 'occluder_plates' && k !== 'occluder_grow' && k !== 'occluder_guard' && k !== 'alternates' && k !== 'motion_seams' && k !== 'cut_ownership');
529
+ const TOP_KEYS = ['assembly_config', 'painting_in_rig', 'rig_size', 'scale_rig_per_source', 'parts', 'ghost_px', 'recomposite', 'scene', 'occluder_plates', 'occluder_grow', 'occluder_guard', 'single_run_pad', 'alternates', 'motion_seams', 'cut_ownership', 'replacement_record'] as const;
530
+ const REQUIRED_TOP_KEYS = TOP_KEYS.filter((k) => k !== 'assembly_config' && k !== 'painting_in_rig' && k !== 'recomposite' && k !== 'scene' && k !== 'single_run_pad' && k !== 'occluder_plates' && k !== 'occluder_grow' && k !== 'occluder_guard' && k !== 'alternates' && k !== 'motion_seams' && k !== 'cut_ownership' && k !== 'replacement_record');
527
531
  export const OCCLUDER_PLATE_KEYS = ['receipt', 'receipt_sha256', 'occluder_sha256', 'painting_sha256', 'output_sha256', 'mask_sha256'] as const;
528
532
  export const OCCLUDER_GROW_KEYS = ['occluder', 'image', 'grow', 'covered_px_before', 'covered_px_after'] as const;
529
533
  export const OCCLUDER_GUARD_KEYS = ['occluder', 'image', 'guard', 'guarded_px_before', 'guarded_px_after'] as const;
@@ -543,6 +547,7 @@ export const PART_KEYS = [
543
547
  'w',
544
548
  'h',
545
549
  'opaque_px',
550
+ 'assembly_opaque_px',
546
551
  'source_visibility',
547
552
  'source_state_map',
548
553
  'source_overlaps',
@@ -569,7 +574,7 @@ const LIMB_KEY = 'limb';
569
574
  const COUNT_KEYS = PART_KEYS.slice(2).filter((k) => k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth' && k !== 'provenance' && k !== 'taken_layers' && k !== 'source_visibility' && k !== 'source_state_map' && k !== 'source_overlaps') as ReadonlyArray<(typeof PART_KEYS)[number]>;
570
575
  /** The port's own counts: all three or none (none = a record the reference wrote). */
571
576
  export const VISIBILITY_KEYS = ['visible_px', 'occluded_px', 'visible_not_projected_px'] as const;
572
- const REQUIRED_KEYS = PART_KEYS.filter((k) => k !== 'painting_extension_px' && !(VISIBILITY_KEYS as readonly string[]).includes(k) && k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth' && k !== 'provenance' && k !== 'taken_layers' && k !== 'source_visibility' && k !== 'source_state_map' && k !== 'source_overlaps');
577
+ const REQUIRED_KEYS = PART_KEYS.filter((k) => k !== 'assembly_opaque_px' && k !== 'painting_extension_px' && !(VISIBILITY_KEYS as readonly string[]).includes(k) && k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth' && k !== 'provenance' && k !== 'taken_layers' && k !== 'source_visibility' && k !== 'source_state_map' && k !== 'source_overlaps');
573
578
 
574
579
  /** Where a part came from: a See-through run and a v3 tag or an author-made layer's `author:<label>` (issue #256), or the painting itself for a patch. */
575
580
  export type From = { run: 'full' | 'head'; tag: string } | { run: 'painting'; patch: string };
@@ -620,14 +625,6 @@ function editedRemovedRegions(value: unknown, removed: number, w: unknown, h: un
620
625
  if (sum !== removed) fail('PARTS_COUNTS_ADD_UP', object, `px sum to ${sum}; removed_opaque_px ${removed} is required`);
621
626
  }
622
627
 
623
- function validEditedPartAuthor(receipt: EditedPartReceipt): boolean {
624
- const keys = Object.keys(receipt).sort().join(',');
625
- if (keys === 'editor,file,from_sha256,part,sha256') return receiptText(receipt.editor);
626
- if (keys !== 'file,from_sha256,part,producer,sha256') return false;
627
- try { parseReceiptProducer(receipt.producer, 'edited part producer'); return true; }
628
- catch { return false; }
629
- }
630
-
631
628
  const OWNERSHIP_KEYS = ['edit', 'from', 'into', 'moved_in_opaque_px', 'retained_band_opaque_px', 'cleared_opaque_px', 'under_filled_px', 'under_filled_opaque_px', 'net_cleared_opaque_px', 'under_plate'] as const;
632
629
  const REQUIRED_OWNERSHIP_KEYS = OWNERSHIP_KEYS.filter((k) => k !== 'under_plate');
633
630
  function orderedOwnership(rows: readonly CutOwnership[]): Array<Record<string, unknown>> {
@@ -766,6 +763,7 @@ export function serializeParts(file: PartsFile): string {
766
763
  } }),
767
764
  parts: serializePartList(file.parts),
768
765
  ...(file.assembly_config === undefined ? {} : { assembly_config: { sha256: file.assembly_config.sha256, fields: file.assembly_config.fields.map(({ name, sha256 }) => ({ name, sha256 })) } }),
766
+ ...(file.replacement_record === undefined ? {} : { replacement_record: file.replacement_record }),
769
767
  ...(file.cut_ownership === undefined ? {} : { cut_ownership: orderedOwnership(file.cut_ownership) }),
770
768
  ...(file.motion_seams === undefined ? {} : { motion_seams: file.motion_seams.map(({ part, neighbour }) => ({ part, neighbour })) }),
771
769
  ghost_px: Object.fromEntries(Object.keys(file.ghost_px).sort().map((k) => [k, file.ghost_px[k]])),
@@ -837,7 +835,10 @@ function paintingImageReference(painting: PaintingInRig): PartsFileReference {
837
835
 
838
836
  /** Read the manifest without opening, hashing or decoding its PNG references. */
839
837
  export function partsFileReferences(dir: string): PartsFileReference[] {
840
- const file = readPartsManifest(join(dir, 'parts.json'));
838
+ return declaredPartsFiles(readPartsManifest(join(dir, 'parts.json')));
839
+ }
840
+
841
+ export function declaredPartsFiles(file: PartsFile): PartsFileReference[] {
841
842
  const references: PartsFileReference[] = [];
842
843
  const addScene = (scene: SceneRecord | undefined): void => {
843
844
  if (scene !== undefined) references.push({ path: scene.figure_mask, role: 'figure_mask' });
@@ -1056,10 +1057,7 @@ function checkProvenance(raw: unknown, opaque: unknown, object: string, fail: (c
1056
1057
  const valid = e !== null && e !== undefined && typeof e === 'object' && !Array.isArray(e) && [keys, withRegions].includes(Object.keys(e).sort().join(',')) &&
1057
1058
  typeof e.edit === 'string' && /^edited_parts\[\d+\]$/.test(e.edit) && relativePath(e.dir) &&
1058
1059
  [e.changed_px, e.changed_counted_px, e.changed_excluded_px, e.removed_opaque_px].every(count) &&
1059
- e.receipt !== null && typeof e.receipt === 'object' && !Array.isArray(e.receipt) &&
1060
- validEditedPartAuthor(e.receipt) &&
1061
- nonempty(e.receipt.part) && e.receipt.part === identity?.name && relativePath(e.receipt.file) &&
1062
- [e.receipt.sha256, e.receipt.from_sha256].every(s => typeof s === 'string' && /^[a-f0-9]{64}$/.test(s));
1060
+ editedPartReceiptProblem(e.receipt) === undefined && e.receipt.part === identity?.name;
1063
1061
  if (!valid) fail('PARTS_FIELD_TYPE', object + ' edited_part', 'requires edited_parts[i], a config-relative dir, a receipt with the enclosing part name, dir-relative file, two lowercase sha256 hashes and either editor or producer, and four nonnegative safe integer change counts');
1064
1062
  else {
1065
1063
  const area = typeof identity?.w === 'number' && typeof identity.h === 'number' ? identity.w * identity.h : NaN;
@@ -1097,6 +1095,9 @@ function checkParts(raw: unknown, path: string): PartsFile {
1097
1095
  const o = raw as Record<string, unknown>;
1098
1096
  for (const k of Object.keys(o)) if (!(TOP_KEYS as readonly string[]).includes(k)) fail('PARTS_KEY_KNOWN', `${path} key "${k}"`, `is not a parts.json field; known: ${TOP_KEYS.join(', ')}`);
1099
1097
  for (const k of REQUIRED_TOP_KEYS) if (!(k in o)) fail('PARTS_FIELD_PRESENT', `${path} field "${k}"`, 'is absent and required');
1098
+ if ('replacement_record' in o && (typeof o.replacement_record !== 'string' || !REPLACEMENT_RECORD_PATH.test(o.replacement_record))) {
1099
+ fail('PARTS_FIELD_TYPE', `${path} field "replacement_record"`, 'requires a .parts-replacements/<lowercase sha256>.json path');
1100
+ }
1100
1101
  if ('assembly_config' in o) {
1101
1102
  const value = o.assembly_config as Partial<AssemblyConfigRecord> | null;
1102
1103
  const digest = (input: unknown): input is string => typeof input === 'string' && /^[a-f0-9]{64}$/.test(input);
@@ -1171,7 +1172,12 @@ function checkParts(raw: unknown, path: string): PartsFile {
1171
1172
  if (k in r && !(Number.isInteger(r[k]) && (r[k] as number) >= 0)) fail('PARTS_FIELD_TYPE', `${label} field "${k}"`, `is ${show(r[k])}; a non-negative integer is required`);
1172
1173
  }
1173
1174
  const count = (k: string): number | null => (Number.isInteger(r[k]) && (r[k] as number) >= 0 ? (r[k] as number) : null);
1174
- if ('provenance' in r) checkProvenance(r.provenance, r.opaque_px, label + ' provenance', fail, 'depth' in r, { name: r.name, w: r.w, h: r.h });
1175
+ const assemblyOpaque = count('assembly_opaque_px');
1176
+ if ('assembly_opaque_px' in r && (!('replacement_record' in o) || assemblyOpaque === null || !Number.isSafeInteger(assemblyOpaque) ||
1177
+ (typeof r.w === 'number' && typeof r.h === 'number' && assemblyOpaque > r.w * r.h))) {
1178
+ fail('PARTS_FIELD_TYPE', label + ' assembly_opaque_px', 'requires a replacement record and an original opaque count within the crop');
1179
+ }
1180
+ if ('provenance' in r) checkProvenance(r.provenance, assemblyOpaque ?? r.opaque_px, label + ' provenance', fail, 'depth' in r, { name: r.name, w: r.w, h: r.h });
1175
1181
  checkPaintingExtensionCount(r, label, fail);
1176
1182
  if ('source_visibility' in r) checkSourceVisibility(r.source_visibility, r.opaque_px, label, fail);
1177
1183
  if ('source_state_map' in r) checkSourceStateMap(r, label, fail);
@@ -1183,10 +1189,10 @@ function checkParts(raw: unknown, path: string): PartsFile {
1183
1189
  }
1184
1190
  if (from !== null && from.run === 'painting' && op !== null) {
1185
1191
  // A patch is 100 % source: every count is opaque_px or 0 (module doc).
1186
- const whole = ['visible_px', 'projected_core_px', 'source_px_taken'].filter((k) => k in r && count(k) !== op);
1192
+ const whole = ['visible_px', 'projected_core_px', 'source_px_taken'].filter((k) => k in r && count(k) !== (k === 'visible_px' ? op : assemblyOpaque ?? op));
1187
1193
  const none = ['occluded_px', 'visible_not_projected_px', 'refused_drift_px', 'merged_px'].filter((k) => k in r && count(k) !== 0);
1188
1194
  if (whole.length > 0 || none.length > 0) {
1189
- const said = [...whole.map((k) => `${k} ${show(r[k])} (opaque_px ${op} required)`), ...none.map((k) => `${k} ${show(r[k])} (0 required)`)].join(', ');
1195
+ const said = [...whole.map((k) => `${k} ${show(r[k])} (${assemblyOpaque === null || k === 'visible_px' ? 'opaque_px' : 'assembly_opaque_px'} ${k === 'visible_px' ? op : assemblyOpaque ?? op} required)`), ...none.map((k) => `${k} ${show(r[k])} (0 required)`)].join(', ');
1190
1196
  fail('PARTS_COUNTS_ADD_UP', `${label}`, `is a painting patch (${String(r.from)}), which is 100 % source; ${said}`);
1191
1197
  }
1192
1198
  }
package/src/partscheck.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /** Assemble-output integrity and explicit unmeasured quality classes. No rig or renderer. */
2
2
  import { createHash } from 'node:crypto';
3
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
4
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
5
  import { failLine, PartsError, type Problem } from './errors.ts';
6
6
  import { FIGURE_MASK_FILE, orderedSourceOverlap, orderedSourceVisibility, partImageReference, partsFileReferences, readParts, type PartsFile, type PartSourceOverlap, type PartSourceVisibility } from './parts.ts';
@@ -8,6 +8,7 @@ import { readPng } from './raster/png.ts';
8
8
  import { RasterError } from './raster/types.ts';
9
9
  import { NotAPngError } from '@rig-c/core/png';
10
10
  import { SOURCE_COVER_SPEC, sourceCoverReport } from './sourcecover.ts';
11
+ import { readRegularFile, walkPartsFiles } from './partsfiles.ts';
11
12
 
12
13
  export const PARTS_CHECK_SPEC = 'rig-parts-parts-check/1';
13
14
  export const PARTS_CHECK_FILE = 'parts-check.json';
@@ -182,7 +183,7 @@ export function checkPartsStage(input: string, output: string, log: (line: strin
182
183
  try {
183
184
  const manifestPath = join(home, 'parts.json');
184
185
  if (lstatSync(manifestPath).isFile()) {
185
- const bytes = readFileSync(manifestPath);
186
+ const bytes = readRegularFile(manifestPath);
186
187
  initialManifestHash = createHash('sha256').update(bytes).digest('hex');
187
188
  const raw: unknown = JSON.parse(bytes.toString('utf8'));
188
189
  if (object(raw)) {
@@ -198,27 +199,16 @@ export function checkPartsStage(input: string, output: string, log: (line: strin
198
199
  }
199
200
  const inventory = (reportErrors: boolean): PartsCheckInput[] => {
200
201
  const rows = new Map<string, PartsCheckInput>();
201
- const visit = (name: string): void => {
202
- if (ignoredPaths.has(name)) return;
203
- const path = join(home, name);
204
- try {
205
- const stat = lstatSync(path);
206
- if (stat.isSymbolicLink() || (!stat.isDirectory() && !stat.isFile())) {
207
- rows.set(name, { path: name, status: 'unreadable', sha256: null });
208
- 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');
209
- } else if (stat.isDirectory()) {
210
- for (const entry of readdirSync(path).sort()) visit(name === '.' ? entry : `${name}/${entry}`);
211
- } else {
212
- rows.set(name, { path: name, status: 'read', sha256: createHash('sha256').update(readFileSync(path)).digest('hex') });
213
- }
214
- } catch (error) {
215
- if (!ioError(error)) throw error;
216
- const missing = 'code' in error && error.code === 'ENOENT';
217
- rows.set(name, { path: name, status: missing ? 'missing' : 'unreadable', sha256: null });
218
- if (reportErrors) refuse('PARTS_CHECK_INPUT_READ', name, clean(error.message), 'readable regular input', 'input inventory could not read this object');
219
- }
220
- };
221
- visit('.');
202
+ walkPartsFiles(home, ignoredPaths, (name, path) => {
203
+ rows.set(name, { path: name, status: 'read', sha256: createHash('sha256').update(readRegularFile(path)).digest('hex') });
204
+ }, (name, error) => {
205
+ const missing = error instanceof Error && 'code' in error && error.code === 'ENOENT';
206
+ rows.set(name, { path: name, status: missing ? 'missing' : 'unreadable', sha256: null });
207
+ if (!reportErrors) return;
208
+ if (error === undefined) refuse('PARTS_CHECK_INPUT_READ', name, 'non-regular input', 'regular file or directory', 'input links and special files require a regular-file scratch copy');
209
+ else if (ioError(error)) refuse('PARTS_CHECK_INPUT_READ', name, clean(error.message), 'readable regular input', 'input inventory could not read this object');
210
+ else throw error;
211
+ });
222
212
  for (const name of [...requiredPaths, ...optionalPaths]) if (!rows.has(name)) {
223
213
  rows.set(name, { path: name, status: optionalPaths.has(name) ? 'absent' : 'missing', sha256: null });
224
214
  }
@@ -0,0 +1,62 @@
1
+ /** Regular-file paths and byte inventories for assembled parts directories. */
2
+ import { createHash } from 'node:crypto';
3
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readdirSync } from 'node:fs';
4
+ import { isAbsolute, join, relative, sep } from 'node:path';
5
+
6
+ export function withinPartsPath(parent: string, path: string): boolean {
7
+ const rel = relative(parent, path);
8
+ return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`));
9
+ }
10
+
11
+ export function inventoryPath(path: string): boolean {
12
+ return !/[\\\0]/.test(path) && path.split('/').every(segment => segment !== '' && segment !== '.' && segment !== '..') &&
13
+ !/^[A-Za-z]:/.test(path);
14
+ }
15
+
16
+ export function readRegularFile(path: string): Buffer {
17
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
18
+ try {
19
+ if (!fstatSync(fd).isFile()) throw Object.assign(new Error('input is not a regular file'), { code: 'EINVAL' });
20
+ return readFileSync(fd);
21
+ } finally {
22
+ closeSync(fd);
23
+ }
24
+ }
25
+
26
+ /** Never descend through symlinks or read special files. Paths are relative, including in refusals. */
27
+ export function walkPartsFiles(
28
+ home: string,
29
+ ignore: ReadonlySet<string>,
30
+ file: (name: string, path: string) => void,
31
+ invalid: (name: string, error?: unknown) => void,
32
+ ): void {
33
+ const visit = (name: string): void => {
34
+ if (ignore.has(name)) return;
35
+ const path = join(home, name);
36
+ try {
37
+ const stat = lstatSync(path);
38
+ if (stat.isSymbolicLink() || (!stat.isDirectory() && !stat.isFile())) {
39
+ invalid(name);
40
+ } else if (stat.isDirectory()) {
41
+ for (const entry of readdirSync(path).sort()) visit(name === '.' ? entry : `${name}/${entry}`);
42
+ } else {
43
+ file(name, path);
44
+ }
45
+ } catch (error) {
46
+ if (error instanceof Error && 'code' in error) invalid(name, error);
47
+ else throw error;
48
+ }
49
+ };
50
+ visit('.');
51
+ }
52
+
53
+ export function partsSha256(bytes: Uint8Array | string): string {
54
+ return createHash('sha256').update(bytes).digest('hex');
55
+ }
56
+
57
+ export interface PartsInventoryRow { path: string; bytes: number; sha256: string }
58
+
59
+ export function partsInventoryDigest(rows: readonly PartsInventoryRow[]): string {
60
+ const ordered = [...rows].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
61
+ return partsSha256(JSON.stringify(ordered.map(({ path, bytes, sha256 }) => ({ path, bytes, sha256 }))) + '\n');
62
+ }
@@ -0,0 +1,172 @@
1
+ /** Browser-free replacement record schema and deterministic parts-tree digest. */
2
+ import { join, resolve } from 'node:path';
3
+ import { SHA256_PATTERN } from './editreceipt.ts';
4
+ import { editedPartReceiptProblem, type EditedPartReceipt, type EditedPixelCounts } from './editedparts.ts';
5
+ import { PartsError, refuseIfAny, type Problem } from './errors.ts';
6
+ import { inventoryPath, partsInventoryDigest, partsSha256, readRegularFile, walkPartsFiles, type PartsInventoryRow } from './partsfiles.ts';
7
+ import { receiptObject } from './receiptproducer.ts';
8
+ import type { DepthReading } from './depthsheets.ts';
9
+
10
+ export const REPLACEMENT_RECORD_SPEC = 'rig-parts-replacement/1';
11
+ export const REPLACEMENT_RECORD_PATH = /^\.parts-replacements\/[0-9a-f]{64}\.json$/;
12
+
13
+ export interface ReplacementRow extends EditedPixelCounts {
14
+ part: string;
15
+ receipt: EditedPartReceipt;
16
+ depth?: {
17
+ from_sha256: string;
18
+ sha256: string;
19
+ reseeded: boolean;
20
+ support?: 'alpha-nonzero' | 'alpha-at-least-128';
21
+ reading?: DepthReading;
22
+ };
23
+ /** Original manifest fields removed from live metadata during replacement. */
24
+ historical?: Record<string, unknown>;
25
+ }
26
+
27
+ export interface ReplacementRecord {
28
+ spec: typeof REPLACEMENT_RECORD_SPEC;
29
+ source_sha256: string;
30
+ result_sha256: string;
31
+ rig_size: [number, number];
32
+ replaced: ReplacementRow[];
33
+ copied: string[];
34
+ rederived: string[];
35
+ omitted: string[];
36
+ }
37
+
38
+ export const replacementRecordPath = (source: string): string => `.parts-replacements/${source}.json`;
39
+ export const replacementHash = (value: unknown): value is string => typeof value === 'string' && SHA256_PATTERN.test(value);
40
+ const count = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
41
+ const grid = (value: unknown): value is [number, number] => Array.isArray(value) && value.length === 2 && value.every(n => count(n) && n > 0);
42
+ const changedKeys = ['changed_px', 'changed_counted_px', 'changed_excluded_px', 'removed_opaque_px'] as const;
43
+ export const REPLACEMENT_HISTORICAL_FIELDS = [
44
+ 'visible_px', 'occluded_px', 'visible_not_projected_px', 'painting_extension_px', 'provenance', 'taken_layers',
45
+ 'fringe_pushed_back', 'source_visibility', 'source_state_map', 'source_overlaps',
46
+ ] as const;
47
+
48
+ export function readReplacementRecord(bytes: Uint8Array): ReplacementRecord {
49
+ const problems: Problem[] = [];
50
+ const fail = (object: string, detail: string): void => { problems.push({ code: 'REPLACE_PART_RECORD', object, detail }); };
51
+ let raw: unknown;
52
+ try { raw = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
53
+ catch { fail('replacement record', 'requires a readable UTF-8 JSON object'); }
54
+ if (!receiptObject(raw)) {
55
+ if (problems.length === 0) fail('replacement record', 'requires a JSON object');
56
+ throw new PartsError(problems);
57
+ }
58
+ const fields = ['spec', 'source_sha256', 'result_sha256', 'rig_size', 'replaced', 'copied', 'rederived', 'omitted'];
59
+ for (const key of Object.keys(raw)) if (!fields.includes(key)) fail(key, 'unknown replacement record field');
60
+ if (raw.spec !== REPLACEMENT_RECORD_SPEC) fail('spec', `requires ${REPLACEMENT_RECORD_SPEC}`);
61
+ for (const key of ['source_sha256', 'result_sha256']) if (!replacementHash(raw[key])) fail(key, 'requires a lowercase SHA-256');
62
+ if (!grid(raw.rig_size)) fail('rig_size', 'requires two positive safe integers');
63
+ const paths = new Set<string>();
64
+ for (const key of ['copied', 'rederived', 'omitted']) {
65
+ const list = raw[key];
66
+ if (!Array.isArray(list)) { fail(key, 'requires a sorted list of relative file paths'); continue; }
67
+ let previous: string | undefined;
68
+ for (const value of list) {
69
+ if (typeof value !== 'string' || !inventoryPath(value)) { fail(key, 'requires safe relative file paths'); continue; }
70
+ if (previous !== undefined && value <= previous) fail(key, `path ${JSON.stringify(value)} must be in code-unit order without repeats`);
71
+ if (paths.has(value)) fail(key, `path ${JSON.stringify(value)} was already classified`);
72
+ previous = value;
73
+ paths.add(value);
74
+ }
75
+ }
76
+ const seen = new Set<string>();
77
+ if (!Array.isArray(raw.replaced) || raw.replaced.length === 0) fail('replaced', 'requires at least one replacement row');
78
+ else for (const [index, row] of raw.replaced.entries()) {
79
+ const at = `replaced[${index}]`;
80
+ if (!receiptObject(row)) { fail(at, 'requires a replacement row object'); continue; }
81
+ const allowed = ['part', 'receipt', ...changedKeys, 'removed_opaque_regions', 'depth', 'historical'];
82
+ for (const key of Object.keys(row)) if (!allowed.includes(key)) fail(`${at}.${key}`, 'unknown replacement row field');
83
+ if (typeof row.part !== 'string' || row.part.trim() === '' || /[\\/\0]/.test(row.part) || row.part.startsWith('.') || seen.has(row.part)) fail(`${at}.part`, 'requires a unique file-name-safe part name');
84
+ if (typeof row.part === 'string') seen.add(row.part);
85
+ const invalidReceipt = editedPartReceiptProblem(row.receipt);
86
+ if (invalidReceipt !== undefined || !receiptObject(row.receipt) || row.receipt.part !== row.part || row.receipt.sha256 === row.receipt.from_sha256) {
87
+ fail(`${at}.receipt`, invalidReceipt ?? 'requires the enclosing part and distinct replacement and source hashes');
88
+ }
89
+ if (!changedKeys.every(key => count(row[key])) ||
90
+ Number(row.changed_px) !== Number(row.changed_counted_px) + Number(row.changed_excluded_px) ||
91
+ Number(row.removed_opaque_px) > Number(row.changed_excluded_px)) fail(at, 'change counts must be nonnegative integers and add up');
92
+ if (Object.hasOwn(row, 'removed_opaque_regions')) {
93
+ const regions = row.removed_opaque_regions;
94
+ if (!Array.isArray(regions) || regions.length === 0 || !regions.every(region => receiptObject(region) &&
95
+ Object.keys(region).sort().join(',') === 'box,px' && Array.isArray(region.box) && region.box.length === 4 &&
96
+ region.box.every(count) && region.box[2] > 0 && region.box[3] > 0 && count(region.px) &&
97
+ region.px > 0 && region.px <= region.box[2] * region.box[3]) ||
98
+ regions.reduce((sum, region) => sum + Number(region.px), 0) !== row.removed_opaque_px) {
99
+ fail(`${at}.removed_opaque_regions`, 'requires bounded nonempty region rows whose counts sum to removed_opaque_px');
100
+ }
101
+ }
102
+ if (Object.hasOwn(row, 'depth')) {
103
+ const depth = row.depth;
104
+ if (!receiptObject(depth) || Object.keys(depth).some(key => !['from_sha256', 'sha256', 'reseeded', 'support', 'reading'].includes(key)) ||
105
+ !replacementHash(depth.from_sha256) || !replacementHash(depth.sha256) || typeof depth.reseeded !== 'boolean' ||
106
+ (Object.hasOwn(depth, 'support') && depth.support !== 'alpha-nonzero' && depth.support !== 'alpha-at-least-128') ||
107
+ (Object.hasOwn(depth, 'reading') && !validDepthReading(depth.reading))) {
108
+ fail(`${at}.depth`, 'requires both lowercase depth hashes, a boolean reseeded, and valid support or reading if present');
109
+ }
110
+ }
111
+ if (Object.hasOwn(row, 'historical') && (!receiptObject(row.historical) || Object.keys(row.historical).length === 0 ||
112
+ Object.keys(row.historical).some(key => !(REPLACEMENT_HISTORICAL_FIELDS as readonly string[]).includes(key)))) {
113
+ fail(`${at}.historical`, 'requires original values of recognized assembly fields');
114
+ }
115
+ }
116
+ refuseIfAny(problems);
117
+ return raw as unknown as ReplacementRecord;
118
+ }
119
+
120
+ function validDepthReading(raw: unknown): boolean {
121
+ const level = (value: unknown): boolean => value === null || (typeof value === 'number' && Number.isFinite(value));
122
+ return receiptObject(raw) && Object.keys(raw).sort().join(',') === 'orderingMedian,relation,sheetMedian' &&
123
+ level(raw.orderingMedian) && level(raw.sheetMedian) &&
124
+ (raw.relation === 'same' || raw.relation === 'opposite' || raw.relation === 'indeterminate');
125
+ }
126
+
127
+ export function captureReplacementTree(root: string): Map<string, PartsInventoryRow> {
128
+ const files = new Map<string, PartsInventoryRow>(), problems: Problem[] = [];
129
+ const invalid = (path: string, detail: string): void => {
130
+ problems.push({ code: 'REPLACE_PART_INPUT', object: path, detail });
131
+ };
132
+ walkPartsFiles(root, new Set(), (name, path) => {
133
+ if (!inventoryPath(name)) { invalid(name, 'requires a safe relative file path'); return; }
134
+ const bytes = readRegularFile(path);
135
+ files.set(name, { path: name, bytes: bytes.length, sha256: partsSha256(bytes) });
136
+ }, (name, error) => invalid(name, error === undefined
137
+ ? 'found a link or special file; regular files and directories are required'
138
+ : 'could not read a regular file or directory'));
139
+ refuseIfAny(problems);
140
+ return files;
141
+ }
142
+
143
+ export function digestReplacementInventory(files: ReadonlyMap<string, PartsInventoryRow>, recordPath?: string): string {
144
+ return partsInventoryDigest([...files.values()].filter(row => row.path !== recordPath));
145
+ }
146
+
147
+ export function readBoundReplacementFile(root: string, files: ReadonlyMap<string, PartsInventoryRow>, path: string): Buffer {
148
+ const row = files.get(path);
149
+ let bytes: Buffer | undefined;
150
+ if (row !== undefined) {
151
+ try { bytes = readRegularFile(join(root, path)); }
152
+ catch { /* A read failure invalidates the inventory binding. */ }
153
+ if (bytes !== undefined && bytes.length === row.bytes && partsSha256(bytes) === row.sha256) return bytes;
154
+ }
155
+ throw new PartsError([{ code: 'REPLACE_PART_INPUT', object: path,
156
+ detail: row === undefined ? 'file is absent from the input inventory' : 'file changed or became unreadable after the input inventory' }]);
157
+ }
158
+
159
+ /** The source digest covers all files. The result digest omits precisely the active record. */
160
+ export function replacementTreeDigest(root: string, options?: { result?: boolean }): string {
161
+ const home = resolve(root), files = captureReplacementTree(home);
162
+ if (options?.result !== true) return digestReplacementInventory(files);
163
+ let raw: unknown;
164
+ try { raw = JSON.parse(readBoundReplacementFile(home, files, 'parts.json').toString('utf8')); }
165
+ catch { /* The result digest requires a readable manifest and an existing record. */ }
166
+ if (!receiptObject(raw) || typeof raw.replacement_record !== 'string' || !REPLACEMENT_RECORD_PATH.test(raw.replacement_record) ||
167
+ !files.has(raw.replacement_record)) {
168
+ throw new PartsError([{ code: 'REPLACE_PART_RECORD', object: 'parts.json replacement_record',
169
+ detail: 'a result digest requires a valid pointer to an existing replacement record inside the set' }]);
170
+ }
171
+ return digestReplacementInventory(files, raw.replacement_record);
172
+ }