@rig-c/review 1.13.0 → 1.14.1

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/docs/WORKFLOWS.md CHANGED
@@ -360,6 +360,24 @@ The managed front forwards only the trusted stage-atlas frame query (`stageEmbed
360
360
 
361
361
  ## Create choice interview
362
362
 
363
+ Open the interview beside its separated parts in the standard inspection host.
364
+ Use the materialized Create review package and designate the exact project and
365
+ rig version. The picks directory must already exist inside the project and be
366
+ separate from its inputs.
367
+
368
+ ```sh
369
+ rig-review open /path/to/project/derived/review/v2/out \
370
+ --project /path/to/project --project-version 2 --picks-dir scratch/review-picks
371
+ ```
372
+
373
+ Select **2 Interview**. The host checks the recorded version's package
374
+ inventory and pins the project digest and inspected source. A different
375
+ project or version returns `INTERVIEW_SOURCE_MISMATCH`. A changed input
376
+ requires reopening and a project without interview content reports
377
+ `INTERVIEW_UNAVAILABLE`. Navigation retains the open form and part selection.
378
+ Use **Save explicit picks** to persist pending choices. Historical answers
379
+ remain read-only and opening or saving picks does not sign off any stage.
380
+
363
381
  From a create project with retained choice sets, create a dedicated output
364
382
  directory and open the foreground Stage 2 view:
365
383
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/review",
3
- "version": "1.13.0",
3
+ "version": "1.14.1",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
package/src/build.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { fileURLToPath } from 'node:url';
2
2
  export const appRoot=fileURLToPath(new URL('..',import.meta.url));
3
- export async function buildWeb(mode:'single'|'compare'|'parts'='single'):Promise<Blob> {
4
- const result=await Bun.build({entrypoints:[appRoot+(mode==='compare'?'web/compare.ts':mode==='parts'?'web/parts.ts':'web/main.ts')],target:'browser',format:'esm',minify:false});
3
+ export async function buildWeb(mode:'single'|'compare'|'parts'|'interview'='single'):Promise<Blob> {
4
+ const result=await Bun.build({entrypoints:[appRoot+(mode==='compare'?'web/compare.ts':mode==='parts'?'web/parts.ts':mode==='interview'?'web/interview.ts':'web/main.ts')],target:'browser',format:'esm',minify:false});
5
5
  if(!result.success)throw new Error(result.logs.map(v=>v.message).join('\n'));
6
6
  const output=result.outputs.find(v=>v.path.endsWith('.js'));if(!output)throw new Error('frontend bundle: JavaScript output missing');return output;
7
7
  }
package/src/cli.ts CHANGED
@@ -24,7 +24,7 @@ import { readCompareSession } from './compare-session.ts';
24
24
  import { exportReviewStrip, exportCompareStrip, stripJson, writeStripOutput, validateStripOutput } from './strip-export.ts';
25
25
  import type { StripInterval, StripRequest } from './strip.ts';
26
26
  const handoffUsage='[--config <path> [--parts <dir>] [--source <png> --full <dir> [--head <dir>]] [--keypoints <file>]]';
27
- const usage='Usage: rig-review open <dir> [--reference <video>] [--compare <dir>] [--animation <name>] [--control] [--direct] [--view-only] '+handoffUsage+'\n --config declares the producer handoff (wins over the review.json "producer" block and discovery of config.json, rig/config.json, ../config.json beside an opened out/); feedback and control take the same flags; --view-only opens without a producer handoff.\n open is managed by default: one loopback front at 127.0.0.1:4318 (RIG_REVIEW_FRONT_PORT overrides) serves /instances/<key>/; --direct serves the worker on its own port.\n rig-review control <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--page <id> --expected-revision <n> --command <JSON> --wait-ms <n>]\n rig-review feedback <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--format json|issue] [--correction <item id>]\n Usage: bun run review -- <review.json|output-directory> [--port 4317] [--checkpoint ID] [--view-only]\n bun run check -- <review.json|output-directory>\n bun run feedback -- <review.json|output-directory>\n bun run review -- compare <a> <b> --reference <video> --animation <name> [--port 4317]\n bun run check -- compare <a> <b> --reference <video> --animation <name>\n bun run feedback -- compare <a> <b> --reference <video> --animation <name>\n rig-review parts <build root | parts dir | review package> [--rig <file>] [--mesh-report <file>] [--check <file>] [--verdict <file>] [--painting <png>] [--format json|issue] [--correction <item id> --parts-file <inventory> [--part-note <part>]] [--port <n>]\n rig-review interview <create-root> --picks-dir <project-relative directory> [--port <n>]\n rig-review --version';
27
+ const usage='Usage: rig-review open <dir> [--reference <video>] [--compare <dir>] [--animation <name>] [--control] [--direct] [--view-only] [--project <create-root> --project-version <n> --picks-dir <dir>] '+handoffUsage+'\n --config declares the producer handoff (wins over the review.json "producer" block and discovery of config.json, rig/config.json, ../config.json beside an opened out/); feedback and control take the same flags; --view-only opens without a producer handoff.\n open is managed by default: one loopback front at 127.0.0.1:4318 (RIG_REVIEW_FRONT_PORT overrides) serves /instances/<key>/; --direct serves the worker on its own port.\n rig-review control <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--page <id> --expected-revision <n> --command <JSON> --wait-ms <n>]\n rig-review feedback <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--format json|issue] [--correction <item id>]\n Usage: bun run review -- <review.json|output-directory> [--port 4317] [--checkpoint ID] [--view-only]\n bun run check -- <review.json|output-directory>\n bun run feedback -- <review.json|output-directory>\n bun run review -- compare <a> <b> --reference <video> --animation <name> [--port 4317]\n bun run check -- compare <a> <b> --reference <video> --animation <name>\n bun run feedback -- compare <a> <b> --reference <video> --animation <name>\n rig-review parts <build root | parts dir | review package> [--rig <file>] [--mesh-report <file>] [--check <file>] [--verdict <file>] [--painting <png>] [--format json|issue] [--correction <item id> --parts-file <inventory> [--part-note <part>]] [--port <n>]\n rig-review interview <create-root> --picks-dir <project-relative directory> [--port <n>]\n rig-review --version';
28
28
  async function stripCommand(args:string[],options:{stateDir?:string}){
29
29
  const compare=args[0]==='compare';if(compare)args.shift();const a=args.shift(),b=compare?args.shift():undefined;if(!a||compare&&!b)throw new Error('strip: expected package input(s)');
30
30
  let reference:string|undefined,referenceVideo:string|undefined,animation:string|undefined,basis:'a'|'b'|undefined,range:string|undefined,output:string|undefined,jsonOnly=false,all=false;
@@ -44,27 +44,36 @@ async function stripCommand(args:string[],options:{stateDir?:string}){
44
44
  }
45
45
  /** `--config` → `config` for the producer handoff flags (#101), else null. */
46
46
  function handoffOption(flag:string):(typeof HANDOFF_FLAGS)[number]|null {const name=flag.slice(2);return flag.startsWith('--')&&(HANDOFF_FLAGS as readonly string[]).includes(name)?name as (typeof HANDOFF_FLAGS)[number]:null;}
47
+ const projectFlags = ['--project','--project-version','--picks-dir'];
47
48
  /** The retrieval words for the handoff flags, in their fixed order. */
48
49
  const handoffWords=(inputs:OpenInputs)=>HANDOFF_FLAGS.flatMap(f=>inputs[f]!==undefined?['--'+f,inputs[f]!]:[]);
49
50
  export function parseOpenInputs(args:string[]):OpenInputs {
50
51
  const input=args.shift();if(!input||input.startsWith('--'))throw new Error(usage);const result:OpenInputs={input},seen=new Set<string>();
51
- while(args.length){const flag=args.shift()!;if(seen.has(flag))throw new Error(`OPEN_OPTION_INVALID ${flag}: Duplicate open option ${flag}`);seen.add(flag);if(flag==='--control'){result.control=true;continue;}if(flag==='--direct'){result.direct=true;continue;}if(flag==='--view-only'){result.viewOnly=true;continue;}const value=args.shift();if(value===undefined||value==='')throw new Error(`OPEN_OPTION_INVALID ${flag}: Missing value for ${flag}`);if(flag==='--reference')result.reference=value;else if(flag==='--compare')result.compare=value;else if(flag==='--animation')result.animation=value;else if(handoffOption(flag))result[handoffOption(flag)!]=value;else throw new Error(`OPEN_OPTION_INVALID ${flag}: Unknown open option ${flag}`);}
52
+ let root:string|undefined,version:string|undefined,picksDir:string|undefined;
53
+ while(args.length){const flag=args.shift()!;if(seen.has(flag))throw new Error(`OPEN_OPTION_INVALID ${flag}: Duplicate open option ${flag}`);seen.add(flag);if(flag==='--control'){result.control=true;continue;}if(flag==='--direct'){result.direct=true;continue;}if(flag==='--view-only'){result.viewOnly=true;continue;}const value=args.shift();if(value===undefined||value==='')throw new Error(`OPEN_OPTION_INVALID ${flag}: Missing value for ${flag}`);if(flag==='--reference')result.reference=value;else if(flag==='--compare')result.compare=value;else if(flag==='--animation')result.animation=value;else if(flag==='--project')root=value;else if(flag==='--project-version')version=value;else if(flag==='--picks-dir')picksDir=value;else if(handoffOption(flag))result[handoffOption(flag)!]=value;else throw new Error(`OPEN_OPTION_INVALID ${flag}: Unknown open option ${flag}`);}
54
+ if(root!==undefined||version!==undefined||picksDir!==undefined){
55
+ if(!root||!picksDir||!version||!/^\d+$/.test(version)||!Number.isSafeInteger(Number(version))||Number(version)<1||result.compare!==undefined)
56
+ throw new Error('OPEN_OPTION_INVALID --project: single-package open requires --project, --project-version and --picks-dir together');
57
+ result.project={root,version:Number(version),picksDir};
58
+ }
52
59
  const problem=checkHandoffFlags(result);if(problem)throw new Error(`OPEN_OPTION_INVALID ${problem.split(':')[0]}: ${problem.slice(problem.indexOf(':')+2)}`);
53
60
  if(result.compare!==undefined&&handoffFlags(result))throw new Error('OPEN_OPTION_INVALID --config: compare takes no producer handoff; open one package with --config');
54
61
  return result;
55
62
  }
56
63
  async function controlCommand(args:string[],stateDir?:string){
57
64
  const input=args.shift();if(!input||input==='--help'||input==='-h'){console.log(usage);return;}
58
- const inputs:OpenInputs={input},options:Parameters<typeof controlReview>[1]={stateDir},seen=new Set<string>();
65
+ const inputs:OpenInputs={input},options:Parameters<typeof controlReview>[1]={stateDir},seen=new Set<string>(),projectOptions:string[]=[];
59
66
  while(args.length){const flag=args.shift()!;if(seen.has(flag))throw new Error(`Duplicate control option ${flag}`);seen.add(flag);const value=args.shift();if(value===undefined||value==='')throw new Error(`Missing value for ${flag}`);
60
67
  if(flag==='--reference')inputs.reference=value;else if(flag==='--compare')inputs.compare=value;else if(flag==='--animation')inputs.animation=value;
61
68
  else if(handoffOption(flag))inputs[handoffOption(flag)!]=value;
69
+ else if(projectFlags.includes(flag))projectOptions.push(flag,value);
62
70
  else if(flag==='--page')options.pageId=value;else if(flag==='--request-id')options.requestId=value;
63
71
  else if(flag==='--expected-revision'){const n=Number(value);if(!/^\d+$/.test(value)||!Number.isSafeInteger(n))throw new Error('--expected-revision: expected safe integer >= 0');options.expectedRevision=n;}
64
72
  else if(flag==='--wait-ms'){const n=Number(value);if(!/^\d+$/.test(value)||!Number.isSafeInteger(n)||n>30000)throw new Error('--wait-ms: expected integer 0..30000');options.waitMs=n;}
65
73
  else if(flag==='--command'){if(value.length>8192)throw new Error('--command: JSON exceeds 8 KiB');options.command=parseControlCommand(JSON.parse(value));}
66
74
  else throw new Error(`Unknown control option ${flag}`);
67
75
  }
76
+ if(projectOptions.length)inputs.project=parseOpenInputs([input,...projectOptions]).project;
68
77
  const result=await controlReview(inputs,options);console.log(JSON.stringify(result,null,2));if(options.command&&(result as {status?:string}).status!=='applied')process.exitCode=2;
69
78
  }
70
79
  /** Formatting is CLI-only; session lookup/save contracts remain unchanged. */
@@ -95,7 +104,7 @@ export function feedbackFormat(args:string[]):{args:string[];format:'json'|'issu
95
104
  function commandHelpRequested(args:readonly string[],command:'open'|'review'|'check'|'feedback'):boolean {
96
105
  if(args[0]==='--help'||args[0]==='-h')return true;
97
106
  const compare=command!=='open'&&args[0]==='compare';
98
- const handoff=HANDOFF_FLAGS.map(f=>'--'+f),flags=command==='open'?['--reference','--compare','--animation',...handoff]:compare?['--reference','--animation','--port']:['--port','--checkpoint','--reference','--compare','--animation',...handoff];
107
+ const handoff=HANDOFF_FLAGS.map(f=>'--'+f),flags=command==='open'?['--reference','--compare','--animation',...projectFlags,...handoff]:compare?['--reference','--animation','--port']:['--port','--checkpoint','--reference','--compare','--animation',...handoff];
99
108
  for(let i=compare?3:1;i<args.length;){
100
109
  const flag=args[i];if(flag==='--help'||flag==='-h')return true;
101
110
  if((command==='open'&&(flag==='--control'||flag==='--direct'||flag==='--view-only'))||(command==='review'&&flag==='--view-only')){i++;continue;}if(!flags.includes(flag!))return false;i+=2;
package/src/front.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import { interviewRefusals, interviewRequest } from './interview-routes.ts';
2
+ import { interviewStale } from './joined-project.ts';
3
+ import { picksLimit } from './interview-picks.ts';
1
4
  import {stageDraftRefusals} from './stage-parts.ts';
2
5
  /** Managed loopback front: one stable origin (127.0.0.1:4318 by default) routing `/instances/<key>/…` to the
3
6
  * worker named by that key's private open record. It is a router, not an authority: it never reads packages,
@@ -53,6 +56,11 @@ export function frontRoute(mode:'single'|'compare',method:string,path:string):Ro
53
56
  if(['/','/index.html','/main.js','/styles.css','/api/access'].includes(path))return read?get:null;
54
57
  if(['/stage-parts.html','/parts.js','/parts.css'].includes(path))return read?get:null;
55
58
  if((mode==='single'?/^\/api\/stage-parts(?:\/(?:image|page)\/\d+)?$/:/^\/api\/compare\/(?:a|b)\/stage-parts(?:\/(?:image|page)\/\d+)?$/).test(path))return read?get:null;
59
+ if(mode==='single'){
60
+ if(['/stage-interview.html','/interview.js','/interview.css'].includes(path))return method==='GET'?get:null;
61
+ if(interviewRequest(path))return path==='/api/interview/picks'?
62
+ method==='POST'?{...get,mutation:true,limit:picksLimit}:null:method==='GET'?get:null;
63
+ }
56
64
  if(path==='/api/control/config')return method==='GET'?{...get,control:true}:null;
57
65
  if(['/api/control/register','/api/control/poll','/api/control/ack','/api/control/close'].includes(path))return method==='POST'?{mutation:true,limit:16384,timeoutMs:10000,control:true}:null;
58
66
  const session=mode==='single'?'/api/session':'/api/compare/session',strip=mode==='single'?'/api/strip':'/api/compare/strip';
@@ -98,10 +106,11 @@ export function stageFrameQuery(mode:'single'|'compare',search:string):boolean {
98
106
  const allowed=mode==='single'?['stageEmbed','lang']:['stageEmbed','lang','side'];
99
107
  return keys.length===allowed.length&&new Set(keys).size===keys.length&&keys.every(k=>allowed.includes(k))&&params.get('stageEmbed')==='1'&&['en','ko'].includes(params.get('lang')??'')&&(mode==='single'||['a','b'].includes(params.get('side')??''));
100
108
  }
101
- /** Preserve only this closed, bounded stage-data refusal; never relay arbitrary worker text. */
102
- async function stagePartsRefusal(mode:'single'|'compare',method:string,path:string,response:Response):Promise<string|null>{
109
+ /** Preserve only closed, bounded inspection refusals. */
110
+ async function inspectionRefusal(mode:'single'|'compare',method:string,path:string,response:Response):Promise<string|null>{
103
111
  const stageData=mode==='single'?path==='/api/stage-parts':/^\/api\/compare\/(?:a|b)\/stage-parts$/.test(path);
104
- if(!stageData||method!=='GET'||response.status!==409||!/^application\/json(?:\s*;|$)/i.test(response.headers.get('content-type')??''))return null;
112
+ const interview=mode==='single'&&interviewRequest(path)&&[400,404,409].includes(response.status);
113
+ if(!(interview||stageData&&method==='GET'&&response.status===409)||!/^application\/json(?:\s*;|$)/i.test(response.headers.get('content-type')??''))return null;
105
114
  const limit=512,declared=response.headers.get('content-length');if(declared!==null&&(!/^\d+$/.test(declared)||Number(declared)>limit))return null;
106
115
  const reader=response.body?.getReader();if(!reader)return null;
107
116
  try{
@@ -111,7 +120,7 @@ async function stagePartsRefusal(mode:'single'|'compare',method:string,path:stri
111
120
  const data:unknown=JSON.parse(new TextDecoder().decode(body)),named='PARTS_ATLAS_UNAVAILABLE: the inspected package has no usable atlas or its source changed.';
112
121
  if(data===null||typeof data!=='object'||Array.isArray(data)||Object.keys(data).length!==1)return null;
113
122
  const error=(data as {error?:unknown}).error;
114
- return typeof error==='string'&&[named,...Object.values(stageDraftRefusals)].includes(error)?error:null;
123
+ return typeof error==='string'&&(interview?[...interviewRefusals]:[named,interviewStale,...Object.values(stageDraftRefusals)] as readonly string[]).some(code=>code===error)?error:null;
115
124
  }catch{return null;}finally{reader.releaseLock();}
116
125
  }
117
126
  export const maximumUpstreamStreams=32;
@@ -133,7 +142,7 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
133
142
  if(req.headers.get('sec-fetch-site')==='cross-site'||sentOrigin!==null&&sentOrigin!==origin)return refuse('FRONT_SAME_ORIGIN_REQUIRED',403);
134
143
  const record=await instanceRecord(options.control,key);if(!record)return refuse('FRONT_INSTANCE_UNKNOWN: reopen with rig-review open',404);
135
144
  const route=frontRoute(record.mode,req.method,path);if(!route)return refuse('FRONT_ROUTE_REFUSED',404);
136
- const landing=path==='/'||path==='/index.html',stageFrame=path==='/stage-parts.html';if(stageFrame?!stageFrameQuery(record.mode,url.search):!landing&&!!url.search)return refuse('FRONT_QUERY_REFUSED',400);
145
+ const landing=path==='/'||path==='/index.html',stageFrame=path==='/stage-parts.html'||path==='/stage-interview.html';if(stageFrame?!stageFrameQuery(record.mode,url.search):!landing&&!!url.search)return refuse('FRONT_QUERY_REFUSED',400);
137
146
  if(route.live){
138
147
  if(sentOrigin!==origin)return refuse('FRONT_SAME_ORIGIN_REQUIRED',403);
139
148
  if(req.headers.get('upgrade')?.toLowerCase()!=='websocket')return refuse('FRONT_UPGRADE_REQUIRED',426);
@@ -167,7 +176,9 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
167
176
  if(sentOrigin!==origin)return refuse('FRONT_SAME_ORIGIN_REQUIRED',403);
168
177
  if(!sameSecret(req.headers.get(capabilityHeader),record.capability))return refuse('FRONT_CAPABILITY_REQUIRED: reopen with rig-review open to edit',403);
169
178
  body=await boundedBody(req,route.limit);
170
- if(!await alive(record))return refuse('FRONT_INSTANCE_EXPIRED: reopen with rig-review open',410);
179
+ // A stale interview worker must still prove its identity before it receives picks.
180
+ // It revalidates the join before saving and returns the specific stale refusal.
181
+ if(!await alive(record,path==='/api/interview/picks'))return refuse('FRONT_INSTANCE_EXPIRED: reopen with rig-review open',410);
171
182
  }
172
183
  if(active>=maximumUpstreamStreams)return refuse('FRONT_BUSY: too many concurrent upstream streams',503);
173
184
  const headers=new Headers({[openNonceHeader]:record.nonce});for(const name of ['accept','range','if-range',...(route.mutation?['content-type']:[]),...(route.control?['authorization']:[])]){const value=req.headers.get(name);if(value!==null)headers.set(name,value);}
@@ -179,7 +190,7 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
179
190
  try{upstream=await fetch(record.origin+path+(landing||stageFrame?url.search:''),{method:req.method,headers,...(body?{body}:{}),redirect:'manual',signal:abort.signal});}
180
191
  catch{release();return abort.signal.aborted&&!req.signal.aborted?refuse('FRONT_UPSTREAM_TIMEOUT',504):refuse('FRONT_INSTANCE_EXPIRED: reopen with rig-review open',410);}
181
192
  if(upstream.headers.get(openKeyHeader)!==key){void upstream.body?.cancel().catch(()=>{});release();return refuse('FRONT_INSTANCE_REPLACED: reopen with rig-review open',410);}
182
- if(upstream.status>=400&&upstream.status!==416){const named=await stagePartsRefusal(record.mode,req.method,path,upstream);void upstream.body?.cancel().catch(()=>{});release();if(named)return refuse(named,409);const code=upstreamFailure[upstream.status];return refuse(code??'FRONT_UPSTREAM_FAILED',code?upstream.status:502);}
193
+ if(upstream.status>=400&&upstream.status!==416){const named=await inspectionRefusal(record.mode,req.method,path,upstream);void upstream.body?.cancel().catch(()=>{});release();if(named)return refuse(named,upstream.status);const code=upstreamFailure[upstream.status];return refuse(code??'FRONT_UPSTREAM_FAILED',code?upstream.status:502);}
183
194
  const out=new Headers();for(const name of responseHeaders){const value=upstream.headers.get(name);if(value!==null)out.set(name,value);}
184
195
  if(!upstream.body||req.method==='HEAD'){void upstream.body?.cancel().catch(()=>{});release();return new Response(null,{status:upstream.status,headers:out});}
185
196
  if(timer)clearTimeout(timer);const reader=upstream.body.getReader();
@@ -32,8 +32,19 @@ async function body(req: Request) {
32
32
  finally {reader.releaseLock();}
33
33
  }
34
34
 
35
- export function interviewRoutes(root: string, output: string, capability: string) {
36
- const opened = readProject(root);
35
+ export const interviewRefusals = [
36
+ 'INTERVIEW_UNAVAILABLE', 'INTERVIEW_SOURCE_MISMATCH', 'INTERVIEW_CHOICE_INVALID',
37
+ 'INTERVIEW_CHOICE_CONSTRAINT', 'INTERVIEW_CHOICE_REQUIRED', 'INTERVIEW_OPTIONS_INVALID',
38
+ 'INTERVIEW_OPTIONS_FILE', 'INTERVIEW_OPTIONS_STALE', 'INTERVIEW_PICKS_OUTPUT',
39
+ ] as const;
40
+ export function interviewRequest(path: string) {
41
+ return path === '/api/interview' || path === '/api/interview/picks' ||
42
+ /^\/api\/interview\/image\/[a-f0-9]{64}\/(0|[1-9]\d*)$/.test(path);
43
+ }
44
+
45
+ export function interviewRoutes(root: string, output: string, capability: string,
46
+ joined?: {opened: ReturnType<typeof readProject>; assertCurrent: () => Promise<void>; available: boolean; sourceHash: string; version: number}) {
47
+ const opened = joined?.opened ?? readProject(root);
37
48
  const outputPath = outputDirectory(opened.root, output, opened.project);
38
49
  const openedOutput = lstatSync(outputPath);
39
50
  const destination = () => {
@@ -42,7 +53,8 @@ export function interviewRoutes(root: string, output: string, capability: string
42
53
  if (info.dev !== openedOutput.dev || info.ino !== openedOutput.ino) throw new Error('INTERVIEW_PICKS_OUTPUT: Output directory changed');
43
54
  return path;
44
55
  };
45
- const current = () => {
56
+ const current = async () => {
57
+ await joined?.assertCurrent();
46
58
  if (readProject(opened.root).hash !== opened.hash) throw new Error('INTERVIEW_OPTIONS_STALE: Project changed; reopen the interview');
47
59
  };
48
60
  return async (req: Request, origin: string): Promise<Response | undefined> => {
@@ -51,17 +63,18 @@ export function interviewRoutes(root: string, output: string, capability: string
51
63
  const denied = accessGate(req, capability);
52
64
  if (denied) return denied;
53
65
  try {
66
+ if (joined && interviewRequest(url.pathname) && !joined.available) return json({error:'INTERVIEW_UNAVAILABLE'}, 404);
54
67
  if (req.method === 'GET' && url.pathname === '/api/interview') {
55
- current();
68
+ await current();
56
69
  const dir = destination();
57
- return json({historical:opened.historical, questions:opened.questions.map(question => ({
70
+ return json({...(joined ? {binding:{projectHash:opened.hash, sourceHash:joined.sourceHash, version:joined.version}} : {}), historical:opened.historical, questions:opened.questions.map(question => ({
58
71
  ...question, saved:question.editable ? readPicks(dir, question) : null,
59
72
  images:question.images.map(({name}, index) => ({name, url:'/api/interview/image/' + question.ref.sha256 + '/' + index})),
60
73
  }))});
61
74
  }
62
75
  const image = /^\/api\/interview\/image\/([a-f0-9]{64})\/(0|[1-9]\d*)$/.exec(url.pathname);
63
76
  if (image && req.method === 'GET') {
64
- current();
77
+ await current();
65
78
  const asset = opened.questions.find(question => question.ref.sha256 === image[1])?.images[Number(image[2])];
66
79
  if (!asset) return json({error:'Not found'}, 404);
67
80
  let bytes: Buffer;
@@ -76,7 +89,7 @@ export function interviewRoutes(root: string, output: string, capability: string
76
89
  if (url.pathname === '/api/interview/picks' && req.method === 'POST') {
77
90
  if (req.headers.get('origin') !== origin) return json({error:'Same-origin Origin required'}, 403);
78
91
  const input = await body(req);
79
- current();
92
+ await current();
80
93
  const ref = object(object(input).set);
81
94
  const question = opened.questions.find(question => question.editable && question.ref.path === ref.path && question.ref.sha256 === ref.sha256);
82
95
  if (!question) {
@@ -1,14 +1,13 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { randomBytes } from 'node:crypto';
3
- import { appRoot } from './build.ts';
3
+ import { appRoot, buildWeb } from './build.ts';
4
4
  import { createLiveLifecycle, LIVE_PATH } from './live-lifecycle.ts';
5
5
  import { interviewHeaders, interviewRoutes } from './interview-routes.ts';
6
6
 
7
7
  export async function startInterviewServer(root: string, output: string, port: number, exitOnClose = false) {
8
8
  const capability = randomBytes(32).toString('hex');
9
9
  const route = interviewRoutes(root, output, capability);
10
- const bundle = await Bun.build({entrypoints:[appRoot + 'web/interview.ts'], target:'browser', format:'esm'});
11
- if (!bundle.success || !bundle.outputs[0]) throw new Error('Interview frontend bundle failed');
10
+ const bundle = await buildWeb('interview');
12
11
  const [html, css] = await Promise.all(['interview.html','interview.css'].map(path => readFile(appRoot + 'web/' + path)));
13
12
  const live = createLiveLifecycle({label:'review interview', exitOnClose, stopServer:() => server.stop(true)});
14
13
  const server = Bun.serve({hostname:'127.0.0.1', port, websocket:live.websocket, async fetch(req, srv) {
@@ -25,7 +24,7 @@ export async function startInterviewServer(root: string, output: string, port: n
25
24
  const files = new Map([
26
25
  ['/', [html, 'text/html; charset=utf-8']],
27
26
  ['/interview.css', [css, 'text/css']],
28
- ['/interview.js', [bundle.outputs[0], 'text/javascript']],
27
+ ['/interview.js', [bundle, 'text/javascript']],
29
28
  ] as const);
30
29
  const file = req.method === 'GET' ? files.get(pathname as '/' | '/interview.css' | '/interview.js') : undefined;
31
30
  return file ? new Response(file[0] as BodyInit, {headers:{...interviewHeaders,'Content-Type':file[1]}}) :
@@ -0,0 +1,75 @@
1
+ import { readdirSync } from 'node:fs';
2
+ import { join, relative, sep } from 'node:path';
3
+ import { boundBytes, checkedPath, digest, literalPath, object, readProject, readRegular } from './interview-project.ts';
4
+ import { outputDirectory } from './interview-picks.ts';
5
+ import { packagePath, type ReviewPackage } from './manifest.ts';
6
+ import { assertReviewUnchanged } from './reference.ts';
7
+
8
+ export interface ProjectDesignation {root: string; version: number; picksDir: string}
9
+ export const interviewUnavailable = 'INTERVIEW_UNAVAILABLE';
10
+ export const interviewMismatch = 'INTERVIEW_SOURCE_MISMATCH';
11
+ export const interviewStale = 'INTERVIEW_OPTIONS_STALE';
12
+
13
+ export function joinProject(p: ReviewPackage, designation: ProjectDesignation) {
14
+ const opened = readProject(designation.root);
15
+ const {root, hash, project} = opened;
16
+ const {version} = designation;
17
+ const fail = (): never => {throw new Error(interviewMismatch + ': expected the designated Create version’s recorded review package');};
18
+ if (!Number.isSafeInteger(version) || version < 1) return fail();
19
+ const matches = (Array.isArray(project.versions) ? project.versions : []).map(object)
20
+ .filter(entry => entry.n === version && entry.kind === 'rig');
21
+ const record = object(matches[0]?.review_package);
22
+ const path = 'derived/review/v' + version;
23
+ const files = new Map<string, string>();
24
+ try {
25
+ if (matches.length !== 1 || !Array.isArray(record.files)) return fail();
26
+ const out = checkedPath(root, path + '/out', true);
27
+ if (p.buildRoot !== out || p.handoff?.parts !== out || p.handoff.rig !== join(out, 'rig') ||
28
+ p.handoff.config !== checkedPath(root, path + '/config.json') || !p.manifest.model) return fail();
29
+ const pkg = checkedPath(root, path, true);
30
+ for (const entry of record.files.map(object)) {
31
+ const {path, sha256} = entry;
32
+ packagePath(path, 'recorded package file');
33
+ if (!literalPath(path) || typeof sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(sha256) || files.has(path)) return fail();
34
+ files.set(path, sha256);
35
+ }
36
+ const covered = (absolute: string, sha256?: string) => {
37
+ const expected = files.get(relative(pkg, absolute).split(sep).join('/'));
38
+ return expected !== undefined && (sha256 === undefined || sha256 === expected);
39
+ };
40
+ if (![...p.files].every(file => covered(join(p.root, file))) ||
41
+ !p.handoff.record.files.every(file => covered(join(p.root, file.path), file.sha256)) ||
42
+ !covered(join(p.root, p.manifest.model), p.reviewedSource.rig?.sha256) ||
43
+ !files.has('out/parts.json') || ![...files.keys()].some(file => file.startsWith('out/parts/'))) return fail();
44
+ } catch {return fail();}
45
+
46
+ const assertInventory = () => {
47
+ const pkg = checkedPath(root, path, true);
48
+ const remaining = new Set(files.keys());
49
+ const visit = (prefix: string) => {
50
+ const directory = prefix ? checkedPath(pkg, prefix.slice(0,-1), true) : pkg;
51
+ for (const entry of readdirSync(directory, {withFileTypes:true})) {
52
+ const name = prefix + entry.name;
53
+ if (!literalPath(name)) return fail();
54
+ if (entry.isDirectory()) visit(name + '/');
55
+ else if (!entry.isFile() || !remaining.delete(name)) return fail();
56
+ }
57
+ };
58
+ visit('');
59
+ if (remaining.size) return fail();
60
+ for (const [path, sha256] of files) boundBytes(pkg, {path, sha256});
61
+ };
62
+ try {assertInventory();} catch {return fail();}
63
+ outputDirectory(root, designation.picksDir, project);
64
+
65
+ const assertCurrent = async () => {
66
+ try {
67
+ await assertReviewUnchanged(p);
68
+ assertInventory();
69
+ if (digest(readRegular(checkedPath(root, 'project.json'), 8 * 1024 * 1024)) !== hash) throw new Error('Project changed');
70
+ } catch {throw new Error(interviewStale + ': project or review package changed; reopen the project');}
71
+ };
72
+ return {opened, designation:{...designation, root}, assertCurrent,
73
+ available:opened.questions.length > 0 || opened.historical.length > 0};
74
+ }
75
+ export type JoinedProject = ReturnType<typeof joinProject>;
package/src/open.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { joinProject, type JoinedProject, type ProjectDesignation } from './joined-project.ts';
1
2
  import {parseControlCommand,type ControlCommand,type ControlReceipt} from './control.ts';
2
3
  /** One fixed-package worker per exact binding. There is no general daemon API. */
3
4
  import {createHash,randomBytes,randomUUID} from 'node:crypto';
@@ -29,10 +30,10 @@ export function buildOpenDiagnostic(build:BuildOpen):string{
29
30
  return `Package: rig-parts build check package ${build.package}\n${h?`Handoff ${how}: ${h.config.path} sha256 ${h.config.sha256}${h.parts?` · parts ${h.parts}`:''}`:`Handoff: ${build.reason??'none'}`}`;
30
31
  }
31
32
  /** `direct` chooses how the page is reached (own port instead of the managed front); `viewOnly` permits opening without a producer handoff (#305); neither is part of the instance identity. */
32
- export interface OpenInputs {input:string;compare?:string;reference?:string;animation?:string;control?:boolean;direct?:boolean;viewOnly?:boolean;config?:string;parts?:string;source?:string;full?:string;head?:string;keypoints?:string}
33
+ export interface OpenInputs {input:string;project?:ProjectDesignation;compare?:string;reference?:string;animation?:string;control?:boolean;direct?:boolean;viewOnly?:boolean;config?:string;parts?:string;source?:string;full?:string;head?:string;keypoints?:string}
33
34
  /** The producer handoff flags (#101) among the inputs, or undefined when none was given. */
34
35
  export function handoffFlags(inputs:OpenInputs):HandoffFlags|undefined{const present=HANDOFF_FLAGS.filter(f=>inputs[f]!==undefined);if(!present.length)return undefined;return Object.fromEntries(present.map(f=>[f,inputs[f]])) as unknown as HandoffFlags;}
35
- export type OpenPackage=({mode:'single';p:ReviewPackage;inputs:OpenInputs;contentHash:string}|{mode:'compare';p:ComparePackage;inputs:OpenInputs;contentHash:string})&{selection:AnimationSelection|null};
36
+ export type OpenPackage=({mode:'single';p:ReviewPackage;joined?:JoinedProject;inputs:OpenInputs;contentHash:string}|{mode:'compare';p:ComparePackage;inputs:OpenInputs;contentHash:string})&{selection:AnimationSelection|null};
36
37
  /** Private 0600 record. `capability` is the 256-bit page write capability, handed out only in the printed `#cap=` fragment. */
37
38
  export interface RecordFile extends OpenIdentity {schema:'rig-review-open-instance/1';pid:number;origin:string;mode:'single'|'compare';capability:string;controlToken?:string}
38
39
  /** `cwd` is the launcher's working directory: the worker runs in the state directory, so Apply · Rebuild looks for the producer from here after the package's own directories. */
@@ -43,7 +44,8 @@ const sleep=(ms:number)=>new Promise(resolveSleep=>setTimeout(resolveSleep,ms));
43
44
  export const defaultStateDir=()=>process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review');
44
45
  export async function loadOpenPackage(inputs:OpenInputs):Promise<OpenPackage>{
45
46
  // Handoff flags become canonical absolute paths here, so the worker and every reload read exactly these files.
46
- if(!inputs.compare){const p=await loadReferencedReview(inputs.input,inputs.reference,handoffFlags(inputs)),selection=selectAnimation([{label:'single',catalog:p.feedbackCatalog,report:p.report}],inputs.animation,true);if(inputs.viewOnly)p.viewOnly=true;return {mode:'single',p,selection,contentHash:p.sourceHash,inputs:{input:p.manifestPath,...(selectedReference(p)?{reference:selectedReference(p)!.path}:{}),...(selection?{animation:selection.name}:{}),...(inputs.control?{control:true}:{}),...(p.handoffInputs??{})}};}
47
+ if(!inputs.compare){const p=await loadReferencedReview(inputs.input,inputs.reference,handoffFlags(inputs)),selection=selectAnimation([{label:'single',catalog:p.feedbackCatalog,report:p.report}],inputs.animation,true);const joined=inputs.project?joinProject(p,inputs.project):undefined;if(inputs.viewOnly)p.viewOnly=true;return {mode:'single',p,selection,contentHash:p.sourceHash,...(joined?{joined}:{}),inputs:{input:p.manifestPath,...(joined?{project:joined.designation}:{}),...(selectedReference(p)?{reference:selectedReference(p)!.path}:{}),...(selection?{animation:selection.name}:{}),...(inputs.control?{control:true}:{}),...(p.handoffInputs??{})}};}
48
+ if(inputs.project)throw new Error('INTERVIEW_SOURCE_MISMATCH: compare takes no joined project');
47
49
  if(handoffFlags(inputs))throw new HandoffError('HANDOFF_FLAGS_INVALID','--config','compare takes no producer handoff; open one package with --config');
48
50
  if(!inputs.reference)throw new Error('open compare: explicit --reference required');
49
51
  const [a,b]=await Promise.all([loadReview(inputs.input),loadReview(inputs.compare)]),selection=selectAnimation([{label:'a',catalog:a.feedbackCatalog,report:a.report},{label:'b',catalog:b.feedbackCatalog,report:b.report}],inputs.animation)!;
@@ -59,7 +61,7 @@ export async function openFingerprint():Promise<string>{
59
61
  hash.update('bun.lock\0');try{hash.update(await readFile(join(appRoot,'bun.lock')));}catch(e){if((e as NodeJS.ErrnoException).code!=='ENOENT')throw e;hash.update('(absent)');}
60
62
  hash.update('@rig-c/play/package.json\0');hash.update(await readFile(playPackagePath()));return hash.digest('hex');
61
63
  }
62
- export function openKey(p:OpenPackage,fingerprint:string):string {return digest({fingerprint,installation:appRoot,mode:p.mode,inputs:p.inputs,content:p.contentHash,identity:p.mode==='single'?p.p.reviewedSource:p.p.response.binding});}
64
+ export function openKey(p:OpenPackage,fingerprint:string):string {return digest({fingerprint,installation:appRoot,mode:p.mode,inputs:p.inputs,content:p.contentHash,identity:p.mode==='single'?p.p.reviewedSource:p.p.response.binding,...(p.mode==='single'&&p.joined?{projectHash:p.joined.opened.hash}:{})});}
63
65
  /** Handoff URL: the managed front's `/instances/<key>/` path (or the worker's own origin when direct). The
64
66
  * capability rides in the fragment, which browsers never send to a server; the page stores and strips it. */
65
67
  export function openUrl(record:Pick<RecordFile,'origin'|'key'|'contentHash'|'capability'>,front?:string):string {const url=new URL(front?`${front}/instances/${record.key}/`:record.origin);url.searchParams.set('input',record.contentHash);url.searchParams.set('handoff',record.key);url.hash='cap='+record.capability;return url.href;}
@@ -72,7 +74,7 @@ export async function readOpenStatus(response:Response,timeoutMs=1500):Promise<u
72
74
  try{return await Promise.race([(async()=>{const chunks:Uint8Array[]=[];let size=0;while(true){const next=await reader.read();if(next.done)break;size+=next.value.length;if(size>65536)throw new Error('open status: exceeds 64 KiB');chunks.push(next.value);}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));})(),new Promise<never>((_,reject)=>{timer=setTimeout(()=>reject(new Error('open status: body timeout')),timeoutMs);})]);}
