@rig-c/review 1.14.1 → 1.16.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
@@ -532,8 +532,9 @@ async function packageVersion(): Promise<string> {
532
532
  return (JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }).version;
533
533
  }
534
534
 
535
- /** Writes the verdict atomically beside its sources. */
536
- export async function saveVerdict(pkg: PartsViewPackage, input: unknown): Promise<PartsVerdict> {
535
+ /** Writes the verdict atomically at its designated destination. */
536
+ export async function saveVerdict(pkg: PartsViewPackage, input: unknown, assertCurrent?: () => Promise<void>): Promise<PartsVerdict> {
537
+ await assertCurrent?.();
537
538
  await assertVerdictDestination(pkg);
538
539
  await assertPartsUnchanged(pkg);
539
540
  await readVerdict(pkg); // Existing read-side evidence errors must never become an implicit reset.
@@ -545,6 +546,7 @@ export async function saveVerdict(pkg: PartsViewPackage, input: unknown): Promis
545
546
  try {
546
547
  await writeFile(tmp, JSON.stringify(verdict, null, 2) + '\n', { flag: 'wx' });
547
548
  await assertVerdictDestination(pkg);
549
+ await assertCurrent?.();
548
550
  await rename(tmp, pkg.verdictPath);
549
551
  } finally { await rm(tmp, { force: true }); }
550
552
  return verdict;
package/src/reference.ts CHANGED
@@ -9,6 +9,14 @@ import type {HandoffFlags} from './handoff.ts';
9
9
  export interface ReferenceBinding {packageSourceHash:string;reference:{id:string;name:string;sha256:string}}
10
10
  export interface PinnedReference {path:string;binding:ReferenceBinding}
11
11
  const pinned=Symbol('explicit CLI reference');
12
+ const sourceAssertion=Symbol('joined source assertion');
13
+ type BoundPackage=ReviewPackage&{[sourceAssertion]?:()=>Promise<void>};
14
+
15
+ /** A composed source verifies its original package and the additional pinned inputs together. */
16
+ export function withReviewAssertion(p:ReviewPackage,assertCurrent:()=>Promise<void>):ReviewPackage {
17
+ const bound:BoundPackage={...p,[sourceAssertion]:assertCurrent};
18
+ return bound;
19
+ }
12
20
  type ReferencedPackage=ReviewPackage&{[pinned]?:PinnedReference};
13
21
  export const selectedReference=(p:ReviewPackage):PinnedReference|undefined=>(p as ReferencedPackage)[pinned];
14
22
  export const referenceBinding=(p:ReviewPackage):ReferenceBinding|undefined=>selectedReference(p)?.binding;
@@ -29,6 +37,8 @@ export async function loadReferencedReview(input:string,reference?:string,handof
29
37
  return {...base,sourceHash,manifest:{...base.manifest,references:[{id,label:video.name+' · selected reference',type:'video',path:'__review_selected_reference__.mp4'},...base.manifest.references]},[pinned]:{path:video.path,binding}} as ReferencedPackage;
30
38
  }
31
39
  export async function assertReviewUnchanged(p:ReviewPackage):Promise<void>{
40
+ const assertCurrent=(p as BoundPackage)[sourceAssertion];
41
+ if(assertCurrent)return assertCurrent();
32
42
  try{const current=await loadReferencedReview(p.manifestPath,selectedReference(p)?.path,p.handoffInputs);if(current.sourceHash!==p.sourceHash||!isDeepStrictEqual(current.reviewedSource,p.reviewedSource)||!isDeepStrictEqual(referenceBinding(current),referenceBinding(p)))throw new Error('source binding differs');}
33
43
  catch{throw new Error('Package inputs changed or are unavailable. Restart review to bind feedback to current inputs.');}
34
44
  }
package/src/server.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { interviewHeaders, interviewRequest, interviewRoutes } from './interview-routes.ts';
2
- import { interviewUnavailable, interviewStale, type JoinedProject } from './joined-project.ts';
2
+ import { directionStale, interviewUnavailable, interviewStale, type JoinedProject } from './joined-project.ts';
3
3
  import {isDeepStrictEqual} from 'node:util';
4
4
  import {appliedValue,parseCorrection,projectSessionCorrection} from './correction-handoff.ts';
5
- import {stagePartsRoutes} from './stage-parts.ts';
5
+ import {stagePartsRoutes,stageVerdictLimit} from './stage-parts.ts';
6
6
  import {createControlServer,type ControlIdentity} from './control-server.ts';
7
7
  import { readFile } from 'node:fs/promises';
8
8
  import { appRoot, buildWeb } from './build.ts';
@@ -39,13 +39,18 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
39
39
  const joined = options.joined;
40
40
  if (joined && !options.capability) throw new Error('Joined interview requires an instance capability');
41
41
  const interview = joined && interviewRoutes(joined.opened.root, joined.designation.picksDir, options.capability!,
42
- {...joined, sourceHash:p.sourceHash, version:joined.designation.version});
42
+ {...joined, sourceHash:p.sourceHash, version:joined.designation.version,draftId:joined.designation.draftId});
43
43
  let interviewBundle: Promise<Blob> | undefined;
44
44
  const bundle=await buildWeb();
45
45
  const unchanged=()=>assertReviewUnchanged(p);
46
46
  const stateDir=options.stateDir??process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review'),starts=[p.root,options.cwd??process.cwd()];
47
47
  const rebuilds=createRebuilds(p,{stateDir,starts,unchanged,bones:p.feedbackCatalog.bones,...(options.stripConcurrency?{stripConcurrency:options.stripConcurrency}:{}),...(options.viewOnly??p.viewOnly?{viewOnly:true}:{})});
48
- const stageParts=stagePartsRoutes({single:p},undefined,rebuilds.stageDraft);
48
+ const stageParts=stagePartsRoutes({single:p},undefined,rebuilds.stageDraft,joined?.draft?{
49
+ joined,viewOnly:options.viewOnly??p.viewOnly??false,readInput:async req=>{
50
+ try{return await bodyJson(req,stageVerdictLimit,'PARTS_VERDICT_BODY_LIMIT');}
51
+ catch(error){if(error instanceof Error&&error.message==='PARTS_VERDICT_BODY_LIMIT')throw error;throw new Error('PARTS_VERDICT_INVALID');}
52
+ },
53
+ }:undefined);
49
54
  // Readings (#108): rigc render's readings on the inspected build and on the latest scratch build, into scratch.
50
55
  const readings=createReadings(p,{stateDir,starts,unchanged,latest:rebuilds.latest});
51
56
  // Bones check (#109): propose --from-config and compare on a scratch copy of the patched handoff config.
@@ -100,6 +105,7 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
100
105
  const controlled=await control?.(req,origin);if(controlled)return controlled;
101
106
  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;}
