rig-review 3.7.0 → 4.0.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/README.md +3 -3
- package/docs/DESIGN.md +145 -74
- package/docs/PANELS.md +20 -12
- package/docs/PARTS_VIEW.md +133 -76
- package/docs/REVIEW_PACKAGE.md +446 -100
- package/docs/STABILITY.md +132 -198
- package/docs/WORKFLOWS.md +41 -120
- package/package.json +4 -3
- package/skills/rig-review/SKILL.md +41 -27
- package/src/build.ts +10 -2
- package/src/cli.ts +17 -16
- package/src/comment-crops.ts +6 -1
- package/src/compare-html.ts +22 -24
- package/src/compare-server.ts +1 -1
- package/src/compare-session.ts +41 -3
- package/src/correction-handoff.ts +27 -4
- package/src/create-pin-gate.ts +3 -0
- package/src/direction-inspection.ts +6 -2
- package/src/feedback-export.ts +68 -1
- package/src/front.ts +5 -200
- package/src/handoff.ts +1 -1
- package/src/interview-routes.ts +1 -1
- package/src/interview-scene.ts +3 -3
- package/src/job-act.ts +77 -73
- package/src/job-api.ts +326 -13
- package/src/job-checkpoint-evidence.ts +113 -0
- package/src/job-cli.ts +27 -14
- package/src/job-contract.ts +284 -62
- package/src/job-front.ts +192 -61
- package/src/job-host.ts +23 -4
- package/src/job-session.ts +109 -24
- package/src/job-source.ts +227 -58
- package/src/job-store.ts +80 -6
- package/src/job-worker.ts +1 -47
- package/src/joined-project.ts +61 -4
- package/src/manifest.ts +32 -4
- package/src/open-workspace.ts +12 -12
- package/src/open.ts +19 -12
- package/src/parts-comment-crops.ts +126 -31
- package/src/parts-comment.ts +351 -28
- package/src/parts-server.ts +19 -7
- package/src/parts-view.ts +588 -109
- package/src/scene-inspection.ts +50 -0
- package/src/server.ts +31 -22
- package/src/session.ts +58 -0
- package/src/stage-comment.ts +48 -1
- package/src/stage-parts.ts +23 -11
- package/web/animation-inspection.ts +1 -1
- package/web/bones-panel.ts +1 -3
- package/web/catalog-en.ts +175 -39
- package/web/catalog-ko.ts +175 -39
- package/web/cloth-panel.ts +1 -2
- package/web/compare.css +3 -13
- package/web/compare.html +3 -3
- package/web/compare.ts +69 -64
- package/web/cuts-panel.ts +1 -3
- package/web/density-strip-panel.ts +1 -2
- package/web/direction-panel.ts +22 -6
- package/web/i18n.ts +13 -1
- package/web/idle-panel.ts +1 -2
- package/web/index.html +1 -5
- package/web/inspection-persistence.ts +2 -1
- package/web/inspector-blocks.ts +149 -40
- package/web/instance-access.ts +24 -5
- package/web/interview-panel.ts +224 -175
- package/web/job-rig-capture.ts +164 -21
- package/web/job-rig-screen.ts +344 -0
- package/web/job-session.ts +611 -1443
- package/web/main.ts +614 -151
- package/web/mesh-panel.ts +1 -2
- package/web/owner-workspace.ts +88 -109
- package/web/part-selection.ts +47 -6
- package/web/part-thumbnails.ts +20 -6
- package/web/parts-render.ts +26 -19
- package/web/parts-viewport-provider.ts +181 -7
- package/web/physics-panel.ts +1 -2
- package/web/readings-panel.ts +1 -2
- package/web/requirements-panel.ts +1 -3
- package/web/retained-frame-stage.ts +105 -0
- package/web/retarget-panel.ts +2 -3
- package/web/rig-fields-panel.ts +1 -2
- package/web/rig-host.ts +64 -0
- package/web/rig-viewport-provider.ts +65 -16
- package/web/scene-plates.ts +57 -4
- package/web/stage-comments.ts +103 -46
- package/web/styles.css +117 -63
- package/web/view-controls.ts +201 -12
- package/web/viewport-capture.ts +12 -2
- package/web/viewport-controller.ts +107 -27
- package/web/viewport-pair.ts +2 -1
- package/web/workspace-preferences.ts +5 -4
- package/web/workspace-ui.ts +151 -19
- package/src/front-worker.ts +0 -2
- package/src/interview-server.ts +0 -54
- package/src/job-hub.ts +0 -304
- package/src/job-image-set.ts +0 -50
- package/web/interview.css +0 -28
- package/web/interview.html +0 -17
- package/web/interview.ts +0 -40
- package/web/job-hub.css +0 -14
- package/web/job-hub.html +0 -5
- package/web/job-hub.ts +0 -179
- package/web/owner-workspace.css +0 -14
- package/web/owner-workspace.html +0 -5
- package/web/parts-flags.ts +0 -48
- package/web/parts.css +0 -104
- package/web/parts.html +0 -49
- package/web/parts.ts +0 -604
- package/web/stage-nav.ts +0 -136
package/src/front.ts
CHANGED
|
@@ -1,66 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
/** Managed loopback front: one stable origin (127.0.0.1:4318 by default) routing `/instances/<key>/…` to the
|
|
6
|
-
* worker named by that key's private open record. It is a router, not an authority: it never reads packages,
|
|
7
|
-
* never serves or logs a capability, and forwards a mutation (rewriting Origin) only with the page capability. */
|
|
8
|
-
import type {ServerWebSocket} from 'bun';
|
|
9
|
-
import {randomUUID} from 'node:crypto';
|
|
10
|
-
import {spawn} from 'node:child_process';
|
|
11
|
-
import {lstat,readFile,readdir,realpath,rename,unlink,writeFile,open as openFile} from 'node:fs/promises';
|
|
12
|
-
import {dirname,join} from 'node:path';
|
|
13
|
-
import {fileURLToPath} from 'node:url';
|
|
14
|
-
import {acquireClaim,alive,openFingerprint,readRecord,releaseClaim,running,smallJson,type RecordFile} from './open.ts';
|
|
15
|
-
import {playBuildConditions} from './build.ts';
|
|
16
|
-
import {capabilityHeader,openKeyHeader,openNonceHeader,sameSecret} from './open-protocol.ts';
|
|
17
|
-
import {DEFAULT_CLOSE_GRACE_MS,LIVE_PATH} from './live-lifecycle.ts';
|
|
1
|
+
import {interviewRequest} from './interview-routes.ts';
|
|
2
|
+
import {picksLimit} from './interview-picks.ts';
|
|
3
|
+
import {stageVerdictLimit} from './stage-parts.ts';
|
|
4
|
+
import {LIVE_PATH} from './live-lifecycle.ts';
|
|
18
5
|
export const defaultFrontPort=4318; // Foreground `review <dir>` keeps 4317.
|
|
19
|
-
|
|
20
|
-
interface FrontRequest {schema:'rig-review-front-request/1';control:string;request:string;record:string;port:number;nonce:string;fingerprint:string;idleMs:number}
|
|
21
|
-
const appRoot=fileURLToPath(new URL('..',import.meta.url));
|
|
22
|
-
const sleep=(ms:number)=>new Promise(resolveSleep=>setTimeout(resolveSleep,ms));
|
|
23
|
-
const uuid=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,hex64=/^[a-f0-9]{64}$/;
|
|
24
|
-
const frontName=(port:number)=>`front-${port}`;
|
|
25
|
-
const noStore={'Cache-Control':'no-store','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer'};
|
|
26
|
-
const refuse=(error:string,status:number)=>Response.json({error},{status,headers:noStore});
|
|
27
|
-
export function frontPort(value?:number):number{const raw=value??(process.env.RIG_REVIEW_FRONT_PORT===undefined?defaultFrontPort:Number(process.env.RIG_REVIEW_FRONT_PORT));if(!Number.isSafeInteger(raw)||raw<1||raw>65535)throw new Error('FRONT_PORT: RIG_REVIEW_FRONT_PORT expects an integer 1..65535');return raw;}
|
|
28
|
-
function frontValue(value:unknown,port:number):FrontRecord|null{if(!value||typeof value!=='object'||Array.isArray(value))return null;const v=value as Partial<FrontRecord>;return v.schema==='rig-review-front/1'&&v.port===port&&v.origin===`http://127.0.0.1:${port}`&&uuid.test(v.nonce??'')&&hex64.test(v.fingerprint??'')&&Number.isSafeInteger(v.pid)&&v.pid!>0?v as FrontRecord:null;}
|
|
29
|
-
async function readFront(file:string,port:number):Promise<FrontRecord|null>{try{return frontValue(await smallJson(file),port);}catch(e){if(['ENOENT','ELOOP'].includes((e as NodeJS.ErrnoException).code??'')||e instanceof SyntaxError)return null;throw e;}}
|
|
30
|
-
async function frontAlive(row:FrontRecord):Promise<boolean>{try{const response=await fetch(row.origin+'/api/front-status',{headers:{authorization:'Bearer '+row.nonce},redirect:'error',signal:AbortSignal.timeout(1500)});if(!response.ok){void response.body?.cancel();return false;}const v=await response.json() as {schema?:string;nonce?:string;fingerprint?:string};return v.schema==='rig-review-front-status/1'&&v.nonce===row.nonce&&v.fingerprint===row.fingerprint;}catch{return false;}}
|
|
31
|
-
/** Ensure this state directory's front on `port`; reuse a verified live one. A front from another tool
|
|
32
|
-
* build is ours (verified nonce) and is replaced. Any other listener is FRONT_PORT_BUSY, never a fallback. */
|
|
33
|
-
export async function ensureFront(options:{control:string;port:number;fingerprint:string;idleMs?:number}):Promise<string>{
|
|
34
|
-
const {control,port,fingerprint}=options,name=frontName(port),recordPath=join(control,name+'.json'),nonce=randomUUID(),deadline=performance.now()+20000,idleMs=options.idleMs??DEFAULT_CLOSE_GRACE_MS;
|
|
35
|
-
const reuse=async()=>{const row=await readFront(recordPath,port);if(!row||!await frontAlive(row))return null;if(row.fingerprint===fingerprint)return row;
|
|
36
|
-
try{process.kill(row.pid,'SIGTERM');}catch{}for(let n=0;n<100&&await frontAlive(row);n++)await sleep(30);return null;};
|
|
37
|
-
const ready=await reuse();if(ready)return ready.origin;
|
|
38
|
-
const claimed=await acquireClaim(control,name,nonce,reuse,deadline,'FRONT_BUSY: front startup claim did not become ready');if('row' in claimed)return claimed.row.origin;
|
|
39
|
-
let request:string|undefined,child:ReturnType<typeof spawn>|undefined,handedOff=false;
|
|
40
|
-
try{
|
|
41
|
-
const row=await reuse();if(row)return row.origin;
|
|
42
|
-
request=join(control,`${name}.${nonce}.request.json`);const log=join(control,`${name}.${nonce}.log`);
|
|
43
|
-
const spec:FrontRequest={schema:'rig-review-front-request/1',control,request,record:recordPath,port,nonce,fingerprint,idleMs};await writeFile(request,JSON.stringify(spec),{mode:0o600,flag:'wx'});
|
|
44
|
-
const logHandle=await openFile(log,'a',0o600);try{child=spawn(process.execPath,[...playBuildConditions().map(c=>`--conditions=${c}`),join(appRoot,'src/front-worker.ts'),request],{cwd:control,detached:true,stdio:['ignore',logHandle.fd,logHandle.fd],env:process.env});child.unref();}finally{await logHandle.close();}
|
|
45
|
-
let exited:string|undefined;child.on('error',error=>{exited=error.message;});child.on('exit',(code,signal)=>{exited=`exit ${code} ${signal??''}`;});
|
|
46
|
-
while(performance.now()<deadline){const live=await reuse();if(live){handedOff=true;return live.origin;}
|
|
47
|
-
if(exited){if(/FRONT_PORT_BUSY/.test(await readFile(log,'utf8').catch(()=>'')))throw new Error(`FRONT_PORT_BUSY: 127.0.0.1:${port} is held by another listener; use --direct (or set RIG_REVIEW_FRONT_PORT)`);throw new Error(`FRONT_START: ${exited}; front log ${log}`);}
|
|
48
|
-
await sleep(30);}
|
|
49
|
-
throw new Error(`FRONT_TIMEOUT: front did not become ready; log ${log}`);
|
|
50
|
-
}finally{if(child&&!handedOff&&child.exitCode===null&&child.signalCode===null)child.kill('SIGTERM');await releaseClaim(join(control,name+'.claim'),nonce);if(request)await unlink(request).catch(e=>{if(e.code!=='ENOENT')throw e;});}
|
|
51
|
-
}
|
|
6
|
+
export function frontPort(value?:number):number{const raw=value??(process.env.RIG_REVIEW_FRONT_PORT===undefined?defaultFrontPort:Number(process.env.RIG_REVIEW_FRONT_PORT));if(!Number.isSafeInteger(raw)||raw<(value===0?0:1)||raw>65535)throw new Error('FRONT_PORT: RIG_REVIEW_FRONT_PORT expects an integer 1..65535');return raw;}
|
|
52
7
|
interface Route {mutation:boolean;limit:number;timeoutMs:number;control:boolean;live?:boolean}
|
|
53
8
|
/** Closed allowlist per method. Agent control endpoints, open-status and anything unlisted are refused. */
|
|
54
9
|
export function frontRoute(mode:'single'|'compare',method:string,path:string):Route|null{
|
|
55
10
|
const read=method==='GET'||method==='HEAD',get:Route={mutation:false,limit:0,timeoutMs:30000,control:false};
|
|
56
11
|
if(path===LIVE_PATH)return method==='GET'?{...get,live:true}:null;
|
|
57
12
|
if(['/','/index.html','/main.js','/styles.css','/api/access'].includes(path))return read?get:null;
|
|
58
|
-
if(['/stage-parts.html','/parts.js','/parts.css'].includes(path))return read?get:null;
|
|
59
13
|
if((mode==='single'?/^\/api\/stage-parts(?:\/(?:image|page)\/\d+)?$/:/^\/api\/compare\/(?:a|b)\/stage-parts(?:\/(?:image|page)\/\d+)?$/).test(path))return read?get:null;
|
|
60
14
|
if(mode==='single'){
|
|
61
15
|
if(path==='/api/stage-parts/verdict')return method==='POST'?{...get,mutation:true,limit:stageVerdictLimit}:null;
|
|
62
16
|
if(path==='/api/stage-parts/export/json'||path==='/api/stage-parts/export/issue')return read?get:null;
|
|
63
|
-
if(['/stage-interview.html','/interview.js','/interview.css'].includes(path))return method==='GET'?get:null;
|
|
64
17
|
if(interviewRequest(path))return path==='/api/interview/picks'?
|
|
65
18
|
method==='POST'?{...get,mutation:true,limit:picksLimit}:null:method==='GET'?get:null;
|
|
66
19
|
}
|
|
@@ -98,152 +51,4 @@ export async function boundedBody(req:Request,limit:number,timeoutMs=10000):Prom
|
|
|
98
51
|
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>limit)throw new Error('FRONT_BODY_LIMIT');chunks.push(next.value);}const bytes=new Uint8Array(size);let at=0;for(const chunk of chunks){bytes.set(chunk,at);at+=chunk.length;}return bytes.buffer;})(),new Promise<never>((_,reject)=>{timer=setTimeout(()=>reject(new Error('FRONT_BODY_TIMEOUT')),timeoutMs);})]);}
|
|
99
52
|
finally{if(timer)clearTimeout(timer);void reader.cancel().catch(()=>{});}
|
|
100
53
|
}
|
|
101
|
-
/** Owner-only regular record for this key, or null. */
|
|
102
|
-
async function instanceRecord(control:string,key:string):Promise<RecordFile|null>{const file=join(control,key+'.json');try{const info=await lstat(file);if(!info.isFile()||(info.mode&0o077)!==0)return null;}catch(e){if((e as NodeJS.ErrnoException).code==='ENOENT')return null;throw e;}return readRecord(file,key);}
|
|
103
|
-
/** Worker errors default to front codes unless an inspection refusal is allowlisted. */
|
|
104
|
-
const upstreamFailure:Record<number,string>={400:'FRONT_UPSTREAM_REJECTED',403:'FRONT_UPSTREAM_FORBIDDEN',404:'FRONT_UPSTREAM_NOT_FOUND',405:'FRONT_UPSTREAM_METHOD',409:'FRONT_UPSTREAM_CONFLICT'};
|
|
105
|
-
const responseHeaders=['content-type','content-length','content-range','accept-ranges','content-disposition','cache-control','content-security-policy','x-content-type-options','referrer-policy'];
|
|
106
|
-
/** The trusted atlas frame alone may carry this closed navigation query. */
|
|
107
|
-
export function stageFrameQuery(mode:'single'|'compare',search:string):boolean {
|
|
108
|
-
const params=new URLSearchParams(search),keys=[...params.keys()];
|
|
109
|
-
const allowed=mode==='single'?['stageEmbed','lang']:['stageEmbed','lang','side'];
|
|
110
|
-
return keys.length===allowed.length&&new Set(keys).size===keys.length&&keys.every(k=>allowed.includes(k))&¶ms.get('stageEmbed')==='1'&&['en','ko'].includes(params.get('lang')??'')&&(mode==='single'||['a','b'].includes(params.get('side')??''));
|
|
111
|
-
}
|
|
112
|
-
// The submitted Apply can supply the check line. Accept the producer's structured
|
|
113
|
-
// summary fields, never an arbitrary suffix after the failed-check code.
|
|
114
|
-
const submitCheckPrefix = 'EDIT_SUBMIT_UNCHECKED: applied build failed check — ';
|
|
115
|
-
const checkBarName = '(?:[A-Z][A-Z0-9_]*|gate|loop|seam)';
|
|
116
|
-
const submitCheckSummary = new RegExp(
|
|
117
|
-
String.raw`^check: FAIL — \d+ bar\(s\) not met(?:, \d+ declared requirement\(s\) not PASS)?; ` +
|
|
118
|
-
String.raw`\d+ of \d+ bar\(s\) measured, \d+ skipped(?: \(${checkBarName}(?:, ${checkBarName})*\))?` +
|
|
119
|
-
String.raw`(?:; \d+ warning\(s\) \((?:SEAM_OVER_MOTION(?:, CLOTH_SETTLES)?|CLOTH_SETTLES), not a bar\))?$`
|
|
120
|
-
);
|
|
121
|
-
const submitCheckFallback = new RegExp(String.raw`^(?:${checkBarName}: FAIL|check exited -?\d+)$`);
|
|
122
|
-
const fixedSubmitRefusals = new Set([
|
|
123
|
-
'EDIT_SUBMIT_UNCHECKED: applied mesh has no successful producer check',
|
|
124
|
-
'CORRECTION_CHECK_FAILED: the settled Apply requires a passing producer check',
|
|
125
|
-
]);
|
|
126
|
-
function isSubmitCheckRefusal(error: string): boolean {
|
|
127
|
-
if(fixedSubmitRefusals.has(error))return true;
|
|
128
|
-
if(!error.startsWith(submitCheckPrefix))return false;
|
|
129
|
-
const detail=error.slice(submitCheckPrefix.length);
|
|
130
|
-
return submitCheckSummary.test(detail)||submitCheckFallback.test(detail);
|
|
131
|
-
}
|
|
132
|
-
/** Preserve only closed, bounded inspection refusals. */
|
|
133
|
-
async function inspectionRefusal(mode:'single'|'compare',method:string,path:string,response:Response,sameFingerprint:boolean):Promise<string|null>{
|
|
134
|
-
const stageData=mode==='single'?path==='/api/stage-parts':/^\/api\/compare\/(?:a|b)\/stage-parts$/.test(path);
|
|
135
|
-
const interview=mode==='single'&&interviewRequest(path)&&[400,404,409].includes(response.status);
|
|
136
|
-
// Both reads race during the single-package page bootstrap.
|
|
137
|
-
const direction=sameFingerprint&&mode==='single'&&method==='GET'&&response.status===409&&
|
|
138
|
-
(path==='/api/review'||path==='/api/session');
|
|
139
|
-
const submit=sameFingerprint&&mode==='single'&&method==='PUT'&&path==='/api/session'&&response.status===400;
|
|
140
|
-
const verdict=mode==='single'&&['/api/stage-parts/verdict','/api/stage-parts/export/json','/api/stage-parts/export/issue'].includes(path)&&[400,409].includes(response.status);
|
|
141
|
-
if(!(submit||direction||interview||verdict||stageData&&method==='GET'&&response.status===409)||!/^application\/json(?:\s*;|$)/i.test(response.headers.get('content-type')??''))return null;
|
|
142
|
-
const limit=512,declared=response.headers.get('content-length');if(declared!==null&&(!/^\d+$/.test(declared)||Number(declared)>limit))return null;
|
|
143
|
-
const reader=response.body?.getReader();if(!reader)return null;
|
|
144
|
-
try{
|
|
145
|
-
const chunks:Uint8Array[]=[];let bytes=0;
|
|
146
|
-
for(;;){const {value,done}=await reader.read();if(done)break;bytes+=value.byteLength;if(bytes>limit){void reader.cancel().catch(()=>{});return null;}chunks.push(value);}
|
|
147
|
-
const body=new Uint8Array(bytes);let offset=0;for(const chunk of chunks){body.set(chunk,offset);offset+=chunk.byteLength;}
|
|
148
|
-
const data:unknown=JSON.parse(new TextDecoder().decode(body)),named='PARTS_ATLAS_UNAVAILABLE: the inspected package has no usable atlas or its source changed.';
|
|
149
|
-
if(data===null||typeof data!=='object'||Array.isArray(data)||Object.keys(data).length!==1)return null;
|
|
150
|
-
const error=(data as {error?:unknown}).error;
|
|
151
|
-
if(submit)return typeof error==='string'&&isSubmitCheckRefusal(error)?error:null;
|
|
152
|
-
if(direction)return error===directionStale?directionStale:null;
|
|
153
|
-
return typeof error==='string'&&(interview?[...interviewRefusals]:[...(stageData&&response.status===409?[named,...Object.values(stageDraftRefusals),...stageVerdictRefusals]:[]),interviewStale,...(verdict?stageVerdictRefusals:[])] as readonly string[]).some(code=>code===error)?error:null;
|
|
154
|
-
}catch{return null;}finally{reader.releaseLock();}
|
|
155
|
-
}
|
|
156
54
|
export const maximumUpstreamStreams=32;
|
|
157
|
-
interface FrontLiveRelay {upstream:WebSocket;client:ServerWebSocket<FrontLiveRelay>|null}
|
|
158
|
-
export function startFront(options:{control:string;port:number;nonce:string;fingerprint:string}){
|
|
159
|
-
const origin=`http://127.0.0.1:${options.port}`;let active=0,last=performance.now();
|
|
160
|
-
const server=Bun.serve<FrontLiveRelay>({hostname:'127.0.0.1',port:options.port,websocket:{
|
|
161
|
-
idleTimeout:0,
|
|
162
|
-
open(ws){last=performance.now();ws.data.client=ws;if(ws.data.upstream.readyState!==WebSocket.OPEN){try{ws.close();}catch{}return;}try{ws.send('live');}catch{}},
|
|
163
|
-
message(ws,msg){last=performance.now();try{ws.data.upstream.send(msg);}catch{}},
|
|
164
|
-
close(ws){last=performance.now();try{ws.data.upstream.close();}catch{}},
|
|
165
|
-
},async fetch(req,srv){
|
|
166
|
-
last=performance.now();
|
|
167
|
-
try{
|
|
168
|
-
const url=new URL(req.url);if(url.origin!==origin)return refuse('FRONT_LOOPBACK_REQUIRED',403);
|
|
169
|
-
if(url.pathname==='/api/front-status'){if(req.method!=='GET'||!sameSecret(req.headers.get('authorization'),'Bearer '+options.nonce))return refuse('FRONT_STATUS_CAPABILITY_REQUIRED',403);return Response.json({schema:'rig-review-front-status/1',nonce:options.nonce,fingerprint:options.fingerprint},{headers:noStore});}
|
|
170
|
-
const match=/^\/instances\/([a-f0-9]{64})(\/.*)$/.exec(url.pathname);if(!match)return refuse('FRONT_ROUTE_REFUSED',404);
|
|
171
|
-
const key=match[1]!,path=match[2]!,sentOrigin=req.headers.get('origin');
|
|
172
|
-
if(req.headers.get('sec-fetch-site')==='cross-site'||sentOrigin!==null&&sentOrigin!==origin)return refuse('FRONT_SAME_ORIGIN_REQUIRED',403);
|
|
173
|
-
const record=await instanceRecord(options.control,key);if(!record)return refuse('FRONT_INSTANCE_UNKNOWN: reopen with rig-review open',404);
|
|
174
|
-
const route=frontRoute(record.mode,req.method,path);if(!route)return refuse('FRONT_ROUTE_REFUSED',404);
|
|
175
|
-
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);
|
|
176
|
-
if(route.live){
|
|
177
|
-
if(sentOrigin!==origin)return refuse('FRONT_SAME_ORIGIN_REQUIRED',403);
|
|
178
|
-
if(req.headers.get('upgrade')?.toLowerCase()!=='websocket')return refuse('FRONT_UPGRADE_REQUIRED',426);
|
|
179
|
-
const upstreamWs=new WebSocket(record.origin.replace(/^http/,'ws')+path,{headers:{[openNonceHeader]:record.nonce}} as unknown as string[]);
|
|
180
|
-
const outcome=await new Promise<'ok'|'replaced'|'timeout'|'closed'>(resolve=>{
|
|
181
|
-
const timer=setTimeout(()=>resolve('timeout'),route.timeoutMs);
|
|
182
|
-
const finish=(result:'ok'|'replaced'|'timeout'|'closed')=>{clearTimeout(timer);resolve(result);};
|
|
183
|
-
req.signal.addEventListener('abort',()=>finish('closed'),{once:true});
|
|
184
|
-
upstreamWs.onmessage=ev=>{try{const msg=JSON.parse(String(ev.data)) as {type?:string;key?:string};finish(msg?.type==='live'&&msg?.key===key?'ok':'replaced');}catch{finish('replaced');}};
|
|
185
|
-
upstreamWs.onerror=()=>finish('closed');
|
|
186
|
-
upstreamWs.onclose=()=>finish('closed');
|
|
187
|
-
});
|
|
188
|
-
if(outcome!=='ok'){
|
|
189
|
-
try{upstreamWs.close();}catch{}
|
|
190
|
-
if(outcome==='timeout'&&!req.signal.aborted)return refuse('FRONT_UPSTREAM_TIMEOUT',504);
|
|
191
|
-
if(outcome==='replaced')return refuse('FRONT_INSTANCE_REPLACED: reopen with rig-review open',410);
|
|
192
|
-
const probe=await fetch(record.origin+'/api/access',{headers:{[openNonceHeader]:record.nonce},redirect:'manual',signal:AbortSignal.timeout(1500)}).catch(()=>null);
|
|
193
|
-
void probe?.body?.cancel().catch(()=>{});
|
|
194
|
-
return probe?refuse('FRONT_INSTANCE_REPLACED: reopen with rig-review open',410):refuse('FRONT_INSTANCE_EXPIRED: reopen with rig-review open',410);
|
|
195
|
-
}
|
|
196
|
-
const relay:FrontLiveRelay={upstream:upstreamWs,client:null};
|
|
197
|
-
upstreamWs.onmessage=ev=>{try{relay.client?.send(String(ev.data));}catch{}};
|
|
198
|
-
upstreamWs.onerror=()=>{try{relay.client?.close();}catch{}};
|
|
199
|
-
upstreamWs.onclose=()=>{try{relay.client?.close();}catch{}};
|
|
200
|
-
if(!srv.upgrade(req,{data:relay,headers:noStore})){try{upstreamWs.close();}catch{}return refuse('FRONT_UPGRADE_FAILED',400);}
|
|
201
|
-
return undefined as unknown as Response;
|
|
202
|
-
}
|
|
203
|
-
let body:ArrayBuffer|undefined;
|
|
204
|
-
if(route.mutation){
|
|
205
|
-
// Never rewrite Origin without this instance's capability; the worker compares it again itself.
|
|
206
|
-
if(sentOrigin!==origin)return refuse('FRONT_SAME_ORIGIN_REQUIRED',403);
|
|
207
|
-
if(!sameSecret(req.headers.get(capabilityHeader),record.capability))return refuse('FRONT_CAPABILITY_REQUIRED: reopen with rig-review open to edit',403);
|
|
208
|
-
body=await boundedBody(req,route.limit);
|
|
209
|
-
// A stale interview worker must still prove its identity before it receives picks.
|
|
210
|
-
// It revalidates the join before saving and returns the specific stale refusal.
|
|
211
|
-
if(!await alive(record,(path==='/api/interview/picks'||path==='/api/stage-parts/verdict')))return refuse('FRONT_INSTANCE_EXPIRED: reopen with rig-review open',410);
|
|
212
|
-
}
|
|
213
|
-
if(active>=maximumUpstreamStreams)return refuse('FRONT_BUSY: too many concurrent upstream streams',503);
|
|
214
|
-
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);}
|
|
215
|
-
if(/^\/api\/stage-parts(?:\/(?:image|page)\/\d+|\/verdict|\/export\/(?:json|issue))?$/.test(path)){const build=req.headers.get('X-Review-Stage-Build');if(build!==null){if(build!=='inspected'&&!/^[a-f0-9]{64}$/.test(build))return refuse('FRONT_QUERY_REFUSED',400);headers.set('X-Review-Stage-Build',build);}}
|
|
216
|
-
if(route.mutation){headers.set('origin',record.origin);headers.set(capabilityHeader,record.capability);}
|
|
217
|
-
active++;let released=false;const abort=new AbortController(),timer=setTimeout(()=>abort.abort(),route.timeoutMs);const release=()=>{if(released)return;released=true;active--;clearTimeout(timer);};
|
|
218
|
-
req.signal.addEventListener('abort',()=>abort.abort(),{once:true});
|
|
219
|
-
let upstream:Response;
|
|
220
|
-
try{upstream=await fetch(record.origin+path+(landing||stageFrame?url.search:''),{method:req.method,headers,...(body?{body}:{}),redirect:'manual',signal:abort.signal});}
|
|
221
|
-
catch{release();return abort.signal.aborted&&!req.signal.aborted?refuse('FRONT_UPSTREAM_TIMEOUT',504):refuse('FRONT_INSTANCE_EXPIRED: reopen with rig-review open',410);}
|
|
222
|
-
if(upstream.headers.get(openKeyHeader)!==key){void upstream.body?.cancel().catch(()=>{});release();return refuse('FRONT_INSTANCE_REPLACED: reopen with rig-review open',410);}
|
|
223
|
-
if(upstream.status>=400&&upstream.status!==416){const named=await inspectionRefusal(record.mode,req.method,path,upstream,record.fingerprint===options.fingerprint);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);}
|
|
224
|
-
const out=new Headers();for(const name of responseHeaders){const value=upstream.headers.get(name);if(value!==null)out.set(name,value);}
|
|
225
|
-
if(!upstream.body||req.method==='HEAD'){void upstream.body?.cancel().catch(()=>{});release();return new Response(null,{status:upstream.status,headers:out});}
|
|
226
|
-
if(timer)clearTimeout(timer);const reader=upstream.body.getReader();
|
|
227
|
-
// Media/model streams stay counted until finished or cancelled by the browser.
|
|
228
|
-
const stream=new ReadableStream<Uint8Array>({async pull(controller){try{const next=await reader.read();if(next.done){controller.close();release();}else controller.enqueue(next.value);}catch(error){release();controller.error(error);}},cancel(reason){release();abort.abort();return reader.cancel(reason).catch(()=>{});}});
|
|
229
|
-
return new Response(stream,{status:upstream.status,headers:out});
|
|
230
|
-
}catch(error){const message=error instanceof Error?error.message:'';return refuse(message.startsWith('FRONT_')?message:'FRONT_REQUEST_FAILED',message==='FRONT_BODY_LIMIT'?413:message==='FRONT_BODY_TIMEOUT'?408:400);}
|
|
231
|
-
}});
|
|
232
|
-
return {origin,stop:()=>server.stop(true),idleMs:()=>performance.now()-last,active:()=>active};
|
|
233
|
-
}
|
|
234
|
-
/** A missing directory or record means gone; any other read error (readdir or a record) throws, and the caller keeps
|
|
235
|
-
* the front up. A record read that failed with EACCES or ENOTDIR used to count as gone and stopped the front (#354). */
|
|
236
|
-
async function liveInstances(control:string):Promise<boolean>{let names:string[];try{names=await readdir(control);}catch(e){if((e as NodeJS.ErrnoException).code==='ENOENT')return false;throw e;}for(const name of names){if(/^[a-f0-9]{64}\.claim$/.test(name))return true;if(/^[a-f0-9]{64}\.json$/.test(name)){const row=await readRecord(join(control,name),name.slice(0,64));if(row&&running(row.pid))return true;}}return false;}
|
|
237
|
-
export async function runFront(requestPath:string):Promise<void>{
|
|
238
|
-
const spec=await smallJson(requestPath) as FrontRequest;if(spec?.schema!=='rig-review-front-request/1'||!uuid.test(spec.nonce??'')||!hex64.test(spec.fingerprint??'')||!Number.isSafeInteger(spec.port)||spec.port<1||spec.port>65535||!Number.isSafeInteger(spec.idleMs)||spec.idleMs<100)throw new Error('front: invalid request');
|
|
239
|
-
const control=await realpath(spec.control);if(dirname(await realpath(requestPath))!==control||spec.request!==requestPath||spec.record!==join(control,frontName(spec.port)+'.json'))throw new Error('front: invalid state locations');
|
|
240
|
-
if(await openFingerprint()!==spec.fingerprint)throw new Error('front: tool changed before startup');
|
|
241
|
-
let front:ReturnType<typeof startFront>;
|
|
242
|
-
try{front=startFront({control,port:spec.port,nonce:spec.nonce,fingerprint:spec.fingerprint});}catch(error){if((error as NodeJS.ErrnoException).code==='EADDRINUSE'||/in use/i.test(error instanceof Error?error.message:''))throw new Error(`FRONT_PORT_BUSY: 127.0.0.1:${spec.port}`);throw error;}
|
|
243
|
-
const record:FrontRecord={schema:'rig-review-front/1',origin:front.origin,port:spec.port,nonce:spec.nonce,fingerprint:spec.fingerprint,pid:process.pid},tmp=spec.record+'.'+spec.nonce+'.tmp';await writeFile(tmp,JSON.stringify(record),{mode:0o600,flag:'wx'});await rename(tmp,spec.record);
|
|
244
|
-
await unlink(requestPath).catch(e=>{if(e.code!=='ENOENT')throw e;});
|
|
245
|
-
let stopped=false;const stop=async(reason:string)=>{if(stopped)return;stopped=true;clearInterval(timer);front.stop();const current=await readFront(spec.record,spec.port).catch(()=>null);if(current?.nonce===spec.nonce)await unlink(spec.record).catch(()=>{});console.log(`review front: exiting — ${reason}.`);process.exit(0);};
|
|
246
|
-
// Idle exit only once no request arrived for idleMs and no live worker record remains.
|
|
247
|
-
const timer=setInterval(()=>{if(front.idleMs()>=spec.idleMs&&front.active()===0)void liveInstances(control).then(live=>{if(!live)void stop(`no live review instances remain (idle for ${spec.idleMs}ms)`)}).catch(()=>{});},Math.min(250,spec.idleMs));
|
|
248
|
-
process.on('SIGTERM',()=>{void stop('received SIGTERM');});process.on('SIGINT',()=>{void stop('received SIGINT');});
|
|
249
|
-
}
|
package/src/handoff.ts
CHANGED
|
@@ -430,7 +430,7 @@ export async function resolveHandoff(root: string, declared: HandoffDeclaration
|
|
|
430
430
|
const full = declared.full !== undefined ? await blockPath(root, declared.full, 'producer.full', 'dir') : undefined;
|
|
431
431
|
const head = declared.head !== undefined ? await blockPath(root, declared.head, 'producer.head', 'dir') : undefined;
|
|
432
432
|
const keypoints = declared.keypoints !== undefined ? await blockPath(root, declared.keypoints, 'producer.keypoints', 'file') : undefined;
|
|
433
|
-
if ((
|
|
433
|
+
if ((full !== undefined && source === undefined) || (head !== undefined && full === undefined)) throw new HandoffError('HANDOFF_FLAGS_INVALID', 'producer', 'full requires source, and head requires full');
|
|
434
434
|
return { handoff: await record(root, root, 'declared', 'review.json producer', config, parts, { source, full, head, keypoints }, declared.parts !== undefined, options), reason: null };
|
|
435
435
|
}
|
|
436
436
|
for (const name of ['config.json', 'rig/config.json']) {
|
package/src/interview-routes.ts
CHANGED
|
@@ -70,7 +70,7 @@ export function interviewRoutes(root: string, output: string, capability: string
|
|
|
70
70
|
if (req.method === 'GET' && url.pathname === '/api/interview') {
|
|
71
71
|
const validated = await current();
|
|
72
72
|
const dir = destination();
|
|
73
|
-
return json({...(joined ? {binding:{projectHash:opened.hash, sourceHash:joined.sourceHash, ...(joined.draftId===undefined?{version:joined.version}:{draftId:joined.draftId})}} : {}), historical:validated.historical, diagnostics:validated.diagnostics, questions:validated.questions.map(question => ({
|
|
73
|
+
return json({...(joined && (joined.version!==undefined||joined.draftId!==undefined) ? {binding:{projectHash:opened.hash, sourceHash:joined.sourceHash, ...(joined.draftId===undefined?{version:joined.version}:{draftId:joined.draftId})}} : {}), historical:validated.historical, diagnostics:validated.diagnostics, questions:validated.questions.map(question => ({
|
|
74
74
|
...question, saved:question.editable ? readPicks(dir, question) : null,
|
|
75
75
|
images:question.images.map(({name}, index) => ({name, url:'/api/interview/image/' + question.ref.sha256 + '/' + index})),
|
|
76
76
|
}))});
|
package/src/interview-scene.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** Shared closed scene shape and private option-context gate, from Create PROJECT rule 4. */
|
|
2
2
|
import {createHash} from 'node:crypto';
|
|
3
3
|
import {isDeepStrictEqual as equal} from 'node:util';
|
|
4
4
|
import type {SetRef} from './interview-project.ts';
|
|
@@ -40,7 +40,7 @@ function plate(value: unknown): boolean {
|
|
|
40
40
|
closed(p.registered, ['kind', 'ref']) && ['input', 'derived'].includes(String(registered.kind)) && text(registered.ref) &&
|
|
41
41
|
(!('citation' in p) || citation(p.citation));
|
|
42
42
|
}
|
|
43
|
-
function
|
|
43
|
+
export function sceneDocumentShape(value: Data, n: unknown): boolean {
|
|
44
44
|
const rig = object(value.rig), animation = object(rig.animation), acceptance = object(rig.acceptance);
|
|
45
45
|
const signoff = object(acceptance.signoff), reviewPackage = object(acceptance.review_package), frame = object(value.frame);
|
|
46
46
|
return closed(value, ['schema', 'n', 'rig', 'frame', 'plates', 'layers']) && value.schema === 'rig-create/scene@1' && count(value.n) && value.n === n &&
|
|
@@ -104,6 +104,6 @@ export function sceneAt(project: Data, at: number, read: (ref: SetRef) => Data)
|
|
|
104
104
|
const reference = {n: candidate.n, path: candidate.path as string, sha256: candidate.sha256 as string};
|
|
105
105
|
let scene: Data;
|
|
106
106
|
try {scene = read(reference);} catch {return stale();}
|
|
107
|
-
if (!
|
|
107
|
+
if (!sceneDocumentShape(scene, candidate.n)) return stale();
|
|
108
108
|
return {context: {kind: 'scene', scene: reference}, current: current(project, scene, at), document: scene};
|
|
109
109
|
}
|
package/src/job-act.ts
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import {
|
|
3
|
-
JOB_ACT_SCHEMA, JOB_API_SCHEMA, JOB_API_V3_SCHEMA, JOB_RECORD_ACT_KINDS, JOB_RECORD_ACT_SCHEMA,
|
|
4
|
-
type ActV3, type JobAct, type
|
|
3
|
+
JOB_ACT_SCHEMA, JOB_API_SCHEMA, JOB_COMMENTS_ACT_SCHEMA, JOB_API_V3_SCHEMA, JOB_RECORD_ACT_KINDS, JOB_RECORD_ACT_SCHEMA, jobStillByteLimit, JOB_ENABLED_ACT_KINDS, JOB_PLAN_BOUND_SIGNOFF_STAGES, JOB_RESERVED_ACT_KINDS,
|
|
4
|
+
type ActV3, type JobAct, type JobCommentsAct, type JobApiSchema, type JobPendingAsk, type JobPublicationMode, type JobReviewerBinding,
|
|
5
5
|
type JobSourceBinding, type JobSubject, type JobUISubmission, type JobRigCapture, type JobRigStill,
|
|
6
6
|
type PendingAskV3, type RecordAct, type RecordSource, type RecordSubject, type SourceV3, type UISubmissionV3,
|
|
7
7
|
} from './job-contract.ts';
|
|
8
|
+
import { parsePartsIssue, type PartsIssue } from './parts-comment.ts';
|
|
8
9
|
import {
|
|
9
10
|
isRecordSource, jobHash, jobId, jobInteger, jobObject,
|
|
10
|
-
parseRecordAct, parseRecordSource, requestDigest, validateRecordAskSubject,
|
|
11
|
+
parseCommentsAct, parseRecordAct, parseRecordSource, requestDigest, validateRecordAskSubject,
|
|
11
12
|
} from './job-api.ts';
|
|
13
|
+
import { checkpointNoteComments, feedbackItemComments, noteComments, partsIssueComments } from './feedback-export.ts';
|
|
14
|
+
import type { Feedback } from './session.ts';
|
|
12
15
|
import { validatePicks } from './interview-picks.ts';
|
|
13
16
|
import {
|
|
14
17
|
isRetainedRecordSource,
|
|
@@ -18,7 +21,6 @@ import {
|
|
|
18
21
|
} from './job-source.ts';
|
|
19
22
|
import { JobError } from './job-store.ts';
|
|
20
23
|
import { checkedPath, readRegular } from './interview-project.ts';
|
|
21
|
-
import { prepareJobImageSet } from './job-image-set.ts';
|
|
22
24
|
import {validatePngBytes} from './comment-crops.ts';
|
|
23
25
|
|
|
24
26
|
function words(value: unknown): string {
|
|
@@ -26,6 +28,12 @@ function words(value: unknown): string {
|
|
|
26
28
|
return value;
|
|
27
29
|
}
|
|
28
30
|
|
|
31
|
+
/** The writer's output must decode through the public @6 decoder; its refusal is JOB_ACT_INVALID. */
|
|
32
|
+
function commentsAct(act: JobCommentsAct): JobCommentsAct {
|
|
33
|
+
parseCommentsAct(act);
|
|
34
|
+
return act;
|
|
35
|
+
}
|
|
36
|
+
|
|
29
37
|
function choice<Value extends string>(value: unknown, allowed: readonly Value[]): Value {
|
|
30
38
|
if (!allowed.includes(value as Value)) throw new JobError('JOB_ACT_INVALID');
|
|
31
39
|
return value as Value;
|
|
@@ -92,16 +100,6 @@ export function bindJobAsk(subject: JobSubject | RecordSubject, retained: JobRet
|
|
|
92
100
|
return bindJobRecordAsk(subject, retained);
|
|
93
101
|
}
|
|
94
102
|
const source = structuredClone(retained.source);
|
|
95
|
-
if (source.subject === 'image-set') {
|
|
96
|
-
if (subject.kind !== 'review-verdict' || subject.stage !== 'image-review') throw new JobError('JOB_ASK_INVALID');
|
|
97
|
-
const identity = prepareJobImageSet(source.imageSet,
|
|
98
|
-
path => readRegular(checkedPath(retained.root.path, path), 64 * 1024 * 1024));
|
|
99
|
-
if (requestDigest(identity) !== requestDigest({imageSet: source.imageSet,
|
|
100
|
-
imageSetDigest: source.imageSetDigest, duplicateHashes: source.duplicateHashes})) {
|
|
101
|
-
throw new JobError('JOB_SOURCE_MISMATCH');
|
|
102
|
-
}
|
|
103
|
-
return {...source, ...identity};
|
|
104
|
-
}
|
|
105
103
|
const declared = retained.subjects.some(candidate => requestDigest(candidate) === requestDigest(subject));
|
|
106
104
|
switch (subject.kind) {
|
|
107
105
|
case 'interview-picks': {
|
|
@@ -189,7 +187,7 @@ export function prepareJobStill(input: UISubmissionV3, ask: JobPendingAsk, retai
|
|
|
189
187
|
} else {
|
|
190
188
|
if (typeof frame !== 'number' || !Number.isFinite(frame) || frame < 0 ||
|
|
191
189
|
typeof capture.animation !== 'string' || !capture.animation || capture.animation.length > 512 ||
|
|
192
|
-
|
|
190
|
+
!retained.source.model) throw new JobError('JOB_STILL_CAPTURE_FAILED');
|
|
193
191
|
const model = JSON.parse(readRegular(checkedPath(retained.snapshotRoot, retained.source.model.path), 64 * 1024 * 1024).toString('utf8'));
|
|
194
192
|
const clip = model.animations?.find((item: {name: string; duration: number}) => item.name === capture.animation);
|
|
195
193
|
if (!clip || !Number.isFinite(clip.duration) || frame > clip.duration) throw new JobError('JOB_STILL_CAPTURE_FAILED');
|
|
@@ -503,29 +501,8 @@ export function finalizeJobAct(options: {
|
|
|
503
501
|
authority: { actor: 'human' as const, channel: 'review-ui' as const, reviewer: structuredClone(reviewer) },
|
|
504
502
|
at,
|
|
505
503
|
};
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
ask.subject.stage !== 'image-review') throw new JobError('JOB_ACT_INVALID');
|
|
509
|
-
const value = jobObject(submission.value, ['stage', 'verdict', 'words', 'imageNotes']);
|
|
510
|
-
if (value.stage !== 'image-review') throw new JobError('JOB_ACT_INVALID');
|
|
511
|
-
let imageNotes: {name: string; words: string}[] | undefined;
|
|
512
|
-
if (value.imageNotes !== undefined) {
|
|
513
|
-
if (!Array.isArray(value.imageNotes) || value.imageNotes.length > source.imageSet.images.length) {
|
|
514
|
-
throw new JobError('JOB_ACT_INVALID');
|
|
515
|
-
}
|
|
516
|
-
const names = new Set<string>();
|
|
517
|
-
imageNotes = value.imageNotes.map(raw => {
|
|
518
|
-
const note = jobObject(raw, ['name', 'words']);
|
|
519
|
-
if (typeof note.name !== 'string' || names.has(note.name) ||
|
|
520
|
-
!source.imageSet.images.some(image => image.name === note.name)) throw new JobError('JOB_ACT_INVALID');
|
|
521
|
-
names.add(note.name);
|
|
522
|
-
return {name: note.name, words: words(note.words)};
|
|
523
|
-
});
|
|
524
|
-
}
|
|
525
|
-
return {...envelope, kind: 'review-verdict', source, value: {stage: 'image-review',
|
|
526
|
-
verdict: choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const), words: words(value.words),
|
|
527
|
-
...(imageNotes === undefined ? {} : {imageNotes})}};
|
|
528
|
-
}
|
|
504
|
+
// Image-review and interview-picks keep act@2: Create refuses both under act@6.
|
|
505
|
+
const comments = {...envelope, schema: JOB_COMMENTS_ACT_SCHEMA};
|
|
529
506
|
switch (submission.kind) {
|
|
530
507
|
case 'interview-picks': {
|
|
531
508
|
const value = jobObject(submission.value, ['questionId', 'selections', 'note']);
|
|
@@ -552,59 +529,86 @@ export function finalizeJobAct(options: {
|
|
|
552
529
|
const value = jobObject(submission.value, ['checkpointId', 'outcome', 'words']);
|
|
553
530
|
const subject = ask.subject;
|
|
554
531
|
if (subject.kind !== 'checkpoint' || value.checkpointId !== subject.checkpointId) throw new JobError('JOB_ACT_INVALID');
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
532
|
+
const planStepId = subject.planStepId ?? subject.checkpointId, note = words(value.words);
|
|
533
|
+
return commentsAct({ ...comments, kind: 'checkpoint', source: { ...source, plan: source.plan! }, value: {
|
|
534
|
+
checkpointId: subject.checkpointId, planStepId,
|
|
535
|
+
outcome: choice(value.outcome, ['pass', 'fail'] as const),
|
|
536
|
+
comments: note.trim() ? checkpointNoteComments({checkpointId: subject.checkpointId, planStepId, note}) : [],
|
|
537
|
+
} });
|
|
559
538
|
}
|
|
560
539
|
case 'parts-verdict': {
|
|
561
|
-
const value = jobObject(submission.value, ['verdict', '
|
|
562
|
-
|
|
540
|
+
const value = jobObject(submission.value, ['verdict', 'issues', 'words']);
|
|
541
|
+
const verdict = choice(value.verdict, ['approved', 'changes-requested'] as const);
|
|
542
|
+
if (
|
|
543
|
+
!Array.isArray(value.issues) ||
|
|
544
|
+
value.issues.length > 1000 ||
|
|
545
|
+
(verdict === 'approved') !== (value.issues.length === 0)
|
|
546
|
+
) {
|
|
547
|
+
throw new JobError('JOB_ACT_INVALID');
|
|
548
|
+
}
|
|
563
549
|
const ids = new Set<string>();
|
|
564
|
-
const
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
550
|
+
const issues: PartsIssue[] = value.issues.map(raw => {
|
|
551
|
+
let issue: PartsIssue;
|
|
552
|
+
try {
|
|
553
|
+
issue = parsePartsIssue(raw, true, false, false);
|
|
554
|
+
} catch {
|
|
555
|
+
throw new JobError('JOB_ACT_INVALID');
|
|
556
|
+
}
|
|
557
|
+
if (issue.sourceHash !== source.sourceHash || ids.has(issue.id)) {
|
|
558
|
+
throw new JobError('JOB_ACT_INVALID');
|
|
559
|
+
}
|
|
560
|
+
ids.add(issue.id);
|
|
561
|
+
for (const part of issue.parts) {
|
|
562
|
+
const matchesSource = source.parts!.images.some(
|
|
563
|
+
img => img.role === 'part' && img.path === `parts/${part.name}.png` && img.sha256 === part.imageHash,
|
|
564
|
+
);
|
|
565
|
+
if (!retained.partIds.includes(part.name) || !matchesSource) {
|
|
566
|
+
throw new JobError('JOB_ACT_INVALID');
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return structuredClone(issue);
|
|
570
|
+
});
|
|
571
|
+
return commentsAct({
|
|
572
|
+
...comments,
|
|
573
|
+
kind: 'parts-verdict',
|
|
574
|
+
source: {
|
|
575
|
+
...source,
|
|
576
|
+
projectHash: source.projectHash!,
|
|
577
|
+
selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, { kind: 'draft' }>,
|
|
578
|
+
parts: source.parts!,
|
|
579
|
+
},
|
|
580
|
+
value: { verdict, comments: [...partsIssueComments(issues), ...noteComments(words(value.words))] },
|
|
577
581
|
});
|
|
578
|
-
const verdict = choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const);
|
|
579
|
-
const outcomes = parts.flatMap(part => [part.part.outcome, part.mesh.outcome]);
|
|
580
|
-
if (verdict === 'approved' && outcomes.some(outcome => outcome !== 'clean') ||
|
|
581
|
-
verdict === 'changes-requested' && !outcomes.includes('flagged')) throw new JobError('JOB_ACT_INVALID');
|
|
582
|
-
return { ...envelope, kind: 'parts-verdict', source: { ...source, projectHash: source.projectHash!,
|
|
583
|
-
selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, { kind: 'draft' }>, parts: source.parts! },
|
|
584
|
-
value: { verdict, parts, words: words(value.words) } };
|
|
585
582
|
}
|
|
586
583
|
case 'review-verdict': {
|
|
587
|
-
const value = jobObject(submission.value, ['stage', 'verdict', 'words'
|
|
584
|
+
const value = jobObject(submission.value, ['stage', 'verdict', 'words',
|
|
585
|
+
...(ask.subject.kind === 'review-verdict' && ask.subject.stage === 'rig-review' ? ['feedback'] : [])]);
|
|
588
586
|
if (ask.subject.kind !== 'review-verdict' || ask.subject.stage === 'image-review' || value.stage !== ask.subject.stage) throw new JobError('JOB_ACT_INVALID');
|
|
589
587
|
if (ask.subject.stage === 'rig-review') {
|
|
590
588
|
if (!options.still) throw new JobError('JOB_STILL_CAPTURE_FAILED');
|
|
591
|
-
|
|
589
|
+
const note = words(value.words);
|
|
590
|
+
if (value.feedback !== undefined && !Array.isArray(value.feedback)) throw new JobError('JOB_ACT_INVALID');
|
|
591
|
+
let verdictComments: ReturnType<typeof noteComments>;
|
|
592
|
+
try {
|
|
593
|
+
verdictComments = value.feedback === undefined ? noteComments(note) : feedbackItemComments(value.feedback as Feedback[]);
|
|
594
|
+
} catch { throw new JobError('JOB_ACT_INVALID'); }
|
|
595
|
+
return commentsAct({...comments, kind: 'review-verdict',
|
|
592
596
|
source: {...source, model: source.model!, selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, {kind: 'rig'}>},
|
|
593
|
-
value: {stage: 'rig-review', verdict: choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const),
|
|
594
|
-
still: options.still};
|
|
597
|
+
value: {stage: 'rig-review', verdict: choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const), comments: verdictComments},
|
|
598
|
+
still: options.still});
|
|
595
599
|
}
|
|
596
|
-
return { ...
|
|
600
|
+
return commentsAct({ ...comments, kind: 'review-verdict', source: { ...source, model: source.model!,
|
|
597
601
|
selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, { kind: 'rig' | 'post' }> }, value: {
|
|
598
|
-
stage: ask.subject.stage, verdict: choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const),
|
|
599
|
-
} };
|
|
602
|
+
stage: ask.subject.stage, verdict: choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const), comments: noteComments(words(value.words)),
|
|
603
|
+
} });
|
|
600
604
|
}
|
|
601
605
|
case 'signoff': {
|
|
602
606
|
const value = jobObject(submission.value, ['stage', 'decision', 'words']);
|
|
603
607
|
if (ask.subject.kind !== 'signoff' || value.stage !== ask.subject.stage || value.decision !== 'approved') {
|
|
604
608
|
throw new JobError('JOB_ACT_INVALID');
|
|
605
609
|
}
|
|
606
|
-
|
|
607
|
-
|
|
610
|
+
return commentsAct({ ...comments, kind: 'signoff', source,
|
|
611
|
+
value: { stage: ask.subject.stage, decision: 'approved', comments: noteComments(words(value.words)) } });
|
|
608
612
|
}
|
|
609
613
|
}
|
|
610
614
|
}
|