@rig-c/review 3.7.0 → 4.0.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.
Files changed (109) hide show
  1. package/README.md +1 -1
  2. package/docs/DESIGN.md +145 -74
  3. package/docs/PANELS.md +20 -12
  4. package/docs/PARTS_VIEW.md +133 -76
  5. package/docs/REVIEW_PACKAGE.md +445 -99
  6. package/docs/STABILITY.md +132 -198
  7. package/docs/WORKFLOWS.md +41 -120
  8. package/package.json +4 -3
  9. package/skills/rig-review/SKILL.md +41 -27
  10. package/src/build.ts +10 -2
  11. package/src/cli.ts +17 -16
  12. package/src/comment-crops.ts +6 -1
  13. package/src/compare-html.ts +22 -24
  14. package/src/compare-server.ts +1 -1
  15. package/src/compare-session.ts +41 -3
  16. package/src/correction-handoff.ts +27 -4
  17. package/src/create-pin-gate.ts +3 -0
  18. package/src/direction-inspection.ts +6 -2
  19. package/src/feedback-export.ts +68 -1
  20. package/src/front.ts +5 -200
  21. package/src/handoff.ts +1 -1
  22. package/src/interview-routes.ts +1 -1
  23. package/src/interview-scene.ts +3 -3
  24. package/src/job-act.ts +77 -73
  25. package/src/job-api.ts +326 -13
  26. package/src/job-checkpoint-evidence.ts +113 -0
  27. package/src/job-cli.ts +27 -14
  28. package/src/job-contract.ts +284 -62
  29. package/src/job-front.ts +157 -58
  30. package/src/job-host.ts +23 -4
  31. package/src/job-session.ts +109 -24
  32. package/src/job-source.ts +209 -57
  33. package/src/job-store.ts +80 -6
  34. package/src/job-worker.ts +1 -47
  35. package/src/joined-project.ts +61 -4
  36. package/src/manifest.ts +32 -4
  37. package/src/open-workspace.ts +12 -12
  38. package/src/open.ts +19 -12
  39. package/src/parts-comment-crops.ts +126 -31
  40. package/src/parts-comment.ts +351 -28
  41. package/src/parts-server.ts +19 -7
  42. package/src/parts-view.ts +588 -109
  43. package/src/scene-inspection.ts +50 -0
  44. package/src/server.ts +31 -22
  45. package/src/session.ts +58 -0
  46. package/src/stage-comment.ts +48 -1
  47. package/src/stage-parts.ts +23 -11
  48. package/web/animation-inspection.ts +1 -1
  49. package/web/bones-panel.ts +1 -3
  50. package/web/catalog-en.ts +175 -39
  51. package/web/catalog-ko.ts +175 -39
  52. package/web/cloth-panel.ts +1 -2
  53. package/web/compare.css +3 -13
  54. package/web/compare.html +3 -3
  55. package/web/compare.ts +69 -64
  56. package/web/cuts-panel.ts +1 -3
  57. package/web/density-strip-panel.ts +1 -2
  58. package/web/direction-panel.ts +22 -6
  59. package/web/i18n.ts +13 -1
  60. package/web/idle-panel.ts +1 -2
  61. package/web/index.html +1 -5
  62. package/web/inspection-persistence.ts +2 -1
  63. package/web/inspector-blocks.ts +149 -40
  64. package/web/instance-access.ts +24 -5
  65. package/web/interview-panel.ts +224 -175
  66. package/web/job-rig-capture.ts +164 -21
  67. package/web/job-rig-screen.ts +337 -0
  68. package/web/job-session.ts +611 -1437
  69. package/web/main.ts +614 -151
  70. package/web/mesh-panel.ts +1 -2
  71. package/web/owner-workspace.ts +88 -109
  72. package/web/part-selection.ts +47 -6
  73. package/web/part-thumbnails.ts +20 -6
  74. package/web/parts-render.ts +26 -19
  75. package/web/parts-viewport-provider.ts +181 -7
  76. package/web/physics-panel.ts +1 -2
  77. package/web/readings-panel.ts +1 -2
  78. package/web/requirements-panel.ts +1 -3
  79. package/web/retained-frame-stage.ts +105 -0
  80. package/web/retarget-panel.ts +2 -3
  81. package/web/rig-fields-panel.ts +1 -2
  82. package/web/rig-host.ts +64 -0
  83. package/web/rig-viewport-provider.ts +65 -16
  84. package/web/scene-plates.ts +57 -4
  85. package/web/stage-comments.ts +103 -46
  86. package/web/styles.css +117 -63
  87. package/web/view-controls.ts +201 -12
  88. package/web/viewport-capture.ts +12 -2
  89. package/web/viewport-controller.ts +107 -27
  90. package/web/viewport-pair.ts +2 -1
  91. package/web/workspace-preferences.ts +5 -4
  92. package/web/workspace-ui.ts +151 -19
  93. package/src/front-worker.ts +0 -2
  94. package/src/interview-server.ts +0 -54
  95. package/src/job-hub.ts +0 -304
  96. package/src/job-image-set.ts +0 -50
  97. package/web/interview.css +0 -28
  98. package/web/interview.html +0 -17
  99. package/web/interview.ts +0 -40
  100. package/web/job-hub.css +0 -14
  101. package/web/job-hub.html +0 -5
  102. package/web/job-hub.ts +0 -179
  103. package/web/owner-workspace.css +0 -14
  104. package/web/owner-workspace.html +0 -5
  105. package/web/parts-flags.ts +0 -48
  106. package/web/parts.css +0 -104
  107. package/web/parts.html +0 -49
  108. package/web/parts.ts +0 -604
  109. package/web/stage-nav.ts +0 -136
