@rig-c/review 0.17.0 → 0.18.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/README.md CHANGED
@@ -51,7 +51,7 @@ http://127.0.0.1:4318/instances/<key>/?input=…&handoff=…#cap=…
51
51
  | <a id="feedback-ownership"></a>Retrieve submitted feedback | `feedback` | [Feedback ownership — WORKFLOWS](docs/WORKFLOWS.md#feedback-ownership) |
52
52
  | <a id="frame-strip-export"></a>Export feedback intervals as strips | `strip` | [Frame strip export — WORKFLOWS](docs/WORKFLOWS.md#frame-strip-export) |
53
53
  | **Inspect** | | |
54
- | <a id="workspace-settings-and-panels"></a>Navigate the workspace | Setup, Animate, Settings | [Workspace panels — PANELS](docs/PANELS.md#workspace-settings-and-panels) |
54
+ | <a id="workspace-settings-and-panels"></a>Navigate the workspace | Setup, Animate, Compare, Settings | [Workspace panels — PANELS](docs/PANELS.md#workspace-settings-and-panels) |
55
55
  | <a id="inspect-animation-keys"></a>Inspect stored animation keys | Timeline, Curves, Bone tree | [Animation keys — PANELS](docs/PANELS.md#inspect-animation-keys) |
56
56
  | <a id="inspect-a-part"></a>Select and fit a model slot | Parts explorer | [Part inspection — PANELS](docs/PANELS.md#inspect-a-part) |
57
57
  | <a id="weights-setup-pose-watch-only"></a>Inspect setup-pose weights | Weights | [Weights — PANELS](docs/PANELS.md#weights-setup-pose-watch-only) |
package/docs/PANELS.md CHANGED
@@ -8,8 +8,14 @@ The review page has a left column (Parts explorer, with checkpoints and the
8
8
  reference select folded above it), the stage, the Inspector below it with
9
9
  **Setup** and **Animate** sections, and a status footer. The compare page
10
10
  keeps sources on the left and the Parts explorer on the right. The page
11
- header carries the **Setup** / **Animate** mode switch next to the package
12
- title; it is the only way to change the Inspector's section. Setup is the
11
+ header carries the **Setup · Animate · Compare** mode switch next to the package
12
+ title. In a single-build session (`rig-review open <built>`), **Compare** is
13
+ disabled with a tooltip explaining that a second build and reference video are
14
+ required (`--compare <built> --reference <video>`). In a comparison session, the
15
+ page starts in **Compare** mode with Reference, Build A and Build B side by
16
+ side, and switching to **Setup** or **Animate** keeps time, animation and
17
+ selection while exposing the **Editing Build A / Build B** picker so the shared
18
+ Setup and Animate panels operate on the picked build only. Setup is the
13
19
  mesh-review composition (selected part, part presets, modeling-review
14
20
  proposals) and holds nothing that seeks or plays; the angle inspection, the
15
21
  transport and frame navigation are in Animate. **Write review** at the top
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/review",
3
- "version": "0.17.0",
3
+ "version": "0.18.0",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Single-source Setup and Animate workspace markup for comparison sessions (#234).
3
+ *
4
+ * `web/index.html` owns the Setup and Animate panel markup; `web/compare.html` holds placeholders for those shared
5
+ * sections and `renderCompareHtml` splices them from `web/index.html` at serve time, refusing missing landmarks,
6
+ * duplicate IDs or any byte difference between the two pages' Setup and Animate sections.
7
+ */
8
+
9
+ export interface SharedWorkspaceMarkup {
10
+ viewTools: string;
11
+ stageBars: string;
12
+ stageHandles: string;
13
+ appliedRecords: string;
14
+ setupBlockRow: string;
15
+ setupPanels: string;
16
+ animateBlockRow: string;
17
+ transportStrips: string;
18
+ animatePanels: string;
19
+ }
20
+
21
+ const REGIONS: readonly {
22
+ key: keyof SharedWorkspaceMarkup;
23
+ placeholder: string;
24
+ start: string;
25
+ end: string;
26
+ compareEnd: string;
27
+ }[] = [
28
+ {
29
+ key: 'viewTools',
30
+ placeholder: '<!-- shared:view-tools -->',
31
+ start: '<div class="view-tools">',
32
+ end: '<div class="zoom-controls">',
33
+ compareEnd: '<div class="row"><label class="camera-sync">',
34
+ },
35
+ {
36
+ key: 'stageBars',
37
+ placeholder: '<!-- shared:stage-bars -->',
38
+ start: '<div id="chest-editor-bar"',
39
+ end: '<div id="stage-layout"',
40
+ compareEnd: '<div id="stage-layout"',
41
+ },
42
+ {
43
+ key: 'stageHandles',
44
+ placeholder: '<!-- shared:stage-handles -->',
45
+ start: '<div id="idle-handles"',
46
+ end: '<div id="rig-empty"',
47
+ compareEnd: '<p id="a-empty"',
48
+ },
49
+ {
50
+ key: 'appliedRecords',
51
+ placeholder: '<!-- shared:applied-records -->',
52
+ start: '<section id="applied-records"',
53
+ end: '<section id="inspector-rig"',
54
+ compareEnd: '<section id="inspector-view"',
55
+ },
56
+ {
57
+ key: 'setupBlockRow',
58
+ placeholder: '<!-- shared:setup-block-row -->',
59
+ start: '<nav class="block-row" aria-label="Setup blocks">',
60
+ end: '<section id="selected-part"',
61
+ compareEnd: '<section id="selected-part"',
62
+ },
63
+ {
64
+ key: 'setupPanels',
65
+ placeholder: '<!-- shared:setup-panels -->',
66
+ start: '<section id="modeling-tools">',
67
+ end: '</section><section id="inspector-playback"',
68
+ compareEnd: '</section><section id="inspector-playback"',
69
+ },
70
+ {
71
+ key: 'animateBlockRow',
72
+ placeholder: '<!-- shared:animate-block-row -->',
73
+ start: '<nav class="block-row" aria-label="Animate blocks">',
74
+ end: '<section id="transport"',
75
+ compareEnd: '<section id="transport"',
76
+ },
77
+ {
78
+ key: 'transportStrips',
79
+ placeholder: '<!-- shared:transport-strips -->',
80
+ start: '<div id="reading-ticks"',
81
+ end: '</section><section id="frame-controls"',
82
+ compareEnd: '</section><div class="compare-info">',
83
+ },
84
+ {
85
+ key: 'animatePanels',
86
+ placeholder: '<!-- shared:animate-panels -->',
87
+ start: '<section id="motion-tools">',
88
+ end: '</section></div></section></main>',
89
+ compareEnd: '</section><section id="inspector-feedback"',
90
+ },
91
+ ];
92
+
93
+ function sliceRegion(html: string, start: string, end: string, label: string): string {
94
+ const a = html.indexOf(start);
95
+ if (a < 0) throw new Error(`COMPARE_SHARED_MARKUP_MISSING: ${label} start landmark not found (${start})`);
96
+ const b = html.indexOf(end, a);
97
+ if (b < a) throw new Error(`COMPARE_SHARED_MARKUP_MISSING: ${label} end landmark not found (${end})`);
98
+ return html.slice(a, b);
99
+ }
100
+
101
+ export function extractSharedWorkspaceMarkup(indexHtml: string): SharedWorkspaceMarkup {
102
+ const out = {} as Record<keyof SharedWorkspaceMarkup, string>;
103
+ for (const r of REGIONS) out[r.key] = sliceRegion(indexHtml, r.start, r.end, r.key);
104
+ return out;
105
+ }
106
+
107
+ export function assertNoDuplicateIds(html: string, label = 'compare.html'): void {
108
+ const seen = new Set<string>();
109
+ for (const m of html.matchAll(/\bid="([^"]+)"/g)) {
110
+ const id = m[1]!;
111
+ if (seen.has(id)) throw new Error(`COMPARE_DUPLICATE_ID: duplicate id="${id}" in ${label}`);
112
+ seen.add(id);
113
+ }
114
+ }
115
+
116
+ export function assertSharedCompareMarkup(compareHtml: string, indexHtml: string): void {
117
+ const shared = extractSharedWorkspaceMarkup(indexHtml);
118
+ for (const r of REGIONS) {
119
+ const piece = shared[r.key].trim();
120
+ let actual: string;
121
+ try {
122
+ actual = sliceRegion(compareHtml, r.start, r.compareEnd, r.key).trim();
123
+ } catch {
124
+ throw new Error(`COMPARE_SHARED_MARKUP_DRIFT: ${r.key} in compare markup differs from web/index.html`);
125
+ }
126
+ if (actual !== piece) {
127
+ throw new Error(`COMPARE_SHARED_MARKUP_DRIFT: ${r.key} in compare markup differs from web/index.html`);
128
+ }
129
+ }
130
+ assertNoDuplicateIds(compareHtml, 'rendered compare HTML');
131
+ }
132
+
133
+ export function renderCompareHtml(compareTemplate: string, indexHtml: string): string {
134
+ const shared = extractSharedWorkspaceMarkup(indexHtml);
135
+ let out = compareTemplate;
136
+ for (const r of REGIONS) {
137
+ if (!out.includes(r.placeholder)) {
138
+ throw new Error(`COMPARE_SHARED_MARKUP_MISSING: placeholder ${r.placeholder} missing in web/compare.html`);
139
+ }
140
+ out = out.replace(r.placeholder, shared[r.key]);
141
+ }
142
+ if (out.includes('<!-- shared:')) {
143
+ throw new Error('COMPARE_SHARED_MARKUP_MISSING: unreplaced shared placeholder in web/compare.html');
144
+ }
145
+ assertSharedCompareMarkup(out, indexHtml);
146
+ return out;
147
+ }
@@ -1,22 +1,34 @@
1
1
  import {createControlServer,type ControlIdentity} from './control-server.ts';
2
2
  import {openGate,staleOpenStatus,accessGate,openNonceGate,openNonceHeader,sameSecret,stampOpen,type OpenIdentity} from './open-protocol.ts';
3
3
  import { readFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { join } from 'node:path';
4
6
  import { appRoot, buildWeb } from './build.ts';
5
- import { packagePath, safeFile } from './manifest.ts';
7
+ import { packagePath, safeFile, type ReviewPackage } from './manifest.ts';
6
8
  import { assertCompareUnchanged, safeCompareReference, type ComparePackage } from './compare.ts';
7
- import { serveReference } from './reference.ts';
9
+ import { assertReviewUnchanged, serveReference } from './reference.ts';
8
10
  import {referenceFrameIndex} from './reference-frame-index.ts';
9
11
  import { exportCompareStrip, stripJson } from './strip-export.ts';
10
12
  import { readCompareSession, saveCompareSession } from './compare-session.ts';
13
+ import { createRebuilds, RebuildError } from './rebuild.ts';
14
+ import { DENSITY_STRIP_LIMIT } from './density-strip.ts';
15
+ import { createReadings } from './readings-run.ts';
16
+ import { ReadingsError } from './readings.ts';
17
+ import { BONES_CHECK_LIMIT, createBonesCheck } from './bones-check.ts';
18
+ import { createRequirementsCheck } from './requirements-run.ts';
19
+ import { REQUIREMENTS_LIMIT, RequirementsError } from './requirements.ts';
20
+ import { createEnvironmentCheck, ENVIRONMENT_CHECK_LIMIT, EnvironmentCheckError } from './environment-check.ts';
21
+ import { renderCompareHtml } from './compare-html.ts';
11
22
  import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
12
23
 
13
- const headers={'X-Content-Type-Options':'nosniff','Cache-Control':'no-store','Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; media-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",'Referrer-Policy':'no-referrer'};
24
+ const headers={'X-Content-Type-Options':'nosniff','Cache-Control':'no-store','Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; media-src 'self'; connect-src 'self'; font-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",'Referrer-Policy':'no-referrer'};
25
+ const MALFORMED=new Set(['REBUILD_REQUEST_INVALID','DENSITY_STRIP_REQUEST_INVALID','DENSITY_STRIP_FIELD','MESH_PATCH_SCOPE','EDIT_PATCH_INVALID','EDIT_PATCH_OP_UNKNOWN','EDIT_PATCH_POINTER_INVALID','EDIT_PATCH_CMD_UNKNOWN','EDIT_PATCH_ARG_UNKNOWN','BONES_OP_OUT_OF_SCOPE','RETARGET_REQUEST_INVALID']);
14
26
  const json=(value:unknown,status=200)=>Response.json(value,{status,headers});
15
- async function bodyJson(req:Request):Promise<unknown>{
27
+ async function bodyJson(req:Request,limit=1024*1024,what='Session payload exceeds 1 MiB'):Promise<unknown>{
16
28
  if(!/^application\/json(?:\s*;|$)/i.test(req.headers.get('content-type')??''))throw new Error('Expected application/json');
17
- if(Number(req.headers.get('content-length')??0)>1024*1024)throw new Error('Session payload exceeds 1 MiB');
29
+ if(Number(req.headers.get('content-length')??0)>limit)throw new Error(what);
18
30
  if(!req.body)throw new Error('JSON body required');const reader=req.body.getReader(),chunks:Uint8Array[]=[];let size=0;
19
- while(true){const {value,done}=await reader.read();if(done)break;size+=value.length;if(size>1024*1024){await reader.cancel();throw new Error('Session payload exceeds 1 MiB');}chunks.push(value);}
31
+ while(true){const {value,done}=await reader.read();if(done)break;size+=value.length;if(size>limit){await reader.cancel();throw new Error(what);}chunks.push(value);}
20
32
  const bytes=new Uint8Array(size);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.length;}return JSON.parse(new TextDecoder().decode(bytes));
21
33
  }
22
34
  function serveAsset(req:Request,path:string):Response{
@@ -30,9 +42,20 @@ function serveAsset(req:Request,path:string):Response{
30
42
  return new Response(req.method==='HEAD'?null:file,{headers:{...assetHeaders,'Content-Length':String(size)}});
31
43
  }
32
44
  /** `capability` (open workers and foreground CLI serving) gates every non-GET request; tests may omit it. */
33
- export async function startCompareServer(p:ComparePackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;activity?:()=>void;control?:ControlIdentity;capability?:string;graceMs?:number;unopenedTimeoutMs?:number;exitOnClose?:boolean;onClose?:(info:LiveExitInfo)=>void|Promise<void>;log?:(line:string)=>void}={}){
45
+ export async function startCompareServer(p:ComparePackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;activity?:()=>void;control?:ControlIdentity;capability?:string;cwd?:string;stripConcurrency?:number;graceMs?:number;unopenedTimeoutMs?:number;exitOnClose?:boolean;onClose?:(info:LiveExitInfo)=>void|Promise<void>;log?:(line:string)=>void}={}){
34
46
  const bundle=await buildWeb('compare');
35
47
  const frames=referenceFrameIndex(p.referencePath,p.response.binding.reference.sha256,p.response.sourceHash);
48
+ const stateDir=options.stateDir??process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review');
49
+ const makeSideTools=(side:'a'|'b',pkg:ReviewPackage)=>{
50
+ const unchanged=()=>assertReviewUnchanged(pkg),starts=[pkg.root,options.cwd??process.cwd()];
51
+ const rebuilds=createRebuilds(pkg,{stateDir,starts,unchanged,bones:pkg.feedbackCatalog.bones,assetPrefix:`/compare-rebuild/${side}`,stripPrefix:`/compare-density-strip/${side}`,...(options.stripConcurrency?{stripConcurrency:options.stripConcurrency}:{})});
52
+ const readings=createReadings(pkg,{stateDir,starts,unchanged,latest:rebuilds.latest});
53
+ const bonesCheck=createBonesCheck(pkg,{stateDir,starts,unchanged});
54
+ const requirements=createRequirementsCheck(pkg,{stateDir,starts,unchanged,latest:rebuilds.latest});
55
+ const environmentCheck=createEnvironmentCheck(pkg,{stateDir,starts,unchanged,latest:rebuilds.latest});
56
+ return {rebuilds,readings,bonesCheck,requirements,environmentCheck,busy:()=>Boolean(rebuilds.busy()||readings.running()||requirements.running()||environmentCheck.running()||bonesCheck.running())};
57
+ };
58
+ const sideTools={a:makeSideTools('a',p.a),b:makeSideTools('b',p.b)};
36
59
  const control=options.control?createControlServer({identity:options.control,sourceHash:p.response.sourceHash,mode:'compare',unchanged:()=>assertCompareUnchanged(p),activity:options.activity}):null;
37
60
  let rawStop:((closeActiveConnections?:boolean)=>void)|null=null;
38
61
  const live=createLiveLifecycle({
@@ -42,6 +65,7 @@ export async function startCompareServer(p:ComparePackage,options:{port?:number;
42
65
  exitOnClose:options.exitOnClose,
43
66
  onClose:options.onClose,
44
67
  log:options.log,
68
+ busy:()=>sideTools.a.busy()||sideTools.b.busy(),
45
69
  stopServer:()=>{rawStop?.(true);},
46
70
  });
47
71
  const handle=async(req:Request,port:number|undefined,srv:UpgradableServer):Promise<Response|undefined>=>{try{
@@ -66,14 +90,82 @@ export async function startCompareServer(p:ComparePackage,options:{port?:number;
66
90
  const result=await exportCompareStrip(p,await bodyJson(req));
67
91
  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'}"`}});
68
92
  }
93
+ const sideApi=/^\/api\/compare\/(a|b)(\/.+)$/.exec(url.pathname);
94
+ if(sideApi){
95
+ const side=sideApi[1] as 'a'|'b',sub=sideApi[2]!,tools=sideTools[side];
96
+ if(req.method==='POST'){
97
+ if(req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
98
+ if(sub==='/rebuild'){
99
+ try{const result=await tools.rebuilds.start(await bodyJson(req,64*1024,'REBUILD_BODY_LIMIT: maximum 64 KiB'));return json(result.body,result.status);}
100
+ catch(e){if(e instanceof RebuildError)return json({status:'refused',error:e.message,producerLine:null},MALFORMED.has(e.code)?400:200);throw e;}
101
+ }
102
+ if(sub==='/rebuild/undo'){
103
+ try{const result=await tools.rebuilds.undo(await bodyJson(req,1024,'REBUILD_BODY_LIMIT: maximum 1 KiB'));return json(result.body,result.status);}
104
+ catch(e){if(e instanceof RebuildError)return json({status:'refused',error:e.message,producerLine:null},MALFORMED.has(e.code)?400:200);throw e;}
105
+ }
106
+ if(sub==='/density-strip'){
107
+ try{const result=await tools.rebuilds.startStrip(await bodyJson(req,DENSITY_STRIP_LIMIT,'DENSITY_STRIP_BODY_LIMIT: maximum 320 KiB'));return json(result.body,result.status);}
108
+ catch(e){if(e instanceof RebuildError)return json({status:'refused',error:e.message,producerLine:null},MALFORMED.has(e.code)?400:200);throw e;}
109
+ }
110
+ if(sub==='/density-strip/close'){
111
+ try{const result=await tools.rebuilds.closeStrip(await bodyJson(req,1024,'DENSITY_STRIP_BODY_LIMIT: maximum 1 KiB'));return json(result.body,result.status);}
112
+ catch(e){if(e instanceof RebuildError)return json({status:'refused',error:e.message,producerLine:null},MALFORMED.has(e.code)?400:200);throw e;}
113
+ }
114
+ if(sub==='/bones-check'){
115
+ try{return json(await tools.bonesCheck.run(await bodyJson(req,BONES_CHECK_LIMIT,'BONES_CHECK_BODY_LIMIT: maximum 64 KiB')));}
116
+ catch(e){if(e instanceof RebuildError)return json({status:'refused',error:e.message},MALFORMED.has(e.code)?400:200);throw e;}
117
+ }
118
+ if(sub==='/requirements'){
119
+ try{const result=await tools.requirements.start(await bodyJson(req,REQUIREMENTS_LIMIT,'REQUIREMENTS_BODY_LIMIT: maximum 64 KiB'));return json(result.body,result.status);}
120
+ catch(e){if(e instanceof RequirementsError)return json({status:'refused',error:e.message},e.code==='REQUIREMENTS_REQUEST_INVALID'?400:200);throw e;}
121
+ }
122
+ if(sub==='/environment-check'){
123
+ try{const result=await tools.environmentCheck.start(await bodyJson(req,ENVIRONMENT_CHECK_LIMIT,'ENVIRONMENT_CHECK_BODY_LIMIT: maximum 64 KiB'));return json(result.body,result.status);}
124
+ catch(e){if(e instanceof EnvironmentCheckError)return json({status:'refused',error:e.message},e.code==='ENVIRONMENT_CHECK_REQUEST_INVALID'?400:200);throw e;}
125
+ }
126
+ if(sub==='/readings'){
127
+ try{const result=await tools.readings.start(await bodyJson(req,64*1024,'READINGS_BODY_LIMIT: maximum 64 KiB'));return json(result.body,result.status);}
128
+ catch(e){if(e instanceof ReadingsError)return json({status:'refused',error:e.message},e.code==='READINGS_REQUEST_INVALID'?400:200);throw e;}
129
+ }
130
+ return json({error:'Not found'},404);
131
+ }
132
+ if(req.method!=='GET'&&req.method!=='HEAD')return json({error:'Method not allowed'},405);
133
+ if(sub==='/rebuild')return json(await tools.rebuilds.describe());
134
+ if(sub==='/rebuild/history')return json(await tools.rebuilds.history());
135
+ if(sub==='/density-strip')return json({strip:tools.rebuilds.readStrip()});
136
+ const stripStatus=/^\/density-strip\/([a-f0-9]{64})(?:\/([a-f0-9]{64}))?$/.exec(sub);
137
+ if(stripStatus){try{return json(stripStatus[2]?tools.rebuilds.stripJob(stripStatus[1]!,stripStatus[2]):tools.rebuilds.readStrip(stripStatus[1]!));}catch(e){if(e instanceof RebuildError)return json({error:e.message},404);throw e;}}
138
+ const rebuildStatus=/^\/rebuild\/([a-f0-9]{64})$/.exec(sub);
139
+ if(rebuildStatus){try{return json(tools.rebuilds.read(rebuildStatus[1]!));}catch(e){if(e instanceof RebuildError)return json({error:e.message},404);throw e;}}
140
+ if(sub==='/requirements')return json(await tools.requirements.describe());
141
+ const requirementsStatus=/^\/requirements\/([a-f0-9]{64})$/.exec(sub);
142
+ if(requirementsStatus){try{return json(tools.requirements.read(requirementsStatus[1]!));}catch(e){if(e instanceof RequirementsError)return json({error:e.message},404);throw e;}}
143
+ const environmentCheckStatus=/^\/environment-check\/([a-f0-9]{64})$/.exec(sub);
144
+ if(environmentCheckStatus){try{return json(tools.environmentCheck.read(environmentCheckStatus[1]!));}catch(e){if(e instanceof EnvironmentCheckError)return json({error:e.message},404);throw e;}}
145
+ const readingsStatus=/^\/readings\/([a-f0-9]{64})$/.exec(sub);
146
+ if(readingsStatus){try{return json(tools.readings.read(readingsStatus[1]!));}catch(e){if(e instanceof ReadingsError)return json({error:e.message},404);throw e;}}
147
+ return json({error:'Not found'},404);
148
+ }
69
149
  if(req.method!=='GET'&&req.method!=='HEAD')return json({error:'Method not allowed'},405);
150
+ const compareRebuildFile=/^\/compare-rebuild\/(a|b)\/([a-f0-9]{64})\/(.+)$/.exec(url.pathname);
151
+ if(compareRebuildFile){
152
+ const side=compareRebuildFile[1] as 'a'|'b';
153
+ let full:string;try{full=await sideTools[side].rebuilds.file(compareRebuildFile[2]!,decodeURIComponent(compareRebuildFile[3]!));}catch(e){return json({error:e instanceof Error?e.message:'Not found'},404);}
154
+ const file=Bun.file(full);return new Response(req.method==='HEAD'?null:file,{headers:{...headers,'Content-Security-Policy':"default-src 'none'; script-src 'none'; sandbox",'Content-Type':file.type||'application/octet-stream','Content-Length':String(file.size)}});
155
+ }
156
+ const compareStripFile=/^\/compare-density-strip\/(a|b)\/([a-f0-9]{64})\/([a-f0-9]{64})\/(.+)$/.exec(url.pathname);
157
+ if(compareStripFile){
158
+ const side=compareStripFile[1] as 'a'|'b';
159
+ let full:string;try{full=await sideTools[side].rebuilds.stripFile(compareStripFile[2]!,compareStripFile[3]!,decodeURIComponent(compareStripFile[4]!));}catch(e){return json({error:e instanceof Error?e.message:'Not found'},404);}
160
+ const file=Bun.file(full);return new Response(req.method==='HEAD'?null:file,{headers:{...headers,'Content-Security-Policy':"default-src 'none'; script-src 'none'; sandbox",'Content-Type':file.type||'application/octet-stream','Content-Length':String(file.size)}});
161
+ }
70
162
  if(url.pathname==='/api/compare/reference-frames'){if(url.search)return json({error:'Reference frame index accepts no parameters'},400);await assertCompareUnchanged(p);await safeCompareReference(p);return json(await frames());}
71
163
  if(url.pathname==='/api/compare'){await assertCompareUnchanged(p);return json(p.response);}
72
164
  if(url.pathname==='/api/compare/session')return json(await readCompareSession(p,options.stateDir));
73
165
  if(url.pathname==='/compare-reference')return await serveReference(req,await safeCompareReference(p),p.response.binding.reference.sha256,headers);
74
166
  if(url.pathname.startsWith('/compare-assets/')){const match=/^\/compare-assets\/(a|b)\/(.+)$/.exec(url.pathname);if(!match)return json({error:'Unknown comparison side'},404);const side=match[1] as 'a'|'b',path=packagePath(decodeURIComponent(match[2]!));if(!p[side].files.has(path))return json({error:'Asset not declared by package'},404);return serveAsset(req,await safeFile(p[side].root,path));}
75
167
  if(url.pathname==='/main.js')return new Response(req.method==='HEAD'?null:bundle,{headers:{...headers,'Content-Type':'text/javascript'}});
76
- if(url.pathname==='/'||url.pathname==='/index.html')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/compare.html'),{headers:{...headers,'Content-Type':'text/html; charset=utf-8'}});
168
+ if(url.pathname==='/'||url.pathname==='/index.html'){const html=renderCompareHtml(await readFile(appRoot+'web/compare.html','utf8'),await readFile(appRoot+'web/index.html','utf8'));return new Response(req.method==='HEAD'?null:html,{headers:{...headers,'Content-Type':'text/html; charset=utf-8'}});}
77
169
  if(url.pathname==='/styles.css')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/compare.css'),{headers:{...headers,'Content-Type':'text/css'}});
78
170
  return json({error:'Not found'},404);
79
171
  } finally { live.onRequestEnd(url.pathname); }
package/src/front.ts CHANGED
@@ -58,27 +58,23 @@ export function frontRoute(mode:'single'|'compare',method:string,path:string):Ro
58
58
  const reads=mode==='single'?['/api/review','/review-reference']:['/api/compare','/api/compare/reference-frames','/compare-reference'];
59
59
  if(reads.includes(path))return read?get:null;
60
60
  if((mode==='single'?/^\/assets\/[^/]/:/^\/compare-assets\/(a|b)\/[^/]/).test(path))return read?get:null;
61
- // Apply · Rebuild (single only): status, one typed request, a job's status and its served scratch build.
62
- if(mode==='single'&&path==='/api/rebuild')return read?get:method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
63
- // #166 (single only): the applied records, and undo of the last one ({from}).
64
- if(mode==='single'&&path==='/api/rebuild/history')return read?get:null;
65
- if(mode==='single'&&path==='/api/rebuild/undo')return method==='POST'?{mutation:true,limit:1024,timeoutMs:30000,control:false}:null;
66
- if(mode==='single'&&(/^\/api\/rebuild\/[a-f0-9]{64}$/.test(path)||/^\/rebuild\/[a-f0-9]{64}\/[^/]/.test(path)))return read?get:null;
67
- // #173 (single only): a density strip (2–5 patches, 320 KiB), its status, a candidate's job, its served build, and closing it.
68
- if(mode==='single'&&path==='/api/density-strip')return read?get:method==='POST'?{mutation:true,limit:320*1024,timeoutMs:30000,control:false}:null;
69
- if(mode==='single'&&path==='/api/density-strip/close')return method==='POST'?{mutation:true,limit:1024,timeoutMs:30000,control:false}:null;
70
- if(mode==='single'&&(/^\/api\/density-strip\/[a-f0-9]{64}(?:\/[a-f0-9]{64})?$/.test(path)||/^\/density-strip\/[a-f0-9]{64}\/[a-f0-9]{64}\/[^/]/.test(path)))return read?get:null;
71
- // Bones check (#109, single only): one typed request {ops, configHash}, answered in the response.
72
- if(mode==='single'&&path==='/api/bones-check')return method==='POST'?{mutation:true,limit:64*1024,timeoutMs:60000,control:false}:null;
73
- // Readings (#108, single only): one typed request, then its job's status.
74
- if(mode==='single'&&path==='/api/readings')return method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
75
- if(mode==='single'&&/^\/api\/readings\/[a-f0-9]{64}$/.test(path))return read?get:null;
76
- // Declared requirements (#113, single only): the stage's catalog, one typed request, then its job's status.
77
- if(mode==='single'&&path==='/api/requirements')return read?get:method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
78
- if(mode==='single'&&/^\/api\/requirements\/[a-f0-9]{64}$/.test(path))return read?get:null;
79
- // Check under this world (#112, single only): one typed request {build, schedule}, then its job's status.
80
- if(mode==='single'&&path==='/api/environment-check')return method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
81
- if(mode==='single'&&/^\/api\/environment-check\/[a-f0-9]{64}$/.test(path))return read?get:null;
61
+ // Apply · Rebuild and producer checks: un-prefixed in single mode, side-scoped (/api/compare/(a|b)/*, /compare-rebuild/(a|b)/*) in compare mode (#234).
62
+ const toolPath=mode==='compare'?path.replace(/^\/api\/compare\/(?:a|b)(?=\/)/,'/api').replace(/^\/compare-rebuild\/(?:a|b)\//,'/rebuild/').replace(/^\/compare-density-strip\/(?:a|b)\//,'/density-strip/'):path;
63
+ if(mode==='compare'&&toolPath===path)return null;
64
+ if(toolPath==='/api/rebuild')return read?get:method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
65
+ if(toolPath==='/api/rebuild/history')return read?get:null;
66
+ if(toolPath==='/api/rebuild/undo')return method==='POST'?{mutation:true,limit:1024,timeoutMs:30000,control:false}:null;
67
+ if(/^\/api\/rebuild\/[a-f0-9]{64}$/.test(toolPath)||/^\/rebuild\/[a-f0-9]{64}\/[^/]/.test(toolPath))return read?get:null;
68
+ if(toolPath==='/api/density-strip')return read?get:method==='POST'?{mutation:true,limit:320*1024,timeoutMs:30000,control:false}:null;
69
+ if(toolPath==='/api/density-strip/close')return method==='POST'?{mutation:true,limit:1024,timeoutMs:30000,control:false}:null;
70
+ if(/^\/api\/density-strip\/[a-f0-9]{64}(?:\/[a-f0-9]{64})?$/.test(toolPath)||/^\/density-strip\/[a-f0-9]{64}\/[a-f0-9]{64}\/[^/]/.test(toolPath))return read?get:null;
71
+ if(toolPath==='/api/bones-check')return method==='POST'?{mutation:true,limit:64*1024,timeoutMs:60000,control:false}:null;
72
+ if(toolPath==='/api/readings')return method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
73
+ if(/^\/api\/readings\/[a-f0-9]{64}$/.test(toolPath))return read?get:null;
74
+ if(toolPath==='/api/requirements')return read?get:method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
75
+ if(/^\/api\/requirements\/[a-f0-9]{64}$/.test(toolPath))return read?get:null;
76
+ if(toolPath==='/api/environment-check')return method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
77
+ if(/^\/api\/environment-check\/[a-f0-9]{64}$/.test(toolPath))return read?get:null;
82
78
  return null;
83
79
  }
84
80
  async function boundedBody(req:Request,limit:number,timeoutMs=10000):Promise<ArrayBuffer>{
package/src/rebuild.ts CHANGED
@@ -409,6 +409,8 @@ export interface RebuildOptions {
409
409
  stateDir: string; starts: readonly string[]; unchanged: () => Promise<void>; bones: readonly string[] | null;
410
410
  /** #179: how many strip candidates run at once, at most four including the recording candidate. */
411
411
  stripConcurrency?: number;
412
+ assetPrefix?: string;
413
+ stripPrefix?: string;
412
414
  }
413
415
  /** #173: a density strip's scratch — one folder per package, holding at most the one strip on screen. */
414
416
  export const stripRoot = (stateDir: string, sourceHash: string) => join(stateDir, 'density-strip', sourceHash);
@@ -568,16 +570,17 @@ async function assembledAfter(job: PatchJob, dir: string, inputs: ProducerInputs
568
570
  }
569
571
 
570
572
  /** Hash every page the compiled model names and the model itself; names are literal relative paths inside the build. */
571
- async function hashBuild(build: string, id: string): Promise<RebuildBuild> {
573
+ async function hashBuild(build: string, id: string, assetPrefix = '/rebuild'): Promise<RebuildBuild> {
572
574
  const dir = await realpath(build), model = 'skeleton.model.json', bytes = await readFile(await safeFile(dir, model)), doc = object(JSON.parse(bytes.toString('utf8')), 'model');
573
575
  if (doc.spec !== 'rigc-compiled/3' || !Array.isArray(doc.pages)) throw new RebuildError('REBUILD_BUILD_INVALID', 'the compiled scratch model is not rigc-compiled/3 with pages');
574
576
  const files: Record<string, string> = { [model]: sha256(bytes) };
575
577
  for (const page of doc.pages) { const name = packagePath(object(page, 'model.pages[]').name, 'model.pages[].name'); files[name] = sha256(await readFile(await safeFile(dir, name))); }
576
- return { model, modelUrl: `/rebuild/${id}/${model}`, modelHash: files[model]!, files };
578
+ return { model, modelUrl: `${assetPrefix}/${id}/${model}`, modelHash: files[model]!, files };
577
579
  }
578
580
 
579
581
  /** One rebuild at a time per review instance; finished jobs stay readable by id. */
580
582
  export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
583
+ const assetPrefix = options.assetPrefix ?? '/rebuild', stripPrefix = options.stripPrefix ?? '/density-strip';
581
584
  const jobs = new Map<string, RebuildJob | PatchJob | DeltaJob | RetargetJob>();
582
585
  let running: string | null = null;
583
586
  /** #173: the density strip on screen (at most one per review): its candidates run beside each other, none of them applied. */
@@ -821,9 +824,9 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
821
824
  try {
822
825
  const stored = JSON.parse(await readFile(resultFile, 'utf8')) as J;
823
826
  if (stored.schema !== REBUILD_SCHEMA || stored.id !== id || stored.status !== 'built' || !stored.build) return null;
824
- const now = await hashBuild(join(dir, 'build'), id);
827
+ const now = await hashBuild(join(dir, 'build'), id, assetPrefix);
825
828
  if (JSON.stringify(now.files) !== JSON.stringify(stored.build.files)) return null;
826
- const job = { ...stored, reused: true };
829
+ const job = { ...stored, build: now, reused: true };
827
830
  // A retarget built before the job carried its report's frameTimes (#164): read them from the build's own report.
828
831
  if ('kind' in job && job.kind === 'retarget' && (job as RetargetJob).frameTimes === undefined) {
829
832
  let times: unknown = null;
@@ -888,7 +891,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
888
891
  // The package and its producer inputs must still be the bytes the request was made against.
889
892
  // The handoff files are in the reviewed identity, so this also catches a config, parts or rig change.
890
893
  try { await options.unchanged(); } catch { throw new RebuildError('REBUILD_INPUTS_CHANGED', 'the package or its producer handoff changed during the rebuild'); }
891
- job.build = await hashBuild(join(dir, 'build'), job.id);
894
+ job.build = await hashBuild(join(dir, 'build'), job.id, assetPrefix);
892
895
  if (steps.hashed) await steps.hashed();
893
896
  // #166: an undo's re-run must reproduce the build its record names, file for file; otherwise it is refused, not guessed.
894
897
  const changed = steps.candidate ? null : restoredDifference(job.id, job.build.files);
@@ -1244,7 +1247,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1244
1247
  function stripView(): DensityStripView | null {
1245
1248
  if (!strip) return null;
1246
1249
  const s = strip;
1247
- const rows = s.candidates.map(c => candidateRow({ value: c.value, id: c.id, entry: c.entry, job: c.job, part: s.part, modelUrl: c.job.build ? `/density-strip/${s.id}/${c.id}/${c.job.build.model}` : null, applied: c.applied }));
1250
+ const rows = s.candidates.map(c => candidateRow({ value: c.value, id: c.id, entry: c.entry, job: c.job, part: s.part, modelUrl: c.job.build ? `${stripPrefix}/${s.id}/${c.id}/${c.job.build.model}` : null, applied: c.applied }));
1248
1251
  return { schema: DENSITY_STRIP_SCHEMA, id: s.id, status: s.status, part: s.part, field: s.field, concurrency: s.concurrency, configHash: s.configHash, producer: s.producer, compiler: s.compiler, wallMs: s.wallMs, rows, labels: s.status === 'done' ? stripLabels(rows) : { fewest: null, widest: null } };
1249
1252
  }
1250
1253
  /** `GET /api/density-strip/<id>` (and `GET /api/density-strip`: the strip on screen, or null). */
@@ -26,8 +26,8 @@ export function stageCommentMode(value:unknown):CommentMode {
26
26
  const c=obj(value);
27
27
  if(!Object.hasOwn(c,'mode'))throw new Error('COMMENT_MODE_MISSING: placement mode is required');
28
28
  if(!commentModes.includes(c.mode))throw new Error('COMMENT_MODE_UNKNOWN: expected setup, animate or compare');
29
- const b=c.bookmark;
30
- if(c.mode==='compare' ? b?.binding?.mode!=='compare'||c.viewport==='rig' : b?.binding?.mode!=='single'||!['rig','reference'].includes(c.viewport)||b?.selection?.inspector!==(c.mode==='setup'?'rig':'playback'))throw new Error('COMMENT_MODE_MISMATCH: placement mode differs from page, viewport or saved inspector');
29
+ const b=c.bookmark,bm=b?.binding?.mode,selMode=b?.selection?.mode;
30
+ if(bm==='single' ? c.mode==='compare'||!['rig','reference'].includes(c.viewport)||b?.selection?.inspector!==(c.mode==='setup'?'rig':'playback') : bm!=='compare'||c.viewport==='rig'||selMode!==undefined&&selMode!==c.mode||(c.mode==='setup'&&b?.selection?.inspector!=='rig')||(c.mode==='animate'&&b?.selection?.inspector!=='playback'))throw new Error('COMMENT_MODE_MISMATCH: placement mode differs from page, viewport or saved inspector');
31
31
  return c.mode;
32
32
  }
33
33
  export function parseStageComment(value:unknown):StageComment {