rig-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/parts-view.ts CHANGED
@@ -16,7 +16,7 @@
16
16
  * is relative to the verdict file's directory. rig-c/create recomputes it, so the definition is fixed here.
17
17
  */
18
18
  import {differencePixels,assertOriginalPaintingSize} from './parts-comparison.ts';
19
- import {parsePartsComment,assertPartsCommentBinding,type PartsComment} from './parts-comment.ts';
19
+ import {parsePartsIssue,assertPartsIssueBinding,type PartsComment,type PartsIssue} from './parts-comment.ts';
20
20
  import {preparePartsComment,validateStoredPartsComment} from './parts-comment-crops.ts';
21
21
  import {resolvedCropPath} from './comment-crops.ts';
22
22
  import { createHash } from 'node:crypto';
@@ -27,13 +27,15 @@ import { PNG } from 'pngjs';
27
27
  import { loadReview, safeFile, packagePath, type ReviewPackage } from './manifest.ts';
28
28
  import { destinationDirectory } from './destination-directory.ts';
29
29
 
30
- export const PARTS_VERDICT_SCHEMA = 'rig-review-parts-verdict/2';
31
- const NAMED_VERDICT_SCHEMA = 'rig-review-parts-verdict/3';
30
+ export const PARTS_VERDICT_SCHEMA = 'rig-review-parts-verdict/4';
31
+ const LEGACY_VERDICT_SCHEMAS = ['rig-review-parts-verdict/1', 'rig-review-parts-verdict/2', 'rig-review-parts-verdict/3'] as const;
32
+ export type LegacyVerdictSchema = typeof LEGACY_VERDICT_SCHEMAS[number];
32
33
  export const PARTS_VERDICT_FILE = 'parts-review.json';
33
34
  export const PARTS_NOTE_LIMIT = 10000;
34
35
  export type PartsViewMode = 'parts' | 'atlas';
35
36
  export type PartOutcome = 'pending' | 'clean' | 'flagged';
36
- export type VerdictStatus = 'pending' | 'approved' | 'changes-requested';
37
+ export type VerdictStatus = 'approved' | 'changes-requested';
38
+ export type LegacyVerdictStatus = 'pending' | 'approved' | 'changes-requested';
37
39
 
38
40
  /** One file the verdict rests on: `path` relative to the verdict file's directory, POSIX separators. */
39
41
  export interface HashedFile { path: string; bytes: number; sha256: string }
@@ -43,6 +45,7 @@ interface LocalFile { abs: string; bytes: number; sha256: string }
43
45
  export interface PartMesh { vertices: number[]; triangles: number[]; figures: Record<string, unknown>; width: number; height: number; image: string }
