rig-review 1.8.0 → 1.10.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.
@@ -1,11 +1,12 @@
1
1
  /** Serves the parts and atlas view (#348): the page, its bundle, the part and page images by index, and the sign-off. */
2
+ import { PNG } from 'pngjs';
2
3
  import { readFile } from 'node:fs/promises';
3
4
  import { appRoot, buildWeb } from './build.ts';
4
5
  import { accessGate } from './open-protocol.ts';
5
6
  import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
6
7
  import {preparePartsComment} from './parts-comment-crops.ts';
7
8
  import {serveReference} from './reference.ts';
8
- import { partsViewJson, exportPartsVerdict, assertPartsUnchanged, readVerdict, saveVerdict, servedImage, type PartsViewPackage } from './parts-view.ts';
9
+ import { partsDifference, partsViewJson, exportPartsVerdict, assertPartsUnchanged, readVerdict, saveVerdict, servedImage, type PartsViewPackage } from './parts-view.ts';
9
10
 
10
11
  const headers = { 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" };
11
12
  const json = (value: unknown, status = 200) => Response.json(value, { status, headers });
@@ -56,13 +57,21 @@ export async function startPartsServer(pkg: PartsViewPackage, options: PartsServ
56
57
  try {
57
58
  if (url.pathname === '/api/parts' && req.method === 'GET'){await assertPartsUnchanged(pkg);return json(partsViewJson(pkg,await readVerdict(pkg)));}
58
59
  if(url.pathname==='/api/parts/comment'&&req.method==='POST'){if(req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);await assertPartsUnchanged(pkg);return json({comment:await preparePartsComment(pkg,await bodyJson(req))});}
59
- if(url.pathname==='/api/parts/export'&&req.method==='GET'){const saved=await readVerdict(pkg);if(!saved.verdict)return json({error:'PARTS_VERDICT_UNAVAILABLE: save a verdict first'},409);return new Response(exportPartsVerdict(saved.verdict,url.searchParams.get('format')==='issue'?'issue':'json'),{headers:{...headers,'Content-Type':url.searchParams.get('format')==='issue'?'text/markdown':'application/json'}});}
60
+ if(url.pathname==='/api/parts/export'&&req.method==='GET'){await assertPartsUnchanged(pkg);const saved=await readVerdict(pkg);if(!saved.verdict)return json({error:'PARTS_VERDICT_UNAVAILABLE: save a verdict first'},409);return new Response(exportPartsVerdict(saved.verdict,url.searchParams.get('format')==='issue'?'issue':'json'),{headers:{...headers,'Content-Type':url.searchParams.get('format')==='issue'?'text/markdown':'application/json'}});}
60
61
  if (url.pathname === '/api/parts/verdict' && req.method === 'POST') {
61
62
  if (req.headers.get('origin') !== origin) return json({ error: 'Same-origin Origin required' }, 403);
62
63
  saving = true;
63
64
  try { return json({ verdict: await saveVerdict(pkg, await bodyJson(req)) }); } finally { saving = false; }
64
65
  }
65
66
  if(url.pathname==='/api/parts/painting'&&req.method==='GET'){if(!pkg.painting)return json({error:'PARTS_REFERENCE_UNAVAILABLE: supply --painting to compare the original painting'},404);return serveReference(req,pkg.painting.abs,pkg.painting.sha256,headers);}
67
+ const difference=/^\/api\/parts\/difference\/(\d+)$/.exec(url.pathname);
68
+ if(difference&&req.method==='GET'){
69
+ const t=url.searchParams.get('threshold'),f=url.searchParams.get('footprints');
70
+ if(!t||!/^\d{1,3}$/.test(t)||!['true','false'].includes(f??''))throw new Error('PARTS_COMPARISON_INVALID: threshold and footprints required');
71
+ const r=await partsDifference(pkg,Number(difference[1]),Number(t),f==='true');
72
+ const png=new PNG({width:r.width,height:r.height});png.data=Buffer.from(r.data);
73
+ return new Response(new Uint8Array(PNG.sync.write(png)),{headers:{...headers,'Content-Type':'image/png','X-Difference-Count':String(r.count),'X-Difference-Covered':String(r.covered),'X-Difference-Compared':String(r.compared)}});
74
+ }
66
75
  const image = /^\/api\/parts\/(image|page)\/(\d+)$/.exec(url.pathname);
67
76
  if (image && (req.method === 'GET' || req.method === 'HEAD')) {
68
77
  const path = servedImage(pkg, image[1] as 'image' | 'page', Number(image[2]));
package/src/parts-view.ts CHANGED
@@ -8,13 +8,14 @@
8
8
  *
9
9
  * Producer flags are read from the files rig-parts writes and shown on their part; nothing is re-measured here:
10
10
  * - `mesh_report.json` rows: `contour.bridges.faint[]` (rig-parts #326), each a faint island the mesh left out;
11
- * - `check.json`: a gate whose `status` is FAIL or WARN, `seam_pairs` and `figure_openings`, on every part they name.
11
+ * - `check.json`: read-only row metadata drives display counts; the historical FAIL/WARN extraction below
12
+ * stays separate for verdict/2 compatibility. No display classification rewrites saved flag IDs.
12
13
  *
13
14
  * The sign-off is `rig-review-parts-verdict/2` (docs/PARTS_VIEW.md), written beside `parts.json` by default. Its
14
15
  * `source.sha256` is the sha256 over the UTF-8 lines `<path>\t<sha256>\n`, sorted by path bytewise, where every path
15
16
  * is relative to the verdict file's directory. rig-c/create recomputes it, so the definition is fixed here.
16
17
  */
17
- import {assertOriginalPaintingSize} from './parts-comparison.ts';
18
+ import {differencePixels,assertOriginalPaintingSize} from './parts-comparison.ts';
18
19
  import {parsePartsComment,assertPartsCommentBinding,type PartsComment} from './parts-comment.ts';
19
20
  import {preparePartsComment,validateStoredPartsComment} from './parts-comment-crops.ts';
20
21
  import {resolvedCropPath} from './comment-crops.ts';
@@ -56,9 +57,11 @@ export type ProducerFlag =
56
57
  | { id: string; item: string; source: 'mesh_report'; kind: 'faint'; art: number; maxAlpha: number; box: [number, number, number, number] }
57
58
  | { id: string; item: string; source: 'check'; kind: 'check'; path: string; line: string;
58
59
  /** The top-level check.json key the line sits under, the gate's status when it is a gate, and the object as written. */
59
- root: string; status: string | null; entry: Record<string, unknown> };
60
+ root: string; status: string | null; entry: Record<string, unknown>;
61
+ classification?: 'part' | 'pair' | 'evidence' | 'unclassified' };
60
62
 
61
63
  export interface PartsViewPackage {
64
+ paintingInRig?: LocalFile & {width:number;height:number;declaredPath:string};
62
65
  painting?:{sha256:string;width:number;height:number;abs:string};
63
66
  mode: PartsViewMode;
64
67
  root: string;
@@ -67,6 +70,8 @@ export interface PartsViewPackage {
67
70
  items: ViewItem[];
68
71
  pages: ViewPage[];
69
72
  flags: ProducerFlag[];
73
+ /** Read-only check presentation; never serialized into verdict/2. */
74
+ readings?: ProducerFlag[];
70
75
  /** The files the sign-off rests on (parts.json and every part PNG; or the model and every page). */
71
76
  files: LocalFile[];
72
77
  /** The producer files the flags were read from. */
@@ -180,6 +185,42 @@ export function checkFlags(doc: unknown, names: ReadonlySet<string>): ProducerFl
180
185
  return flags;
181
186
  }
182
187
 
188
+ /** Additive check-row metadata is authoritative only as a complete valid tuple.
189
+ * Walk all roots (including PASS/SKIP), nested arrays, sets and requirements.lines.
190
+ * Legacy extraction and verdict IDs deliberately remain in checkFlags above.
191
+ */
192
+ export function checkReadings(doc: unknown, names: ReadonlySet<string>): ProducerFlag[] {
193
+ const rows: ProducerFlag[] = [];
194
+ let labelled = false;
195
+ const visit = (value: unknown, path: string, root: string, status: string | null, row = false, depth = 0): void => {
196
+ if (depth > 32) return;
197
+ if (Array.isArray(value)) { value.forEach((v, i) => visit(v, `${path}[${i}]`, root, status, true, depth + 1)); return; }
198
+ const obj = record(value); if (!obj) return;
199
+ const hasMetadata = ['row_scope', 'row_kind', 'row_subjects'].some(k => Object.hasOwn(obj, k));
200
+ labelled ||= hasMetadata;
201
+ // Preserve failed/warning root gates even when only their child rows carry metadata.
202
+ const unlabelledProblemRoot = path === root && !hasMetadata && PROBLEM_STATUSES.has(String(obj.status));
203
+ if (hasMetadata || row || unlabelledProblemRoot) {
204
+ const scope = obj.row_scope, kind = obj.row_kind, subjects = obj.row_subjects;
205
+ const valid = ['part', 'pair', 'rig'].includes(String(scope)) && ['finding', 'evidence'].includes(String(kind)) &&
206
+ Array.isArray(subjects) && subjects.length === (scope === 'part' ? 1 : scope === 'pair' ? 2 : 0) &&
207
+ subjects.every(s => typeof s === 'string' && s.length > 0 && names.has(s)) && new Set(subjects).size === subjects.length;
208
+ const classification = !valid ? 'unclassified' : scope === 'rig' || kind === 'evidence' ? 'evidence' : scope === 'part' ? 'part' : 'pair';
209
+ // Invalid/missing metadata or any unheld subject has no implied attribution. Keep the whole row globally unclassified.
210
+ const items = valid ? (subjects as string[]).filter(s => names.has(s)) : [];
211
+ for (const item of items.length ? items : ['']) rows.push({id: `check:${path}`, item, source:'check', kind:'check', path, root, status, entry:obj, line:JSON.stringify(obj), classification});
212
+ }
213
+ for (const [key, child] of Object.entries(obj)) {
214
+ // requirements.lines is the producer's dictionary of individual rows, not an array.
215
+ if (key === 'lines' && /(?:^|\.)requirements$/.test(path) && record(child)) {
216
+ for (const [name, entry] of Object.entries(child as Record<string, unknown>)) visit(entry, `${path}.lines.${name}`, root, status, true, depth + 1);
217
+ } else visit(child, path ? `${path}.${key}` : key, root, status, false, depth + 1);
218
+ }
219
+ };
220
+ for (const [root, value] of Object.entries(record(doc) ?? {})) visit(value, root, root, typeof record(value)?.status === 'string' ? record(value)!.status as string : null);
221
+ return labelled ? rows : checkFlags(doc, names).map(f => ({...f, classification:'unclassified' as const, ...(f.kind === 'check' ? {line:JSON.stringify(f.entry)} : {})}));
222
+ }
223
+
183
224
  async function readJson(abs: string, what: string): Promise<unknown> {
184
225
  try { return JSON.parse(await readFile(abs, 'utf8')); } catch (e) { return refuse('PARTS_FLAGS_MALFORMED', `${what}: ${e instanceof Error ? e.message : String(e)}`); }
185
226
  }
@@ -189,8 +230,8 @@ async function readJson(abs: string, what: string): Promise<unknown> {
189
230
  * writes `mesh_report.json` beside `parts.json` in `rig/`, and `check` writes `check/check.json` beside `rig/`.
190
231
  * `rigDir` is that `rig/` directory (parts mode) or null (atlas mode: explicit paths only, or `buildRoot`'s files).
191
232
  */
192
- async function producerFlags(rigDir: string | null, buildRoot: string | null, names: ReadonlySet<string>, options: PartsViewOptions): Promise<{ flags: ProducerFlag[]; files: LocalFile[]; notes: string[] }> {
193
- const flags: ProducerFlag[] = [], files: LocalFile[] = [], notes: string[] = [];
233
+ async function producerFlags(rigDir: string | null, buildRoot: string | null, names: ReadonlySet<string>, options: PartsViewOptions): Promise<{ flags: ProducerFlag[]; readings: ProducerFlag[]; files: LocalFile[]; notes: string[] }> {
234
+ const flags: ProducerFlag[] = [], readings: ProducerFlag[] = [], files: LocalFile[] = [], notes: string[] = [];
194
235
  // A discovered file must resolve inside the directory it was discovered in; a path given on the command line is the user's own choice.
195
236
  const pick = async (explicit: string | undefined, candidates: ([string, string] | null)[], what: string): Promise<string | null> => {
196
237
  if (explicit !== undefined) return resolve(explicit);
@@ -201,9 +242,9 @@ async function producerFlags(rigDir: string | null, buildRoot: string | null, na
201
242
  if (mesh) { files.push(await hashFile(mesh)); flags.push(...meshReportFlags(await readJson(mesh, 'mesh_report.json'), names)); }
202
243
  else notes.push('mesh_report.json');
203
244
  const check = await pick(options.check, [rigDir ? [dirname(rigDir), join(dirname(rigDir), 'check', 'check.json')] : null, buildRoot ? [buildRoot, join(buildRoot, 'check', 'check.json')] : null], 'check/check.json');
204
- if (check) { files.push(await hashFile(check)); flags.push(...checkFlags(await readJson(check, 'check.json'), names)); }
245
+ if (check) { files.push(await hashFile(check)); const doc = await readJson(check, 'check.json'); flags.push(...checkFlags(doc, names)); readings.push(...checkReadings(doc, names)); }
205
246
  else notes.push('check.json');
206
- return { flags, files, notes };
247
+ return { flags, readings, files, notes };
207
248
  }
208
249
 
209
250
  /** Exact attachment identity and UV-derived geometry; never reconstruct through weights. */
@@ -293,6 +334,23 @@ async function loadPartsMode(root: string, options: PartsViewOptions): Promise<P
293
334
  imagePaths.push(real);
294
335
  items.push({ name: part.name, index, x: part.x, y: part.y, w: part.w, h: part.h, image: true });
295
336
  }
337
+ let paintingInRig:PartsViewPackage['paintingInRig'];
338
+ if(Object.hasOwn(doc,'painting_in_rig')){
339
+ const d=record(doc.painting_in_rig);
340
+ if(!d||Object.keys(d).length!==3||typeof d.path!=='string'||typeof d.sha256!=='string'||!/^[a-f0-9]{64}$/.test(d.sha256)||d.resample!=='lanczos3-rgb-opaque')refuse('PARTS_DIFFERENCE_PROVENANCE','declared path, lowercase SHA-256 and lanczos3-rgb-opaque required');
341
+ try{packagePath(d!.path,'painting_in_rig');}catch{refuse('PARTS_DIFFERENCE_PATH','literal portable inside-package path required');}
342
+ const declaredPath=join(root,d!.path as string);
343
+ const unreadable=()=>refuse('PARTS_DIFFERENCE_PATH','declared painting must be readable inside the package');
344
+ const abs=await safeFile(root,d!.path as string).catch(unreadable);
345
+ const bytes=await readFile(abs).catch(unreadable);
346
+ const sha256=createHash('sha256').update(bytes).digest('hex');
347
+ if(sha256!==d!.sha256)refuse('PARTS_DIFFERENCE_HASH','declared painting hash differs');
348
+ let png:PNG;try{png=PNG.sync.read(bytes);}catch{refuse('PARTS_DIFFERENCE_PNG','declared painting must be RGBA8 PNG');}
349
+ if(bytes[24]!==8||bytes[25]!==6)refuse('PARTS_DIFFERENCE_PNG','declared painting must be RGBA8 PNG');
350
+ if(!rigSize||!rigSize.every(Number.isSafeInteger)||png!.width!==rigSize[0]||png!.height!==rigSize[1])refuse('PARTS_DIFFERENCE_SIZE','declared painting dimensions must equal integer rig_size');
351
+ for(let i=3;i<png!.data.length;i+=4)if(png!.data[i]!==255)refuse('PARTS_DIFFERENCE_ALPHA','declared painting must have alpha 255');
352
+ paintingInRig={abs,declaredPath,bytes:bytes.length,sha256,width:png!.width,height:png!.height};files.push(paintingInRig);
353
+ }
296
354
  let painting:PartsViewPackage['painting'];if(options.painting){
297
355
  const candidate=resolve(options.painting),rel=relative(resolve(root),candidate);if(!rel||rel==='..'||rel.startsWith('..'+sep)||isAbsolute(rel))refuse('PARTS_PAINTING_OUTSIDE','painting must be inside the parts package');
298
356
  let abs:string,bytes:Buffer;try{abs=await insideRoot(root,candidate,'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');}
@@ -300,7 +358,7 @@ async function loadPartsMode(root: string, options: PartsViewOptions): Promise<P
300
358
  assertOriginalPaintingSize(png!.width,png!.height,rigSize,doc.scale_rig_per_source);
301
359
  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);
302
360
  }
303
- const { flags, files: flagFiles, notes } = await producerFlags(root, null, seen, options);
361
+ const { flags, readings, files: flagFiles, notes } = await producerFlags(root, null, seen, options);
304
362
  const protectedPaths = [join(root, 'rig.json'), join(root, 'config.json'), join(root, 'review.json'), join(root, 'report.json')];
305
363
  if (basename(root) === 'rig') protectedPaths.push(...['parts.json', 'config.json', 'review.json', 'report.json'].map(name => join(dirname(root), name)));
306
364
  if (options.rig !== undefined) protectedPaths.push(resolve(options.rig));
@@ -319,7 +377,7 @@ async function loadPartsMode(root: string, options: PartsViewOptions): Promise<P
319
377
  files.push({ abs: rigPath, bytes: rigBytes.length, sha256: createHash('sha256').update(rigBytes).digest('hex') });
320
378
  if (report) files.push(report);
321
379
  }
322
- return { ...(painting?{painting}:{}),mode: 'parts', root, title: basename(root) === 'rig' ? basename(dirname(root)) : basename(root), rigSize, items, pages: [], flags, files, flagFiles, flagNotes: notes, protectedPaths, verdictPath, imagePaths, pagePaths: [] };
380
+ return { ...(paintingInRig?{paintingInRig}:{}),...(painting?{painting}:{}),mode: 'parts', root, title: basename(root) === 'rig' ? basename(dirname(root)) : basename(root), rigSize, items, pages: [], flags, readings, files, flagFiles, flagNotes: notes, protectedPaths, verdictPath, imagePaths, pagePaths: [] };
323
381
  }
324
382
 
325
383
  async function loadAtlasMode(input: string, options: PartsViewOptions): Promise<PartsViewPackage> {
@@ -356,12 +414,12 @@ export async function loadPartsAtlas(p: ReviewPackage, options: PartsViewOptions
356
414
  }
357
415
  // A build root opens as its check package (#149); its own rig/ and check/ hold the flags.
358
416
  const buildRoot = p.buildRoot ?? null;
359
- const { flags, files: flagFiles, notes } = await producerFlags(null, buildRoot, names, options);
417
+ const { flags, readings, files: flagFiles, notes } = await producerFlags(null, buildRoot, names, options);
360
418
  const protectedPaths = [...p.files].map(path => resolve(p.root, path));
361
419
  protectedPaths.push(...['rig.json', 'config.json', 'report.json', 'review.json'].map(name => join(p.root, name)));
362
420
  if (p.handoff) protectedPaths.push(...p.handoff.record.files.map(file => resolve(p.root, file.path)));
363
421
  if (buildRoot) protectedPaths.push(...['parts.json', 'config.json', 'rig/rig.json', 'rig/parts.json'].map(name => join(buildRoot, name)));
364
- return { mode: 'atlas', root: p.root, title: p.manifest.title, rigSize: null, items, pages, flags, files, flagFiles, flagNotes: notes, protectedPaths, verdictPath: options.verdict ? resolve(options.verdict) : join(dirname(modelAbs), PARTS_VERDICT_FILE), imagePaths: [], pagePaths };
422
+ return { mode: 'atlas', root: p.root, title: p.manifest.title, rigSize: null, items, pages, flags, readings, files, flagFiles, flagNotes: notes, protectedPaths, verdictPath: options.verdict ? resolve(options.verdict) : join(dirname(modelAbs), PARTS_VERDICT_FILE), imagePaths: [], pagePaths };
365
423
  }
366
424
 
367
425
  /**
@@ -422,7 +480,7 @@ export interface VerdictSubmission { status: VerdictStatus; parts: Record<string
422
480
  export const itemNames = (pkg: Pick<PartsViewPackage, 'items'>): string[] => [...new Set(pkg.items.map(i => i.name))];
423
481
 
424
482
  /** Builds the verdict document, or refuses by name. Pure but for the clock. */
425
- export function buildVerdict(pkg: Pick<PartsViewPackage, 'mode' | 'items' | 'flags' | 'files' | 'flagFiles' | 'verdictPath' | 'imagePaths' | 'painting'>, input: unknown, version: string, now = new Date()): PartsVerdict {
483
+ export function buildVerdict(pkg: Pick<PartsViewPackage, 'mode' | 'items' | 'flags' | 'files' | 'flagFiles' | 'verdictPath' | 'imagePaths' | 'painting' | 'paintingInRig'>, input: unknown, version: string, now = new Date()): PartsVerdict {
426
484
  const body = record(input);
427
485
  if (!body) return refuse('PARTS_VERDICT_INVALID', 'expected { status, parts }');
428
486
  const status = body.status;
@@ -457,12 +515,13 @@ export function buildVerdict(pkg: Pick<PartsViewPackage, 'mode' | 'items' | 'fla
457
515
  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`);
458
516
  if (status === 'changes-requested' && !outcomes.includes('flagged')) refuse('PARTS_VERDICT_NOTHING_FLAGGED', 'changes-requested needs at least one flagged part');
459
517
  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');
460
- 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');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);}
518
+ 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);}
461
519
  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() };
462
520
  }
463
521
 
464
522
  /** Every file the package was loaded from still has the bytes it was loaded with. */
465
- export async function assertPartsUnchanged(pkg: Pick<PartsViewPackage, 'files' | 'flagFiles'>): Promise<void> {
523
+ export async function assertPartsUnchanged(pkg: Pick<PartsViewPackage, 'files' | 'flagFiles' | 'paintingInRig'>): Promise<void> {
524
+ if(pkg.paintingInRig&&await realpath(pkg.paintingInRig.declaredPath).catch(()=>null)!==pkg.paintingInRig.abs)refuse('PARTS_VIEW_SOURCE_CHANGED','declared painting path changed');
466
525
  for (const f of [...pkg.files, ...pkg.flagFiles]) {
467
526
  const now = await hashFile(f.abs).catch(() => null);
468
527
  if (!now || now.sha256 !== f.sha256) refuse('PARTS_VIEW_SOURCE_CHANGED', `${basename(f.abs)} changed after the view opened; reopen it to review what is on disk`);
@@ -515,9 +574,10 @@ export async function readVerdict(pkg: PartsViewPackage): Promise<{ verdict: Par
515
574
  export function partsViewJson(pkg: PartsViewPackage, saved: { verdict: PartsVerdict | null; stale: VerdictStale }) {
516
575
  return {
517
576
  schema: 'rig-review-parts-view/1', mode: pkg.mode, title: pkg.title, rigSize: pkg.rigSize,
577
+ differenceAvailable:!!pkg.paintingInRig,
518
578
  painting:pkg.painting?{sha256:pkg.painting.sha256,width:pkg.painting.width,height:pkg.painting.height}:null,
519
579
  sourceHash:verdictSource(pkg).sha256,
520
- 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,
580
+ 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 ?? [],
521
581
  flagSources: pkg.flagFiles.map(f => basename(f.abs)), flagMissing: pkg.flagNotes,
522
582
  verdictFile: basename(pkg.verdictPath), verdict: saved.verdict, verdictStale: saved.stale,
523
583
  };
@@ -536,3 +596,15 @@ export function exportPartsVerdict(verdict:PartsVerdict,format:'json'|'issue'):s
536
596
  if(format==='json')return JSON.stringify({...verdict,comments},null,2)+'\n';
537
597
  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';
538
598
  }
599
+
600
+ /** Numeric comparison is decoded from bound original PNG bytes on the server, never browser pixels. */
601
+ export async function partsDifference(pkg:PartsViewPackage,index:number,threshold:number,footprints:boolean){
602
+ await assertPartsUnchanged(pkg);
603
+ if(!pkg.paintingInRig)refuse('PARTS_DIFFERENCE_UNAVAILABLE','declared painting_in_rig required; legacy records remain readable');
604
+ const item=pkg.items[index];if(pkg.mode!=='parts'||!Number.isInteger(index)||!item)refuse('PARTS_DIFFERENCE_UNAVAILABLE','known original part required');
605
+ 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);};
606
+ const painting=await decode(pkg.paintingInRig!.abs),part=await decode(pkg.imagePaths[index]!);
607
+ 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]!)}))):[];
608
+ const result=differencePixels(part,item!,painting,fronts,threshold,footprints);
609
+ await assertPartsUnchanged(pkg);return result;
610
+ }
package/src/rebuild.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import {isDeepStrictEqual} from 'node:util';
2
+ import {recordFor,type AnyJobView} from '../web/rebuild-client.ts';
1
3
  /**
2
4
  * Apply · Rebuild (issue #99): the user's chest-region designation goes to the installed producer as one mesh entry,
3
5
  * `rig-parts remesh` re-fits that one part of the package's gated rig into a scratch revision, `rigc build` compiles
@@ -263,6 +265,10 @@ export interface AppliedHistory { schema: 'rig-review-applied-history/1'; depth:
263
265
  export type RebuildStatus = 'running' | 'built' | 'refused' | 'failed';
264
266
  export interface RebuildBuild { model: string; modelUrl: string; modelHash: string; files: Record<string, string> }
265
267
  export interface RebuildJob {
268
+ files?: FilesDiff | null;
269
+ remesh?: (RemeshCounts & {modelTriangles:number|null}) | null;
270
+ stageInputHash?: string;
271
+ check?: CheckSummary | null;
266
272
  schema: typeof REBUILD_SCHEMA; id: string; status: RebuildStatus; reused: boolean;
267
273
  request: { part: string; regions: ProducerRegion[]; configHash: string; entrySha256: string; bust?: BustSpec };
268
274
  producer: { package: string; version: string }; compiler: { package: string; version: string };
@@ -277,6 +283,7 @@ export interface RebuildJob {
277
283
  * inspected one (`diff`) — and, #125, every document the producer writes, per file, with the images by hash (`files`).
278
284
  */
279
285
  export interface PatchJob {
286
+ stageInputHash?: string;
280
287
  schema: typeof REBUILD_SCHEMA; kind: 'patch'; id: string; status: RebuildStatus; reused: boolean;
281
288
  /** #136: the producer op that ran — a `rig` patch runs `retune` when `patchRoute` routes it there, else `rig`; a remesh patch `remesh`. */
282
289
  op: AppliedOp;
@@ -359,6 +366,7 @@ export const BUILD_SOURCE_UNAVAILABLE = 'MODELING_INPUT_UNAVAILABLE: source pain
359
366
  * motion holds against the inspected rig's.
360
367
  */
361
368
  export interface RetargetJob {
369
+ stageInputHash?: string;
362
370
  schema: typeof REBUILD_SCHEMA; kind: 'retarget'; id: string; status: RebuildStatus; reused: boolean; op: 'retarget';
363
371
  request: { record: RetargetRecord; recordSha256: string; configHash: string };
364
372
  producer: { package: string; version: string }; compiler: { package: string; version: string };
@@ -398,6 +406,8 @@ export function deltaId(input: { sourceHash: string; configHash: string; part: s
398
406
  }
399
407
  /** A delta Apply's job (#135): `remesh --delta`, then the shared tail with the per-file diff (#125); remesh's own gate holds check. */
400
408
  export interface DeltaJob {
409
+ stageInputHash?: string;
410
+ check?: CheckSummary | null;
401
411
  schema: typeof REBUILD_SCHEMA; kind: 'delta'; id: string; status: RebuildStatus; reused: boolean; op: 'remesh';
402
412
  request: { part: string; delta: Record<string, unknown>; deltaSha256: string; configHash: string };
403
413
  producer: { package: string; version: string }; compiler: { package: string; version: string };
@@ -446,6 +456,7 @@ export function animationId(input: { sourceHash: string; configHash: string; ani
446
456
  return sha256(JSON.stringify([REBUILD_SCHEMA, 'animation', input.sourceHash, input.configHash, input.animationsFromHash, input.opsText, input.producer, input.compiler, ...(input.args?.length ? [input.args] : []), ...(input.environment ? ['environment', input.environment] : [])]));
447
457
  }
448
458
  export interface AnimationJob {
459
+ stageInputHash?: string;
449
460
  schema: typeof REBUILD_SCHEMA; kind: 'animation'; id: string; status: RebuildStatus; reused: boolean; op: 'rig';
450
461
  request: { configHash: string; animationsFrom: { path: string; beforeSha256: string; afterSha256: string }; ops: AnimationSourceOp[]; opsSha256: string; args?: string[] };
451
462
  producer: { package: string; version: string }; compiler: { package: string; version: string };
@@ -619,6 +630,15 @@ async function namedDirDigest(root: string, dir: string, field: string): Promise
619
630
  }
620
631
 
621
632
  /** #115: what a build-routed patch runs with — the handoff's painting and runs, absolute; never from the client. */
633
+ /** Inputs and produced spec share a revision pin; result.json and compiled outputs have their separate records. */
634
+ async function stageInputDigest(dir:string,spec:string):Promise<string>{
635
+ const root=await realpath(dir);
636
+ const rows:[string,string][]=[['revision',await namedDirDigest(root,spec,'scratch revision')]];
637
+ for(const name of ['mesh.json','mesh-edit.json','config.json','patch.json','environment.json']){
638
+ if(await exists(join(dir,name))){const path=await safeFile(await realpath(dir),name);rows.push([name,sha256(await readFile(path))]);}
639
+ }
640
+ return sha256(JSON.stringify(rows));
641
+ }
622
642
  export interface BuildPlan { source: string; full: string; head: string | null; inputsHash: string; inputs: AssembledView['inputs'] }
623
643
  /**
624
644
  * The build's inputs for a patch (`null` refusal line when the handoff declares no painting and full run): the painting
@@ -864,6 +884,54 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
864
884
  const dir = job ? rebuildDir(options.stateDir, p.sourceHash, job.id) : '';
865
885
  return job && job.status === 'built' && job.build ? { id: job.id, build: join(dir, 'build'), modelHash: job.build.modelHash, spec: join(dir, !('kind' in job) ? 'revision' : job.op === 'build' || (job.kind === 'patch' && job.cloth?.route === 'build') ? 'out/rig' : 'rig') } : null;
866
886
  }
887
+ /** Stage 1 can read only the revision explicitly drawn by the page, never a pending candidate. */
888
+ async function stageDraft(id: string) {
889
+ await options.unchanged();
890
+ const current = latest();
891
+ if (!current || current.id !== id || busy()) throw new RebuildError('STAGE_DRAFT_STALE', 'the requested scratch build is not the settled applied revision');
892
+ const job = jobs.get(id)!;
893
+ if (!job.stageInputHash || await stageInputDigest(rebuildDir(options.stateDir,p.sourceHash,id),current.spec) !== job.stageInputHash) throw new RebuildError('STAGE_DRAFT_CHANGED', 'scratch revision bytes differ from Apply');
894
+ const now = await hashBuild(current.build, id, assetPrefix);
895
+ if (JSON.stringify(now.files) !== JSON.stringify(job.build!.files)) throw new RebuildError('STAGE_DRAFT_CHANGED', 'scratch build bytes differ from the applied record');
896
+ if (!('check' in job) || !job.check || job.check.pass !== true || job.check.exitCode !== 0) throw new RebuildError('STAGE_DRAFT_UNCHECKED', 'this revision has no successful recorded producer check');
897
+ if (!('kind' in job) || job.kind === 'delta' || (job.kind === 'patch' && job.op === 'remesh')) {
898
+ const carried = await opCarried('remesh', current.spec, null, () => {});
899
+ if (carried && 'refused' in carried) throw new RebuildError('STAGE_DRAFT_CHANGED', carried.refused);
900
+ } else throw new RebuildError('STAGE_DRAFT_OPERATION', 'only applied mesh corrections belong to this inspection');
901
+ return {id, spec: current.spec, model: join(current.build, 'skeleton.model.json'), evidence: snapshot(job)};
902
+ }
903
+ /** Historical evidence is independent of the disposable Undo cache; current-stage reads still use stageDraft. */
904
+ const evidenceBinding={id:p.manifest.id,revision:p.manifest.revision,sourceHash:p.sourceHash,reviewedSource:p.reviewedSource};
905
+ const evidencePath=(id:string)=>join(options.stateDir,'applied-evidence',p.sourceHash,id+'.json');
906
+ const evidenceLimit=1024*1024;
907
+ async function sealApplied(job:RebuildJob|PatchJob|DeltaJob|RetargetJob|AnimationJob):Promise<void>{
908
+ if(!job.build||job.status!=='built')throw new RebuildError('STAGE_DRAFT_STALE','only a settled applied build can be sealed');
909
+ const dir=rebuildDir(options.stateDir,p.sourceHash,job.id);
910
+ const spec=join(dir,!('kind' in job)?'revision':job.op==='build'||(job.kind==='patch'&&job.cloth?.route==='build')?'out/rig':'rig');
911
+ const inputHash='stageInputHash' in job?job.stageInputHash??null:null;
912
+ if(inputHash&&await stageInputDigest(dir,spec)!==inputHash)throw new RebuildError('STAGE_DRAFT_CHANGED','scratch inputs differ before evidence settlement');
913
+ const now=await hashBuild(join(dir,'build'),job.id,assetPrefix);
914
+ if(!isDeepStrictEqual(now.files,job.build.files))throw new RebuildError('STAGE_DRAFT_CHANGED','compiled files differ before evidence settlement');
915
+ const body={schema:'rig-review-applied-evidence/1',binding:evidenceBinding,buildId:job.id,operation:!('kind' in job)?'regions':job.kind==='patch'?job.op:job.kind,inputHash,outputHash:sha256(JSON.stringify(now.files)),modelHash:now.modelHash,check:'check' in job?job.check:null,record:recordFor(job as AnyJobView)};
916
+ const text=JSON.stringify({body,digest:sha256(JSON.stringify(body))})+'\n';
917
+ if(Buffer.byteLength(text)>evidenceLimit)throw new RebuildError('STAGE_DRAFT_STALE','applied evidence exceeds the bounded record size');
918
+ const file=evidencePath(job.id);await mkdir(dirname(file),{recursive:true,mode:0o700});
919
+ const temporary=file+'.'+crypto.randomUUID()+'.tmp';
920
+ try{await writeFile(temporary,text,{mode:0o600,flag:'wx'});await rename(temporary,file);}finally{await rm(temporary,{force:true});}
921
+ }
922
+ /** A made claim names historical settled evidence, not a claim that its build is still current or on disk. */
923
+ async function validateApplied(value:unknown):Promise<void>{
924
+ if(!value||typeof value!=='object'||!('stageInputHash' in value))return;
925
+ const v=value as Record<string,unknown>;
926
+ if(!['rig-review-applied/1','rig-review-applied/3'].includes(String(v.schema))&&!(v.schema==='rig-review-applied/2'&&v.op==='remesh'))return;
927
+ if(typeof v.buildId!=='string'||!/^[a-f0-9]{64}$/.test(v.buildId))throw new RebuildError('STAGE_DRAFT_STALE','invalid applied identity');
928
+ try{
929
+ const file=await safeFile(await realpath(dirname(evidencePath(v.buildId))),v.buildId+'.json');
930
+ if((await lstat(file)).size>evidenceLimit)throw new Error('oversized evidence');
931
+ const seal=JSON.parse(await readFile(file,'utf8')),body=seal.body;
932
+ if(!body||body.schema!=='rig-review-applied-evidence/1'||seal.digest!==sha256(JSON.stringify(body))||!isDeepStrictEqual(body.binding,evidenceBinding)||body.buildId!==v.buildId||body.inputHash!==v.stageInputHash||body.modelHash!==v.modelHash||!isDeepStrictEqual(body.check,v.check)||!isDeepStrictEqual(body.record,v))throw new Error('evidence mismatch');
933
+ }catch{throw new RebuildError('STAGE_DRAFT_STALE','the made claim has no matching sealed applied evidence');}
934
+ }
867
935
  /**
868
936
  * #166: the line refusing an undo's re-run whose build is not the one its record names (the first differing file by
869
937
  * hash), or null — also null for any job that is not an undo's re-run.
@@ -901,6 +969,8 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
901
969
  else if (stack.at(-1)?.id !== job.id && job.build) stack.push({ id: job.id, body: bodies.get(job.id) ?? null, configHash: job.request.configHash, producer: { ...job.producer }, compiler: { ...job.compiler }, files: { ...job.build.files }, modelHash: job.build.modelHash, job: snapshot(job) });
902
970
  latestId = stack.at(-1)?.id ?? null;
903
971
  await arrange();
972
+ // Seal only after settlement succeeds; pending candidates and failed settlement have no authority.
973
+ await sealApplied(job);
904
974
  }
905
975
  async function arrange(): Promise<void> {
906
976
  const root = rebuildRoot(options.stateDir, p.sourceHash), kept = keptRoot(options.stateDir, p.sourceHash);
@@ -990,6 +1060,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
990
1060
  try {
991
1061
  const stored = JSON.parse(await readFile(resultFile, 'utf8')) as J;
992
1062
  if (stored.schema !== REBUILD_SCHEMA || stored.id !== id || stored.status !== 'built' || !stored.build) return null;
1063
+ if ((!('kind' in stored) || stored.kind === 'delta'||(stored.kind==='patch'&&stored.op==='remesh')) && (!Object.hasOwn(stored, 'check')||!stored.stageInputHash)) return null;
993
1064
  const now = await hashBuild(join(dir, 'build'), id, assetPrefix);
994
1065
  if (JSON.stringify(now.files) !== JSON.stringify(stored.build.files)) return null;
995
1066
  const job = { ...stored, build: now, reused: true };
@@ -1057,6 +1128,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1057
1128
  // The package and its producer inputs must still be the bytes the request was made against.
1058
1129
  // The handoff files are in the reviewed identity, so this also catches a config, parts or rig change.
1059
1130
  try { await options.unchanged(); } catch { throw new RebuildError('REBUILD_INPUTS_CHANGED', 'the package or its producer handoff changed during the rebuild'); }
1131
+ if(!('kind' in job)||job.kind==='delta'||(job.kind==='patch'&&job.op==='remesh'))job.stageInputHash = await stageInputDigest(dir, join(dir, op.spec));
1060
1132
  job.build = await hashBuild(join(dir, 'build'), job.id, assetPrefix);
1061
1133
  if (steps.hashed) await steps.hashed();
1062
1134
  // #166: an undo's re-run must reproduce the build its record names, file for file; otherwise it is refused, not guessed.
@@ -1081,6 +1153,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1081
1153
 
1082
1154
  /** #99: the designation's entry → `rig-parts remesh` → a scratch revision, compiled with the revision's own pack flags. */
1083
1155
  function execute(job: RebuildJob, dir: string, inputs: ProducerInputs, resolved: Resolved, entry: string): Promise<void> {
1156
+ let counts:RemeshCounts|null=null;
1084
1157
  return apply(job, dir, inputs, resolved, {
1085
1158
  cmd: 'remesh', spec: 'revision',
1086
1159
  async run(push) {
@@ -1091,8 +1164,14 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1091
1164
  wallMs: ms => { job.wallMs.remesh = ms; },
1092
1165
  async flags() {
1093
1166
  const provenance = object(JSON.parse(await readFile(join(dir, 'revision', 'remesh.json'), 'utf8')), 'remesh.json'), request = object(provenance.request, 'remesh.json request');
1167
+ counts = remeshCounts(provenance);
1094
1168
  return { pageEdges: request.page_edges === 'pot' ? 'pot' : 'free', packShape: request.pack_shape === 'rect' ? 'rect' : 'polygon', note: ' (the revision\'s own pack flags)' };
1095
1169
  },
1170
+ }, {
1171
+ check: summary => { job.check = summary; },
1172
+ carried: push => opCarried('remesh', join(dir, 'revision'), null, push),
1173
+ diff: files => {job.files=files;},
1174
+ hashed: async()=>{if(counts)job.remesh={...counts,modelTriangles:modelMeshTriangles(JSON.parse(await readFile(join(dir,'build/skeleton.model.json'),'utf8')),counts.part)};},
1096
1175
  });
1097
1176
  }
1098
1177
 
@@ -1480,6 +1559,8 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1480
1559
  return { pageEdges: request.page_edges === 'pot' ? 'pot' : 'free', packShape: request.pack_shape === 'rect' ? 'rect' : 'polygon', note: ' (remesh.json\'s pack flags)' };
1481
1560
  },
1482
1561
  }, {
1562
+ check: summary => { job.check = summary; },
1563
+ carried: push => opCarried('remesh', join(dir, 'rig'), null, push),
1483
1564
  diff: files => { job.files = files; },
1484
1565
  hashed: async () => { if (counts) job.remesh = { ...counts, modelTriangles: modelMeshTriangles(JSON.parse(await readFile(join(dir, 'build', 'skeleton.model.json'), 'utf8')), counts.part) }; },
1485
1566
  });
@@ -1515,6 +1596,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1515
1596
  const reused = await reuse<DeltaJob>(dir, id);
1516
1597
  if (reused) { jobs.set(id, reused); latestId = id; bodies.set(id, input); await landed(reused); return { status: 200, body: snapshot(reused) }; }
1517
1598
  const job: DeltaJob = { schema: REBUILD_SCHEMA, kind: 'delta', id, status: 'running', reused: false, op: 'remesh', request: { part: request.part, delta: request.delta, deltaSha256: sha256(text), configHash: inputs.configHash }, producer: tool(resolved.producer), compiler: tool(resolved.compiler), lines: [], producerLine: null, exitCode: null, wallMs: { op: null, compile: null }, files: null, remesh: null, build: null };
1599
+ if (!('kind' in job) || job.kind === 'delta') job.check = null;
1518
1600
  jobs.set(id, job); running = id; bodies.set(id, input);
1519
1601
  void executeDelta(job, dir, inputs, resolved, text).finally(() => { if (running === id) running = null; });
1520
1602
  return { status: 202, body: snapshot(job) };
@@ -1832,6 +1914,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1832
1914
  const reused = await reuse(dir, id);
1833
1915
  if (reused) { jobs.set(id, reused); latestId = id; bodies.set(id, input); await landed(reused); return { status: 200, body: snapshot(reused) }; }
1834
1916
  const job: RebuildJob = { schema: REBUILD_SCHEMA, id, status: 'running', reused: false, request: { ...request, entrySha256: sha256(entry) }, producer: tool(resolved.producer), compiler: tool(resolved.compiler), lines: [], producerLine: null, exitCode: null, wallMs: { remesh: null, compile: null }, build: null };
1917
+ if (!('kind' in job) || job.kind === 'delta') job.check = null;
1835
1918
  jobs.set(id, job); running = id; bodies.set(id, input);
1836
1919
  void execute(job, dir, inputs, resolved, entry).finally(() => { if (running === id) running = null; });
1837
1920
  return { status: 202, body: snapshot(job) };
@@ -1853,5 +1936,5 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1853
1936
  return safeFile(await realpath(join(rebuildDir(options.stateDir, p.sourceHash, id), 'build')), packagePath(name));
1854
1937
  }
1855
1938
 
1856
- return { describe, start, read, file, running: () => running, busy: () => busy() !== null, baseline: settledBaseline, inspectedCheck: settledInspectedCheck, latest, undo, history, startStrip, readStrip, stripJob, closeStrip, stripFile };
1939
+ return { describe, start, read, file, running: () => running, busy: () => busy() !== null, baseline: settledBaseline, inspectedCheck: settledInspectedCheck, latest, stageDraft, validateApplied, undo, history, startStrip, readStrip, stripJob, closeStrip, stripFile };
1857
1940
  }
@@ -40,7 +40,7 @@ export const provenanceFile = (op: CarryingOp): string => FILE[op];
40
40
  const isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
41
41
  /** check.json's bar keys as review's `checkSummary` reads them: an upper-case name. */
42
42
  const BAR = /^[A-Z][A-Z0-9_]+$/;
43
- const STATUSES = new Set(['PASS', 'FAIL', 'SKIP', 'WARN', 'CLEAR', 'REPORTED']);
43
+ const STATUSES = new Set(['PASS', 'FAIL', 'SKIP', 'WARN', 'CLEAR', 'REPORTED', 'UNCLASSIFIED']);
44
44
 
45
45
  export interface RetuneRevisionRow { path: string; bytes: number; sha256: string }
46
46
  export interface CarriedCheck { pass: boolean; line: string; status: Record<string, string> }
package/src/server.ts CHANGED
@@ -32,11 +32,11 @@ async function bodyJson(req:Request,limit=1024*1024,what='Session payload exceed
32
32
  /** `capability` (open workers and foreground CLI serving) gates every non-GET request; tests may omit it.
33
33
  * `cwd` is where the producer is looked for after the package's own directories (review's working directory by default). */
34
34
  export async function startServer(p:ReviewPackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;initialAnimation?:string;activity?:()=>void;control?:ControlIdentity;capability?:string;cwd?:string;stripConcurrency?:number;graceMs?:number;unopenedTimeoutMs?:number;exitOnClose?:boolean;onClose?:(info:LiveExitInfo)=>void|Promise<void>;log?:(line:string)=>void;viewOnly?:boolean}={}){
35
- const stageParts=stagePartsRoutes({single:p});
36
35
  const bundle=await buildWeb();
37
36
  const unchanged=()=>assertReviewUnchanged(p);
38
37
  const stateDir=options.stateDir??process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review'),starts=[p.root,options.cwd??process.cwd()];
39
38
  const rebuilds=createRebuilds(p,{stateDir,starts,unchanged,bones:p.feedbackCatalog.bones,...(options.stripConcurrency?{stripConcurrency:options.stripConcurrency}:{}),...(options.viewOnly??p.viewOnly?{viewOnly:true}:{})});
39
+ const stageParts=stagePartsRoutes({single:p},undefined,rebuilds.stageDraft);
40
40
  // Readings (#108): rigc render's readings on the inspected build and on the latest scratch build, into scratch.
41
41
  const readings=createReadings(p,{stateDir,starts,unchanged,latest:rebuilds.latest});
42
42
  // Bones check (#109): propose --from-config and compare on a scratch copy of the patched handoff config.
@@ -74,7 +74,9 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
74
74
  options.activity?.();const gate=openGate(req,options.open);if(gate){if(gate.status===200){try{await unchanged();}catch{return staleOpenStatus(options.open!);}if(!live.rearmUnopened())return json({error:'Server is closing'},503);}return gate;}
75
75
  if(req.method==='PUT'&&url.pathname==='/api/session'){
76
76
  if(req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
77
- const input=await bodyJson(req);await unchanged();return json(await saveSession(p,input,options.stateDir));
77
+ const input=await bodyJson(req);await unchanged();
78
+ if(input&&typeof input==='object'&&Array.isArray((input as any).feedback))for(const feedback of (input as any).feedback)await rebuilds.validateApplied(feedback?.context?.applied);
79
+ return json(await saveSession(p,input,options.stateDir));
78
80
  }
79
81
  // Apply · Rebuild (#99 regions, #102 {patch}): typed data, never a path; the server runs the installed producer into scratch.
80
82
  if(req.method==='POST'&&url.pathname==='/api/rebuild'){
@@ -1,10 +1,12 @@
1
1
  /** Read-only embedding of the existing atlas inspector. No browser-supplied filesystem paths or verdict writes. */
2
+ import {join} from 'node:path';
2
3
  import {readFile} from 'node:fs/promises';
3
4
  import {appRoot,buildWeb} from './build.ts';
4
5
  import type {ReviewPackage} from './manifest.ts';
5
- import {loadPartsAtlas,assertPartsUnchanged,partsViewJson,servedImage} from './parts-view.ts';
6
+ import {loadPartsAtlas,loadPartsView,assertPartsUnchanged,partsViewJson,servedImage,type PartsViewPackage} from './parts-view.ts';
6
7
  import {serveReference,assertReviewUnchanged} from './reference.ts';
7
- export function stagePartsRoutes(packages:{single:ReviewPackage}|{a:ReviewPackage;b:ReviewPackage},loadAtlas:typeof loadPartsAtlas=loadPartsAtlas) {
8
+ export function stagePartsRoutes(packages:{single:ReviewPackage}|{a:ReviewPackage;b:ReviewPackage},loadAtlas:typeof loadPartsAtlas=loadPartsAtlas,draft?:DraftReader) {
9
+ const corrections=new Map<string,Promise<{pkg:PartsViewPackage;metadata:unknown}>>();
8
10
  const loaded=new Map<string,ReturnType<typeof loadPartsAtlas>>();let bundle:Promise<Blob>|undefined;
9
11
  const headers={'X-Content-Type-Options':'nosniff','Cache-Control':'no-store','Referrer-Policy':'no-referrer','Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'"};
10
12
  return async(req:Request):Promise<Response|null>=>{
@@ -19,6 +21,31 @@ export function stagePartsRoutes(packages:{single:ReviewPackage}|{a:ReviewPackag
19
21
  const key='single' in packages?'single':match[1] as 'a'|'b',p='single' in packages?packages.single:packages[key as 'a'|'b'];
20
22
  const kind=match['single' in packages?1:2] as 'image'|'page'|undefined,index=match['single' in packages?2:3];
21
23
  try{
24
+ // Single-package Stage 1 uses the declared handoff's real separated parts, not the atlas names.
25
+ if ('single' in packages && p.handoff?.parts && p.handoff.rig) {
26
+ await assertReviewUnchanged(p);
27
+ const build=req.headers.get('X-Review-Stage-Build')??'inspected';
28
+ if(build!=='inspected'&&!/^[a-f0-9]{64}$/.test(build))throw new Error('STAGE_DRAFT_STALE');
29
+ const applied=build==='inspected'?null:await draft?.(build);
30
+ if(build!=='inspected'&&!applied)throw new Error('STAGE_DRAFT_UNAVAILABLE');
31
+ const model=applied?.model??(p.manifest.model?join(p.root,p.manifest.model):null);
32
+ if(!model)throw new Error('STAGE_DRAFT_UNAVAILABLE');
33
+ let promise=corrections.get(build);
34
+ if(!promise){
35
+ promise=(async()=>{
36
+ const rig=join(applied?.spec??p.handoff!.rig!,'rig.json');
37
+ const pkg=await loadPartsView(p.handoff!.parts!,{rig,meshReport:join(applied?.spec??p.handoff!.rig!,'mesh_report.json')});
38
+ const mappings=await draftMappings(model,rig,pkg);
39
+ await assertReviewUnchanged(p);await assertPartsUnchanged(pkg);
40
+ return {pkg,metadata:mappings.length?{label:'Draft rig · structure evidence only',buildId:build,inspectionSourceHash:p.sourceHash,mappings,evidence:applied?.evidence??null}:null};
41
+ })();corrections.set(build,promise);
42
+ }
43
+ const {pkg,metadata}=await promise;
44
+ // Every image is served against the same full pinned draft, including geometry and flags.
45
+ await assertReviewUnchanged(p);await assertPartsUnchanged(pkg);
46
+ if(kind){const file=servedImage(pkg,kind,Number(index));if(!file)return Response.json({error:'PARTS_IMAGE_UNAVAILABLE'},{status:404,headers});const pinned=pkg.files.find(f=>f.abs===file)!;return serveReference(req,file,pinned.sha256,headers);}
47
+ return Response.json({...partsViewJson(pkg,{verdict:null,stale:null}),differenceAvailable:false,readOnly:true,inspectionSourceHash:p.sourceHash,...(metadata?{draft:metadata}:{draftUnavailable:stageDraftRefusals.STAGE_DRAFT_NO_MESH})},{headers});
48
+ }
22
49
  let promise=loaded.get(key);
23
50
  const initializing=!promise;
24
51
  if(!promise){
@@ -31,7 +58,57 @@ export function stagePartsRoutes(packages:{single:ReviewPackage}|{a:ReviewPackag
31
58
  if(!kind&&!initializing){await assertReviewUnchanged(p);await assertPartsUnchanged(pkg);}
32
59
  if(kind){const model=pkg.files[0]!;await serveReference(new Request(req.url,{method:'HEAD'}),model.abs,model.sha256,headers);}
33
60
  if(kind){const file=servedImage(pkg,kind,Number(index));if(!file)return Response.json({error:'PARTS_IMAGE_UNAVAILABLE'},{status:404,headers});const pinned=pkg.files.find(f=>f.abs===file);if(!pinned)throw new Error('Unbound atlas page');return await serveReference(req,file,pinned.sha256,headers);}
34
- return Response.json({...partsViewJson(pkg,{verdict:null,stale:null}),readOnly:true,inspectionSourceHash:p.sourceHash},{headers});
35
- }catch{return Response.json({error:'PARTS_ATLAS_UNAVAILABLE: the inspected package has no usable atlas or its source changed.'},{status:409,headers});}
61
+ return Response.json({...partsViewJson(pkg,{verdict:null,stale:null}),differenceAvailable:false,readOnly:true,inspectionSourceHash:p.sourceHash,draftUnavailable:stageDraftRefusals.STAGE_DRAFT_UNAVAILABLE},{headers});
62
+ }catch(error){const code=error instanceof Error?error.message.split(':')[0]:'';const named=stageDraftRefusals[code??'']??(code==='PARTS_MESH_IMAGE_MISMATCH'?stageDraftRefusals.STAGE_DRAFT_MISMATCH:undefined);return Response.json({error:named??'PARTS_ATLAS_UNAVAILABLE: the inspected package has no usable atlas or its source changed.'},{status:409,headers});}
36
63
  };
37
64
  }
65
+
66
+ export interface DraftSnapshot {id:string;spec:string;model:string;evidence:unknown}
67
+ export type DraftReader=(id:string)=>Promise<DraftSnapshot>;
68
+ /** Closed public refusals; never send paths or producer output through the managed-front error channel. */
69
+ export const stageDraftRefusals:Record<string,string>={
70
+ STAGE_DRAFT_GEOMETRY_UNSUPPORTED:'STAGE_DRAFT_GEOMETRY_UNSUPPORTED: raw indexed vertex geometry is unavailable in this draft connection.',
71
+ STAGE_DRAFT_UNAVAILABLE:'STAGE_DRAFT_UNAVAILABLE: no producer-compatible draft is supplied.',
72
+ STAGE_DRAFT_NO_MESH:'STAGE_DRAFT_NO_MESH: this part has no mesh attachment; direct correction is unavailable.',
73
+ STAGE_DRAFT_MISMATCH:'STAGE_DRAFT_MISMATCH: separated parts and draft mesh identity differ.',
74
+ STAGE_DRAFT_STALE:'STAGE_DRAFT_STALE: the requested revision is pending or no longer applied.',
75
+ STAGE_DRAFT_CHANGED:'STAGE_DRAFT_CHANGED: scratch inputs changed after Apply.',
76
+ STAGE_DRAFT_UNCHECKED:'STAGE_DRAFT_UNCHECKED: this revision has no successful producer check.',
77
+ STAGE_DRAFT_OPERATION:'STAGE_DRAFT_OPERATION: this applied operation is not a mesh correction.',
78
+ };
79
+ /** Same names alone cannot bind a producer operation: exact skin/slot/attachment, raster crop and mesh arrays must agree.
80
+ * Compiler UV decimals round-trip float32; compare the represented float32 values exactly, with no numeric tolerance.
81
+ */
82
+ async function draftMappings(modelPath:string,rigPath:string,pkg:PartsViewPackage){
83
+ const model=JSON.parse(await readFile(modelPath,'utf8')),rig=JSON.parse(await readFile(rigPath,'utf8'));
84
+ const mappings:{part:string;skin:string;slot:string;attachment:string;vertices:number;triangles:number}[]=[];
85
+ for(const item of pkg.items){
86
+ if(!item.mesh)continue;
87
+ for(const [key,count]of [['vertices',item.mesh.vertices.length/2],['triangles',item.mesh.triangles.length/3]]as const)if(Object.hasOwn(item.mesh.figures,key)&&item.mesh.figures[key]!==count)throw new Error('STAGE_DRAFT_MISMATCH');
88
+ const candidates=[];
89
+ for(const [skin,slots]of Object.entries(rig.skins??{}))for(const [slot,attachments]of Object.entries(slots as Record<string,unknown>)){
90
+ const a=(attachments as Record<string,any>)[item.name];if(a?.type!=='mesh')continue;
91
+ const b=(model.skins as any[])?.find(s=>s.name===skin)?.attachments?.[slot]?.[item.name];
92
+ if(!b||b.kind!=='mesh'||b.width!==a.width||b.height!==a.height||JSON.stringify(b.uvs?.map(Math.fround))!==JSON.stringify(a.uvs.map(Math.fround))||JSON.stringify(b.triangles)!==JSON.stringify(a.triangles))throw new Error('STAGE_DRAFT_MISMATCH');
93
+ if(!matchingVertexGeometry(a,b))throw new Error('STAGE_DRAFT_MISMATCH');
94
+ candidates.push({part:item.name,skin,slot,attachment:item.name,vertices:a.uvs.length/2,triangles:a.triangles.length/3});
95
+ }
96
+ if(candidates.length!==1)throw new Error('STAGE_DRAFT_MISMATCH');
97
+ mappings.push(candidates[0]!);
98
+ }
99
+ return mappings;
100
+ }
101
+
102
+ /** Compare authored components in the compiler's representation; no posing, meshing or weight judgment. */
103
+ function matchingVertexGeometry(a:Record<string,any>,b:Record<string,any>):boolean {
104
+ const equalNumbers=(a:unknown,b:unknown)=>Array.isArray(a)&&Array.isArray(b)&&a.length===b.length&&a.every((v,i)=>typeof v==='number'&&typeof b[i]==='number'&&Math.fround(v)===Math.fround(b[i]));
105
+ if(Array.isArray(a.weights)){
106
+ if(a.weights.length!==a.uvs.length/2||b.vertices?.weighted!==true||!Array.isArray(b.vertices.bindings)||a.weights.length!==b.vertices.bindings.length)return false;
107
+ return a.weights.every((row:unknown,i:number)=>Array.isArray(row)&&Array.isArray(b.vertices.bindings[i])&&row.length>0&&row.length===b.vertices.bindings[i].length&&row.every((v:unknown,j:number)=>{
108
+ const x=v as Record<string,unknown>,y=b.vertices.bindings[i][j];
109
+ return x&&y&&x.bone===y.bone&&equalNumbers([x.x,x.y,x.weight],[y.x,y.y,y.weight]);
110
+ }));
111
+ }
112
+ if(Array.isArray(a.vertices)&&a.vertices.length===a.uvs.length)return b.vertices?.weighted===false&&equalNumbers(a.vertices,b.vertices.xy);
113
+ throw new Error('STAGE_DRAFT_GEOMETRY_UNSUPPORTED');
114
+ }