102
107
  if(req.method==='PUT'&&url.pathname==='/api/session'){
108
+ if(joined?.draft)return json({error:'MODEL_UNAVAILABLE'},409);
103
109
  if(req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
104
110
  const input=await bodyJson(req);await unchanged();
105
111
  return json(await saveSession(p,input,options.stateDir,async(session,sessionBytes,previous)=>{
@@ -170,7 +176,7 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
170
176
  return new Response(result.png?new Uint8Array(result.png):stripJson(result),{headers:{...headers,'Content-Type':result.png?'image/png':'application/json; charset=utf-8','Content-Disposition':`attachment; filename="review-strip.${result.png?'png':'json'}"`}});
171
177
  }
172
178
  if(req.method!=='GET'&&req.method!=='HEAD')return json({error:'Method not allowed'},405);
173
- if(url.pathname==='/api/review'){await unchanged();return json({manifest:p.manifest,...(p.direction?{direction:p.direction}:{}),...(p.setsHash?{setsHash:p.setsHash}:{}),initialAnimation:options.initialAnimation??null,sourceHash:p.sourceHash,reviewedSource:p.reviewedSource,...(referenceBinding(p)?{referenceBinding:referenceBinding(p),explicitReference:{...referenceBinding(p)!.reference,url:'/review-reference'}}:{}),...(p.sourcePainting?{sourcePainting:{...p.sourcePainting,url:'/review-painting'}}:{}),referenceHashes:{...p.referenceHashes,...(referenceBinding(p)?{[referenceBinding(p)!.reference.id]:referenceBinding(p)!.reference.sha256}:{})},report:p.report,feedbackCatalog:p.feedbackCatalog,assetsBase:'/assets/',capabilities:{...(joined?.available?{interview:true}:{}),playback:!!p.manifest.model,modeling:false,motion:false,feedback:true,audio:true}});}
179
+ if(url.pathname==='/api/review'){await unchanged();return json({manifest:p.manifest,...(p.direction?{direction:p.direction}:{}),...(p.setsHash?{setsHash:p.setsHash}:{}),initialAnimation:options.initialAnimation??null,sourceHash:p.sourceHash,reviewedSource:p.reviewedSource,...(referenceBinding(p)?{referenceBinding:referenceBinding(p),explicitReference:{...referenceBinding(p)!.reference,url:'/review-reference'}}:{}),...(p.sourcePainting?{sourcePainting:{...p.sourcePainting,url:'/review-painting'}}:{}),referenceHashes:{...p.referenceHashes,...(referenceBinding(p)?{[referenceBinding(p)!.reference.id]:referenceBinding(p)!.reference.sha256}:{})},report:p.report,feedbackCatalog:p.feedbackCatalog,assetsBase:'/assets/',capabilities:{...(joined?.available?{interview:true}:{}),...(joined?.draft?{preRig:true}:{}),playback:!!p.manifest.model,modeling:false,motion:false,feedback:!joined?.draft,audio:true}});}
174
180
  if(url.pathname==='/api/session'){await unchanged();return json(await readSession(p,options.stateDir));}
175
181
  if(url.pathname==='/api/rebuild')return json(await rebuilds.describe());
176
182
  if(url.pathname==='/api/rebuild/history')return json(await rebuilds.history());
@@ -218,7 +224,7 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
218
224
  if(url.pathname==='/styles.css')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/styles.css'),{headers:{...headers,'Content-Type':'text/css'}});
219
225
  return json({error:'Not found'},404);
220
226
  } finally { live.onRequestEnd(url.pathname); }
221
- }catch(e){const message=e instanceof Error?e.message:'Request failed';return json({error:message},message.includes('inputs changed')?409:400);}};
227
+ }catch(e){const message=e instanceof Error?e.message:'Request failed';return json({error:message},message===directionStale || message.startsWith(interviewStale) || message.includes('inputs changed')?409:400);}};
222
228
  const server=Bun.serve({hostname:'127.0.0.1',port:options.port??4317,websocket:live.websocket,async fetch(req,srv){const res=await handle(req,srv.port,srv);if(!res)return undefined as unknown as Response;return stampOpen(req,res,options.open);}});
223
229
  rawStop=server.stop.bind(server);
224
230
  server.stop=((closeActiveConnections?:boolean)=>{live.stop();return rawStop!(closeActiveConnections);}) as typeof server.stop;
@@ -1,50 +1,80 @@
1
- /** Read-only embedding of the existing atlas inspector. No browser-supplied filesystem paths or verdict writes. */
1
+ /** Embedded parts inspector. Only the designated joined source can save a verdict. */
2
2
  import {join} from 'node:path';
3
- import {readFile} from 'node:fs/promises';
3
+ import {lstat,readFile} from 'node:fs/promises';
4
4
  import {appRoot,buildWeb} from './build.ts';
5
5
  import type {ReviewPackage} from './manifest.ts';
6
- import {loadPartsAtlas,loadPartsView,assertPartsUnchanged,partsViewJson,servedImage,type PartsViewPackage} from './parts-view.ts';
6
+ import {loadPartsAtlas,loadPartsView,assertPartsUnchanged,partsViewJson,servedImage,verdictSource,readVerdict,saveVerdict,exportPartsVerdict,type PartsViewPackage} from './parts-view.ts';
7
7
  import {serveReference,assertReviewUnchanged} from './reference.ts';
