@rig-c/parts 2.26.1 → 2.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,186 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { basename, join, relative, resolve, sep } from 'node:path';
4
+ import { type AssembleResult, FIGURE_MASK_FILE } from './assemble.ts';
5
+ import { ERROR_MAP_FILE } from './build.ts';
6
+ import { CUT_MATERIAL_SOURCES } from './cutmaterial.ts';
7
+ import { EDGE_RESIDUAL_FILE } from './edgeresidual.ts';
8
+ import { PartsError } from './errors.ts';
9
+ import { LAYOUT_FILE } from './limblayout.ts';
10
+ import { PAINTING_ALLOCATION_FILE } from './paintingedges.ts';
11
+ import { PAINTING_IN_RIG_FILE } from './parts.ts';
12
+ import { STAGE_MAP_FILE } from './provenance.ts';
13
+ import { rigJsonText, type RigOutput, SETS_FILE } from './rig.ts';
14
+ import { SOURCE_COVER_FILE } from './sourcecover.ts';
15
+ import { SUPPORT_DOMAINS_FILE } from './supportdomains.ts';
16
+
17
+ export const RUN_STAMP_SPEC = 'rig-run/1' as const;
18
+ export const RUN_STAMP_FILE = 'run.json' as const;
19
+
20
+ export type RunStampCommand = 'rig' | 'assemble';
21
+
22
+ export interface RunStampPackage {
23
+ name: string;
24
+ version: string;
25
+ }
26
+
27
+ export interface RunStampFileEntry {
28
+ path: string;
29
+ sha256: string;
30
+ }
31
+
32
+ export interface RunStamp {
33
+ spec: typeof RUN_STAMP_SPEC;
34
+ package: RunStampPackage;
35
+ command: RunStampCommand;
36
+ started_at: string;
37
+ finished_at: string;
38
+ config: RunStampFileEntry;
39
+ outputs: RunStampFileEntry[];
40
+ }
41
+
42
+ export interface RunStampInput {
43
+ pkg: RunStampPackage;
44
+ command: RunStampCommand;
45
+ startedAt: string;
46
+ finishedAt: string;
47
+ outDir: string;
48
+ configPath: string;
49
+ outputPaths: readonly string[];
50
+ }
51
+
52
+ function sha256OnDisk(filePath: string): string {
53
+ return createHash('sha256').update(readFileSync(filePath)).digest('hex');
54
+ }
55
+
56
+ function relativeToOutRoot(outDir: string, targetPath: string): string {
57
+ const realOut = realpathSync(resolve(outDir));
58
+ const realTarget = realpathSync(resolve(targetPath));
59
+ return relative(realOut, realTarget).split(sep).join('/');
60
+ }
61
+
62
+ function sortCodeUnits(paths: readonly string[]): string[] {
63
+ return [...new Set(paths.filter((p) => p !== RUN_STAMP_FILE))].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
64
+ }
65
+
66
+ /** Remove `<outDir>/run.json` before a stage starts so a refused run never leaves a stale stamp behind. */
67
+ export function clearRunStamp(outDir: string): void {
68
+ rmSync(join(outDir, RUN_STAMP_FILE), { force: true });
69
+ }
70
+
71
+ /**
72
+ * Read package `name` and `version` from `package.json`, refusing with `RUN_STAMP_PACKAGE`
73
+ * when the file is missing, invalid JSON, or lacks a non-empty string `name` or `version`.
74
+ */
75
+ export function readPackageIdentity(pkgPath: string): RunStampPackage {
76
+ if (!existsSync(pkgPath)) {
77
+ throw new PartsError([{ code: 'RUN_STAMP_PACKAGE', object: pkgPath, detail: 'no such file; a package.json with non-empty string "name" and "version" is required to write run.json' }]);
78
+ }
79
+ let parsed: unknown;
80
+ try {
81
+ parsed = JSON.parse(readFileSync(pkgPath, 'utf8'));
82
+ } catch (err) {
83
+ throw new PartsError([{ code: 'RUN_STAMP_PACKAGE', object: pkgPath, detail: `${(err as Error).message}; valid JSON with non-empty string "name" and "version" is required to write run.json` }]);
84
+ }
85
+ const obj = typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null;
86
+ const name = obj !== null && typeof obj.name === 'string' ? obj.name.trim() : '';
87
+ const version = obj !== null && typeof obj.version === 'string' ? obj.version.trim() : '';
88
+ if (name === '' || version === '') {
89
+ const missing = [...(name === '' ? ['name'] : []), ...(version === '' ? ['version'] : [])].join(' and ');
90
+ throw new PartsError([{ code: 'RUN_STAMP_PACKAGE', object: pkgPath, detail: `missing non-empty string ${missing}; both "name" and "version" are required to write run.json` }]);
91
+ }
92
+ return { name, version };
93
+ }
94
+
95
+ /** The exact relative output paths `rigStage` writes under `--out`, derived from its returned `RigOutput`. */
96
+ export function rigOutputFiles(rig: RigOutput): string[] {
97
+ return sortCodeUnits([
98
+ 'rig.json',
99
+ 'motion.json',
100
+ 'mesh_report.json',
101
+ ...(rig.depthReferences === undefined ? [] : ['depth_sheets.json']),
102
+ ...(rig.sets === undefined ? [] : [SETS_FILE]),
103
+ ...(rig.layout === undefined ? [] : [LAYOUT_FILE]),
104
+ ...rig.images.map(([file]) => `images/${file}`),
105
+ ]);
106
+ }
107
+
108
+ function writtenAllocationReports(outDir: string): string[] {
109
+ const allocationPath = join(outDir, 'rig', PAINTING_ALLOCATION_FILE);
110
+ if (!existsSync(allocationPath)) return [];
111
+ try {
112
+ const parsed: unknown = JSON.parse(readFileSync(allocationPath, 'utf8'));
113
+ if (
114
+ parsed !== null &&
115
+ typeof parsed === 'object' &&
116
+ 'written_reports' in parsed &&
117
+ Array.isArray(parsed.written_reports)
118
+ ) {
119
+ return parsed.written_reports
120
+ .filter((f): f is string => typeof f === 'string' && f.startsWith('painting_allocation.') && f.endsWith('.json') && basename(f) === f)
121
+ .map((f) => `rig/${f}`);
122
+ }
123
+ } catch {
124
+ return [];
125
+ }
126
+ return [];
127
+ }
128
+
129
+ /** The exact relative output paths `assembleStage` writes under `--out`, derived from its returned `AssembleResult`. */
130
+ export function assembleOutputFiles(outDir: string, result: AssembleResult): string[] {
131
+ return sortCodeUnits([
132
+ 'rig/parts.json',
133
+ `rig/${PAINTING_IN_RIG_FILE}`,
134
+ `rig/${SOURCE_COVER_FILE}`,
135
+ `rig/${SUPPORT_DOMAINS_FILE}`,
136
+ ...(result.stageMap === undefined ? [] : [`rig/${STAGE_MAP_FILE}`]),
137
+ ...(result.edgeResiduals === undefined ? [] : [`rig/${EDGE_RESIDUAL_FILE}`]),
138
+ ...(result.paintingEdges?.allocation === undefined ? [] : [`rig/${PAINTING_ALLOCATION_FILE}`, ...writtenAllocationReports(outDir)]),
139
+ ...(existsSync(join(outDir, 'rig', CUT_MATERIAL_SOURCES)) ? [`rig/${CUT_MATERIAL_SOURCES}`] : []),
140
+ ...result.parts.parts.flatMap((p) => [`rig/parts/${p.name}.png`, ...(p.depth === undefined ? [] : [`rig/parts/${p.depth.image}`])]),
141
+ ...(result.parts.alternates ?? []).flatMap((alt) =>
142
+ alt.records.flatMap((p) => [`rig/parts/${alt.name}_${p.name}.png`, ...(p.depth === undefined ? [] : [`rig/parts/${p.depth.image}`])]),
143
+ ),
144
+ 'render/recomposite_rig.png',
145
+ `render/${ERROR_MAP_FILE}`,
146
+ ...(result.figure === null ? [] : [`render/${FIGURE_MASK_FILE}`, `rig/${FIGURE_MASK_FILE}`]),
147
+ ]);
148
+ }
149
+
150
+ /**
151
+ * Build a `rig-run/1` run stamp from the files actually written by the stage under `outDir`
152
+ * and the config file on disk, using the caller-supplied package metadata and
153
+ * UTC ISO-8601 timestamps. Pure with respect to the clock: no time is read here.
154
+ */
155
+ export function buildRunStamp(input: RunStampInput): RunStamp {
156
+ const relPaths = sortCodeUnits(input.outputPaths);
157
+ const outputs: RunStampFileEntry[] = relPaths.map((rel) => ({
158
+ path: rel,
159
+ sha256: sha256OnDisk(join(input.outDir, ...rel.split('/'))),
160
+ }));
161
+ return {
162
+ spec: RUN_STAMP_SPEC,
163
+ package: {
164
+ name: input.pkg.name,
165
+ version: input.pkg.version,
166
+ },
167
+ command: input.command,
168
+ started_at: input.startedAt,
169
+ finished_at: input.finishedAt,
170
+ config: {
171
+ path: relativeToOutRoot(input.outDir, input.configPath),
172
+ sha256: sha256OnDisk(input.configPath),
173
+ },
174
+ outputs,
175
+ };
176
+ }
177
+
178
+ /**
179
+ * Format and write `<outDir>/run.json` (`spec: "rig-run/1"`). Called by the CLI
180
+ * only after the command's gate and output writes have succeeded.
181
+ */
182
+ export function writeRunStamp(input: RunStampInput): RunStamp {
183
+ const stamp = buildRunStamp(input);
184
+ writeFileSync(join(input.outDir, RUN_STAMP_FILE), rigJsonText(stamp));
185
+ return stamp;
186
+ }
package/src/scene.ts CHANGED
@@ -91,6 +91,7 @@
91
91
  * clock, no randomness, no network, no child process. The rigc gate and the