73
75
  finally{if(timer)clearTimeout(timer);void reader.cancel().catch(()=>{});try{reader.releaseLock();}catch{}}
74
76
  }
75
- export async function alive(record:RecordFile):Promise<boolean>{try{const response=await fetch(record.origin+'/api/open-status',{headers:{authorization:`Bearer ${record.nonce}`},redirect:'error',signal:AbortSignal.timeout(1500)});if(!response.ok){void response.body?.cancel();return false;}const v=await readOpenStatus(response) as OpenIdentity&{schema:string};return v.schema==='rig-review-open-status/1'&&v.key===record.key&&v.contentHash===record.contentHash&&v.nonce===record.nonce&&v.fingerprint===record.fingerprint;}catch{return false;}}
77
+ export async function alive(record:RecordFile,allowStale=false):Promise<boolean>{try{const response=await fetch(record.origin+'/api/open-status',{headers:{authorization:`Bearer ${record.nonce}`},redirect:'error',signal:AbortSignal.timeout(1500)});if(!response.ok&&!(allowStale&&response.status===409)){void response.body?.cancel();return false;}const v=await readOpenStatus(response) as OpenIdentity&{schema:string;ready?:boolean};return (response.ok||v.ready===false)&&v.schema==='rig-review-open-status/1'&&v.key===record.key&&v.contentHash===record.contentHash&&v.nonce===record.nonce&&v.fingerprint===record.fingerprint;}catch{return false;}}
76
78
 