8
- export function stagePartsRoutes(packages:{single:ReviewPackage}|{a:ReviewPackage;b:ReviewPackage},loadAtlas:typeof loadPartsAtlas=loadPartsAtlas,draft?:DraftReader) {
8
+ import {digest,object} from './interview-project.ts';
9
+ import {interviewStale,type JoinedProject} from './joined-project.ts';
10
+
11
+ export const stageVerdictLimit=4*1024*1024;
12
+ export const stageVerdictRefusals=[
13
+ 'PARTS_VERDICT_READ_ONLY','PARTS_VERDICT_SOURCE_MISMATCH','PARTS_VERDICT_OUTPUT','PARTS_VERDICT_UNAVAILABLE',
14
+ 'PARTS_VERDICT_BODY_LIMIT','PARTS_VERDICT_READ','PARTS_VERDICT_INVALID','PARTS_VERDICT_UNKNOWN_PART',
15
+ 'PARTS_VERDICT_MISSING_PART','PARTS_VERDICT_NOTE_REQUIRED','PARTS_MESH_OUTCOME_UNAVAILABLE','PARTS_MESH_OUTCOME',
16
+ 'PARTS_VERDICT_NOT_CLEAN','PARTS_VERDICT_NOTHING_FLAGGED','PARTS_VIEW_SOURCE_CHANGED','PARTS_VERDICT_INPUT_COLLISION',
17
+ ] as const;
18
+ interface JoinedVerdictOptions {
19
+ joined:JoinedProject;
20
+ readInput:(req:Request)=>Promise<unknown>;
21
+ viewOnly:boolean;
22
+ }
23
+
24
+ export function stagePartsRoutes(packages:{single:ReviewPackage}|{a:ReviewPackage;b:ReviewPackage},loadAtlas:typeof loadPartsAtlas=loadPartsAtlas,draft?:DraftReader,verdictOptions?:JoinedVerdictOptions) {
9
25
  const corrections=new Map<string,Promise<{pkg:PartsViewPackage;metadata:unknown}>>();
10
26
  const loaded=new Map<string,ReturnType<typeof loadPartsAtlas>>();let bundle:Promise<Blob>|undefined;
11
27
  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'"};
12
28
  return async(req:Request):Promise<Response|null>=>{
13
29
  const url=new URL(req.url),path=url.pathname,read=req.method==='GET'||req.method==='HEAD';
14
- if(!read)return null;
30
+ const save=path==='/api/stage-parts/verdict'&&req.method==='POST';
31
+ const format=read&&path==='/api/stage-parts/export/json'?'json':read&&path==='/api/stage-parts/export/issue'?'issue':null;
32
+ const verdictRequest=save||format!==null;
33
+ if(!read&&!save)return null;
34
+ if(save&&req.headers.get('origin')!==url.origin)return Response.json({error:'Same-origin Origin required'},{status:403,headers});
35
+ if(verdictRequest&&(!verdictOptions?.joined.verdictDirectory||verdictOptions.viewOnly||(req.headers.get('X-Review-Stage-Build')??'inspected')!=='inspected')){
36
+ return Response.json({error:'PARTS_VERDICT_READ_ONLY'},{status:409,headers});
37
+ }
15
38
  if(['/stage-parts.html','/parts.js','/parts.css'].includes(path)){
16
39
  if(path==='/parts.js'){bundle??=buildWeb('parts');return new Response(req.method==='HEAD'?null:await bundle,{headers:{...headers,'Content-Type':'text/javascript'}});}
17
40
  return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/'+(path==='/stage-parts.html'?'parts.html':'parts.css')),{headers:{...headers,'Content-Type':path.endsWith('.css')?'text/css':'text/html; charset=utf-8'}});
18
41
  }
19
- const match=('single' in packages?/^\/api\/stage-parts(?:\/(image|page)\/(\d+))?$/:/^\/api\/compare\/(a|b)\/stage-parts(?:\/(image|page)\/(\d+))?$/).exec(path);
42
+ const match=('single' in packages?/^\/api\/stage-parts(?:\/(image|page)\/(\d+))?$/:/^\/api\/compare\/(a|b)\/stage-parts(?:\/(image|page)\/(\d+))?$/).exec(verdictRequest?'/api/stage-parts':path);
20
43
  if(!match)return null;
21
44
  const key='single' in packages?'single':match[1] as 'a'|'b',p='single' in packages?packages.single:packages[key as 'a'|'b'];
22
45
  const kind=match['single' in packages?1:2] as 'image'|'page'|undefined,index=match['single' in packages?2:3];
23
46
  try{
24
47
  // 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) {
48
+ const recorded=verdictOptions?.joined.draft;
49
+ if ('single' in packages && (recorded||p.handoff?.parts&&p.handoff.rig)) {
26
50
  await assertReviewUnchanged(p);
27
51
  const build=req.headers.get('X-Review-Stage-Build')??'inspected';
28
52
  if(build!=='inspected'&&!/^[a-f0-9]{64}$/.test(build))throw new Error('STAGE_DRAFT_STALE');
29
53
  const applied=build==='inspected'?null:await draft?.(build);
30
54
  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);
55
+ const model=recorded?.model??applied?.model??(p.manifest.model?join(p.root,p.manifest.model):null);
32
56
  if(!model)throw new Error('STAGE_DRAFT_UNAVAILABLE');
33
57
  let promise=corrections.get(build);
34
58
  if(!promise){
35
59
  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);
60
+ const rig=recorded?.rig??join(applied?.spec??p.handoff!.rig!,'rig.json');
61
+ const meshReport=recorded?.meshReport??join(applied?.spec??p.handoff!.rig!,'mesh_report.json');
62
+ const pkg=await loadPartsView(recorded?.parts??p.handoff!.parts!,{rig,meshReport});
63
+ if(recorded&&[...pkg.files,...pkg.flagFiles].some(file=>recorded.files.get(file.abs)!==file.sha256))
64
+ throw new Error('PARTS_VERDICT_SOURCE_MISMATCH');
65
+ const mappings=await draftMappings(model,rig,pkg,recorded?.files);
39
66
  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};
67
+ return {pkg,metadata:mappings.length?{label:'Draft rig · structure evidence only',buildId:build,inspectionSourceHash:p.sourceHash,mappings,evidence:applied?.evidence??null,...(recorded?{inspectionOnly:true}:{})}:null};
41
68
  })();corrections.set(build,promise);
42
69
  }
43
70
  const {pkg,metadata}=await promise;
44
71
  // Every image is served against the same full pinned draft, including geometry and flags.
45
72
  await assertReviewUnchanged(p);await assertPartsUnchanged(pkg);
46
73
  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});
74
+ const writable=build==='inspected'&&verdictOptions?.joined.verdictDirectory&&!verdictOptions.viewOnly;
75
+ const saved=writable?await joinedVerdict(req,p,pkg,verdictOptions,save,format,headers):null;
76
+ if(saved instanceof Response)return saved;
77
+ return Response.json({...partsViewJson(pkg,saved??{verdict:null,stale:null}),differenceAvailable:false,readOnly:!writable,...(recorded&&!writable?{verdictReadOnlyReason:'PARTS_VERDICT_READ_ONLY: a pending parts review and an explicit verdict output directory are required.'}:{}),inspectionSourceHash:p.sourceHash,...(saved?{joinedVerdictBinding:saved.binding,verdictFile:saved.filename}:{}),...(metadata?{draft:metadata}:{draftUnavailable:stageDraftRefusals.STAGE_DRAFT_NO_MESH})},{headers});
48
78
  }
49
79
  let promise=loaded.get(key);
50
80
  const initializing=!promise;
@@ -59,8 +89,49 @@ export function stagePartsRoutes(packages:{single:ReviewPackage}|{a:ReviewPackag
59
89
  if(kind){const model=pkg.files[0]!;await serveReference(new Request(req.url,{method:'HEAD'}),model.abs,model.sha256,headers);}
60
90
  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);}
61
91
  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});}