92
92
  * check are run by {@link composeStage} through an injected `RigcRunner`.
93
93
  */
94
+ import { createHash } from 'node:crypto';
94
95
  import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
95
96
  import { dirname, join, resolve } from 'node:path';
96
97
  import type { RigStop } from '@rig-c/core/rig';
@@ -849,7 +850,8 @@ export interface SceneReport {
849
850
  canvas: { width: number; height: number };
850
851
  rig_name: string;
851
852
  pack_mode: { page_edges: string; pack_shape: string };
852
- plate: { image: string; provenance: Provenance; note: string | null; bone: string; slot: string; size: [number, number]; judged_by: 'nothing' } | null;
853
+ /** `sha256` (issue #1183) is of the plate PNG's bytes as compose read them, so a verdict can bind to them. */
854
+ plate: { image: string; provenance: Provenance; note: string | null; bone: string; slot: string; size: [number, number]; sha256: string; judged_by: 'nothing' } | null;
853
855
  characters: SceneCharacterReport[];
854
856
  order: { declared: string[]; slots: string[]; judged_by: 'nothing' };
855
857
  idle_duration: number;
@@ -1239,7 +1241,7 @@ export function composeScene(
1239
1241
  canvas: { ...canvas },
1240
1242
  rig_name: name,
1241
1243
  pack_mode: { page_edges: mode.pageEdges, pack_shape: mode.packShape },
1242
- plate: scene.plate === null || plate === null ? null : { image: scene.plate.image, provenance: scene.plate.provenance, note: scene.plate.note, bone: PLATE, slot: PLATE, size: [plate.width, plate.height], judged_by: 'nothing' },
1244
+ plate: scene.plate === null || plate === null ? null : { image: scene.plate.image, provenance: scene.plate.provenance, note: scene.plate.note, bone: PLATE, slot: PLATE, size: [plate.width, plate.height], sha256: createHash('sha256').update(plate.bytes).digest('hex'), judged_by: 'nothing' },
1243
1245
  characters: rows,
1244
1246
  order: { declared: [...scene.order], slots: slots.map((s) => s.name), judged_by: 'nothing' },
1245
1247
  idle_duration: durations[0],
@@ -1,10 +1,10 @@
1
1
  /** Optional source-bound independent assembly domains (#998). */
2
2
  import { createHash } from 'node:crypto';
3
3
  import { existsSync, readFileSync, writeFileSync } from 'node:fs';
4
- import { dirname, join } from 'node:path';
4
+ import { basename, dirname, join } from 'node:path';
5
5
  import { SUPPORT_GRID_CODE, type SupportDomain, type SupportDomainReading } from './coincide.ts';
6
6
  import { refuseIfAny } from './errors.ts';
7
- import type { PartsFile } from './parts.ts';
7
+ import { partImageReference, type PartsFile } from './parts.ts';
8
8
 
9
9
  export const SUPPORT_DOMAINS_FILE = 'part_support_domains.json';
10
10
  const SPEC = 'rig-parts-support-domains/1';
@@ -37,7 +37,7 @@ export function writeSupportDomains(partsPath: string, partsDir: string, parts:
37
37
  });
38
38
  writeFileSync(join(dirname(partsPath), SUPPORT_DOMAINS_FILE), JSON.stringify({
39
39
  spec: SPEC, grid: parts.rig_size, declarations_sha256: sha(declarations), parts_sha256: sha(readFileSync(partsPath)),
40
- images: parts.parts.map(p => ({ part: p.name, sha256: sha(readFileSync(join(partsDir, `${p.name}.png`))) })),
40
+ images: parts.parts.map(p => ({ part: p.name, sha256: sha(readFileSync(join(partsDir, basename(partImageReference(p).path)))) })),
41
41
  domains_sha256: sha(JSON.stringify(entries)), domains: entries,
42
42
  }, null, 2) + '\n');
43
43
  }