44
46
  export interface ViewItem {
45
47
  mesh?: PartMesh;
48
+ meshUnavailable?: 'PARTS_MESH_GENERATED';
46
49
  name: string;
47
50
  /** Draw order, back first (parts mode); the region's place in the atlas file (atlas mode). */
48
51
  index: number;
@@ -88,7 +91,7 @@ export interface PartsViewPackage {
88
91
  pagePaths: string[];
89
92
  }
90
93
 
91
- export interface PartsViewOptions { rig?: string; meshReport?: string; check?: string; verdict?: string;painting?:string }
94
+ export interface PartsViewOptions { rig?: string; meshReport?: string; check?: string; verdict?: string; painting?: string; paintingRoot?: string }
92
95
 
93
96
  const record = (v: unknown): Record<string, unknown> | null => v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null;
94
97
  const finite = (v: unknown, min: number): v is number => typeof v === 'number' && Number.isFinite(v) && v >= min;
@@ -277,8 +280,16 @@ export function readPartMeshes(raw: unknown, items: ViewItem[], reports: unknown
277
280
  if (a?.type !== 'mesh') continue;
278
281
  const item = byName.get(name);
279
282
  if (!item) refuse('PARTS_MESH_UNKNOWN_PART', `${name}: found mesh; required a part in parts.json`);
280
- if (item!.mesh) refuse('PARTS_MESH_AMBIGUOUS', `${name}: found multiple meshes; required one attachment`);
283
+ if (item!.mesh || item!.meshUnavailable) refuse('PARTS_MESH_AMBIGUOUS', `${name}: found multiple meshes; required one attachment`);
281
284
  if (!finite(a.width, 1) || !Number.isInteger(a.width) || !finite(a.height, 1) || !Number.isInteger(a.height) || typeof a.image !== 'string') refuse('PARTS_MESH_SIZE', `${name}: found invalid raster declaration; required image and positive integer dimensions`);
285
+ if (Object.hasOwn(a, 'generator')) {
286
+ if (!record(a.generator) || Object.hasOwn(a, 'uvs')) refuse('PARTS_MESH_UV', `${name}: found invalid uvs; required nonempty coordinate pairs in [0,1]`);
287
+ if (Object.hasOwn(a, 'triangles')) refuse('PARTS_MESH_TRIANGLE', `${name}: found invalid triangles; required nonempty index triples`);
288
+ const rows = Array.isArray(reports) ? reports.filter(r => record(r)?.part === name) : [];
289
+ if (rows.length > 1) refuse('PARTS_MESH_REPORT_AMBIGUOUS', `${name}: found ${rows.length} report rows; required at most one`);
290
+ item!.meshUnavailable = 'PARTS_MESH_GENERATED';
291
+ continue;
292
+ }
282
293
  const uv = a.uvs, triangles = a.triangles;
283
294
  if (!Array.isArray(uv) || !uv.length || uv.length % 2) refuse('PARTS_MESH_UV', `${name}: found invalid uvs; required nonempty coordinate pairs in [0,1]`);
284
295
  for (const v of uv as unknown[]) if (!finite(v, 0) || v > 1) refuse('PARTS_MESH_UV', `${name}: found ${String(v)}; required UV in [0,1]`);
@@ -374,7 +385,12 @@ async function loadPartsMode(root: string, options: PartsViewOptions): Promise<P
374
385
  let painting:PartsViewPackage['painting'];if(options.painting){
375
386
  // Both paths are physical: a user-designated alias to an inside file is valid,
376
387
  // while a link reaching outside is refused before any painting bytes are read.
377
- let abs:string,bytes:Buffer;try{abs=await insideRoot(root,resolve(options.painting),'PARTS_PAINTING_OUTSIDE','painting');packagePath(relative(root,abs).split(sep).join('/'),'painting');bytes=await readFile(abs);}catch(error){if(error instanceof Error&&error.message.startsWith('PARTS_PAINTING_OUTSIDE:'))throw error;refuse('PARTS_PAINTING_UNAVAILABLE','painting must be a readable portable package PNG');}
388
+ let abs:string,bytes:Buffer;try{
389
+ const paintingRoot = options.paintingRoot !== undefined ? await realpath(resolve(options.paintingRoot)) : root;
390
+ abs = await insideRoot(paintingRoot, resolve(options.painting), 'PARTS_PAINTING_OUTSIDE', 'painting');
391
+ packagePath(relative(paintingRoot, abs).split(sep).join('/'), 'painting');
392
+ bytes = await readFile(abs);
393
+ }catch(error){if(error instanceof Error&&error.message.startsWith('PARTS_PAINTING_OUTSIDE:'))throw error;refuse('PARTS_PAINTING_UNAVAILABLE','painting must be a readable portable package PNG');}
378
394
  let png:PNG;try{png=PNG.sync.read(bytes!);}catch{refuse('PARTS_PAINTING_PNG','painting must be a valid PNG');}
379
395
  assertOriginalPaintingSize(png!.width,png!.height,rigSize,doc.scale_rig_per_source);
380
396
  const file={abs:abs!,bytes:bytes!.length,sha256:createHash('sha256').update(bytes!).digest('hex')};painting={...file,width:png!.width,height:png!.height};files.push(file);
@@ -490,55 +506,255 @@ export interface PartsVerdict {
490
506
  tool: { name: '@rig-c/review'; version: string };
491
507
  source: ReturnType<typeof verdictSource>;
492
508
  status: VerdictStatus;
493
- parts: Record<string, { outcome: PartOutcome; note: string; flags: string[]; mesh?: { outcome: PartOutcome; note: string } }>;
494
- comments: PartsComment[];
509
+ issues: PartsIssue[];
495
510
  updatedAt: string;
511
+ by?: string;
496
512
  }
497
513
 
498
- /** What the page submits: the status and every item's outcome and note. */
499
- export interface VerdictSubmission { status: VerdictStatus; parts: Record<string, { outcome: PartOutcome; note?: string }> }
514
+ export interface LegacyPartsVerdictView {
515
+ schema: LegacyVerdictSchema;
516
+ status: LegacyVerdictStatus;
517
+ readOnly: true;
518
+ code: 'PARTS_VERDICT_LEGACY_FORMAT';
519
+ flaggedCount: number;
520
+ flaggedParts: { name: string; note: string }[];
521
+ issues: PartsIssue[];
522
+ by?: string;
523
+ }
524
+
525
+ export interface LegacyPartsVerdictRecord {
526
+ schema: LegacyVerdictSchema;
527
+ mode: PartsViewMode;
528
+ tool: { name: '@rig-c/review'; version: string };
529
+ source: ReturnType<typeof verdictSource>;
530
+ status: LegacyVerdictStatus;
531
+ parts: Record<string, { outcome: PartOutcome; note: string; flags: string[]; mesh?: { outcome: PartOutcome; note: string; flags: string[] } }>;
532
+ comments?: import('./parts-comment.ts').PartsComment[];
533
+ issues: PartsIssue[];
534
+ updatedAt: string;
535
+ by?: string;
536
+ }
537
+
538
+ /** What the page submits: the status and pointed issues. */
539
+ export interface VerdictSubmission { status: VerdictStatus; issues: PartsIssue[] }
500
540
 
501
541
  /** The distinct names, in item order (atlas sequence frames share a name). */
502
542
  export const itemNames = (pkg: Pick<PartsViewPackage, 'items'>): string[] => [...new Set(pkg.items.map(i => i.name))];
503
543
 
504
544
  /** Builds the verdict document, or refuses by name. Pure but for the clock. */
505
- export function buildVerdict(pkg: Pick<PartsViewPackage, 'mode' | 'items' | 'flags' | 'files' | 'flagFiles' | 'verdictPath' | 'imagePaths' | 'painting' | 'paintingInRig'>, input: unknown, version: string, now = new Date()): PartsVerdict {
545
+ export function buildVerdict(
546
+ pkg: Pick<PartsViewPackage, 'mode' | 'items' | 'flags' | 'files' | 'flagFiles' | 'verdictPath' | 'imagePaths' | 'painting' | 'paintingInRig'>,
547
+ input: unknown,
548
+ version: string,
549
+ now = new Date(),
550
+ by?: string,
551
+ ): PartsVerdict {
506
552
  const body = record(input);
507
- if (!body) return refuse('PARTS_VERDICT_INVALID', 'expected { status, parts }');
553
+ if (!body || body.parts !== undefined || body.comments !== undefined) {
554
+ return refuse('PARTS_VERDICT_INVALID', 'expected { status, issues }');
555
+ }
508
556
  const status = body.status;
509
- if (status !== 'pending' && status !== 'approved' && status !== 'changes-requested') return refuse('PARTS_VERDICT_INVALID', 'status is pending, approved or changes-requested');
510
- const given = record(body.parts);
511
- if (!given) return refuse('PARTS_VERDICT_INVALID', 'parts is an object keyed by part name');
512
- const names = itemNames(pkg), known = new Set(names);
513
- for (const name of Object.keys(given)) if (!known.has(name)) refuse('PARTS_VERDICT_UNKNOWN_PART', `${name} is not a part of this input`);
514
- const parts: PartsVerdict['parts'] = {};
557
+ if (status !== 'approved' && status !== 'changes-requested') {
558
+ return refuse('PARTS_VERDICT_INVALID', 'status is approved or changes-requested');
559
+ }
560
+ const issues = body.issues;
561
+ if (!Array.isArray(issues) || issues.length > 1000) {
562
+ return refuse('PARTS_COMMENT_LIMIT', 'issues must be an array of at most 1000 entries');
563
+ }
564
+ if (status === 'approved' && issues.length > 0) {
565
+ return refuse('PARTS_VERDICT_NOT_CLEAN', `approved needs zero issues; ${issues.length} present`);
566
+ }
567
+ if (status === 'changes-requested' && issues.length === 0) {
568
+ return refuse('PARTS_VERDICT_NOTHING_FLAGGED', 'changes-requested needs at least one issue');
569
+ }
570
+ if (by !== undefined && (typeof by !== 'string' || !by.trim())) {
571
+ return refuse('PARTS_VERDICT_INVALID', 'reviewer name must be nonblank');
572
+ }
573
+ const itemMap = new Map(
574
+ pkg.items.map(i => [i.name, { ...i, imageHash: pkg.files.find(f => f.abs === pkg.imagePaths[i.index])?.sha256 ?? '' }]),
575
+ );
576
+ const sourceHash = verdictSource(pkg).sha256;
577
+ const ids = new Set<string>();
578
+ const parsedIssues: PartsIssue[] = [];
579
+ for (const raw of issues as unknown[]) {
580
+ const c = parsePartsIssue(raw, true, false);
581
+ if (c.view.comparison?.mode === 'overlay' && !pkg.painting) {
582
+ refuse('PARTS_COMPARISON_UNAVAILABLE', 'original painting required');
583
+ }
584
+ if (c.view.comparison?.mode === 'difference' && !pkg.paintingInRig) {
585
+ refuse('PARTS_DIFFERENCE_UNAVAILABLE', 'declared painting_in_rig required');
586
+ }
587
+ if (pkg.mode !== 'parts') {
588
+ refuse('PARTS_COMMENT_UNAVAILABLE', 'original part required');
589
+ }
590
+ if (ids.has(c.id)) {
591
+ refuse('PARTS_COMMENT_DUPLICATE', 'duplicate issue id');
592
+ }
593
+ ids.add(c.id);
594
+ assertPartsIssueBinding(c, itemMap, sourceHash);
595
+ parsedIssues.push(c);
596
+ }
597
+ return {
598
+ schema: PARTS_VERDICT_SCHEMA,
599
+ mode: pkg.mode,
600
+ tool: { name: '@rig-c/review', version },
601
+ source: verdictSource(pkg),
602
+ status,
603
+ issues: parsedIssues,
604
+ updatedAt: now.toISOString(),
605
+ ...(by !== undefined ? { by } : {}),
606
+ };
607
+ }
608
+
609
+ /** Decode-only reader for legacy /1, /2 and /3 files: /1 comments become /2 item issues; uncommented flagged rows and pending open read-only. */
610
+ async function decodeLegacyVerdict(
611
+ pkg: PartsViewPackage,
612
+ v: Record<string, unknown>,
613
+ version: string,
614
+ date: Date,
615
+ by: string | null,
616
+ ) {
617
+ const status = v.status;
618
+ if (status !== 'pending' && status !== 'approved' && status !== 'changes-requested') {
619
+ return refuse('PARTS_VERDICT_INVALID', 'status is pending, approved or changes-requested');
620
+ }
621
+ const given = record(v.parts);
622
+ if (!given) {
623
+ return refuse('PARTS_VERDICT_INVALID', 'parts is an object keyed by part name');
624
+ }
625
+ const names = itemNames(pkg);
626
+ const known = new Set(names);
627
+ for (const name of Object.keys(given)) {
628
+ if (!known.has(name)) {
629
+ return refuse('PARTS_VERDICT_UNKNOWN_PART', `${name} is not a part of this input`);
630
+ }
631
+ }
632
+ const parts: LegacyPartsVerdictRecord['parts'] = {};
515
633
  for (const name of names) {
516
634
  const entry = record(given[name]);
517
- if (!entry) return refuse('PARTS_VERDICT_MISSING_PART', `${name} has no entry`);
635
+ if (!entry) {
636
+ return refuse('PARTS_VERDICT_MISSING_PART', `${name} has no entry`);
637
+ }
518
638
  const outcome = entry.outcome;
519
- if (outcome !== 'pending' && outcome !== 'clean' && outcome !== 'flagged') return refuse('PARTS_VERDICT_INVALID', `${name}.outcome is pending, clean or flagged`);
639
+ if (outcome !== 'pending' && outcome !== 'clean' && outcome !== 'flagged') {
640
+ return refuse('PARTS_VERDICT_INVALID', `${name}.outcome is pending, clean or flagged`);
641
+ }
520
642
  const note = entry.note === undefined ? '' : entry.note;
521
- if (typeof note !== 'string' || note.length > PARTS_NOTE_LIMIT) return refuse('PARTS_VERDICT_INVALID', `${name}.note is a string of at most ${PARTS_NOTE_LIMIT} characters`);
522
- if (outcome === 'flagged' && !note.trim()) return refuse('PARTS_VERDICT_NOTE_REQUIRED', `${name} is flagged and has no note saying what is wrong`);
643
+ if (typeof note !== 'string' || note.length > PARTS_NOTE_LIMIT) {
644
+ return refuse('PARTS_VERDICT_INVALID', `${name}.note is a string of at most ${PARTS_NOTE_LIMIT} characters`);
645
+ }
646
+ if (outcome === 'flagged' && !note.trim()) {
647
+ return refuse('PARTS_VERDICT_NOTE_REQUIRED', `${name} is flagged and has no note saying what is wrong`);
648
+ }
649
+ const partFlags = Array.isArray(entry.flags) ? entry.flags.map(String) : [];
523
650
  const meshInput = record(entry.mesh);
524
651
  const hasMesh = pkg.items.some(i => i.name === name && i.mesh);
525
- if (!hasMesh && entry.mesh !== undefined) refuse('PARTS_MESH_OUTCOME_UNAVAILABLE', `${name}: no mesh; required no mesh outcome`);
526
- let mesh: { outcome: PartOutcome; note: string } | undefined;
652
+ if (!hasMesh && entry.mesh !== undefined) {
653
+ return refuse('PARTS_MESH_OUTCOME_UNAVAILABLE', `${name}: no mesh; required no mesh outcome`);
654
+ }
655
+ let mesh: { outcome: PartOutcome; note: string; flags: string[] } | undefined;
527
656
  if (hasMesh) {
528
- if (!meshInput || !['pending', 'clean', 'flagged'].includes(String(meshInput.outcome))) refuse('PARTS_MESH_OUTCOME', `${name}: required mesh outcome pending, clean or flagged`);
529
- const meshNote = meshInput!.note ?? '';
530
- if (typeof meshNote !== 'string' || meshNote.length > PARTS_NOTE_LIMIT) refuse('PARTS_MESH_OUTCOME', `${name}: required mesh note up to ${PARTS_NOTE_LIMIT} characters`);
531
- if (meshInput!.outcome === 'flagged' && !(meshNote as string).trim()) refuse('PARTS_VERDICT_NOTE_REQUIRED', `${name}.mesh is flagged and has no note`);
532
- mesh = { outcome: meshInput!.outcome as PartOutcome, note: meshNote as string };
657
+ if (!meshInput || !['pending', 'clean', 'flagged'].includes(String(meshInput.outcome))) {
658
+ return refuse('PARTS_MESH_OUTCOME', `${name}: required mesh outcome pending, clean or flagged`);
659
+ }
660
+ const meshNote = meshInput.note ?? '';
661
+ if (typeof meshNote !== 'string' || meshNote.length > PARTS_NOTE_LIMIT) {
662
+ return refuse('PARTS_MESH_OUTCOME', `${name}: required mesh note up to ${PARTS_NOTE_LIMIT} characters`);
663
+ }
664
+ if (meshInput.outcome === 'flagged' && !meshNote.trim()) {
665
+ return refuse('PARTS_VERDICT_NOTE_REQUIRED', `${name}.mesh is flagged and has no note`);
666
+ }
667
+ const meshFlags = Array.isArray(meshInput.flags) ? meshInput.flags.map(String) : [];
668
+ mesh = { outcome: meshInput.outcome as PartOutcome, note: meshNote, flags: meshFlags };
669
+ }
670
+ parts[name] = { ...(mesh ? { mesh } : {}), outcome, note, flags: partFlags };
671
+ }
672
+ const outcomes = Object.values(parts).flatMap(p => (p.mesh ? [p.outcome, p.mesh.outcome] : [p.outcome]));
673
+ if (status === 'approved' && outcomes.some(o => o !== 'clean')) {
674
+ return refuse('PARTS_VERDICT_NOT_CLEAN', 'approved needs every part clean');
675
+ }
676
+ if (status === 'changes-requested' && !outcomes.includes('flagged')) {
677
+ return refuse('PARTS_VERDICT_NOTHING_FLAGGED', 'changes-requested needs at least one flagged part');
678
+ }
679
+ const rawComments = v.schema === 'rig-review-parts-verdict/1' ? [] : (v.comments ?? []);
680
+ if (!Array.isArray(rawComments) || rawComments.length > 1000) {
681
+ return refuse('PARTS_COMMENT_LIMIT', 'comments must be an array of at most 1000 entries');
682
+ }
683
+ const ids = new Set<string>();
684
+ const issues: PartsIssue[] = [];
685
+ const legacyComments: import('./parts-comment.ts').PartsComment[] = [];
686
+ for (const raw of rawComments as unknown[]) {
687
+ const c = await validateStoredPartsComment(pkg, raw, true);
688
+ if (ids.has(c.id)) {
689
+ return refuse('PARTS_COMMENT_DUPLICATE', 'duplicate comment id');
533
690
  }
534
- parts[name] = { ...(mesh ? { mesh } : {}), outcome, note, flags: [...new Set(pkg.flags.filter(f => f.item === name).map(f => f.id))] };
691
+ ids.add(c.id);
692
+ issues.push(c);
693
+ const primary = c.parts[0]!;
694
+ const { mode: _mode, ...restView } = c.view;
695
+ legacyComments.push({
696
+ schema: 'rig-review-parts-comment/1',
697
+ id: c.id,
698
+ part: primary.name,
699
+ imageHash: primary.imageHash,
700
+ sourceHash: c.sourceHash,
701
+ summary: c.summary,
702
+ imageRegion: c.imageRegion!,
703
+ rigRegion: c.rigRegion,
704
+ crop: { ...c.crop, png: c.crop.png ?? '' },
705
+ nativeCrop: c.nativeCrop!,
706
+ view: restView,
707
+ });
708
+ }
709
+ const commentedParts = new Set(issues.flatMap(i => i.parts.map(p => p.name)));
710
+ const flaggedParts: { name: string; note: string }[] = [];
711
+ for (const name of names) {
712
+ const p = parts[name]!;
713
+ const pf = p.outcome === 'flagged';
714
+ const mf = p.mesh?.outcome === 'flagged';
715
+ if ((pf || mf) && !commentedParts.has(name)) {
716
+ flaggedParts.push({
717
+ name,
718
+ note: [pf ? p.note.trim() : '', mf ? p.mesh!.note.trim() : ''].filter(Boolean).join(' / '),
719
+ });
720
+ }
721
+ }
722
+ const legacyRecord: LegacyPartsVerdictRecord = {
723
+ schema: v.schema as LegacyVerdictSchema,
724
+ mode: pkg.mode,
725
+ tool: { name: '@rig-c/review', version },
726
+ source: verdictSource(pkg),
727
+ status,
728
+ parts,
729
+ ...(v.schema === 'rig-review-parts-verdict/1' ? {} : { comments: legacyComments }),
730
+ issues,
731
+ updatedAt: date.toISOString(),
732
+ ...(by ? { by } : {}),
733
+ };
734
+ if (flaggedParts.length > 0 || status === 'pending' || (status === 'approved') !== (issues.length === 0)) {
735
+ const legacy: LegacyPartsVerdictView = {
736
+ schema: v.schema as LegacyVerdictSchema,
737
+ status,
738
+ readOnly: true,
739
+ code: 'PARTS_VERDICT_LEGACY_FORMAT',
740
+ flaggedCount: flaggedParts.length,
741
+ flaggedParts,
742
+ issues,
743
+ ...(by ? { by } : {}),
744
+ };
745
+ return { verdict: null, legacy, legacyRecord };
535
746
  }
536
- const outcomes = Object.values(parts).flatMap(p => p.mesh ? [p.outcome, p.mesh.outcome] : [p.outcome]);
537
- if (status === 'approved' && outcomes.some(o => o !== 'clean')) refuse('PARTS_VERDICT_NOT_CLEAN', `approved needs every part clean; ${outcomes.filter(o => o !== 'clean').length} are not`);
538
- if (status === 'changes-requested' && !outcomes.includes('flagged')) refuse('PARTS_VERDICT_NOTHING_FLAGGED', 'changes-requested needs at least one flagged part');
539
- const comments=body.comments??[];if(!Array.isArray(comments)||comments.length>1000)refuse('PARTS_COMMENT_LIMIT','comments must be an array of at most 1000 entries');
540
- const ids=new Set<string>();for(const raw of comments as unknown[]){const c=parsePartsComment(raw);if(c.view.comparison?.mode==='overlay'&&!pkg.painting)refuse('PARTS_COMPARISON_UNAVAILABLE','original painting required');if(c.view.comparison?.mode==='difference'&&!pkg.paintingInRig)refuse('PARTS_DIFFERENCE_UNAVAILABLE','declared painting_in_rig required');const item=pkg.items.find(i=>i.name===c.part);if(!item||pkg.mode!=='parts')refuse('PARTS_COMMENT_UNAVAILABLE','original part required');if(ids.has(c.id))refuse('PARTS_COMMENT_DUPLICATE','duplicate comment id');ids.add(c.id);const file=pkg.files.find(f=>f.abs===pkg.imagePaths[item!.index]);assertPartsCommentBinding(c,item!,file?.sha256??'',verdictSource(pkg).sha256);}
541
- return { schema: PARTS_VERDICT_SCHEMA, mode: pkg.mode, tool: { name: '@rig-c/review', version }, source: verdictSource(pkg), status, parts, comments:comments as PartsComment[], updatedAt: now.toISOString() };
747
+ const verdict: PartsVerdict = {
748
+ schema: PARTS_VERDICT_SCHEMA,
749
+ mode: pkg.mode,
750
+ tool: { name: '@rig-c/review', version },
751
+ source: verdictSource(pkg),
752
+ status,
753
+ issues,
754
+ updatedAt: date.toISOString(),
755
+ ...(by ? { by } : {}),
756
+ };
757
+ return { verdict, legacy: null, legacyRecord };
542
758
  }
543
759
 
544
760
  /** Every file the package was loaded from still has the bytes it was loaded with. */
@@ -572,11 +788,10 @@ export async function saveVerdictWithReceipt(pkg: PartsViewPackage, input: unkno
572
788
  await assertVerdictDestination(pkg);
573
789
  await assertPartsUnchanged(pkg);
574
790
  await readVerdict(pkg); // Existing read-side evidence errors must never become an implicit reset.
575
- const verdict = buildVerdict(pkg, input, await packageVersion());
576
- for(const comment of verdict.comments)await preparePartsComment(pkg,comment,true);
791
+ const verdict = buildVerdict(pkg, input, await packageVersion(), new Date(), by);
792
+ for(const issue of verdict.issues)await preparePartsComment(pkg,issue,true);
577
793
  await assertPartsUnchanged(pkg);
578
- const stored = by === undefined ? verdict : {...verdict, schema: NAMED_VERDICT_SCHEMA, by};
579
- const bytes = Buffer.from(JSON.stringify(stored, null, 2) + '\n');
794
+ const bytes = Buffer.from(JSON.stringify(verdict, null, 2) + '\n');
580
795
  const parent = dirname(pkg.verdictPath);
581
796
  const firstCreated = await verdictWrite('mkdir', () => mkdir(parent, { recursive: true }));
582
797
  const tmp = `${pkg.verdictPath}.${crypto.randomUUID()}.tmp`;
@@ -618,53 +833,129 @@ export type VerdictStale = 'files' | 'flags' | null;
618
833
  * were not shown.
619
834
  */
620
835
  async function readVerdictSnapshot(pkg: PartsViewPackage): Promise<{
621
- verdict: PartsVerdict | null; stale: VerdictStale; by: string | null; savedFileSha256: string | null;
836
+ verdict: PartsVerdict | null;
837
+ stale: VerdictStale;
838
+ legacy: LegacyPartsVerdictView | null;
839
+ legacyRecord: LegacyPartsVerdictRecord | null;
840
+ by: string | null;
841
+ savedFileSha256: string | null;
622
842
  }> {
623
843
  let raw: unknown;
624
- const unavailable = {verdict: null, by: null, savedFileSha256: null};
844
+ const unavailable = { verdict: null, legacy: null, legacyRecord: null, by: null, savedFileSha256: null };
625
845
  let bytes: Buffer;
626
- try { bytes = await readFile(pkg.verdictPath); }
627
- catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {...unavailable, stale: null}; throw new Error('PARTS_VERDICT_READ: saved verdict cannot be read'); }
628
- try{raw=JSON.parse(bytes.toString('utf8'));}catch{throw new Error('PARTS_VERDICT_INVALID: saved verdict is not valid JSON');}
629
- const v = record(raw), source = record(v?.source), now = verdictSource(pkg);
630
- if(!v||![PARTS_VERDICT_SCHEMA,'rig-review-parts-verdict/1',NAMED_VERDICT_SCHEMA].includes(String(v.schema))||typeof source?.sha256!=='string')throw new Error('PARTS_VERDICT_INVALID: saved verdict schema or binding is invalid');
846
+ try {
847
+ bytes = await readFile(pkg.verdictPath);
848
+ } catch (error) {
849
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
850
+ return { ...unavailable, stale: null };
851
+ }
852
+ throw new Error('PARTS_VERDICT_READ: saved verdict cannot be read');
853
+ }
854
+ try {
855
+ raw = JSON.parse(bytes.toString('utf8'));
856
+ } catch {
857
+ throw new Error('PARTS_VERDICT_INVALID: saved verdict is not valid JSON');
858
+ }
859
+ const v = record(raw);
860
+ const source = record(v?.source);
861
+ const now = verdictSource(pkg);
862
+ const isLegacy = Boolean(v && (LEGACY_VERDICT_SCHEMAS as readonly string[]).includes(String(v.schema)));
863
+ if (!v || (v.schema !== PARTS_VERDICT_SCHEMA && !isLegacy) || typeof source?.sha256 !== 'string') {
864
+ throw new Error('PARTS_VERDICT_INVALID: saved verdict schema or binding is invalid');
865
+ }
631
866
  let by: string | null = null;
632
- if (v.schema === NAMED_VERDICT_SCHEMA) {
633
- if (typeof v.by !== 'string' || !v.by.trim()) refuse('PARTS_VERDICT_INVALID', 'saved reviewer name must be nonblank');
867
+ if (v.schema === 'rig-review-parts-verdict/3' || (v.schema === PARTS_VERDICT_SCHEMA && v.by !== undefined)) {
868
+ if (typeof v.by !== 'string' || !v.by.trim()) {
869
+ refuse('PARTS_VERDICT_INVALID', 'saved reviewer name must be nonblank');
870
+ }
634
871
  by = v.by as string;
635
872
  }
636
- if(v.mode!==pkg.mode||source.sha256!==now.sha256)return {...unavailable,stale:'files'};
637
- if (JSON.stringify(source.flags) !== JSON.stringify(now.flags)) return { ...unavailable, stale: 'flags' };
638
- const date=new Date(String(v.updatedAt));if(!Number.isFinite(date.getTime()))throw new Error('PARTS_VERDICT_INVALID: saved verdict date is invalid');
639
- const normalized=buildVerdict(pkg,{...v,comments:v.schema==='rig-review-parts-verdict/1'?[]:v.comments},String(record(v.tool)?.version??''),date);
640
- for(const c of normalized.comments)await validateStoredPartsComment(pkg,c);
641
- return {verdict:normalized,stale:null,by,savedFileSha256:createHash('sha256').update(bytes).digest('hex')};
873
+ if (v.mode !== pkg.mode || source.sha256 !== now.sha256) {
874
+ return { ...unavailable, stale: 'files' };
875
+ }
876
+ if (JSON.stringify(source.flags) !== JSON.stringify(now.flags)) {
877
+ return { ...unavailable, stale: 'flags' };
878
+ }
879
+ const date = new Date(String(v.updatedAt));
880
+ if (!Number.isFinite(date.getTime())) {
881
+ throw new Error('PARTS_VERDICT_INVALID: saved verdict date is invalid');
882
+ }
883
+ const savedFileSha256 = createHash('sha256').update(bytes).digest('hex');
884
+ const version = String(record(v.tool)?.version ?? '');
885
+ if (isLegacy) {
886
+ const decoded = await decodeLegacyVerdict(pkg, v, version, date, by);
887
+ return { ...decoded, stale: null, by, savedFileSha256 };
888
+ }
889
+ const normalized = buildVerdict(pkg, v, version, date, by ?? undefined);
890
+ for (const c of normalized.issues) {
891
+ await validateStoredPartsComment(pkg, c, false);
892
+ }
893
+ return { verdict: normalized, stale: null, legacy: null, legacyRecord: null, by, savedFileSha256 };
642
894
  }
643
895
 
644
896
  /** Explicitly project the shared response so retrieval metadata cannot escape through joined wrappers. */
645
- export async function readVerdict(pkg: PartsViewPackage): Promise<{verdict: PartsVerdict | null; stale: VerdictStale}> {
646
- const {verdict, stale} = await readVerdictSnapshot(pkg);
647
- return {verdict, stale};
897
+ export async function readVerdict(
898
+ pkg: PartsViewPackage,
899
+ ): Promise<{ verdict: PartsVerdict | null; stale: VerdictStale; legacy?: LegacyPartsVerdictView }> {
900
+ const { verdict, stale, legacy } = await readVerdictSnapshot(pkg);
901
+ return legacy ? { verdict, stale, legacy } : { verdict, stale };
902
+ }
903
+
904
+ /** Validated current or legacy verdict record for CLI read and correction projection paths. */
905
+ export async function readPartsVerdictForCli(
906
+ pkg: PartsViewPackage,
907
+ ): Promise<PartsVerdict | LegacyPartsVerdictRecord | null> {
908
+ const saved = await readVerdictSnapshot(pkg);
909
+ return saved.verdict ?? saved.legacyRecord;
648
910
  }
649
911
 
650
912
  /** Standalone CLI retrieval metadata and content come from one validated saved-file buffer. */
651
913
  export async function readPartsVerdictJson(pkg: PartsViewPackage): Promise<string> {
652
914
  const saved = await readVerdictSnapshot(pkg);
653
- if (!saved.verdict) refuse('PARTS_VERDICT_UNAVAILABLE', 'save a verdict first');
915
+ const target = saved.verdict ?? saved.legacyRecord;
916
+ if (!target) {
917
+ return refuse('PARTS_VERDICT_UNAVAILABLE', 'save a verdict first');
918
+ }
654
919
  await assertPartsUnchanged(pkg);
655
- return JSON.stringify({...JSON.parse(exportPartsVerdict(saved.verdict!, 'json')), by: saved.by, savedFileSha256: saved.savedFileSha256}, null, 2) + '\n';
920
+ return (
921
+ JSON.stringify(
922
+ {
923
+ ...JSON.parse(exportPartsVerdict(target, 'json')),
924
+ by: saved.by,
925
+ savedFileSha256: saved.savedFileSha256,
926
+ },
927
+ null,
928
+ 2,
929
+ ) + '\n'
930
+ );
656
931
  }
657
932
 
658
933
  /** What the page reads: no absolute path leaves the server but the verdict file's name. */
659
- export function partsViewJson(pkg: PartsViewPackage, saved: { verdict: PartsVerdict | null; stale: VerdictStale }) {
934
+ export function partsViewJson(
935
+ pkg: PartsViewPackage,
936
+ saved: { verdict: PartsVerdict | null; stale: VerdictStale; legacy?: LegacyPartsVerdictView | null },
937
+ ) {
660
938
  return {
661
- schema: 'rig-review-parts-view/1', mode: pkg.mode, title: pkg.title, rigSize: pkg.rigSize,
662
- differenceAvailable:!!pkg.paintingInRig,
663
- painting:pkg.painting?{sha256:pkg.painting.sha256,width:pkg.painting.width,height:pkg.painting.height}:null,
664
- sourceHash:verdictSource(pkg).sha256,
665
- items:pkg.items.map(item=>({...item,...(pkg.mode==='parts'?{imageHash:pkg.files.find(f=>f.abs===pkg.imagePaths[item.index])?.sha256}:{})})), pages: pkg.pages, flags: pkg.flags, readings: pkg.readings ?? [],
666
- flagSources: pkg.flagFiles.map(f => basename(f.abs)), flagMissing: pkg.flagNotes,
667
- verdictFile: basename(pkg.verdictPath), verdict: saved.verdict, verdictStale: saved.stale,
939
+ schema: 'rig-review-parts-view/1',
940
+ mode: pkg.mode,
941
+ title: pkg.title,
942
+ rigSize: pkg.rigSize,
943
+ differenceAvailable: !!pkg.paintingInRig,
944
+ painting: pkg.painting ? { sha256: pkg.painting.sha256, width: pkg.painting.width, height: pkg.painting.height } : null,
945
+ sourceHash: verdictSource(pkg).sha256,
946
+ items: pkg.items.map(item => ({
947
+ ...item,
948
+ ...(pkg.mode === 'parts' ? { imageHash: pkg.files.find(f => f.abs === pkg.imagePaths[item.index])?.sha256 } : {}),
949
+ })),
950
+ pages: pkg.pages,
951
+ flags: pkg.flags,
952
+ readings: pkg.readings ?? [],
953
+ flagSources: pkg.flagFiles.map(f => basename(f.abs)),
954
+ flagMissing: pkg.flagNotes,
955
+ verdictFile: basename(pkg.verdictPath),
956
+ verdict: saved.verdict,
957
+ verdictStale: saved.stale,
958
+ ...(saved.legacy ? { legacyVerdict: saved.legacy } : {}),
668
959
  };
669
960
  }
670
961
 
@@ -674,31 +965,136 @@ export function servedImage(pkg: PartsViewPackage, kind: 'image' | 'page', index
674
965
  return Number.isInteger(index) && index >= 0 && index < list.length ? list[index]! : null;
675
966
  }
676
967
 
677
-
678
968
  /** Both export forms preserve original text, native and rig coordinates and resolved evidence. */
679
- export function exportPartsVerdict(verdict:PartsVerdict,format:'json'|'issue'):string {
680
- const comments=verdict.comments.map(c=>{const {png,...crop}=c.crop;return {...c,crop:{...crop,path:resolvedCropPath(crop.path)},nativeCrop:c.nativeCrop?{...c.nativeCrop,path:resolvedCropPath(c.nativeCrop.path)}:null};});
681
- if(format==='json')return JSON.stringify({...verdict,comments},null,2)+'\n';
682
- return [`# Parts review`, `Source: ${verdict.source.sha256}`,`Status: ${verdict.status}`,...Object.entries(verdict.parts).flatMap(([name,p])=>[`\n## ${name}`,`${p.outcome}: ${p.note}`,...comments.filter(c=>c.part===name).flatMap(c=>[`\n### ${c.summary}`,`Part: ${c.part} · image SHA-256: ${c.imageHash}`,`Image region: ${JSON.stringify(c.imageRegion)}`,`Rig region: ${JSON.stringify(c.rigRegion)}`,`Viewport crop: ${c.crop.path} · SHA-256 ${c.crop.sha256}`,`Native crop: ${c.nativeCrop!.path} · SHA-256 ${c.nativeCrop!.sha256}`,`View: ${JSON.stringify(c.view)}`])])].join('\n')+'\n';
969
+ export function exportPartsVerdict(
970
+ verdict: PartsVerdict | LegacyPartsVerdictRecord,
971
+ format: 'json' | 'issue',
972
+ ): string {
973
+ const issues = verdict.issues.map(c => {
974
+ const { png, ...crop } = c.crop;
975
+ return {
976
+ ...c,
977
+ crop: { ...crop, path: resolvedCropPath(crop.path) },
978
+ nativeCrop: c.nativeCrop ? { ...c.nativeCrop, path: resolvedCropPath(c.nativeCrop.path) } : null,
979
+ };
980
+ });
981
+ const comments =
982
+ 'comments' in verdict && Array.isArray(verdict.comments)
983
+ ? verdict.comments.map(c => {
984
+ const { png, ...crop } = c.crop;
985
+ return {
986
+ ...c,
987
+ crop: { ...crop, path: resolvedCropPath(crop.path) },
988
+ nativeCrop: { ...c.nativeCrop!, path: resolvedCropPath(c.nativeCrop!.path) },
989
+ };
990
+ })
991
+ : undefined;
992
+ if (format === 'json') {
993
+ return (
994
+ JSON.stringify(
995
+ {
996
+ ...verdict,
997
+ issues,
998
+ ...(comments !== undefined ? { comments } : {}),
999
+ },
1000
+ null,
1001
+ 2,
1002
+ ) + '\n'
1003
+ );
1004
+ }
1005
+ const commentedParts = new Set(issues.flatMap(i => i.parts.map(p => p.name)));
1006
+ const bareFlaggedLines =
1007
+ 'parts' in verdict && verdict.parts
1008
+ ? Object.entries(verdict.parts).flatMap(([name, p]) => {
1009
+ const pf = p.outcome === 'flagged';
1010
+ const mf = p.mesh?.outcome === 'flagged';
1011
+ if ((!pf && !mf) || commentedParts.has(name)) {
1012
+ return [];
1013
+ }
1014
+ const note = [pf ? p.note.trim() : '', mf ? p.mesh!.note.trim() : ''].filter(Boolean).join(' / ');
1015
+ return [`\n## ${name}`, note];
1016
+ })
1017
+ : [];
1018
+ return (
1019
+ [
1020
+ `# Parts review`,
1021
+ `Source: ${verdict.source.sha256}`,
1022
+ `Status: ${verdict.status}`,
1023
+ ...bareFlaggedLines,
1024
+ ...issues.flatMap(c => [
1025
+ `\n## ${c.parts.map(p => p.name).join(', ')}`,
1026
+ `\n### ${c.summary}`,
1027
+ `Part: ${c.parts.map(p => `${p.name} · image SHA-256: ${p.imageHash}`).join(', ')}`,
1028
+ `Image region: ${JSON.stringify(c.imageRegion)}`,
1029
+ `Rig region: ${JSON.stringify(c.rigRegion)}`,
1030
+ `Viewport crop: ${c.crop.path} · SHA-256 ${c.crop.sha256}`,
1031
+ ...(c.nativeCrop ? [`Native crop: ${c.nativeCrop.path} · SHA-256 ${c.nativeCrop.sha256}`] : []),
1032
+ `View: ${JSON.stringify(c.view)}`,
1033
+ ]),
1034
+ ].join('\n') + '\n'
1035
+ );
683
1036
  }
684
1037
 
685
1038
  /** Numeric comparison is decoded from bound original PNG bytes on the server, never browser pixels. */
686
- export async function partsDifference(pkg:PartsViewPackage,index:number,threshold:number,footprints:boolean){
687
- await assertPartsUnchanged(pkg);
688
- if(!pkg.paintingInRig)refuse('PARTS_DIFFERENCE_UNAVAILABLE','declared painting_in_rig required; legacy records remain readable');
689
- const item=pkg.items[index];if(pkg.mode!=='parts'||!Number.isInteger(index)||!item)refuse('PARTS_DIFFERENCE_UNAVAILABLE','known original part required');
690
- const decode=async(path:string)=>{const bytes=await readFile(path);if(bytes[24]!==8||bytes[25]!==6)refuse('PARTS_DIFFERENCE_PNG','exact RGBA8 operands required');return PNG.sync.read(bytes);};
691
- const painting=await decode(pkg.paintingInRig!.abs),part=await decode(pkg.imagePaths[index]!);
692
- const fronts=footprints?await Promise.all(pkg.items.filter(f=>f.index>index&&f.x<item!.x+item!.w&&f.x+f.w>item!.x&&f.y<item!.y+item!.h&&f.y+f.h>item!.y).map(async box=>({box,raster:await decode(pkg.imagePaths[box.index]!)}))):[];
693
- const result=differencePixels(part,item!,painting,fronts,threshold,footprints);
694
- await assertPartsUnchanged(pkg);return result;
1039
+ export async function partsDifference(pkg: PartsViewPackage, index: number, threshold: number, footprints: boolean) {
1040
+ await assertPartsUnchanged(pkg);
1041
+ if (!pkg.paintingInRig) {
1042
+ refuse('PARTS_DIFFERENCE_UNAVAILABLE', 'declared painting_in_rig required; legacy records remain readable');
1043
+ }
1044
+ const item = pkg.items[index];
1045
+ if (pkg.mode !== 'parts' || !Number.isInteger(index) || !item) {
1046
+ refuse('PARTS_DIFFERENCE_UNAVAILABLE', 'known original part required');
1047
+ }
1048
+ const decode = async (path: string) => {
1049
+ const bytes = await readFile(path);
1050
+ if (bytes[24] !== 8 || bytes[25] !== 6) {
1051
+ refuse('PARTS_DIFFERENCE_PNG', 'exact RGBA8 operands required');
1052
+ }
1053
+ return PNG.sync.read(bytes);
1054
+ };
1055
+ const painting = await decode(pkg.paintingInRig!.abs);
1056
+ const part = await decode(pkg.imagePaths[index]!);
1057
+ const fronts = footprints
1058
+ ? await Promise.all(
1059
+ pkg.items
1060
+ .filter(
1061
+ f =>
1062
+ f.index > index &&
1063
+ f.x < item!.x + item!.w &&
1064
+ f.x + f.w > item!.x &&
1065
+ f.y < item!.y + item!.h &&
1066
+ f.y + f.h > item!.y,
1067
+ )
1068
+ .map(async box => ({ box, raster: await decode(pkg.imagePaths[box.index]!) })),
1069
+ )
1070
+ : [];
1071
+ const result = differencePixels(part, item!, painting, fronts, threshold, footprints);
1072
+ await assertPartsUnchanged(pkg);
1073
+ return result;
695
1074
  }
696
1075
 
697
1076
  /** Selected JSON keeps the canonical verdict and names the user's handoff selection. */
698
- export function exportPartsCorrection(verdict:PartsVerdict, correction:ReturnType<typeof import('./correction-handoff.ts').projectPartsDescription>):string {
699
- return JSON.stringify({...verdict,correction:{
700
- path:'described',stage:correction.stage,itemId:correction.itemId,part:correction.part,
701
- verbatim:correction.verbatim,selectorArgs:correction.on,outcome:null,
702
- ...('imageHash' in correction?{imageHash:correction.imageHash}:{}),
703
- }},null,2)+'\n';
1077
+ export function exportPartsCorrection(
1078
+ verdict: PartsVerdict | LegacyPartsVerdictRecord,
1079
+ correction: ReturnType<typeof import('./correction-handoff.ts').projectPartsDescription>,
1080
+ ): string {
1081
+ return (
1082
+ JSON.stringify(
1083
+ {
1084
+ ...verdict,
1085
+ correction: {
1086
+ path: 'described',
1087
+ stage: correction.stage,
1088
+ itemId: correction.itemId,
1089
+ part: correction.part,
1090
+ verbatim: correction.verbatim,
1091
+ selectorArgs: correction.on,
1092
+ outcome: null,
1093
+ ...('imageHash' in correction ? { imageHash: correction.imageHash } : {}),
1094
+ },
1095
+ },
1096
+ null,
1097
+ 2,
1098
+ ) + '\n'
1099
+ );
704
1100
  }