92
+ }catch(error){const code=error instanceof Error?error.message.split(':')[0]??'':'';
93
+ if((verdictRequest||verdictOptions)&& (code===interviewStale||stageVerdictRefusals.some(refusal=>refusal===code))){
94
+ const invalid=save&&!['PARTS_VERDICT_SOURCE_MISMATCH','PARTS_VERDICT_OUTPUT','PARTS_VERDICT_READ_ONLY','PARTS_VIEW_SOURCE_CHANGED',interviewStale].includes(code);
95
+ return Response.json({error:code},{status:invalid?400:409,headers});
96
+ }
97
+ 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});}
98
+ };
99
+ }
100
+
101
+ /** The output address and request binding share the exact joined and parts identities.
102
+ * Only the standard verdict is exported, with source paths relative to the file on disk.
103
+ */
104
+ async function joinedVerdict(req:Request,p:ReviewPackage,pkg:PartsViewPackage,options:JoinedVerdictOptions,
105
+ save:boolean,format:'json'|'issue'|null,headers:Record<string,string>){
106
+ const {joined}=options,{hash}=joined.opened,{version}=joined.designation;
107
+ const binding=digest(JSON.stringify({projectHash:hash,version,sourceHash:p.sourceHash,parts:verdictSource(pkg)}));
108
+ const filename=`parts-review-${binding}.json`;
109
+ const directory=joined.verdictDirectory!();
110
+ const destination={...pkg,verdictPath:join(directory,filename)};
111
+ const assertCurrent=async()=>{
112
+ await joined.assertCurrent();
113
+ await assertPartsUnchanged(pkg);
114
+ try{
115
+ joined.verdictDirectory!();
116
+ const entry=await lstat(destination.verdictPath).catch((e:NodeJS.ErrnoException)=>{if(e.code!=='ENOENT')throw e;return null;});
117
+ if(entry&&(!entry.isFile()||entry.nlink!==1))throw new Error('Aliased output');
118
+ }catch{throw new Error('PARTS_VERDICT_OUTPUT');}
63
119
  };
120
+ const input=save?object(await options.readInput(req)):null;
121
+ if(input&&input.binding!==binding)throw new Error('PARTS_VERDICT_SOURCE_MISMATCH');
122
+ // Pointed comments use the standalone crop endpoints. Joined sign-off exposes part and mesh notes.
123
+ if(input&&input.comments!==undefined)throw new Error('PARTS_VERDICT_INVALID');
124
+ await assertCurrent();
125
+ const saved=await readVerdict(destination);
126
+ if(saved.stale)throw new Error('PARTS_VERDICT_SOURCE_MISMATCH');
127
+ if(input)return Response.json({verdict:await saveVerdict(destination,input,assertCurrent)},{headers});
128
+ if(format){
129
+ if(!saved.verdict)throw new Error('PARTS_VERDICT_UNAVAILABLE');
130
+ return new Response(req.method==='HEAD'?null:exportPartsVerdict(saved.verdict,format),{headers:{...headers,
131
+ 'Content-Type':format==='json'?'application/json':'text/markdown; charset=utf-8',
132
+ 'Content-Disposition':`attachment; filename="${format==='json'?filename:filename.replace(/\.json$/,'.md')}"`}});
133
+ }
134
+ return {...saved,binding,filename};
64
135
  }
65
136
 
66
137
  export interface DraftSnapshot {id:string;spec:string;model:string;evidence:unknown}