77
79
  export function running(pid:number):boolean{try{process.kill(pid,0);return true;}catch(e){return (e as NodeJS.ErrnoException).code==='EPERM';}}
78
80
  async function claimOwner(claim:string):Promise<{file:string;pid:number;nonce:string}|null>{
@@ -129,6 +131,7 @@ export async function openReview(inputs:OpenInputs,options:{stateDir?:string;idl
129
131
  const fingerprint=await openFingerprint(),key=openKey(p,fingerprint);
130
132
  // #187: canonical (symlinks and ancestors resolved) and outside every supplied folder: the package, the build root a check package belongs to, the handoff root.
131
133
  const stateDir=await canonicalDestination(resolve(options.stateDir??defaultStateDir())),roots=p.mode==='single'?stateRoots(p.p):[...stateRoots(p.p.a),...stateRoots(p.p.b)];
134
+ if(p.mode==='single'&&p.joined&&stateDirInside(stateDir,[{kind:'package',path:p.joined.opened.root}]))throw new Error('OPEN_STATE_INSIDE_PACKAGE: review state must be outside the joined project');
132
135
  const inside=stateDirInside(stateDir,roots);if(inside)throw new Error(`OPEN_STATE_INSIDE_PACKAGE ${inside.kind}: the review state directory must be outside input packages; it is inside the ${inside.kind}; set RIG_REVIEW_STATE_DIR outside it`);
133
136
  await verifyOpenLoad(p,viewOnly,options.cwd);
134
137
  const control=join(stateDir,'open');await mkdir(control,{recursive:true,mode:0o700});const canonicalControl=await realpath(control);if((await lstat(control)).isSymbolicLink())throw new Error('open.state: control directory cannot be a symlink');
@@ -161,7 +164,7 @@ export async function runOpenWorker(requestPath:string):Promise<void>{
161
164
  // The worker mints its own page capability; it lives only in this process and the private record.
162
165
  const removeRecord=async()=>{const current=await readRecord(spec.registry,spec.identity.key);if(current?.nonce===spec.identity.nonce)await unlink(spec.registry).catch(()=>{});};
163
166
  const capability=randomBytes(32).toString('hex');const options={port:0,stateDir:spec.stateDir,open:spec.identity,capability,unopenedTimeoutMs:spec.idleMs,...(spec.graceMs!==undefined?{graceMs:spec.graceMs}:{}),exitOnClose:true,onClose:removeRecord,...(spec.inputs.control?{control:{token:spec.controlToken!,instanceKey:spec.identity.key}}:{})};
164
- const server=p.mode==='single'?await startServer(p.p,{...options,initialAnimation:p.selection?.name,...(typeof spec.cwd==='string'&&isAbsolute(spec.cwd)?{cwd:spec.cwd}:{}),...(spec.viewOnly?{viewOnly:true}:{})}):await startCompareServer(p.p,options);
167
+ const server=p.mode==='single'?await startServer(p.p,{...options,joined:p.joined,initialAnimation:p.selection?.name,...(typeof spec.cwd==='string'&&isAbsolute(spec.cwd)?{cwd:spec.cwd}:{}),...(spec.viewOnly?{viewOnly:true}:{})}):await startCompareServer(p.p,options);
165
168
  const check=()=>p.mode==='single'?assertReviewUnchanged(p.p):assertCompareUnchanged(p.p);
166
169
  await check();const record:RecordFile={schema:'rig-review-open-instance/1',...spec.identity,pid:process.pid,origin:`http://127.0.0.1:${server.port}`,mode:p.mode,capability,...(spec.inputs.control?{controlToken:spec.controlToken}:{})};const tmp=spec.registry+'.'+spec.identity.nonce+'.tmp';await writeFile(tmp,JSON.stringify(record),{mode:0o600,flag:'wx'});await rename(tmp,spec.registry);
167
170
  await unlink(requestPath).catch(e=>{if(e.code!=='ENOENT')throw e;});
package/src/rebuild.ts CHANGED
@@ -13,7 +13,7 @@ import {recordFor,type AnyJobView} from '../web/rebuild-client.ts';
13
13
  import { createHash } from 'node:crypto';
14
14
  import { existsSync } from 'node:fs';
15
15
  import { copyFile, mkdir, readFile, readdir, realpath, rename, rm, writeFile, lstat } from 'node:fs/promises';
16
- import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
16
+ import { dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
17
17
  import { object, packagePath, safeFile, type ReviewPackage } from './manifest.ts';
18
18
  import { compileArgs, firstRefusal, modelingProducerTooOld, REMESH_DELTA_SINCE, remeshArgs, remeshDeltaArgs, resolvePose, resolveProducer, runTool, versionAtLeast, type CompileRequest, type InstalledTool, type ProcessResult } from './producer.ts';
19
19
  import { meshEditText } from './mesh-edit.ts';
@@ -75,7 +75,9 @@ export async function producerInputs(handoff: Handoff | null, reason: string | n
75
75
  if(source!==lexical)throw new Error('source redirected');
76
76
  }
77
77
  catch { throw new RebuildError('REBUILD_REQUIREMENTS_UNAVAILABLE', 'config.requirements is missing or outside the bound handoff'); }
78
- const binding = handoff.record.files.find(file => file.path === relative(handoff.root, source).split(sep).join('/'));
78
+ // The containment root can be above the inspected check package. Inventory paths are relative to the check package.
79
+ const recordedPath = posix.join(posix.dirname(handoff.record.config.path), value);
80
+ const binding = handoff.record.files.find(file => file.path === recordedPath);
79
81
  if (!binding) throw new RebuildError('REBUILD_REQUIREMENTS_UNAVAILABLE', 'config.requirements has no bound handoff hash');
80
82
  requirements = { source, sha256: binding.sha256 };
81
83
  }
package/src/server.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { interviewHeaders, interviewRequest, interviewRoutes } from './interview-routes.ts';
2
+ import { interviewUnavailable, interviewStale, type JoinedProject } from './joined-project.ts';
1
3
  import {isDeepStrictEqual} from 'node:util';
2
4
  import {appliedValue,parseCorrection,projectSessionCorrection} from './correction-handoff.ts';
3
5
  import {stagePartsRoutes} from './stage-parts.ts';
@@ -33,7 +35,12 @@ async function bodyJson(req:Request,limit=1024*1024,what='Session payload exceed
33
35
  }
34
36
  /** `capability` (open workers and foreground CLI serving) gates every non-GET request; tests may omit it.
35
37
  * `cwd` is where the producer is looked for after the package's own directories (review's working directory by default). */
36
- export async function startServer(p:ReviewPackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;initialAnimation?:string;activity?:()=>void;control?:ControlIdentity;capability?:string;cwd?:string;stripConcurrency?:number;graceMs?:number;unopenedTimeoutMs?:number;exitOnClose?:boolean;onClose?:(info:LiveExitInfo)=>void|Promise<void>;log?:(line:string)=>void;viewOnly?:boolean}={}){
38
+ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir?:string;joined?:JoinedProject;open?:OpenIdentity;initialAnimation?:string;activity?:()=>void;control?:ControlIdentity;capability?:string;cwd?:string;stripConcurrency?:number;graceMs?:number;unopenedTimeoutMs?:number;exitOnClose?:boolean;onClose?:(info:LiveExitInfo)=>void|Promise<void>;log?:(line:string)=>void;viewOnly?:boolean}={}){
39
+ const joined = options.joined;
40
+ if (joined && !options.capability) throw new Error('Joined interview requires an instance capability');
41
+ const interview = joined && interviewRoutes(joined.opened.root, joined.designation.picksDir, options.capability!,
42
+ {...joined, sourceHash:p.sourceHash, version:joined.designation.version});
43
+ let interviewBundle: Promise<Blob> | undefined;
37
44
  const bundle=await buildWeb();
38
45
  const unchanged=()=>assertReviewUnchanged(p);
39
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()];
@@ -70,6 +77,24 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
70
77
  }
71
78
  live.onRequestStart(url.pathname);
72
79
  try {
80
+ const path = url.pathname;
81
+ if (interviewRequest(path)) {
82
+ return await interview?.(req, origin) ?? json({error:interviewUnavailable},404);
83
+ }
84
+ if (req.method === 'GET' && ['/stage-interview.html','/interview.js','/interview.css'].includes(path)) {
85
+ if (!joined?.available) return json({error:interviewUnavailable},404);
86
+ const script = path === '/interview.js';
87
+ const html = path === '/stage-interview.html';
88
+ const body = script ? await (interviewBundle ??= buildWeb('interview')) :
89
+ await readFile(appRoot + 'web/' + (html ? 'interview.html' : 'interview.css'));
90
+ return new Response(body as BodyInit, {headers:{...interviewHeaders, 'Referrer-Policy':'no-referrer',
91
+ 'Content-Security-Policy':interviewHeaders['Content-Security-Policy'].replace("frame-ancestors 'none'", "frame-ancestors 'self'"),
92
+ 'Content-Type':script?'text/javascript':html?'text/html; charset=utf-8':'text/css'}});
93
+ }
94
+ if (joined && /^\/api\/stage-parts(?:\/|$)/.test(path)) {
95
+ try {await joined.assertCurrent();}
96
+ catch {return json({error:interviewStale},409);}
97
+ }
73
98
  const stageResponse=await stageParts(req);if(stageResponse)return stageResponse;
74
99
 
75
100
  const controlled=await control?.(req,origin);if(controlled)return controlled;
@@ -145,7 +170,7 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
145
170
  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'}"`}});
146
171
  }
147
172
  if(req.method!=='GET'&&req.method!=='HEAD')return json({error:'Method not allowed'},405);
148
- 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:{playback:!!p.manifest.model,modeling:false,motion:false,feedback:true,audio:true}});}
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}});}
149
174
  if(url.pathname==='/api/session'){await unchanged();return json(await readSession(p,options.stateDir));}