@@ -56,7 +56,7 @@ export function readSupportDomains(partsPath: string, partsDir: string, parts: P
56
56
  if (!digest(raw.declarations_sha256) || raw.parts_sha256 !== sha(readFileSync(partsPath)) || !Array.isArray(raw.images) || raw.images.length !== parts.parts.length || !Array.isArray(raw.domains) || raw.domains.length !== parts.parts.length || raw.domains_sha256 !== sha(JSON.stringify(raw.domains))) return unavailable('independent support sidecar does not bind these parts or its domain payload');
57
57
  for (let i = 0; i < parts.parts.length; i++) {
58
58
  const binding: unknown = raw.images[i], part = parts.parts[i];
59
- if (!object(binding) || binding.part !== part.name || binding.sha256 !== sha(readFileSync(join(partsDir, `${part.name}.png`)))) return unavailable(`independent support sidecar PNG binding differs for "${part.name}"`);
59
+ if (!object(binding) || binding.part !== part.name || binding.sha256 !== sha(readFileSync(join(partsDir, basename(partImageReference(part).path))))) return unavailable(`independent support sidecar PNG binding differs for "${part.name}"`);
60
60
  }
61
61
  const domains: SupportDomainReading[] = [];
62
62
  for (let i = 0; i < parts.parts.length; i++) {