@@ -0,0 +1,50 @@
1
+ /** Closed, byte-bound inspection of Create's scene@1. Project authority remains Create-owned. */
2
+ import {createHash} from 'node:crypto';
3
+ import {readFile} from 'node:fs/promises';
4
+ import {object, packagePath, safeFile} from './manifest.ts';
5
+ import {sceneDocumentShape} from './interview-scene.ts';
6
+ import type {DirectionInspection} from './direction-inspection.ts';
7
+ export type SceneBox = {x:number;y:number;width:number;height:number};
8
+ type Binding = {path:string;sha256:string};
9
+ export interface SceneInspection {
10
+ file:Binding;n:number;rigVersion:number;animation:string;stage:SceneBox;
11
+ plates:{role:'background'|'foreground';path:string;sha256:string;width:number;height:number;rect:SceneBox}[];
12
+ }
13
+ const fail=(code:string,field:string):never=>{throw new Error(`${code}: ${field}`);};
14
+ const hash=(bytes:Buffer)=>createHash('sha256').update(bytes).digest('hex');
15
+ /** Parse the full closed shape before opening its declared plate files. */
16
+ export function readSceneInspection(value:unknown,file:Binding,direction:DirectionInspection,model:Record<string,unknown>):SceneInspection{
17
+ let d:Record<string,unknown>;try{d=object(value,'scene');}catch{return fail('SCENE_SOURCE_MISMATCH',file.path);}
18
+ if(Array.isArray(d.plates))for(const raw of d.plates){let p:Record<string,unknown>;try{p=object(raw,'scene.plate');}catch{return fail('SCENE_SOURCE_MISMATCH','scene.plate');}
19
+ if(!Number.isSafeInteger(p.width)||!Number.isSafeInteger(p.height)||Number(p.width)<=0||Number(p.height)<=0)fail('SCENE_PLATE_DIMENSIONS',String(p.path));}
20
+ if(!sceneDocumentShape(d,direction.scene?.n))fail('SCENE_SOURCE_MISMATCH',file.path);
21
+ const r=object(d.rig,'scene.rig'),m=object(r.model,'scene.rig.model'),anim=object(r.animation,'scene.rig.animation');
22
+ if(r.version!==direction.rigVersion||m.path!==direction.model.path||m.sha256!==direction.model.sha256)fail('SCENE_MODEL_MISMATCH',file.path);
23
+ if(!Array.isArray(model.animations)||!model.animations.some(v=>object(v,'animation').name===anim.name))fail('SCENE_ANIMATION_MISSING',String(anim.name));
24
+ const f=object(d.frame,'scene.frame'),stage=object(f.stage,'scene.frame.stage') as SceneBox;
25
+ const modelStage=object(model.stage,'model.stage');
26
+ if(Object.entries(stage).some(([k,v])=>!Number.isFinite(v)||modelStage[k]!==v)||stage.width<=0||stage.height<=0)fail('SCENE_MODEL_MISMATCH','scene.frame');
27
+ if((d.plates as unknown[]).length<1||(d.plates as unknown[]).length>2)fail('SCENE_LAYER_ORDER','scene.plates');
28
+ const plates:SceneInspection['plates']=(d.plates as unknown[]).map((raw,index)=>{
29
+ const name=`scene.plates[${index}]`,row=object(raw,name);
30
+ let path:string;try{path=packagePath(row.path,name);}catch{return fail('SCENE_SOURCE_MISMATCH',name);}
31
+ const b={path,sha256:String(row.sha256)},rect=object(row.rect,name+'.rect') as SceneBox;
32
+ const x=rect.width*Number(row.height),y=rect.height*Number(row.width);
33
+ if(!Object.values(rect).every(Number.isFinite)||rect.width<=0||rect.height<=0||!Number.isFinite(x)||!Number.isFinite(y)||Math.abs(x-y)>1e-9*Math.max(Math.abs(x),Math.abs(y)))fail('SCENE_PLATE_DIMENSIONS',b.path);
34
+ return {role:row.role as 'background'|'foreground',...b,width:Number(row.width),height:Number(row.height),rect};
35
+ });
36
+ const expected=plates.length===2?['background','rig','foreground']:['background','rig'];
37
+ if(plates.filter(p=>p.role==='background').length!==1||plates.filter(p=>p.role==='foreground').length!==plates.length-1||JSON.stringify(d.layers)!==JSON.stringify(expected)||new Set(plates.map(p=>p.path)).size!==plates.length||new Set(plates.map(p=>p.sha256)).size!==plates.length)fail('SCENE_LAYER_ORDER','scene.layers');
38
+ return {file,n:Number(d.n),rigVersion:Number(r.version),animation:String(anim.name),stage,plates};
39
+ }
40
+ /** Read contained plate bytes once; these exact bytes subsequently enter the package hash. */
41
+ export async function scenePlateBytes(root:string,scene:SceneInspection):Promise<Map<string,Buffer>>{
42
+ const result=new Map<string,Buffer>();
43
+ for(const plate of scene.plates){
44
+ let bytes:Buffer;try{bytes=await readFile(await safeFile(root,plate.path));}catch{return fail('SCENE_REQUIRED',plate.path);}
45
+ if(hash(bytes)!==plate.sha256)fail('SCENE_PLATE_CHANGED',plate.path);
46
+ if(bytes.length<24||bytes.subarray(0,8).toString('hex')!=='89504e470d0a1a0a'||bytes.toString('ascii',12,16)!=='IHDR'||bytes.readUInt32BE(16)!==plate.width||bytes.readUInt32BE(20)!==plate.height)fail('SCENE_PLATE_DIMENSIONS',plate.path);
47
+ result.set(plate.path,bytes);
48
+ }
49
+ return result;
50
+ }
package/src/server.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { interviewHeaders, interviewRequest, interviewRoutes } from './interview-routes.ts';
1
+ import { interviewRequest, interviewRoutes } from './interview-routes.ts';
2
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';
@@ -61,14 +61,15 @@ export interface ReviewRequestContextOptions extends ReviewServerOptions {
61
61
  }