@@ -79,8 +150,13 @@ export const stageDraftRefusals:Record<string,string>={
79
150
  /** Same names alone cannot bind a producer operation: exact skin/slot/attachment, raster crop and mesh arrays must agree.
80
151
  * Compiler UV decimals round-trip float32; compare the represented float32 values exactly, with no numeric tolerance.
81
152
  */
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'));
153
+ async function draftMappings(modelPath:string,rigPath:string,pkg:PartsViewPackage,files?:ReadonlyMap<string,string>){
154
+ const parse=async(path:string)=>{
155
+ const bytes=await readFile(path);
156
+ if(files&&digest(bytes)!==files.get(path))throw new Error('PARTS_VERDICT_SOURCE_MISMATCH');
157
+ return JSON.parse(bytes.toString('utf8'));
158
+ };
159
+ const [model,rig]=await Promise.all([parse(modelPath),parse(rigPath)]);
84
160
  const mappings:{part:string;skin:string;slot:string;attachment:string;vertices:number;triangles:number}[]=[];
85
161
  for(const item of pkg.items){
86
162
  if(!item.mesh)continue;
package/web/catalog-en.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  export const enCatalog: Readonly<Record<string, string>> = {
2
+ "RIG_VERSION_UNAVAILABLE: this draft has no recorded rig review package.": "RIG_VERSION_UNAVAILABLE: this draft has no recorded rig review package.",
3
+ "DIRECTION_VERSION_UNAVAILABLE: this draft has no recorded rig review package.": "DIRECTION_VERSION_UNAVAILABLE: this draft has no recorded rig review package.",
4
+ "PARTS_VERDICT_READ_ONLY: a pending parts review and an explicit verdict output directory are required.": "PARTS_VERDICT_READ_ONLY: a pending parts review and an explicit verdict output directory are required.",
2
5
  "INTERVIEW_OPTIONS_STALE": "INTERVIEW_OPTIONS_STALE: Project or source changed. Reopen the inspection.",
6
+ "interview.joinedDraft": "Draft {0} · project {1} · source {2}",
3
7
  "interview.joined": "Create version {0} · project SHA-256 {1} · inspection SHA-256 {2}",
4
8
  "interview.mismatch": "INTERVIEW_SOURCE_MISMATCH: The inspection does not match the designated Create package.",
5
9
  "interview.imageUnavailable": "INTERVIEW_IMAGE_INVALID: The bound image could not be displayed.",
@@ -98,6 +102,8 @@ export const enCatalog: Readonly<Record<string, string>> = {
98
102
  "direction.authored": "Authored direction · rig v{0} · {1} · SHA-256 {2}",
99
103
  "direction.authoredUnavailable": "DIRECTION_METADATA_UNAVAILABLE · No authored direction bound to this model on stage.",
100
104
  "direction.runtimeCameraUnavailable": "CAMERA_PLAYBACK_UNAVAILABLE · Authored camera and timing are read-only here. Pan and zoom adjust the inspection viewport.",
105
+ "direction.joined": "Create post {0} · project-relative model {1} · recorded package {2} · project SHA-256 {3} · package source SHA-256 {4}",
106
+ "Choose the joined Create post version.": "Choose the joined Create post version.",
101
107
  "direction.cameraApplyUnavailable": "CAMERA_APPLY_UNSUPPORTED · Camera Apply is unavailable.",
102
108
  "direction.keys": "Authored camera and timing keys",
103
109
  "DIRECTION_UNAVAILABLE: no direction inspection contract is installed.": "DIRECTION_UNAVAILABLE: no direction inspection contract is installed.",
package/web/catalog-ko.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  export const koCatalog: Readonly<Record<string, string>> = {
2
+ "RIG_VERSION_UNAVAILABLE: this draft has no recorded rig review package.": "RIG_VERSION_UNAVAILABLE: 이 초안에는 기록된 리그 검토 패키지가 없습니다.",
3
+ "DIRECTION_VERSION_UNAVAILABLE: this draft has no recorded rig review package.": "DIRECTION_VERSION_UNAVAILABLE: 이 초안에는 기록된 리그 검토 패키지가 없습니다.",
4
+ "PARTS_VERDICT_READ_ONLY: a pending parts review and an explicit verdict output directory are required.": "PARTS_VERDICT_READ_ONLY: 대기 중인 파츠 검토와 명시적으로 지정한 판정 출력 디렉터리가 필요합니다.",
2
5
  "INTERVIEW_OPTIONS_STALE": "INTERVIEW_OPTIONS_STALE: 프로젝트 또는 원본이 바뀌었어요. 검토를 다시 여세요.",
6
+ "interview.joinedDraft": "초안 {0} · 프로젝트 {1} · 원본 {2}",
3
7
  "interview.joined": "Create 버전 {0} · 프로젝트 SHA-256 {1} · 검토 SHA-256 {2}",
4
8
  "interview.mismatch": "INTERVIEW_SOURCE_MISMATCH: 검토 대상이 지정한 Create 패키지와 일치하지 않아요.",
5
9
  "interview.imageUnavailable": "INTERVIEW_IMAGE_INVALID: 바인딩된 이미지를 표시할 수 없습니다.",
@@ -98,6 +102,8 @@ export const koCatalog: Readonly<Record<string, string>> = {
98
102
  "direction.authored": "작성된 연출 · 리그 v{0} · {1} · SHA-256 {2}",
99
103
  "direction.authoredUnavailable": "DIRECTION_METADATA_UNAVAILABLE · 화면의 모델에 연결된 연출 데이터가 없습니다.",
100
104
  "direction.runtimeCameraUnavailable": "CAMERA_PLAYBACK_UNAVAILABLE · 작성된 카메라와 타이밍은 여기서 읽기 전용입니다. 이동과 확대는 검사 화면에만 적용됩니다.",
105
+ "direction.joined": "Create 포스트 {0} · 프로젝트 기준 모델 {1} · 기록된 패키지 {2} · 프로젝트 SHA-256 {3} · 패키지 소스 SHA-256 {4}",
106
+ "Choose the joined Create post version.": "연결된 Create 포스트 버전을 선택하세요.",
101
107
  "direction.cameraApplyUnavailable": "CAMERA_APPLY_UNSUPPORTED · 카메라 적용을 지원하지 않습니다.",
102
108
  "direction.keys": "작성된 카메라 및 타이밍 키",
103
109
  "DIRECTION_UNAVAILABLE: no direction inspection contract is installed.": "DIRECTION_UNAVAILABLE: 연출 검사 계약이 설치되어 있지 않습니다.",
@@ -15,6 +15,7 @@ export interface DirectionView {
15
15
 
16
16
  export function directionRows(view: DirectionView): { key: string; values?: string[] }[] {
17
17
  const model = view.model;
18
+ const joined = model?.inspected ? view.authored?.joined : undefined;
18
19
  return [
19
20
  model ? { key: model.inspected ? 'direction.inspected' : 'direction.scratch', values: [model.path, model.sha256] }
20
21
  : { key: 'direction.modelUnavailable' },
@@ -26,6 +27,8 @@ export function directionRows(view: DirectionView): { key: string; values?: stri
26
27
  model?.inspected && view.authored
27
28
  ? { key: 'direction.authored', values: [String(view.authored.rigVersion), view.authored.file.path, view.authored.file.sha256] }
28
29
  : { key: 'direction.authoredUnavailable' },
30
+ ...(joined ? [{ key: 'direction.joined', values: [String(joined.postVersion), joined.projectModel.path,
31
+ joined.packageRoot, joined.projectHash, joined.packageSourceHash] }] : []),
29
32
  { key: 'direction.runtimeCameraUnavailable' },
30
33
  { key: 'direction.cameraApplyUnavailable' },
31
34
  ];
@@ -33,7 +33,7 @@ async function request(access: InstanceAccess, path: string, body?: Picks) {
33
33
  }
34
34
 
35
35
  export async function mountInterview(host: HTMLElement, access: InstanceAccess) {
36
- let data: {questions:Question[];historical:HistoricalInterview[]; binding?:{projectHash:string;sourceHash:string;version:number}};
36
+ let data: {questions:Question[];historical:HistoricalInterview[]; binding?:{projectHash:string;sourceHash:string;version?:number;draftId?:string}};
37
37
  try {data = await request(access, '/api/interview');}
38
38
  catch (error) {
39
39
  const render = () => {host.textContent = t(errorKey(error));};
@@ -53,7 +53,7 @@ export async function mountInterview(host: HTMLElement, access: InstanceAccess)
53
53
  let busy = false;
54
54
  const render = () => {
55
55
  const joined = data.binding;
56
- const source = joined ? element('p', t('interview.joined', [String(joined.version), joined.projectHash, joined.sourceHash])) : null;
56
+ const source = joined ? element('p', t(joined.draftId===undefined?'interview.joined':'interview.joinedDraft', [joined.draftId??String(joined.version), joined.projectHash, joined.sourceHash])) : null;
57
57
  if (source) source.className = 'interview-binding';
58
58
  const archive = element('details');
59
59
  archive.append(element('summary', t('interview.legacy')));
package/web/main.ts CHANGED
@@ -35,7 +35,7 @@ import {historyRow,isPatchJob,recordFor,refusedText,restoredOutcomeForJob,retarg
35
35
  import {meshEditBinding,meshEditText,type MeshEditDocument} from '../src/mesh-edit.ts';
36
36
  import {chestRegionsBinding,cropWorldMapping,type CropWorldMapping} from '../src/chest-regions.ts';
37
37
  import {bindWorkspaceUI,selectedInspector,type WorkspaceUI} from './workspace-ui.ts';
38
- import {setSourceAttribute,setSourceText,sourceTextContent,tr} from './i18n.ts';
38
+ import {setSourceAttribute,setSourceText,sourceTextContent,t,tr} from './i18n.ts';
39
39
  import {holdScrubBox,releaseScrubBox,scrubBox} from './scrub-box.ts';
40
40
  import {bindInspectorBlocks,activeBlocksUI,restoreActiveBlocksUI,type InspectorBlocks} from './inspector-blocks.ts';
41
41
  import {connectControl} from './control.ts';
@@ -73,7 +73,7 @@ import {assertRigFieldOps,RIG_FIELDS_READOUT_BARS,TURN_BONE} from '../src/rig-fi
73
73
  import {IDLE_READOUT_BARS,type LocalChannel} from '../src/idle-tracks.ts';
74
74
  import type {PatchOp} from '../src/config-patch.ts';
75
75
 
76
- interface ReviewResponse { direction?:DirectionInspection; setsHash?:string; referenceHashes?:Record<string,string>; initialAnimation?:string|null; manifest: ReviewManifest; referenceBinding?:ReferenceBinding; explicitReference?:{id:string;name:string;sha256:string;url:string}; sourcePainting?:{id:string;path:string;sha256:string;url:string}; sourceHash: string; reviewedSource: ReviewedSource; report: ReportSeeds | null; feedbackCatalog: FeedbackCatalog; assetsBase: string; capabilities: { interview?:true; playback: boolean; modeling: false; motion: false; feedback: boolean; audio: boolean } }
76
+ interface ReviewResponse { direction?:DirectionInspection; setsHash?:string; referenceHashes?:Record<string,string>; initialAnimation?:string|null; manifest: ReviewManifest; referenceBinding?:ReferenceBinding; explicitReference?:{id:string;name:string;sha256:string;url:string}; sourcePainting?:{id:string;path:string;sha256:string;url:string}; sourceHash: string; reviewedSource: ReviewedSource; report: ReportSeeds | null; feedbackCatalog: FeedbackCatalog; assetsBase: string; capabilities: { interview?:true; preRig?:true; playback: boolean; modeling: false; motion: false; feedback: boolean; audio: boolean } }
77
77
  interface PoseReference { schema: 'rig-review-pose/1'; coordinateSystem: 'image-pixels-y-down'; width: number; height: number; joints: { id: string; x: number; y: number; parent?: string }[] }
78
78
  interface SequenceJoint { state: 'observed' | 'occluded' | 'missing' | 'inferred'; at?: [number, number]; score?: number }
79
79
  interface PoseSequence { spec: 'rig-pose-sequence/1'; space: { units: 'picture-px'; origin: 'top-left'; y: 'down' }; width: number; height: number; source?: string; frames: { t: number; people: { id: string; joints: Record<string, SequenceJoint> }[] }[]; camera?: { s: number; tx: number; ty: number; inliers: number }[]; cameraSource?: unknown }
@@ -794,6 +794,11 @@ function syncCorrectionStage(): void {
794
794
 
795
795
  function correctionSelection(path: 'described' | 'made'): Json {
796
796
  const stage = select('correction-stage').value, identity = input('correction-selector').value;
797
+ const joined = data.direction?.joined;
798
+ if (stage === 'direction-review' && joined) {
799
+ if (path === 'made') throw new Error(t('direction.cameraApplyUnavailable'));
800
+ if (identity !== String(joined.postVersion)) throw new Error(tr('Choose the joined Create post version.'));
801
+ }
797
802
  if (stage === 'parts-review' && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(identity)) {
798
803
  return { path, selector: { stage, kind: 'draft', id: identity } };
799
804
  }
@@ -981,7 +986,7 @@ function bind(): void {
981
986
  const picker=select('part-set');picker.value=name;picker.dispatchEvent(new Event('change',{bubbles:true}));
982
987
  });
983
988
  viewDisposers.push(()=>directionPanel?.dispose());
984
- viewDisposers.push(bindStageNav({access,interview:data.capabilities.interview,model:!!data.manifest.model,direction:active=>directionPanel?.show(active),setup:()=>showInspector('rig'),draftBuild:()=>appliedOnStage?.buildId??'inspected',correction:openStageCorrection}));
989
+ viewDisposers.push(bindStageNav({access,interview:data.capabilities.interview,preRig:data.capabilities.preRig,model:!!data.manifest.model,direction:active=>directionPanel?.show(active),setup:()=>showInspector('rig'),draftBuild:()=>appliedOnStage?.buildId??'inspected',correction:data.capabilities.preRig?undefined:openStageCorrection}));
985
990
  workspace=bindWorkspaceUI({changed:fitCamera,defaultTheme:theme=>appearance?.set(theme),currentTheme:()=>appearance?.get()});
986
991
  viewport.state.cameraSync=workspace.defaults().defaultCameraSync;input('camera-sync').checked=viewport.state.cameraSync;input('idle-repeat').checked=workspace.defaults().defaultIdleRepeat;
987
992
  appearance=bindAppearance(select('settings-theme'),workspace.defaults().theme);
@@ -1047,6 +1052,7 @@ async function start(): Promise<void> {
1047
1052
  let writes: { capabilityRequired: boolean; control?: boolean };
1048
1053
  [data, session, writes] = await Promise.all([api<ReviewResponse>('/api/review'), api<ReviewSession>('/api/session'), api<{ capabilityRequired: boolean; control?: boolean }>('/api/access')]);
1049
1054
  readOnly = readOnlyReason(access, writes.capabilityRequired);
1055
+ if(data.capabilities.preRig)el('write-review').hidden=true;
1050
1056
  submittedBaseline=structuredClone(session);
1051
1057
  text('package-title', data.manifest.title); text('revision', data.manifest.revision); document.title = `${data.manifest.title} · rig review`; text('source-hash', `source ${data.sourceHash.slice(0, 12)}`); select('review-status').value = session.status; select('feedback-target-kind').value = 'rig'; input('feedback-target-name').value = data.manifest.id;
1052
1058
  select('reference-select').replaceChildren(); for (const reference of data.manifest.references) select('reference-select').append(option(reference.id, `${reference.label} · ${reference.type}`));
package/web/parts.css CHANGED
@@ -50,6 +50,7 @@ h2{font-size:11px;letter-spacing:.06em;color:var(--muted);margin:4px 0 8px}
50
50
  #pv-flags summary{cursor:pointer;font-size:11px;color:var(--muted)}
51
51
  #pv-flags li.pv-none{border-left-color:var(--line);background:none;color:var(--muted)}
52
52
  .pv-verdict{margin-top:16px;display:flex;flex-direction:column;gap:6px}
53
+ #pv-save-status{overflow-wrap:anywhere}
53
54
  .pv-outcomes{display:flex;gap:10px}
54
55
  .pv-label{font-size:11px;color:var(--muted);margin-top:4px}
55
56
  textarea,select{font:inherit;color:inherit;background:var(--bg);border:1px solid var(--line);border-radius:5px;padding:4px}
package/web/parts.ts CHANGED
@@ -30,7 +30,9 @@ type Flag =
30
30
  | { id: string; item: string; source: 'check'; kind: 'check'; path: string; line: string; root: string; status: string | null; entry: Record<string, unknown>; classification?: 'part' | 'pair' | 'evidence' | 'unclassified' };
31
31
  interface ViewData {
32
32
  inspectionSourceHash?:string;
33
- draft?:{label:string;buildId:string;inspectionSourceHash:string;mappings:{part:string;skin:string;slot:string;attachment:string;vertices:number;triangles:number}[];evidence:unknown};draftUnavailable?:string;
33
+ joinedVerdictBinding?:string;
34
+ verdictReadOnlyReason?:string;
35
+ draft?:{inspectionOnly?:boolean;label:string;buildId:string;inspectionSourceHash:string;mappings:{part:string;skin:string;slot:string;attachment:string;vertices:number;triangles:number}[];evidence:unknown};draftUnavailable?:string;
34
36
  differenceAvailable?:boolean;painting:{sha256:string;width:number;height:number}|null;sourceHash:string;mode: 'parts' | 'atlas'; title: string; rigSize: [number, number] | null; items: Item[]; pages: Page[]; flags: Flag[]; readings?: Flag[];
35
37
  flagSources: string[]; flagMissing: string[]; verdictFile: string;
36
38
  verdict: { comments?:PartsComment[];status: string; parts: Record<string, Entry> } | null; verdictStale: 'files' | 'flags' | null;
@@ -320,7 +322,7 @@ function renderMesh(): void {
320
322
  }
321
323
  panel.append(figures);
322
324
  const help = document.createElement('p'); help.textContent = t('Pink: art pixels outside every triangle.'); panel.append(help);
323
- if(stageEmbedded){document.querySelector('.pv-verdict')!.before(panel);return;}
325
+ if(stageEmbedded&&!state.data?.joinedVerdictBinding){document.querySelector('.pv-verdict')!.before(panel);return;}
324
326
  const entry = state.verdict.get(item.name)!;
325
327
  const select = document.createElement('select'); select.setAttribute('aria-label', t('Mesh outcome'));
326
328
  for (const [value, label] of [['pending', 'Pending'], ['clean', 'Clean'], ['flagged', 'Flagged']]) { const option = document.createElement('option'); option.value = value!; option.textContent = t(label!); select.append(option); }
@@ -384,13 +386,21 @@ async function approveAll(): Promise<void> {
384
386
  }
385
387
 
386
388
  async function save(): Promise<void> {
387
- if(stageEmbedded)return;
388
- const status = $('pv-save-status');
389
- const body = { status: $<HTMLSelectElement>('pv-overall').value, parts: Object.fromEntries(state.verdict),comments };
390
- const res = await fetch(access.route('/api/parts/verdict'), { method: 'POST', headers: access.headers({ 'Content-Type': 'application/json' }), body: JSON.stringify(body) });
391
- const out = await res.json() as { error?: string; verdict?: { source: { sha256: string } } };
392
- status.textContent = res.ok ? t('Saved {file}: source {hash}.', { file: state.data!.verdictFile, hash: out.verdict!.source.sha256.slice(0, 12) }) : out.error ?? t('Save failed.');
393
- status.dataset.result = res.ok ? 'saved' : 'refused';
389
+ const data=state.data;
390
+ if(!data||stageEmbedded&&(!data.joinedVerdictBinding||!access.capability||stageBuild!=='inspected'))return;
391
+ const status = $('pv-save-status'),button=$<HTMLButtonElement>('pv-save');
392
+ const body = { status: $<HTMLSelectElement>('pv-overall').value, parts: Object.fromEntries(state.verdict),
393
+ ...(stageEmbedded?{binding:data.joinedVerdictBinding}:{comments}) };
394
+ button.disabled=true;
395
+ try{
396
+ const headers=stageEmbedded?stageHeaders():access.headers();headers.set('Content-Type','application/json');
397
+ const res = await fetch(access.route(stageEmbedded?partsApi+'/verdict':'/api/parts/verdict'), { method: 'POST', headers, body: JSON.stringify(body) });
398
+ const out = await res.json() as { error?: string; verdict?: { source: { sha256: string } } };
399
+ status.textContent = res.ok ? t('Saved {file}: source {hash}.', { file: data.verdictFile, hash: out.verdict!.source.sha256.slice(0, 12) }) : out.error ? t(out.error) : t('Save failed.');
400
+ status.dataset.result = res.ok ? 'saved' : 'refused';
401
+ }catch{
402
+ status.textContent=t('Save failed.');status.dataset.result='refused';
403
+ }finally{button.disabled=false;}
394
404
  }
395
405
 
396
406
  async function boot(): Promise<void> {
@@ -405,7 +415,7 @@ async function boot(): Promise<void> {
405
415
  document.querySelector<HTMLElement>('.pv-layout')!.hidden=true;
406
416
  document.querySelector<HTMLElement>('.pv-verdict')!.hidden=true;
407
417
  const approveButton=$<HTMLButtonElement>('pv-approve-all');approveButton.disabled=true;
408
- const saveButton=$<HTMLButtonElement>('pv-save');saveButton.disabled=true;saveButton.title=t('Embedded atlas inspection is read-only. Use the parts command for a separate sign-off.');
418
+ const saveButton=$<HTMLButtonElement>('pv-save');saveButton.disabled=true;
409
419
  }
410
420
  window.addEventListener('message',event=>{if(event.source!==parent||event.origin!==location.origin||event.data?.type!=='review-stage-language'||!['en','ko'].includes(event.data.language))return;setLinkLanguage(null);setLanguagePreference(event.data.language);});
411
421
  connectLiveWindow(access);
@@ -414,6 +424,14 @@ async function boot(): Promise<void> {
414
424
  const data = await res.json() as ViewData & { error?: string };
415
425
  if (!res.ok) { const status=$('pv-load');status.textContent=t(data.error??'Load failed.');status.dataset.result='refused';return; }
416
426
  state.data = data;if(!data.differenceAvailable)document.querySelector('[data-pv-comparison="difference"]')?.remove();if(stageEmbedded)for(const item of data.items)if(item.mesh)state.meshShown.add(item.name);$('reference-empty').textContent=data.painting?'':t('PARTS_REFERENCE_UNAVAILABLE: supply --painting to compare the original painting');$('reference-empty').hidden=!!data.painting;if(data.painting)viewport.state.cameraSync=true;comments.push(...data.verdict?.comments??[]);setupPartsComments();viewport.bindNavigation(undefined,()=>!commentUi?.active());viewport.observeResize();
427
+ if(stageEmbedded&&data.joinedVerdictBinding){
428
+ document.querySelector<HTMLElement>('.pv-verdict')!.hidden=false;
429
+ $('pv-approve-all').hidden=true;
430
+ $('pv-comment-count').hidden=true;
431
+ const save=$<HTMLButtonElement>('pv-save');
432
+ save.disabled=!access.capability;
433
+ if(!access.capability)save.title=t('Read-only view: reopen with rig-review open to edit.');
434
+ }
417
435
  document.getElementById('parts-correction-hint')!.hidden = data.mode !== 'parts' || stageEmbedded;
418
436
  for (const item of data.items) state.verdict.set(item.name, { outcome: 'pending', note: '', ...(item.mesh ? { mesh: { outcome: 'pending' as Outcome, note: '' } } : {}) });
419
437
  if (data.verdict) { for (const [name, v] of Object.entries(data.verdict.parts)) if (state.verdict.has(name)) state.verdict.set(name, { outcome: v.outcome, note: v.note ?? '', ...(v.mesh ? { mesh: v.mesh } : {}) }); $<HTMLSelectElement>('pv-overall').value = data.verdict.status; }
@@ -421,7 +439,7 @@ async function boot(): Promise<void> {
421
439
  $('pv-title').textContent = data.title;
422
440
  $('pv-mode').textContent = data.mode === 'parts' ? t('Parts package, before rigging') : t('Atlas of a built rig');
423
441
  $('pv-list-title').textContent = data.mode === 'parts' ? t('PARTS') : t('REGIONS');
424
- $('pv-load').textContent = data.verdictStale === 'files' ? t('A saved sign-off was made on other files; this review starts fresh.') : data.verdictStale === 'flags' ? t('The saved sign-off is for different producer flags; this review starts fresh.') : data.verdict ? t('Saved sign-off loaded.') : '';
442
+ $('pv-load').textContent = data.verdictStale === 'files' ? t('A saved sign-off was made on other files; this review starts fresh.') : data.verdictStale === 'flags' ? t('The saved sign-off is for different producer flags; this review starts fresh.') : data.verdict ? t('Saved sign-off loaded.') : data.verdictReadOnlyReason?t(data.verdictReadOnlyReason):'';
425
443
  if(stageEmbedded){$('pv-load').hidden=$('pv-load').textContent==='';document.querySelector<HTMLElement>('.pv-layout')!.hidden=false;}
426
444
  $('pv-atlas-switch').hidden = data.mode !== 'atlas';
427
445
  const assemble=$<HTMLButtonElement>('pv-assemble');assemble.disabled=data.mode!=='parts'||!data.rigSize;assemble.title=assemble.disabled?t(data.mode==='atlas'?'Assembly unavailable: atlas regions carry no rig placement.':'Assembly unavailable: rig_size is not declared.'):'';
@@ -453,7 +471,7 @@ async function boot(): Promise<void> {
453
471
  $<HTMLTextAreaElement>('pv-note').oninput = e => updateEntry({ note: (e.target as HTMLTextAreaElement).value });
454
472
  $('pv-save').onclick = () => { void save(); };
455
473
  $('pv-approve-all').onclick = () => approveAll();
456
- for(const format of ['json','issue'])$('pv-export-'+format).onclick=async()=>{const res=await fetch(access.route('/api/parts/export?format='+format),{headers:access.headers()});const value=await res.text();if(!res.ok){$('pv-save-status').textContent=value;return;}const url=URL.createObjectURL(new Blob([value],{type:format==='json'?'application/json':'text/markdown'})),a=document.createElement('a');a.href=url;a.download=format==='json'?'parts-review-export.json':'parts-review-export.md';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
474
+ for(const format of ['json','issue'])$('pv-export-'+format).onclick=async()=>{const res=await fetch(access.route(stageEmbedded?partsApi+'/export/'+format:'/api/parts/export?format='+format),{headers:stageHeaders()});const value=await res.text();if(!res.ok){$('pv-save-status').textContent=JSON.parse(value).error??t('Save failed.');return;}const url=URL.createObjectURL(new Blob([value],{type:format==='json'?'application/json':'text/markdown'})),a=document.createElement('a');a.href=url;a.download=stageEmbedded?(format==='json'?data.verdictFile:data.verdictFile.replace(/\.json$/,'.md')):format==='json'?'parts-review-export.json':'parts-review-export.md';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
457
475
  onLanguageChange(() => { if (state.data) select(state.selected); });
458
476
  if(stageEmbedded)(window as StagePartsWindow).rigReviewStageParts={snapshot:stagePartsSnapshot};
459
477
  if(data.items.length){if(stageRestore)await restoreStageParts(stageRestore);else select(0);}
@@ -499,6 +517,7 @@ function renderCorrections():void {
499
517
  const label=document.createElement('p');label.textContent=t(data?.draft&&!mapping?'STAGE_DRAFT_NO_MESH: this part has no mesh attachment; direct correction is unavailable.':data?.draft?.label??data?.draftUnavailable??'STAGE_DRAFT_UNAVAILABLE: no producer-compatible draft is supplied.');host.append(label);
500
518
  if(!mapping||!data?.draft)return;
501
519
  label.textContent+=` · ${mapping.part} · ${mapping.skin}/${mapping.slot}/${mapping.attachment} · v ${mapping.vertices} t ${mapping.triangles} · ${data.draft.buildId}`;
520
+ if(data.draft.inspectionOnly)return;
502
521
  for(const [instrument,title,operation]of [['chest','Chest regions',t('rig-parts remesh --mesh')],['mesh','Mesh parameters',t('rig-parts remesh --mesh')],['delta','Edit Mesh',t('rig-parts remesh --delta')]]){
503
522
  const button=document.createElement('button');button.type='button';button.textContent=t(title!);button.title=`${mapping.part} · ${operation}`;button.onclick=()=>parent.postMessage({type:'review-stage-correction',part:mapping.part,sourceHash:data.sourceHash,buildId:data.draft!.buildId,instrument},location.origin);host.append(button);
504
523
  }
@@ -524,5 +543,5 @@ if(typeof window!=='undefined')window.addEventListener('message',event=>{if(even
524
543
 
525
544
  if(typeof window!=='undefined')window.addEventListener('message',event=>{if(event.source!==parent||event.origin!==location.origin||event.data?.type!=='review-stage-revalidate')return;void (async()=>{
526
545
  try{const response=await fetch(access.route(partsApi),{headers:stageHeaders()}),data=await response.json() as ViewData&{error?:string};if(!response.ok||data.sourceHash!==state.data?.sourceHash)throw new Error(data.error??'STAGE_DRAFT_MISMATCH: separated parts and draft mesh identity differ.');if(event.data.state)await restoreStageParts(event.data.state);}
527
- catch(error){const status=$('pv-load');status.hidden=false;status.dataset.result='refused';status.textContent=t(error instanceof Error?error.message:String(error));document.querySelector<HTMLElement>('.pv-layout')!.hidden=true;}
546
+ catch(error){document.querySelector<HTMLElement>('.pv-verdict')!.hidden=true;if(state.data)delete state.data.joinedVerdictBinding;const status=$('pv-load');status.hidden=false;status.dataset.result='refused';status.textContent=t(error instanceof Error?error.message:String(error));document.querySelector<HTMLElement>('.pv-layout')!.hidden=true;}
528
547
  })();});