@rig-c/review 2.7.1 → 2.9.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/job-source.ts CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  JOB_PARTS_ENUMERATOR_RANGE,
9
9
  } from './job-contract.ts';
10
10
  import type {
11
- JobFileIdentity, JobImageSetInput, JobModelSourceBinding, JobPartsEnumerator, JobPartsFileReference, JobPartsIdentity, JobPlanIdentity, JobPublishRequest,
11
+ JobFileIdentity, JobImageSetInput, JobInterviewDiagnostics, JobInterviewRecord, JobModelSourceBinding, JobPartsEnumerator, JobPartsFileReference, JobPartsIdentity, JobPlanIdentity, JobPublishRequest,
12
12
  JobSelector, JobSourceBinding, JobSubject,
13
13
  OptionContext, OptionSource, PackageResultV3, PlanContext, PlanSource, ProjectRecord, PublishRequestV3,
14
14
  RecordFreeze, RecordOptionResult, RecordPlanResult, RecordPublicationReader, RecordPublishedContext,
@@ -30,6 +30,7 @@ import {
30
30
  jobPath,
31
31
  jobSha,
32
32
  jobText,
33
+ parseJobInterviewDiagnostics,
33
34
  parseRecordFreeze,
34
35
  parseRecordPublishedContext,
35
36
  parseRecordResult,
@@ -82,6 +83,7 @@ export interface JobRetainedSource {
82
83
  readonly visual: { readonly status: 'available' } | { readonly status: 'unavailable'; readonly code: string };
83
84
  readonly subjects: readonly JobSubject[];
84
85
  readonly questions: readonly InterviewQuestion[];
86
+ readonly interview?: JobInterviewDiagnostics | null;
85
87
  readonly partIds: readonly string[];
86
88
  }
87
89
 
@@ -100,6 +102,7 @@ export interface JobRetainedRecordSource {
100
102
  readonly visual: { readonly status: 'unavailable'; readonly code: 'MODEL_UNAVAILABLE' };
101
103
  readonly subjects: readonly RecordSubject[];
102
104
  readonly questions: readonly InterviewQuestion[];
105
+ readonly interview?: undefined;
103
106
  readonly partIds: readonly [];
104
107
  readonly context: RecordPublishedContext;
105
108
  }
@@ -335,22 +338,52 @@ async function prepareParts(root: string, snapshotRoot: string, claimed: JobPart
335
338
  return {identity: {enumeratorVersion: version, manifest: {path: manifestPath, sha256: jobHash(manifestBytes)}, images}, bytes};
336
339
  }
337
340
 
338
- function collectQuestionFiles(root: string, questions: readonly InterviewQuestion[]): JobFileIdentity[] {
339
- const result: JobFileIdentity[] = [];
340
- function visit(value: unknown): void {
341
- if (Array.isArray(value)) { value.forEach(visit); return; }
341
+ function collectQuestionFiles(
342
+ root: string,
343
+ questions: readonly InterviewQuestion[],
344
+ records: readonly JobInterviewRecord[] = [],
345
+ ): { readonly required: JobFileIdentity[]; readonly optional: JobFileIdentity[] } {
346
+ const required: JobFileIdentity[] = [];
347
+ const optional: JobFileIdentity[] = [];
348
+ function visit(value: unknown, isOptional: boolean): void {
349
+ if (Array.isArray(value)) { value.forEach(item => visit(item, isOptional)); return; }
342
350
  if (value === null || typeof value !== 'object') return;
343
351
  const entry = value as Record<string, unknown>;
344
352
  if (typeof entry.path === 'string' && typeof entry.sha256 === 'string') {
345
- result.push({ path: jobPath(entry.path), sha256: jobSha(entry.sha256) });
353
+ if (!isOptional) {
354
+ required.push({ path: jobPath(entry.path), sha256: jobSha(entry.sha256) });
355
+ } else {
356
+ try {
357
+ const path = jobPath(entry.path);
358
+ const sha256 = jobSha(entry.sha256);
359
+ if (jobHash(sourceBytes(root, path)) === sha256) {
360
+ optional.push({ path, sha256 });
361
+ }
362
+ } catch {
363
+ // Historical non-editable context file is missing or changed; its stale diagnostic is already recorded.
364
+ }
365
+ }
346
366
  }
347
- Object.values(entry).forEach(visit);
367
+ Object.values(entry).forEach(item => visit(item, isOptional));
348
368
  }
349
369
  for (const question of questions) {
350
- result.push(question.ref, ...question.images.map(image => image.ref));
351
- visit(JSON.parse(sourceBytes(root, question.ref.path).toString('utf8')));
370
+ required.push(question.ref, ...question.images.map(image => image.ref));
371
+ visit(JSON.parse(sourceBytes(root, question.ref.path).toString('utf8')), !question.editable);
352
372
  }
353
- return result;
373
+ for (const row of records) {
374
+ if (row.observedSet) {
375
+ try {
376
+ const path = jobPath(row.observedSet.path);
377
+ const sha256 = jobSha(row.observedSet.sha256);
378
+ if (jobHash(sourceBytes(root, path)) === sha256) {
379
+ optional.push({ path, sha256 });
380
+ }
381
+ } catch {
382
+ // Unreadable or non-retained option set stays unsealed.
383
+ }
384
+ }
385
+ }
386
+ return { required, optional };
354
387
  }
355
388
 
356
389
  function isOptionIdentifier(value: unknown): value is string {
@@ -590,6 +623,7 @@ async function readRecordPublishedPhase(
590
623
  readRecordPublished: RecordPublicationReader,
591
624
  input: RecordReaderInput,
592
625
  phase: 'publish' | 'ask' | 'finalize',
626
+ assertCurrentBeforeGenericRefusal?: () => void,
593
627
  ): Promise<RecordPublishedContext> {
594
628
  let raw: unknown;
595
629
  try {
@@ -609,6 +643,9 @@ async function readRecordPublishedPhase(
609
643
  ...(input.parts !== undefined ? { parts: input.parts } : {}),
610
644
  });
611
645
  } catch (error) {
646
+ if (extractReaderToken(error) === null) {
647
+ assertCurrentBeforeGenericRefusal?.();
648
+ }
612
649
  throw mapRecordReaderError(error, phase);
613
650
  }
614
651
  return parseRecordPublishedContext(raw, input.result, input.record);
@@ -816,7 +853,9 @@ export async function prepareJobRecordSource(options: {
816
853
  options.readRecordPublished,
817
854
  { root: root.path, record, result, phase: 'inventory' },
818
855
  'publish',
856
+ () => assertRecord(root, record),
819
857
  );
858
+ assertRecord(root, record);
820
859
  if (inventory.files.length > maxSourceFiles) {
821
860
  throw new JobError('JOB_SOURCE_UNRETAINABLE');
822
861
  }
@@ -859,12 +898,15 @@ export async function prepareJobRecordSource(options: {
859
898
  }
860
899
  options.afterDirectorySync?.(directory);
861
900
  }
901
+ assertJobSourceCurrent({ root, record, seals });
862
902
  assertRetainedSnapshotIntact(snapshotRoot, seals, snapshotIdentity, 'JOB_SOURCE_UNRETAINABLE');
863
903
  const retainedContext = await readRecordPublishedPhase(
864
904
  options.readRecordPublished,
865
905
  { root: snapshotRoot, record, result, phase: 'retained', parts: inventory.parts },
866
906
  'publish',
907
+ () => assertJobSourceCurrent({ root, record, seals }),
867
908
  );
909
+ assertJobSourceCurrent({ root, record, seals });
868
910
  assertRetainedSnapshotIntact(snapshotRoot, seals, snapshotIdentity, 'JOB_SOURCE_UNRETAINABLE');
869
911
  assertEqualRecordContexts(inventory, retainedContext);
870
912
  const decoded = decodeRetainedRecordProject(snapshotRoot, seals, result, retainedContext);
@@ -936,7 +978,9 @@ export async function verifyJobRecordSourceFresh(options: {
936
978
  options.readRecordPublished,
937
979
  { root: retained.root.path, record: retained.record, result: retained.result, phase: 'inventory' },
938
980
  phase,
981
+ () => assertJobSourceCurrent(retained),
939
982
  );
983
+ assertJobSourceCurrent(retained);
940
984
  if (requestDigest(inventory.parts) !== requestDigest(retained.context.parts)) {
941
985
  throw new JobError(phase === 'finalize' ? 'JOB_ACT_SOURCE_STALE' : 'JOB_SOURCE_MISMATCH');
942
986
  }
@@ -956,7 +1000,9 @@ export async function verifyJobRecordSourceFresh(options: {
956
1000
  parts: retained.context.parts,
957
1001
  },
958
1002
  phase,
1003
+ () => assertJobSourceCurrent(retained),
959
1004
  );
1005
+ assertJobSourceCurrent(retained);
960
1006
  assertRetainedSnapshotIntact(
961
1007
  retained.snapshotRoot,
962
1008
  retained.seals,
@@ -1105,9 +1151,6 @@ export async function prepareJobSource(options: {
1105
1151
  catch { throw new JobError('JOB_RECORD_INCOMPLETE'); }
1106
1152
  if (record.path === 'project.json') {
1107
1153
  project = readProject(root.path);
1108
- // #555 owns API@2 diagnostic carriage. Refuse before publication lookup
1109
- // or snapshot writes when this reader's retained records need it.
1110
- if (project.sceneAnswers || project.diagnostics.length) throw new JobError('JOB_RECORD_INCOMPLETE');
1111
1154
  }
1112
1155
  } else {
1113
1156
  try { lstatSync(join(root.path, 'project.json')); throw new JobError('JOB_FREEZE_REQUIRED'); }
@@ -1143,7 +1186,15 @@ export async function prepareJobSource(options: {
1143
1186
  add(rootRelative(root.path, review.handoff.source), review.handoff.record.source.sha256);
1144
1187
  }
1145
1188
  if (record) add(record.path, record.sha256);
1146
- for (const file of [...declared, ...collectQuestionFiles(root.path, project?.questions ?? [])]) add(file.path, file.sha256);
1189
+ const questionFiles = collectQuestionFiles(
1190
+ root.path,
1191
+ project?.questions ?? [],
1192
+ project?.interview.records ?? [],
1193
+ );
1194
+ for (const file of [...declared, ...questionFiles.required]) add(file.path, file.sha256);
1195
+ for (const file of questionFiles.optional) {
1196
+ if (!wanted.has(file.path)) add(file.path, file.sha256);
1197
+ }
1147
1198
  if (wanted.size > maxSourceFiles) throw new JobError('JOB_SOURCE_UNRETAINABLE');
1148
1199
  const snapshotRoot = join(options.stateRoot, 'snapshots', randomUUID());
1149
1200
  const seals: JobFileIdentity[] = [];
@@ -1213,6 +1264,22 @@ export async function prepareJobSource(options: {
1213
1264
  packageSourceHash: modelSource.sourceHash, record, imageSet: imageSet.imageSet}))};
1214
1265
  }
1215
1266
  const boundReview = { ...review, sourceHash: source.sourceHash };
1267
+ const sealedByPath = new Map(seals.map(seal => [seal.path, seal.sha256]));
1268
+ const retainedInterview = project
1269
+ ? parseJobInterviewDiagnostics(
1270
+ {
1271
+ ...project.interview,
1272
+ records: project.interview.records.map(row => ({
1273
+ ...row,
1274
+ observedSet:
1275
+ row.observedSet && sealedByPath.get(row.observedSet.path) === row.observedSet.sha256
1276
+ ? row.observedSet
1277
+ : null,
1278
+ })),
1279
+ },
1280
+ 'JOB_RECORD_INCOMPLETE',
1281
+ ) ?? null
1282
+ : null;
1216
1283
  const prepared: JobRetainedSource = {
1217
1284
  root, record, seals, snapshotRoot, snapshotIdentity,
1218
1285
  manifestPath: retained.manifestPath,
@@ -1224,9 +1291,14 @@ export async function prepareJobSource(options: {
1224
1291
  { status: 'unavailable', code: 'MODEL_UNAVAILABLE' },
1225
1292
  subjects: context.subjects,
1226
1293
  questions: (project?.questions ?? []).map(question => {
1227
- const { answer, ...fields } = question;
1228
- return answer === undefined ? fields : question;
1294
+ const { answer, partsUnavailable, ...fields } = question;
1295
+ return {
1296
+ ...fields,
1297
+ ...(partsUnavailable === undefined ? {} : { partsUnavailable }),
1298
+ ...(answer === undefined ? {} : { answer: JSON.parse(JSON.stringify(answer)) as Record<string, unknown> }),
1299
+ };
1229
1300
  }),
1301
+ interview: retainedInterview,
1230
1302
  partIds: context.partIds,
1231
1303
  };
1232
1304
  await options.afterSnapshot?.();
package/src/manifest.ts CHANGED
@@ -9,6 +9,8 @@ import { readFile, realpath, stat, lstat, readdir } from 'node:fs/promises';
9
9
  import { createReadStream } from 'node:fs';
10
10
  import { basename, dirname, isAbsolute, relative, resolve, posix } from 'node:path';
11
11
  import { isBuildRoot, parseHandoffDeclaration, resolveHandoff, type Handoff, type HandoffDeclaration, type HandoffFlags, type HandoffRecord } from './handoff.ts';
12
+ import { parsePanelComposition, type JobPanelComposition } from './job-contract.ts';
13
+ export { isPanelComponent, parsePanelComposition } from './job-contract.ts';
12
14
 
13
15
  export type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
14
16
  export interface Reference { id: string; label: string; type: 'image' | 'video' | 'pose'; path: string; width?: number; height?: number }
@@ -22,6 +24,7 @@ export interface ReviewManifest {
22
24
  audio: { clips: { id: string; label?: string; path: string }[]; cues: { id: string; clip: string; time: number; animation?: string }[] };
23
25
  /** Optional producer handoff (#101): package-relative literal paths; checked when the package loads. */
24
26
  producer?: HandoffDeclaration;
27
+ panels?: JobPanelComposition;
25
28
  }
26
29
  export interface ReviewedSource { readonly packageRevision:string; readonly viewerVersion:string; readonly runtimeVersion:string; readonly rig:{readonly path:string;readonly sha256:string}|null; readonly motion:{readonly path:string;readonly sha256:string}|null; readonly handoff?:HandoffRecord }
27
30
  export interface ReviewPackage { direction?:DirectionInspection; setsHash?:string; referenceHashes?:Record<string,string>; root: string; manifestPath: string; manifest: ReviewManifest; sourceHash: string; reviewedSource:ReviewedSource; files: Set<string>; report:ReportSeeds|null; feedbackCatalog:FeedbackCatalog;
@@ -64,6 +67,11 @@ export async function safeFile(root: string, path: string): Promise<string> {
64
67
  export function parseManifest(input: unknown): ReviewManifest {
65
68
  const m = object(input, 'review'); if (m.schema !== 'rig-review/1') fail('schema', 'rig-review/1');
66
69
  const audio = m.audio === undefined ? {} : object(m.audio, 'audio');
70
+ let panels: JobPanelComposition | undefined;
71
+ if (m.panels !== undefined) {
72
+ try { panels = parsePanelComposition(m.panels); }
73
+ catch { panels = undefined; }
74
+ }
67
75
  const manifest: ReviewManifest = {
68
76
  schema: 'rig-review/1', id: id(m.id, 'id'), title: string(m.title, 'title'), revision: string(m.revision, 'revision'),
69
77
  model: m.model === undefined ? undefined : packagePath(m.model, 'model'),
@@ -76,6 +84,7 @@ export function parseManifest(input: unknown): ReviewManifest {
76
84
  authoring:list(m.authoring,'authoring',(v,f)=>({label:string(v.label,f+'.label'),path:packagePath(v.path,f+'.path')})),
77
85
  axes:list(m.axes,'axes',(v,f)=>({id:id(v.id,f+'.id'),label:string(v.label,f+'.label'),animation:string(v.animation,f+'.animation'),min:number(v.min,f+'.min',-Number.MAX_VALUE),max:number(v.max,f+'.max',-Number.MAX_VALUE)})),
78
86
  ...(m.producer===undefined?{}:{producer:parseHandoffDeclaration(m.producer)}),
87
+ ...(panels===undefined?{}:{panels}),
79
88
  audio:{clips:list(audio.clips,'audio.clips',(v,f)=>({id:id(v.id,f+'.id'),label:optionalString(v.label,f+'.label'),path:packagePath(v.path,f+'.path')})),cues:list(audio.cues,'audio.cues',(v,f)=>({id:id(v.id,f+'.id'),clip:string(v.clip,f+'.clip'),time:number(v.time,f+'.time'),animation:optionalString(v.animation,f+'.animation')}))}
80
89
  };
81
90
  if(manifest.model&&!manifest.model.endsWith('.model.json'))fail('model','compiled model path ending .model.json (the play runtime input)');
@@ -2,7 +2,7 @@ import {spawn} from 'node:child_process';
2
2
  import {randomUUID} from 'node:crypto';
3
3
  import {open, readFile, unlink} from 'node:fs/promises';
4
4
  import {join} from 'node:path';
5
- import {appRoot} from './build.ts';
5
+ import {appRoot, playBuildConditions} from './build.ts';
6
6
  import {frontPort} from './front.ts';
7
7
  import {acquireClaim, defaultStateDir, openFingerprint, prepareOpenTarget, readOpenStatus, releaseClaim,
8
8
  type OpenInputs, type OpenOptions} from './open.ts';
@@ -61,7 +61,7 @@ export async function openWorkspace(inputs: readonly OpenInputs[], options: Open
61
61
  const logPath = join(directory, nonce + '.log');
62
62
  const log = await open(logPath, 'a', 0o600);
63
63
  try {
64
- child = spawn(process.execPath, [join(appRoot, 'src/open-workspace-worker.ts'), request],
64
+ child = spawn(process.execPath, [...playBuildConditions().map(c => `--conditions=${c}`), join(appRoot, 'src/open-workspace-worker.ts'), request],
65
65
  {cwd: directory, detached: true, stdio: ['ignore', log.fd, log.fd], env: process.env});
66
66
  child.unref();
67
67
  } finally {await log.close();}
package/src/open.ts CHANGED
@@ -16,6 +16,7 @@ import {startCompareServer} from './compare-server.ts';
16
16
  import {selectAnimation,AnimationSelectionError,type AnimationSelection} from './animation-selection.ts';
17
17
  import {capabilityHeader,capabilityPattern,type OpenIdentity} from './open-protocol.ts';
18
18
  import {ensureFront,frontPort} from './front.ts';
19
+ import {playBuildConditions} from './build.ts';
19
20
  import {playPackagePath} from './versions.ts';
20
21
  import {HandoffError,HANDOFF_FLAGS,isBuildRoot,type HandoffFlags,type HandoffRecord} from './handoff.ts';
21
22
  import {stateDirInside,stateRoots} from './state-dir.ts';
@@ -160,7 +161,7 @@ async function ensureWorker(p:OpenPackage,key:string,fingerprint:string,stateDir
160
161
  const row=await reuse();if(row)return {row,reused:true};
161
162
  const identity:OpenIdentity={key,contentHash:p.contentHash,nonce,fingerprint};request=join(canonicalControl,`${key}.${nonce}.request.json`);const log=join(canonicalControl,`${key}.${nonce}.log`);
162
163
  const spec:WorkerRequest={schema:'rig-review-open-request/1',inputs:p.inputs,identity,stateDir,registry,request,idleMs,...(graceMs!==undefined?{graceMs}:{}),cwd,...(viewOnly?{viewOnly:true}:{}),...(p.inputs.control?{controlToken:randomUUID()}:{} )};await writeFile(request,JSON.stringify(spec),{mode:0o600,flag:'wx'});
163
- const logHandle=await openFile(log,'a',0o600);let child;try{child=spawn(process.execPath,[join(appRoot,'src/open-worker.ts'),request],{cwd:canonicalControl,detached:true,stdio:['ignore',logHandle.fd,logHandle.fd],env:process.env});spawned=child;child.unref();}finally{await logHandle.close();}
164
+ const logHandle=await openFile(log,'a',0o600);let child;try{child=spawn(process.execPath,[...playBuildConditions().map(c=>`--conditions=${c}`),join(appRoot,'src/open-worker.ts'),request],{cwd:canonicalControl,detached:true,stdio:['ignore',logHandle.fd,logHandle.fd],env:process.env});spawned=child;child.unref();}finally{await logHandle.close();}
164
165
  let exited:string|undefined;child.on('error',error=>{exited=error.message;});child.on('exit',(code,signal)=>{exited=`exit ${code} ${signal??''}`;});
165
166
  while(performance.now()<deadline){const record=await reuse();if(record){handedOff=true;return {row:record,reused:false};}if(exited)throw new Error(`OPEN_START: ${exited}; worker log ${log}`);await sleep(30);}throw new Error(`OPEN_TIMEOUT: worker did not become ready; log ${log}`);
166
167
  }finally{if(spawned&&!handedOff&&spawned.exitCode===null&&spawned.signalCode===null)spawned.kill('SIGTERM');await releaseClaim(claim,nonce);if(request)await unlink(request).catch(e=>{if(e.code!=='ENOENT')throw e;});}
@@ -1,33 +1,128 @@
1
1
  /** Native evidence is cut from the bound original PNG, never from a displayed alpha mask. */
2
- import {createHash} from 'node:crypto';
3
- import {readFile} from 'node:fs/promises';
4
- import {PNG} from 'pngjs';
5
- import {parsePartsComment,assertPartsCommentBinding,type PartsComment} from './parts-comment.ts';
6
- import {validatePngCrop,storePngCrop,readPngCrop} from './comment-crops.ts';
7
- import {assertPartsUnchanged,partsDifference,verdictSource,type PartsViewPackage} from './parts-view.ts';
8
- export async function preparePartsComment(pkg:PartsViewPackage,raw:unknown,requireNative=false):Promise<PartsComment>{return resolvePartsComment(pkg,raw,requireNative,true);}
9
- export async function validateStoredPartsComment(pkg:PartsViewPackage,raw:unknown):Promise<PartsComment>{return resolvePartsComment(pkg,raw,true,false);}
10
- async function resolvePartsComment(pkg:PartsViewPackage,raw:unknown,requireNative:boolean,persist:boolean):Promise<PartsComment>{
11
- const c=parsePartsComment(raw,requireNative),item=pkg.items.find(i=>i.name===c.part);
12
- if(pkg.mode!=='parts'||!item)throw new Error('PARTS_COMMENT_UNAVAILABLE: original part image required');
13
- const path=pkg.imagePaths[item.index],file=pkg.files.find(f=>f.abs===path);if(!path||!file)throw new Error('PARTS_COMMENT_UNAVAILABLE: bound original PNG required');
14
- assertPartsCommentBinding(c,item,file.sha256,verdictSource(pkg).sha256);
15
- if(c.view.comparison?.mode==='overlay'&&!pkg.painting)throw new Error('PARTS_COMPARISON_UNAVAILABLE: original painting required');
16
- if(c.view.comparison?.mode==='difference')await partsDifference(pkg,item.index,c.view.comparison.threshold,c.view.footprints);
17
- const bytes=await readFile(path);if(createHash('sha256').update(bytes).digest('hex')!==file.sha256)throw new Error('PARTS_COMMENT_STALE_SOURCE: original PNG changed');
18
- await assertPartsUnchanged(pkg);
19
- validatePngCrop(c.crop);
20
- const original=PNG.sync.read(bytes),r=c.imageRegion;
21
- if(original.width!==item.w||original.height!==item.h)throw new Error('PARTS_COMMENT_IMAGE_SIZE: original dimensions differ from placement');
22
- if(r.width*r.height>16777216)throw new Error('PARTS_COMMENT_CROP_LIMIT: native crop exceeds 16 million pixels');
23
- const native=new PNG({width:r.width,height:r.height});for(let y=0;y<r.height;y++)original.data.copy(native.data,y*r.width*4,((r.y+y)*original.width+r.x)*4,((r.y+y)*original.width+r.x+r.width)*4);
24
- if(requireNative){
25
- const stored=await readPngCrop(c.nativeCrop!),decoded=PNG.sync.read(stored);
26
- if(decoded.width!==r.width||decoded.height!==r.height||!decoded.data.equals(native.data))throw new Error('PARTS_COMMENT_NATIVE_CROP_TAMPERED: native crop differs from bound original');
27
- if(persist)await storePngCrop(c.crop);else await readPngCrop(c.crop);
28
- return c;
29
- }
30
- const png=PNG.sync.write(native),sha256=createHash('sha256').update(png).digest('hex'),nativeCrop={path:`comment-crops/${sha256}.png`,sha256,width:r.width,height:r.height};
31
- await storePngCrop(c.crop);await storePngCrop({...nativeCrop,png:'data:image/png;base64,'+png.toString('base64')});
32
- return {...c,nativeCrop};
2
+ import { createHash } from 'node:crypto';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { PNG } from 'pngjs';
5
+ import { parsePartsIssue, assertPartsIssueBinding, type PartsIssue } from './parts-comment.ts';
6
+ import { validatePngCrop, storePngCrop, readPngCrop, type PngCrop } from './comment-crops.ts';
7
+ import { assertPartsUnchanged, partsDifference, verdictSource, type PartsViewPackage } from './parts-view.ts';
8
+
9
+ export interface PartsCommentBindingOptions {
10
+ readonly sourceHash?: string;
11
+ }
12
+
13
+ export async function preparePartsComment(
14
+ pkg: PartsViewPackage,
15
+ raw: unknown,
16
+ requireNative = false,
17
+ options?: PartsCommentBindingOptions,
18
+ ): Promise<PartsIssue> {
19
+ return resolvePartsComment(pkg, raw, requireNative, true, false, options);
20
+ }
21
+
22
+ export async function validateStoredPartsComment(
23
+ pkg: PartsViewPackage,
24
+ raw: unknown,
25
+ allowLegacy = false,
26
+ options?: PartsCommentBindingOptions,
27
+ ): Promise<PartsIssue> {
28
+ return resolvePartsComment(pkg, raw, true, false, allowLegacy, options);
29
+ }
30
+
31
+ async function resolvePartsComment(
32
+ pkg: PartsViewPackage,
33
+ raw: unknown,
34
+ requireNative: boolean,
35
+ persist: boolean,
36
+ allowLegacy = false,
37
+ options?: PartsCommentBindingOptions,
38
+ ): Promise<PartsIssue> {
39
+ const c = parsePartsIssue(raw, requireNative, allowLegacy, persist && !requireNative);
40
+ if (pkg.mode !== 'parts') {
41
+ throw new Error('PARTS_COMMENT_UNAVAILABLE: original part image required');
42
+ }
43
+ const itemMap = new Map<
44
+ string,
45
+ { name: string; index: number; x: number; y: number; w: number; h: number; imageHash: string; path: string }
46
+ >();
47
+ for (const item of pkg.items) {
48
+ const path = pkg.imagePaths[item.index];
49
+ const file = path ? pkg.files.find(f => f.abs === path) : undefined;
50
+ if (!path || !file) {
51
+ throw new Error('PARTS_COMMENT_UNAVAILABLE: bound original PNG required');
52
+ }
53
+ itemMap.set(item.name, { ...item, imageHash: file.sha256, path });
54
+ }
55
+ const expectedSourceHash = options?.sourceHash ?? verdictSource(pkg).sha256;
56
+ assertPartsIssueBinding(c, itemMap, expectedSourceHash);
57
+ if (c.view.comparison?.mode === 'overlay' && !pkg.painting) {
58
+ throw new Error('PARTS_COMPARISON_UNAVAILABLE: original painting required');
59
+ }
60
+ if (c.view.comparison?.mode === 'difference') {
61
+ for (const part of c.parts) {
62
+ const item = itemMap.get(part.name)!;
63
+ await partsDifference(pkg, item.index, c.view.comparison.threshold, c.view.footprints);
64
+ }
65
+ }
66
+ const partBuffers = new Map<string, Buffer>();
67
+ for (const part of c.parts) {
68
+ const item = itemMap.get(part.name)!;
69
+ const bytes = await readFile(item.path);
70
+ if (createHash('sha256').update(bytes).digest('hex') !== item.imageHash) {
71
+ throw new Error('PARTS_COMMENT_STALE_SOURCE: original PNG changed');
72
+ }
73
+ partBuffers.set(part.name, bytes);
74
+ }
75
+ await assertPartsUnchanged(pkg);
76
+ if (c.crop.png !== undefined) {
77
+ validatePngCrop(c.crop as PngCrop);
78
+ }
79
+ if (c.view.mode !== 'item') {
80
+ if (persist && c.crop.png !== undefined) {
81
+ await storePngCrop(c.crop as PngCrop);
82
+ } else {
83
+ await readPngCrop(c.crop);
84
+ }
85
+ await assertPartsUnchanged(pkg);
86
+ return { ...c, nativeCrop: null };
87
+ }
88
+ const primary = itemMap.get(c.parts[0]!.name)!;
89
+ const r = c.imageRegion!;
90
+ if (r.width * r.height > 16777216) {
91
+ throw new Error('PARTS_COMMENT_CROP_LIMIT: native crop exceeds 16 million pixels');
92
+ }
93
+ const bytes = partBuffers.get(primary.name)!;
94
+ const original = PNG.sync.read(bytes);
95
+ if (original.width !== primary.w || original.height !== primary.h) {
96
+ throw new Error('PARTS_COMMENT_IMAGE_SIZE: original dimensions differ from placement');
97
+ }
98
+ const native = new PNG({ width: r.width, height: r.height });
99
+ for (let y = 0; y < r.height; y++) {
100
+ original.data.copy(
101
+ native.data,
102
+ y * r.width * 4,
103
+ ((r.y + y) * original.width + r.x) * 4,
104
+ ((r.y + y) * original.width + r.x + r.width) * 4,
105
+ );
106
+ }
107
+ if (requireNative) {
108
+ const stored = await readPngCrop(c.nativeCrop!);
109
+ const decoded = PNG.sync.read(stored);
110
+ if (decoded.width !== r.width || decoded.height !== r.height || !decoded.data.equals(native.data)) {
111
+ throw new Error('PARTS_COMMENT_NATIVE_CROP_TAMPERED: native crop differs from bound original');
112
+ }
113
+ if (persist && c.crop.png !== undefined) {
114
+ await storePngCrop(c.crop as PngCrop);
115
+ } else {
116
+ await readPngCrop(c.crop);
117
+ }
118
+ await assertPartsUnchanged(pkg);
119
+ return c;
120
+ }
121
+ const png = PNG.sync.write(native);
122
+ const sha256 = createHash('sha256').update(png).digest('hex');
123
+ const nativeCrop = { path: `comment-crops/${sha256}.png`, sha256, width: r.width, height: r.height };
124
+ await storePngCrop(c.crop as PngCrop);
125
+ await storePngCrop({ ...nativeCrop, png: 'data:image/png;base64,' + png.toString('base64') });
126
+ await assertPartsUnchanged(pkg);
127
+ return { ...c, nativeCrop };
33
128
  }