150
175
  if(url.pathname==='/api/rebuild')return json(await rebuilds.describe());
151
176
  if(url.pathname==='/api/rebuild/history')return json(await rebuilds.history());
package/web/catalog-en.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  export const enCatalog: Readonly<Record<string, string>> = {
2
+ "INTERVIEW_OPTIONS_STALE": "INTERVIEW_OPTIONS_STALE: Project or source changed. Reopen the inspection.",
3
+ "interview.joined": "Create version {0} · project SHA-256 {1} · inspection SHA-256 {2}",
4
+ "interview.mismatch": "INTERVIEW_SOURCE_MISMATCH: The inspection does not match the designated Create package.",
2
5
  "interview.imageUnavailable": "INTERVIEW_IMAGE_INVALID: The bound image could not be displayed.",
3
6
  "interview.legacy": "Legacy answers",
4
7
  "interview.partsUnavailable": "The retained draft part files are unavailable.",
@@ -10,7 +13,7 @@ export const enCatalog: Readonly<Record<string, string>> = {
10
13
  "interview.required": "Create must prepare a choice set.",
11
14
  "interview.invalidOptions": "The option set is invalid.",
12
15
  "interview.file": "The retained option file is unavailable.",
13
- "interview.stale": "The option set or its context changed. Reopen the interview.",
16
+ "interview.stale": "The project, review package, or option context changed. Reopen the interview.",
14
17
  "interview.output": "The picks output is unavailable or conflicts with an input.",
15
18
  "interview.failed": "The interview request failed.",
16
19
  "interview.empty": "This project has no retained choice sets.",
@@ -78,7 +81,7 @@ export const enCatalog: Readonly<Record<string, string>> = {
78
81
  "Inspection stages": "Inspection stages",
79
82
  "Open setup mesh instruments": "Open setup mesh instruments",
80
83
  "Parts and atlas inspection": "Parts and atlas inspection",
81
- "INTERVIEW_UNAVAILABLE: Open a designated create project with rig-review interview.": "INTERVIEW_UNAVAILABLE: Open a designated create project with rig-review interview.",
84
+ "INTERVIEW_UNAVAILABLE: No interview is attached to this inspection.": "INTERVIEW_UNAVAILABLE: No interview is attached to this inspection.",
82
85
  "DIRECTION_SOURCE_CHANGED: undeclared playback input": "DIRECTION_SOURCE_CHANGED: undeclared playback input",
83
86
  "DIRECTION_SOURCE_CHANGED: playback bytes differ from the bound SHA-256": "DIRECTION_SOURCE_CHANGED: playback bytes differ from the bound SHA-256",
84
87
  "direction.title": "Direction inspection",
package/web/catalog-ko.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  export const koCatalog: Readonly<Record<string, string>> = {
2
+ "INTERVIEW_OPTIONS_STALE": "INTERVIEW_OPTIONS_STALE: 프로젝트 또는 원본이 바뀌었어요. 검토를 다시 여세요.",
3
+ "interview.joined": "Create 버전 {0} · 프로젝트 SHA-256 {1} · 검토 SHA-256 {2}",
4
+ "interview.mismatch": "INTERVIEW_SOURCE_MISMATCH: 검토 대상이 지정한 Create 패키지와 일치하지 않아요.",
2
5
  "interview.imageUnavailable": "INTERVIEW_IMAGE_INVALID: 바인딩된 이미지를 표시할 수 없습니다.",
3
6
  "interview.legacy": "기존 서술형 답변",
4
7
  "interview.partsUnavailable": "보관된 초안 파츠 파일을 읽을 수 없습니다.",
@@ -10,7 +13,7 @@ export const koCatalog: Readonly<Record<string, string>> = {
10
13
  "interview.required": "Create에서 선택지 세트를 준비해야 합니다.",
11
14
  "interview.invalidOptions": "선택지 세트가 유효하지 않습니다.",
12
15
  "interview.file": "보관된 선택지 파일을 읽을 수 없습니다.",
13
- "interview.stale": "선택지 세트나 컨텍스트가 변경됐습니다. 인터뷰를 다시 여세요.",
16
+ "interview.stale": "프로젝트, 검토 패키지 또는 선택지의 근거가 바뀌었어요. 인터뷰를 다시 여세요.",
14
17
  "interview.output": "선택 기록 출력 경로를 사용할 수 없거나 입력과 충돌합니다.",
15
18
  "interview.failed": "인터뷰 요청에 실패했습니다.",
16
19
  "interview.empty": "이 프로젝트에 보관된 선택지 세트가 없습니다.",
@@ -78,7 +81,7 @@ export const koCatalog: Readonly<Record<string, string>> = {
78
81
  "Inspection stages": "검사 단계",
79
82
  "Open setup mesh instruments": "Setup 메시 도구 열기",
80
83
  "Parts and atlas inspection": "파츠 및 아틀라스 검사",
81
- "INTERVIEW_UNAVAILABLE: Open a designated create project with rig-review interview.": "INTERVIEW_UNAVAILABLE: rig-review interview로 지정한 create 프로젝트를 여세요.",
84
+ "INTERVIEW_UNAVAILABLE: No interview is attached to this inspection.": "INTERVIEW_UNAVAILABLE: 이 검토에 연결된 인터뷰가 없어요.",
82
85
  "DIRECTION_SOURCE_CHANGED: undeclared playback input": "DIRECTION_SOURCE_CHANGED: 선언되지 않은 재생 입력입니다.",
83
86
  "DIRECTION_SOURCE_CHANGED: playback bytes differ from the bound SHA-256": "DIRECTION_SOURCE_CHANGED: 재생 입력의 SHA-256이 기록된 값과 다릅니다.",
84
87
  "direction.title": "연출 검사",