62
62
 
63
63
  /** Package-scoped routes without a listener. An injected lifecycle belongs to its caller. */
64
- export async function createReviewRequestContext(p: ReviewPackage, options: ReviewRequestContextOptions = {}) {
64
+ export async function createReviewRequestContext(p: ReviewPackage | null, options: ReviewRequestContextOptions = {}) {
65
65
  const joined = options.joined;
66
+ if(!p&&(!joined||!('interviewOnly' in joined)))throw new Error(interviewUnavailable);
66
67
  if (joined && !options.capability) throw new Error('Joined interview requires an instance capability');
67
68
  const interview = joined && interviewRoutes(joined.opened.root, joined.designation.picksDir, options.capability!,
68
- {...joined, sourceHash:p.sourceHash, version:joined.designation.version,draftId:joined.designation.draftId});
69
- let interviewBundle: Promise<Blob> | undefined;
69
+ {...joined, sourceHash:p?.sourceHash??(joined as import('./joined-project.ts').JoinedInterview).sourceHash, version:joined.designation.version,draftId:joined.designation.draftId});
70
70
  const bundle=options.bundle??await buildWeb();
71
- const unchanged=()=>assertReviewUnchanged(p);
71
+ const unchanged=()=>p?assertReviewUnchanged(p):joined!.assertCurrent();
72
+ const services=p?(()=>{
72
73
  const stateDir=options.stateDir??process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review'),starts=[p.root,options.cwd??process.cwd()];
73
74
  const rebuilds=createRebuilds(p,{stateDir,starts,unchanged,bones:p.feedbackCatalog.bones,...(options.stripConcurrency?{stripConcurrency:options.stripConcurrency}:{}),...(options.viewOnly??p.viewOnly?{viewOnly:true}:{}),...(joined?.draft?{draft:draftRebuildOption(joined,starts)}:{})});
74
75
  const stageParts=stagePartsRoutes({single:p},undefined,rebuilds.stageDraft,joined?.draft?{
@@ -86,7 +87,10 @@ export async function createReviewRequestContext(p: ReviewPackage, options: Revi
86
87
  // Check under this world (#112): the exported schedule written into scratch; the installed producer's check --environment reads it.
87
88
  const environmentCheck=createEnvironmentCheck(p,{stateDir,starts,unchanged,latest:rebuilds.latest});
88
89
  const control=options.control?createControlServer({identity:options.control,sourceHash:p.sourceHash,mode:'single',unchanged,activity:options.activity}):null;
89
- const busy=()=>Boolean(rebuilds.busy()||readings.running()||requirements.running()||environmentCheck.running()||bonesCheck.running());
90
+ return {rebuilds,stageParts,readings,bonesCheck,requirements,environmentCheck,control,
91
+ busy:()=>Boolean(rebuilds.busy()||readings.running()||requirements.running()||environmentCheck.running()||bonesCheck.running())};
92
+ })():null;
93
+ const busy=()=>services?.busy()??false;
90
94
  const ownsLifecycle=options.lifecycle===undefined;
91
95
  const live=options.lifecycle??createLiveLifecycle({
92
96
  label:'review',
@@ -101,7 +105,7 @@ export async function createReviewRequestContext(p: ReviewPackage, options: Revi
101
105
  const handle=async(req:Request,port:number|undefined,srv:UpgradableServer):Promise<Response|undefined>=>{try {
102
106
  const url=new URL(req.url);const origin=`http://127.0.0.1:${port}`;
103
107
  if(url.origin!==origin)return json({error:'Loopback host required'},403);
104
- const refused=openNonceGate(req,options.open)??accessGate(req,options.capability,!!control);if(refused)return refused;
108
+ const refused=openNonceGate(req,options.open)??accessGate(req,options.capability,!!services?.control);if(refused)return refused;
105
109
  if(req.method==='GET'&&url.pathname===LIVE_PATH){
106
110
  const fromFront=Boolean(options.open&&sameSecret(req.headers.get(openNonceHeader),options.open.nonce)&&req.headers.get('origin')===null);
107
111
  if(!fromFront&&req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
@@ -113,16 +117,24 @@ export async function createReviewRequestContext(p: ReviewPackage, options: Revi
113
117
  if (interviewRequest(path)) {
114
118
  return await interview?.(req, origin) ?? json({error:interviewUnavailable},404);
115
119
  }
116
- if (req.method === 'GET' && ['/stage-interview.html','/interview.js','/interview.css'].includes(path)) {
117
- if (!joined?.available) return json({error:interviewUnavailable},404);
118
- const script = path === '/interview.js';
119
- const html = path === '/stage-interview.html';
120
- const body = script ? await (interviewBundle ??= buildWeb('interview')) :
121
- await readFile(appRoot + 'web/' + (html ? 'interview.html' : 'interview.css'));
122
- return new Response(body as BodyInit, {headers:{...interviewHeaders, 'Referrer-Policy':'no-referrer',
123
- 'Content-Security-Policy':interviewHeaders['Content-Security-Policy'].replace("frame-ancestors 'none'", "frame-ancestors 'self'"),
124
- 'Content-Type':script?'text/javascript':html?'text/html; charset=utf-8':'text/css'}});
120
+ 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;}
121
+ if(req.method==='GET'||req.method==='HEAD'){
122
+ if(url.pathname==='/main.js')return new Response(req.method==='HEAD'?null:bundle,{headers:{...headers,'Content-Type':'text/javascript'}});
123
+ if(url.pathname==='/'||url.pathname==='/index.html')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/index.html'),{headers:{...headers,'Content-Type':'text/html; charset=utf-8'}});
124
+ if(url.pathname==='/styles.css')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/styles.css'),{headers:{...headers,'Content-Type':'text/css'}});
125
+ }
126
+ if(!p){
127
+ await unchanged();
128
+ if(req.method!=='GET'&&req.method!=='HEAD'&&req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
129
+ if((req.method==='GET'||req.method==='HEAD')&&path==='/api/review'){
130
+ const source=joined as import('./joined-project.ts').JoinedInterview;
131
+ return json({subject:'interview',project:{path:'project.json',sha256:source.opened.hash},
132
+ label:typeof source.opened.project.name==='string'?source.opened.project.name:source.opened.root.split('/').at(-1),sourceHash:source.sourceHash,
133
+ capabilities:{interview:true,playback:false,modeling:false,motion:false,feedback:false,audio:false},unavailable:'MODEL_UNAVAILABLE'});
134
+ }
135
+ return /^\/api\/(?:session|stage-parts|rebuild|density-strip|bones-check|requirements|environment-check|readings|strip|control)(?:\/|$)/.test(path)?json({error:'MODEL_UNAVAILABLE'},409):json({error:'Not found'},404);
125
136
  }
137
+ const {rebuilds,stageParts,readings,bonesCheck,requirements,environmentCheck,control}=services!;
126
138
  if (joined && /^\/api\/stage-parts(?:\/|$)/.test(path)) {
127
139
  try {await joined.assertCurrent();}
128
140
  catch {return json({error:interviewStale},409);}
@@ -130,7 +142,7 @@ export async function createReviewRequestContext(p: ReviewPackage, options: Revi
130
142
  const stageResponse=await stageParts(req);if(stageResponse)return stageResponse;
131
143
 
132
144
  const controlled=await control?.(req,origin);if(controlled)return controlled;
133
- 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;}
145
+
134
146
  if(req.method==='PUT'&&url.pathname==='/api/session'){
135
147
  if(joined?.draft)return json({error:'MODEL_UNAVAILABLE'},409);
136
148
  if(req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
@@ -203,7 +215,7 @@ export async function createReviewRequestContext(p: ReviewPackage, options: Revi
203
215
  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'}"`}});
204
216
  }
205
217
  if(req.method!=='GET'&&req.method!=='HEAD')return json({error:'Method not allowed'},405);
206
- 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}});}
218
+ if(url.pathname==='/api/review'){await unchanged();return json({manifest:p.manifest,...(p.scene?{scene:p.scene}:{}),...(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}});}
207
219
  if(url.pathname==='/api/session'){await unchanged();return json(await readSession(p,options.stateDir));}
208
220
  if(url.pathname==='/api/rebuild')return json(await rebuilds.describe());
209
221
  if(url.pathname==='/api/rebuild/history')return json(await rebuilds.history());
@@ -246,9 +258,6 @@ export async function createReviewRequestContext(p: ReviewPackage, options: Revi
246
258
  }
247
259
  return new Response(req.method==='HEAD'?null:file,{headers:{...assetHeaders,'Content-Length':String(size)}});
248
260
  }
249
- if(url.pathname==='/main.js')return new Response(req.method==='HEAD'?null:bundle,{headers:{...headers,'Content-Type':'text/javascript'}});
250
- if(url.pathname==='/'||url.pathname==='/index.html')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/index.html'),{headers:{...headers,'Content-Type':'text/html; charset=utf-8'}});
251
- if(url.pathname==='/styles.css')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/styles.css'),{headers:{...headers,'Content-Type':'text/css'}});
252
261
  return json({error:'Not found'},404);
253
262
  } finally { live.onRequestEnd(url.pathname); }
254
263
  }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);}};
@@ -263,7 +272,7 @@ export async function createReviewRequestContext(p: ReviewPackage, options: Revi
263
272
  };
264
273
  }
265
274
 
266
- export async function startServer(p: ReviewPackage, options: ReviewServerOptions = {}) {
275
+ export async function startServer(p: ReviewPackage | null, options: ReviewServerOptions = {}) {
267
276
  let rawStop:((closeActiveConnections?:boolean)=>void)|null=null;
268
277
  const context=await createReviewRequestContext(p,{...options,stopServer:()=>{rawStop?.(true);}});
269
278
  const server=Bun.serve({hostname:'127.0.0.1',port:options.port??4317,websocket:context.live.websocket,async fetch(req,srv){return await context.handle(req,srv.port,srv) as Response;}});
package/src/session.ts CHANGED
@@ -17,6 +17,64 @@ import { parseReadingsContext } from './readings.ts';
17
17
  import { parseRequirementsContext } from './requirements.ts';
18
18
  import { parseScheduleContext } from './environment-schedule.ts';
19
19
  import { choice, object, string, type Json, type ReviewPackage, type ReviewedSource } from './manifest.ts';
20
+ import { commentsObject, jobSha, parseComments } from './job-api.ts';
21
+ import { REVIEW_COMMENTS_SESSION_SCHEMA, type ReviewCommentsSession } from './job-contract.ts';
22
+
23
+ /** Shared declared provenance decoder. Native source freshness belongs to the package owner. */
24
+ export function parseCommentsReviewedSource(value: unknown): ReviewedSource {
25
+ const source = commentsObject(value, ['packageRevision', 'viewerVersion', 'runtimeVersion', 'rig', 'motion'], ['handoff']);
26
+ for (const key of ['packageRevision', 'viewerVersion', 'runtimeVersion']) string(source[key], `reviewedSource.${key}`);
27
+ for (const key of ['rig', 'motion']) {
28
+ if (source[key] === null) continue;
29
+ const file = commentsObject(source[key], ['path', 'sha256']);
30
+ string(file.path, `reviewedSource.${key}.path`); jobSha(file.sha256);
31
+ }
32
+ if ('handoff' in source) object(source.handoff, 'reviewedSource.handoff');
33
+ return structuredClone(source) as unknown as ReviewedSource;
34
+ }
35
+
36
+ /** The two standalone envelopes share their existing diagnostic row shape. */
37
+ export function parseCommentsWarnings(value: unknown): FeedbackWarning[] {
38
+ if (!Array.isArray(value) || value.length > 1000) throw new Error('JOB_ACT_INVALID');
39
+ for (const warning of value) {
40
+ const row = commentsObject(warning, ['id', 'error']);
41
+ string(row.id, 'warning.id'); string(row.error, 'warning.error');
42
+ }
43
+ return structuredClone(value) as FeedbackWarning[];
44
+ }
45
+
46
+ /** Read-only session/2 decoder. The active UI/save path remains session/1. */
47
+ export function parseCommentsSession(value: unknown): ReviewCommentsSession {
48
+ const raw = commentsObject(value, ['schema', 'id', 'revision', 'sourceHash', 'reviewedSource', 'status',
49
+ 'checkpoints', 'comments', 'feedbackWarnings', 'updatedAt'], ['referenceBinding']);
50
+ if (raw.schema !== REVIEW_COMMENTS_SESSION_SCHEMA) throw new Error('JOB_ACT_INVALID');
51
+ string(raw.id, 'session.id'); string(raw.revision, 'session.revision'); jobSha(raw.sourceHash);
52
+ parseCommentsReviewedSource(raw.reviewedSource);
53
+ choice(raw.status, ['pending', 'approved', 'changes-requested'], 'session.status');
54
+ const checkpoints = object(raw.checkpoints, 'session.checkpoints');
55
+ for (const item of Object.values(checkpoints)) {
56
+ const checkpoint = commentsObject(item, ['outcome']);
57
+ choice(checkpoint.outcome, ['pending', 'pass', 'fail'], 'checkpoint.outcome');
58
+ }
59
+ parseCommentsWarnings(raw.feedbackWarnings);
60
+ if (raw.updatedAt !== null && (typeof raw.updatedAt !== 'string' || !Number.isFinite(Date.parse(raw.updatedAt)))) throw new Error('JOB_ACT_INVALID');
61
+ if ('referenceBinding' in raw) {
62
+ const binding = commentsObject(raw.referenceBinding, ['packageSourceHash', 'reference']);
63
+ jobSha(binding.packageSourceHash);
64
+ const reference = commentsObject(binding.reference, ['id', 'name', 'sha256']);
65
+ string(reference.id, 'reference.id'); string(reference.name, 'reference.name'); jobSha(reference.sha256);
66
+ }
67
+ const comments = parseComments(raw.comments, raw.sourceHash as string);
68
+ if (comments.some(comment => comment.anchor && 'side' in comment.anchor)) throw new Error('JOB_ACT_INVALID');
69
+ const reviewed = raw.reviewedSource as unknown as ReviewedSource;
70
+ for (const {anchor} of comments) {
71
+ if (!anchor || !('frameStart' in anchor) || !hasStageComment((anchor.context as any)?.comment)) continue;
72
+ const mark = parseStageComment((anchor.context as any).comment);
73
+ parseBookmark(mark.bookmark, {mode: 'single', sourceHash: raw.sourceHash as string, rigs: [reviewed.rig?.sha256 ?? null]});
74
+ if (!['rig', 'reference'].includes(mark.viewport) || mark.modelHash !== (mark.viewport === 'reference' ? null : reviewed.rig?.sha256 ?? null)) throw new Error('JOB_ACT_INVALID');
75
+ }
76
+ return {...structuredClone(raw), comments} as unknown as ReviewCommentsSession;
77
+ }
20
78
  export interface Feedback {id:string;frameStart:number|null;frameEnd:number|null;target:{kind:'bone'|'slot'|'rig';name:string};category:'defect'|'quality';summary:string;context?:Json}
21
79
  export function parseFeedback(item:unknown,strict=true):Feedback {
22
80
  const f=object(item,'feedback');const target=object(f.target,'feedback.target');
@@ -1,8 +1,47 @@
1
1
  /** Stage marks are optional inspection evidence on an ordinary feedback row. */
2
2
  import type {PosedFrame} from '@rig-c/play';
3
3
  import type {ControlNumericCamera} from './control.ts';
4
+ import type {JobActValues, JobComment, JobCommentAnchor, JobCommentFeedbackAnchor} from './job-contract.ts';
5
+ import type {Feedback} from './session.ts';
6
+ import type {CompareFeedback} from './compare-session.ts';
4
7
  export interface MarkPoint {x:number;y:number}
5
8
  export interface MarkRegion {x:number;y:number;width:number;height:number}
9
+
10
+ /** Stable logical labels survive a new Apply capture; raw anchors retain its full evidence. */
11
+ function commentLabel(anchor: JobCommentAnchor): string {
12
+ if ('checkpointId' in anchor) return JSON.stringify(['checkpoint', anchor.checkpointId]);
13
+ if ('schema' in anchor) return JSON.stringify([anchor.schema, anchor.parts.map(part => part.name), anchor.view.mode]);
14
+ if ('name' in anchor) return JSON.stringify([anchor.name]);
15
+ const context = anchor.context as Record<string, unknown> | undefined;
16
+ if (hasStageComment(context?.comment)) {
17
+ const mark = parseStageComment(context!.comment);
18
+ return JSON.stringify([mark.schema, mark.mode, mark.viewport, anchor.target.kind, anchor.target.name,
19
+ anchor.frameStart, anchor.frameEnd]);
20
+ }
21
+ return JSON.stringify([anchor.target.kind, anchor.target.name, anchor.frameStart, anchor.frameEnd,
22
+ 'side' in anchor ? anchor.side : null]);
23
+ }
24
+
25
+ /** The signed scalar projection. Entry text and array order are never normalized. */
26
+ export function projectComments(comments: readonly JobComment[]): string {
27
+ if (!Array.isArray(comments) || comments.length > 1000) throw new Error('JOB_ACT_INVALID');
28
+ const blocks = comments.map(comment => {
29
+ if (!comment || typeof comment.text !== 'string' || !comment.text.trim() || comment.text.length > 10000 ||
30
+ Object.keys(comment).some(key => key !== 'text' && key !== 'anchor')) throw new Error('JOB_ACT_INVALID');
31
+ return `[${comment.anchor === undefined ? 'general' : commentLabel(comment.anchor)}]\n${comment.text}`;
32
+ });
33
+ const text = blocks.join('\n\n');
34
+ if (text.length > 10000) throw new Error('JOB_ACT_INVALID');
35
+ return text;
36
+ }
37
+ /** Pure preparation only: the caller still decodes the complete source-bound envelope. */
38
+ export function feedbackItemComments(items: readonly (Feedback | CompareFeedback)[]): {text: string; anchor: JobCommentFeedbackAnchor}[] {
39
+ return items.map(({summary, ...anchor}) => ({text: summary, anchor: structuredClone(anchor)}));
40
+ }
41
+ /** Mapping comes from the decoded plan/ask, never from an inferred checkpoint ID. */
42
+ export function checkpointNoteComments(value: Pick<JobActValues['checkpoint'], 'checkpointId' | 'planStepId'> & {note: string}): JobComment[] {
43
+ return [{text: value.note, anchor: {checkpointId: value.checkpointId, planStepId: value.planStepId}}];
44
+ }
6
45
  export const commentModes=['setup','animate','compare'] as const;
7
46
  export type CommentMode=typeof commentModes[number];
8
47
  export const timeOnlyReason='frame is unavailable: no explicit producer frame index at this time (COMMENT_FRAME_UNAVAILABLE)' as const;
@@ -63,7 +102,15 @@ export function requireFeedbackFrames(f:{frameStart:number|null;frameEnd:number|
63
102
  if(hasStageComment(comment)&&comment.frame?.basis==='reference')throw new Error('COMMENT_REFERENCE_STRIP_UNAVAILABLE: decoded reference frames are not producer frames; reference-basis comments cannot be exported as producer-frame strips');
64
103
  return frames;
65
104
  }
66
- export function region(a:MarkPoint,b:MarkPoint):MarkRegion{return {x:Math.min(a.x,b.x),y:Math.min(a.y,b.y),width:Math.abs(a.x-b.x),height:Math.abs(a.y-b.y)};}
105
+ /** Optional bounds select only the intersecting portion of a dragged region. */
106
+ export function region(a:MarkPoint,b:MarkPoint,bounds?:MarkRegion):MarkRegion {
107
+ const bounded=(point:MarkPoint)=>bounds?{
108
+ x:Math.max(bounds.x,Math.min(bounds.x+bounds.width,point.x)),
109
+ y:Math.max(bounds.y,Math.min(bounds.y+bounds.height,point.y)),
110
+ }:point;
111
+ const first=bounded(a),last=bounded(b);
112
+ return {x:Math.min(first.x,last.x),y:Math.min(first.y,last.y),width:Math.abs(first.x-last.x),height:Math.abs(first.y-last.y)};
113
+ }
67
114
  export function projectMark(p:MarkPoint,c:ControlNumericCamera):MarkPoint {const s=c.viewport.width/c.visible.width;return {x:(p.x-c.visible.x)*s,y:c.space==='world'?(c.visible.y+c.visible.height-p.y)*s:(p.y-c.visible.y)*s};}
68
115
  export function unprojectMark(p:MarkPoint,c:ControlNumericCamera):MarkPoint {const s=c.visible.width/c.viewport.width;return {x:c.visible.x+p.x*s,y:c.space==='world'?c.visible.y+c.visible.height-p.y*s:c.visible.y+p.y*s};}
69
116
  const cross=(a:MarkPoint,b:MarkPoint,c:MarkPoint)=>(b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
@@ -1,7 +1,6 @@
1
1
  /** Embedded parts inspector. Only the designated joined source can save a verdict. */
2
2
  import {join} from 'node:path';
3
3
  import {lstat,readFile} from 'node:fs/promises';
4
- import {appRoot,buildWeb} from './build.ts';
5
4
  import type {ReviewPackage} from './manifest.ts';
6
5
  import {loadPartsAtlas,loadPartsView,assertPartsUnchanged,partsViewJson,servedImage,verdictSource,readVerdict,saveVerdict,exportPartsVerdict,type PartsViewPackage} from './parts-view.ts';
7
6
  import {serveReference,assertReviewUnchanged} from './reference.ts';
@@ -14,6 +13,9 @@ export const stageVerdictRefusals=[
14
13
  'PARTS_VERDICT_BODY_LIMIT','PARTS_VERDICT_READ','PARTS_VERDICT_INVALID','PARTS_VERDICT_UNKNOWN_PART',
15
14
  'PARTS_VERDICT_MISSING_PART','PARTS_VERDICT_NOTE_REQUIRED','PARTS_MESH_OUTCOME_UNAVAILABLE','PARTS_MESH_OUTCOME',
16
15
  'PARTS_VERDICT_NOT_CLEAN','PARTS_VERDICT_NOTHING_FLAGGED','PARTS_VIEW_SOURCE_CHANGED','PARTS_VERDICT_INPUT_COLLISION',
16
+ 'PARTS_JOINED_ISSUE_UNSUPPORTED','PARTS_COMMENT_LIMIT','PARTS_COMMENT_INVALID','PARTS_COMMENT_DUPLICATE','PARTS_COMMENT_UNAVAILABLE',
17
+ 'PARTS_COMMENT_PART_MISMATCH','PARTS_COMMENT_STALE_SOURCE','PARTS_COMMENT_OUT_OF_BOUNDS','PARTS_COMMENT_RIG_REGION',
18
+ 'PARTS_COMMENT_CROP_INVALID','PARTS_COMMENT_EMPTY','PARTS_COMMENT_FRACTIONAL','PARTS_CAMERA_RANGE','COMMENT_CROP_INVALID',
17
19
  ] as const;
18
20
  interface JoinedVerdictOptions {
19
21
  joined:JoinedProject;
@@ -23,7 +25,7 @@ interface JoinedVerdictOptions {
23
25
 
24
26
  export function stagePartsRoutes(packages:{single:ReviewPackage}|{a:ReviewPackage;b:ReviewPackage},loadAtlas:typeof loadPartsAtlas=loadPartsAtlas,draft?:DraftReader,verdictOptions?:JoinedVerdictOptions) {
25
27
  const corrections=new Map<string,Promise<{pkg:PartsViewPackage;modelPath:string;modelSha256:string;metadata:Record<string,unknown>|null}>>();
26
- const loaded=new Map<string,ReturnType<typeof loadPartsAtlas>>();let bundle:Promise<Blob>|undefined;
28
+ const loaded=new Map<string,ReturnType<typeof loadPartsAtlas>>();
27
29
  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'"};
28
30
  return async(req:Request):Promise<Response|null>=>{
29
31
  const url=new URL(req.url),path=url.pathname,read=req.method==='GET'||req.method==='HEAD';
@@ -35,10 +37,6 @@ export function stagePartsRoutes(packages:{single:ReviewPackage}|{a:ReviewPackag
35
37
  if(verdictRequest&&(!verdictOptions?.joined.verdictDirectory||verdictOptions.viewOnly||(req.headers.get('X-Review-Stage-Build')??'inspected')!=='inspected')){
36
38
  return Response.json({error:'PARTS_VERDICT_READ_ONLY'},{status:409,headers});
37
39
  }
38
- if(['/stage-parts.html','/parts.js','/parts.css'].includes(path)){
39
- if(path==='/parts.js'){bundle??=buildWeb('parts');return new Response(req.method==='HEAD'?null:await bundle,{headers:{...headers,'Content-Type':'text/javascript'}});}
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'}});
41
- }
42
40
  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);
43
41
  if(!match)return null;
44
42
  const key='single' in packages?'single':match[1] as 'a'|'b',p='single' in packages?packages.single:packages[key as 'a'|'b'];
@@ -151,11 +149,12 @@ async function joinedVerdict(req:Request,p:ReviewPackage,pkg:PartsViewPackage,op
151
149
  };
152
150
  const input=save?object(await options.readInput(req)):null;
153
151
  if(input&&input.binding!==binding)throw new Error('PARTS_VERDICT_SOURCE_MISMATCH');
154
- // Pointed comments use the standalone crop endpoints. Joined sign-off exposes part and mesh notes.
152
+ // Joined issue editing is deferred. The standing job route owns issue submission.
155
153
  if(input&&input.comments!==undefined)throw new Error('PARTS_VERDICT_INVALID');
156
154
  await assertCurrent();
157
155
  const saved=await readVerdict(destination);
158
156
  if(saved.stale)throw new Error('PARTS_VERDICT_SOURCE_MISMATCH');
157
+ if(input&&(input.status==='approved'||input.status==='changes-requested')&&Array.isArray(input.issues)&&input.issues.length>0)throw new Error('PARTS_JOINED_ISSUE_UNSUPPORTED');
159
158
  if(input)return Response.json({verdict:await saveVerdict(destination,input,assertCurrent)},{headers});
160
159
  if(format){
161
160
  if(!saved.verdict)throw new Error('PARTS_VERDICT_UNAVAILABLE');
@@ -212,10 +211,23 @@ function matchingVertexGeometry(a:Record<string,any>,b:Record<string,any>):boole
212
211
  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]));
213
212
  if(Array.isArray(a.weights)){
214
213
  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;
215
- 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)=>{
216
- const x=v as Record<string,unknown>,y=b.vertices.bindings[i][j];
217
- return x&&y&&x.bone===y.bone&&equalNumbers([x.x,x.y,x.weight],[y.x,y.y,y.weight]);
218
- }));
214
+ // A vertex's bindings are a set: the compiler writes them in bone order (rigc canonical), the producer in its own order.
215
+ // Compare them sorted by bone, then by the float32 values, so order alone never refuses and every value still must agree.
216
+ const sorted=(row:unknown[])=>[...row].sort((p,q)=>{
217
+ const x=p as Record<string,unknown>,y=q as Record<string,unknown>;
218
+ if(x?.bone!==y?.bone)return String(x?.bone)<String(y?.bone)?-1:1;
219
+ for(const key of ['x','y','weight'] as const){const u=Math.fround(Number(x?.[key])),v=Math.fround(Number(y?.[key]));if(u!==v)return u<v?-1:1;}
220
+ return 0;
221
+ });
222
+ return a.weights.every((row:unknown,i:number)=>{
223
+ const other=b.vertices.bindings[i];
224
+ if(!Array.isArray(row)||!Array.isArray(other)||row.length===0||row.length!==other.length)return false;
225
+ const left=sorted(row),right=sorted(other);
226
+ return left.every((v:unknown,j:number)=>{
227
+ const x=v as Record<string,unknown>,y=right[j] as Record<string,unknown>;
228
+ return x&&y&&typeof x.bone==='string'&&x.bone===y.bone&&equalNumbers([x.x,x.y,x.weight],[y.x,y.y,y.weight]);
229
+ });
230
+ });
219
231
  }
220
232
  if(Array.isArray(a.vertices)&&a.vertices.length===a.uvs.length)return b.vertices?.weighted===false&&equalNumbers(a.vertices,b.vertices.xy);
221
233
  throw new Error('STAGE_DRAFT_GEOMETRY_UNSUPPORTED');
@@ -31,11 +31,11 @@ import type {AnimationSourceView} from './rebuild-client.ts';
31
31
  import {bindStagePick,domHoverPainter,type StagePick} from './stage-pick.ts';
32
32
  import {InspectionSelection} from './inspection-selection.ts';
33
33
  import {animationPreviewAdjust} from './preview.ts';
34
+ import {actionButton as button} from './view-controls.ts';
34
35
 
35
36
  const NS='http://www.w3.org/2000/svg';
36
37
  const svg=(tag:string,attrs:Record<string,string|number>)=>{const n=document.createElementNS(NS,tag);for(const [k,v]of Object.entries(attrs))n.setAttribute(k,String(v));return n;};
37
38
  const numeric=(value:number)=>Object.is(value,-0)?'-0':String(value);
38
- const button=(label:string,click:(e?:MouseEvent)=>void)=>{const b=document.createElement('button');b.type='button';b.textContent=label;b.onclick=click;return b;};
39
39
 
40
40
  /** Clean human-readable seconds without Float32 noise (e.g. 1.6 instead of 1.600000023841858). */
41
41
  export function formatSeconds(value:number):string {
@@ -12,7 +12,7 @@ import type {CropWorldMapping} from '../src/chest-regions.ts';
12
12
  import type {BonesCheckResult} from '../src/bones-check.ts';
13
13
  import {canvasToCrop} from './chest-editor.ts';
14
14
  import type {OverlayAnchors,OverlayPoint,OverlayProject} from './rig-overlays.ts';
15
- import {textEntryFocused} from './view-controls.ts';
15
+ import {panelNode as node,panelMake as make,textEntryFocused} from './view-controls.ts';
16
16
 
17
17
  export type BonesCheckView=BonesCheckResult|{status:'refused';error:string};
18
18
  export interface BonesPanelDeps {
@@ -68,8 +68,6 @@ export function anchorLines(bones:readonly ConfigBone[],at:(path:string)=>RigPoi
68
68
  return out;
69
69
  }
70
70
  const fmt=(p:RigPoint)=>`[${p[0]}, ${p[1]}]`;
71
- const node=<T extends HTMLElement>(id:string)=>{const found=document.getElementById(id);if(!found)throw new Error(`Missing UI element: ${id}`);return found as T;};
72
- const make=<K extends keyof HTMLElementTagNameMap>(tag:K,props:Record<string,unknown>={},...children:(Node|string)[]):HTMLElementTagNameMap[K]=>{const item=document.createElement(tag);Object.assign(item,props);item.append(...children);return item;};
73
71
 
74
72
  export function bindBonesPanel(deps:BonesPanelDeps):BonesPanel {
75
73
  const state=node('bones-panel-state'),toggle=node<HTMLButtonElement>('bones-edit'),picker=node<HTMLSelectElement>('bones-select'),editor=node('bones-anchor-editor'),pending=node('bones-pending-list');