@rig-c/review 1.15.0 → 1.16.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/PANELS.md CHANGED
@@ -475,12 +475,12 @@ Reset returns to the inspected revision. New scratch reads and made-mesh feedbac
475
475
  submissions recheck pinned producer inputs, revision files and compiled files.
476
476
  A changed scratch input cannot inherit clean checked evidence.
477
477
 
478
- The embedding is read-only: original verdicts and comments are never copied onto
478
+ The compiled inspection embedding is read-only: original verdicts and comments are never copied onto
479
479
  scratch geometry or saved by navigating. Use the standalone `parts` command for
480
480
  its separate explicit original-parts sign-off. Parts-only inputs remain
481
481
  inspectable and name `STAGE_DRAFT_UNAVAILABLE` for direct correction. A missing
482
482
  handoff keeps the inspected atlas available where supplied. Compare retains its
483
- read-only, side-specific inspected atlas. Neither flow guesses a sibling draft.
483
+ read-only, side-specific inspected atlas. Neither flow guesses a sibling draft. A [joined Create draft](WORKFLOWS.md#open-a-recorded-draft-before-rig-review) displays its recorded parts and mesh without a production rig package. A pending parts review with an explicit output directory can save a separate verdict here.
484
484
 
485
485
  Named draft boundaries are `STAGE_DRAFT_UNAVAILABLE`, `STAGE_DRAFT_MISMATCH`,
486
486
  `STAGE_DRAFT_STALE`, `STAGE_DRAFT_CHANGED`, `STAGE_DRAFT_UNCHECKED` and
@@ -73,6 +73,7 @@ Audio clips contain `id`, local `path` and optional `label`. Cues require `id`,
73
73
  - `GET /assets/<path>` serves an allowlisted local asset. Encode each path segment when building the URL. Responses use no-store and nosniff headers.
74
74
  - `GET /api/session` returns the current session or a fresh pending session.
75
75
  - `PUT /api/session` accepts the full session object below, with matching schema/id/revision/sourceHash. It requires the server's exact Origin, `application/json`, and <= 1 MiB. It returns the saved session with server-generated `updatedAt`.
76
+ - On a single-package session PUT, the managed front preserves allowlisted failed-check refusals from a matching worker as HTTP 400. It accepts the structured check summary or fallback and fixed check refusals in a JSON error object of at most 512 bytes. Other worker 400 errors use `FRONT_UPSTREAM_REJECTED`.
76
77
 
77
78
  ```json
78
79
  {
package/docs/WORKFLOWS.md CHANGED
@@ -384,6 +384,28 @@ to the joined command. The post must explicitly name the selected
384
384
  printed feedback command, including the project, rig, post and picks arguments,
385
385
  to export from that session.
386
386
 
387
+ ### Open a recorded draft before rig review
388
+
389
+ Select a Create draft explicitly and open its recorded compiled check directory.
390
+ Create the picks directory and, for a pending parts verdict, a separate verdict
391
+ directory inside the project before opening the host.
392
+
393
+ ```sh
394
+ rig-review open /path/to/project/derived/drafts/chain/out/check \
395
+ --project /path/to/project --project-draft chain --picks-dir scratch/review-picks \
396
+ --parts-verdict-dir scratch/review-verdicts
397
+ ```
398
+
399
+ **1 Parts + mesh** displays the draft's recorded parts and matching mesh.
400
+ Use **Save sign-off** to write a standard parts verdict with the part and mesh
401
+ outcomes and notes. Its filename is bound to the inspected project and source.
402
+ Keep the JSON file at its saved location for Create to resolve the source paths.
403
+ The verdict does not sign the Create project. A closed parts review or an open
404
+ without `--parts-verdict-dir` keeps this surface read-only. **2 Interview**
405
+ offers the registered pending sets and displays historical answers read-only.
406
+ **3 Rig + animation** and **4 Direction** report that the recorded rig review
407
+ package is unavailable. Reopen with a rig version once Create records one.
408
+
387
409
  From a create project with retained choice sets, create a dedicated output
388
410
  directory and open the foreground Stage 2 view:
389
411
 
@@ -444,3 +466,56 @@ Standalone parts notes and comments use
444
466
  For a part note, also pass `--part-note <part>` and supply its correction ID.
445
467
  Selected parts JSON keeps the saved verdict and adds the correction selection.
446
468
  The inventory names a retained Create-side input. Review does not read that path.
469
+
470
+ ## Four-stage acceptance fixture
471
+
472
+ The explicit browser runner in the Review checkout walks four independent Create
473
+ checkpoint prefixes using the managed loopback route for every stage and the
474
+ independent replay. The direct-route Save defect is tracked in
475
+ [Review #443](https://github.com/rig-c/review/issues/443).
476
+ Its inputs come from one archive of Create
477
+ [a1a5162](https://github.com/rig-c/create/commit/a1a5162cf4ce7fdef8caba50dc3979cf416467dd)
478
+ with SHA-256
479
+ `68034a42a70765ddda434195b945c9d87da85cf86443c657c31848ee163a8096`.
480
+ The materializer verifies the archive and each checkpoint sidecar before using
481
+ disposable copies. Checkpoint commands identify the declared acts and option
482
+ sets. The runner calls selected public consumers with explicit arguments.
483
+
484
+ Run `bun tests/four-stage-browser.ts` in a bounded Nova job from the Review
485
+ checkout after installing its frozen lock. Supply the original archive in
486
+ `REVIEW_371_CREATE_ARCHIVE`, the directory with Create's frozen-lock
487
+ `node_modules` in `REVIEW_371_CREATE_BENCH`, a new evidence directory in
488
+ `REVIEW_371_OUTPUT`, and the retained Stage 3 failed Apply JSON in
489
+ `REVIEW_371_FAILED_APPLIED`. The runner checks the failed artifact digest.
490
+ Keep Chromium's child `TMPDIR` short (the runner uses `/tmp` during launch).
491
+ The profile, Review state, input copies and producer scratch belong to the job.
492
+ The runner defaults to English followed by Korean. For a gated run, launch
493
+ `bash tests/four-stage-job.sh en` with the same pinned inputs, then launch
494
+ `bash tests/four-stage-job.sh ko` after accepting the English result. Each job
495
+ has a 600-second command deadline and uses a new evidence directory. The
496
+ `walk-checkpoints.jsonl` file records the last step entered if a run stops.
497
+
498
+ 1. Save and export the pre-rig parts and mesh verdict through the joined Review
499
+ surface. Create's shared parts-verdict checker verifies the actual saved
500
+ artifact. The next prefix already has a signature bound to its original
501
+ synthetic verdict.
502
+ 2. Save the explicit bones picks, then register and answer meshes, constraints
503
+ and motion in the generator's order. Refresh the joined view on identity
504
+ changes and check each answer and exact note in Create.
505
+ 3. Preview and Apply the body idle amplitude change from 0.5 to 2.5. The check
506
+ must pass with at least 6.12/255 torso breath heat. Export the made correction
507
+ and read back the Create config-patch record in its pending state. Replay the
508
+ exported patch in separate Review scratch. The measured 0.75 failed-check
509
+ control uses the refused UI request for a separate pending capture and
510
+ checked-claim refusal. It writes no resolved outcome.
511
+ 4. Write and check post 2 through Create on its pending prefix, then open rig 1
512
+ with explicit post 2. Inspect the authored keys and timing, exercise the
513
+ named camera Apply refusal, and save the described request. Verify the
514
+ inspected and project-relative model bindings and Create's pending readback.
515
+ The Create writer checks the explicit model selector and stores the exported
516
+ context string verbatim.
517
+
518
+ Both locales have browser captures. The runner checks original inventories
519
+ against each copy after the walk, retains named public record changes separately,
520
+ and records the first consumer verdict for each planted mutation. Inspecting,
521
+ navigating and saving a Review draft produce no Create signoff.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/review",
3
- "version": "1.15.0",
3
+ "version": "1.16.1",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
package/src/cli.ts CHANGED
@@ -25,7 +25,7 @@ import { readCompareSession } from './compare-session.ts';
25
25
  import { exportReviewStrip, exportCompareStrip, stripJson, writeStripOutput, validateStripOutput } from './strip-export.ts';
26
26
  import type { StripInterval, StripRequest } from './strip.ts';
27
27
  const handoffUsage='[--config <path> [--parts <dir>] [--source <png> --full <dir> [--head <dir>]] [--keypoints <file>]]';
28
- const usage='Usage: rig-review open <dir> [--reference <video>] [--compare <dir>] [--animation <name>] [--control] [--direct] [--view-only] [--project <create-root> --project-version <rig> --picks-dir <dir> [--post-version <post>]] '+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+' [--project <create-root> --project-version <rig> --picks-dir <dir> [--post-version <post>]] [--page <id> --expected-revision <n> --command <JSON> --wait-ms <n>]\n rig-review feedback <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--project <create-root> --project-version <rig> --picks-dir <dir> [--post-version <post>]] [--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
+ const usage='Usage: rig-review open <dir> [--reference <video>] [--compare <dir>] [--animation <name>] [--control] [--direct] [--view-only] [--project <create-root> (--project-version <rig> [--post-version <post>] | --project-draft <id> [--parts-verdict-dir <dir>]) --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+' [--project <create-root> --project-version <rig> --picks-dir <dir> [--post-version <post>]] [--page <id> --expected-revision <n> --command <JSON> --wait-ms <n>]\n rig-review feedback <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--project <create-root> --project-version <rig> --picks-dir <dir> [--post-version <post>]] [--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';
29
29
  async function stripCommand(args:string[],options:{stateDir?:string}){
30
30
  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)');
31
31
  let reference:string|undefined,referenceVideo:string|undefined,animation:string|undefined,basis:'a'|'b'|undefined,range:string|undefined,output:string|undefined,jsonOnly=false,all=false;
@@ -45,23 +45,26 @@ async function stripCommand(args:string[],options:{stateDir?:string}){
45
45
  }
46
46
  /** `--config` → `config` for the producer handoff flags (#101), else null. */
47
47
  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;}
48
- const projectFlags = ['--project','--project-version','--picks-dir','--post-version'];
48
+ const projectFlags = ['--project','--project-version','--picks-dir','--post-version','--project-draft','--parts-verdict-dir'];
49
49
  /** The retrieval words for the handoff flags, in their fixed order. */
50
50
  const projectWords=(inputs:OpenInputs)=>{const p=inputs.project;return p?[
51
- '--project',p.root,'--project-version',String(p.version),'--picks-dir',p.picksDir,
51
+ '--project',p.root,...(p.draftId===undefined?['--project-version',String(p.version)]:['--project-draft',p.draftId]),'--picks-dir',p.picksDir,
52
+ ...(p.partsVerdictDir===undefined?[]:['--parts-verdict-dir',p.partsVerdictDir]),
52
53
  ...(p.postVersion===undefined?[]:['--post-version',String(p.postVersion)]),
53
54
  ]:[];};
54
55
  const handoffWords=(inputs:OpenInputs)=>HANDOFF_FLAGS.flatMap(f=>inputs[f]!==undefined?['--'+f,inputs[f]!]:[]);
55
56
  export function parseOpenInputs(args:string[]):OpenInputs {
56
57
  const input=args.shift();if(!input||input.startsWith('--'))throw new Error(usage);const result:OpenInputs={input},seen=new Set<string>();
57
- let root:string|undefined,version:string|undefined,postVersion:string|undefined,picksDir:string|undefined;
58
- 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(flag==='--post-version')postVersion=value;else if(handoffOption(flag))result[handoffOption(flag)!]=value;else throw new Error(`OPEN_OPTION_INVALID ${flag}: Unknown open option ${flag}`);}
59
- if(root!==undefined||version!==undefined||picksDir!==undefined||postVersion!==undefined){
60
- if(!root||!picksDir||!version||!/^\d+$/.test(version)||!Number.isSafeInteger(Number(version))||Number(version)<1||result.compare!==undefined)
61
- throw new Error('OPEN_OPTION_INVALID --project: single-package open requires --project, --project-version and --picks-dir together');
58
+ let root:string|undefined,version:string|undefined,postVersion:string|undefined,picksDir:string|undefined,draftId:string|undefined,partsVerdictDir:string|undefined;
59
+ 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(flag==='--project-draft')draftId=value;else if(flag==='--parts-verdict-dir')partsVerdictDir=value;else if(flag==='--post-version')postVersion=value;else if(handoffOption(flag))result[handoffOption(flag)!]=value;else throw new Error(`OPEN_OPTION_INVALID ${flag}: Unknown open option ${flag}`);}
60
+ if(root!==undefined||version!==undefined||picksDir!==undefined||postVersion!==undefined||draftId!==undefined||partsVerdictDir!==undefined){
61
+ if(!root||!picksDir||(Boolean(version)===Boolean(draftId))||result.compare!==undefined||version!==undefined&&(!/^\d+$/.test(version)||!Number.isSafeInteger(Number(version))||Number(version)<1))
62
+ throw new Error('OPEN_OPTION_INVALID --project: single-package open requires --project, --picks-dir and one of --project-version or --project-draft together');
62
63
  if(postVersion!==undefined&&(!/^\d+$/.test(postVersion)||!Number.isSafeInteger(Number(postVersion))||Number(postVersion)<1))
63
64
  throw new Error('OPEN_OPTION_INVALID --post-version: expected a positive Create post version');
64
- result.project={root,version:Number(version),picksDir,...(postVersion!==undefined?{postVersion:Number(postVersion)}:{})};
65
+ if(draftId&&postVersion)throw new Error('OPEN_OPTION_INVALID --post-version: requires --project-version');
66
+ if(partsVerdictDir&&(!draftId||result.viewOnly))throw new Error('OPEN_OPTION_INVALID --parts-verdict-dir: requires a writable --project-draft');
67
+ result.project=draftId?{root,draftId,picksDir,...(partsVerdictDir?{partsVerdictDir}:{})}:{root,version:Number(version),picksDir,...(postVersion!==undefined?{postVersion:Number(postVersion)}:{})};
65
68
  }
66
69
  const problem=checkHandoffFlags(result);if(problem)throw new Error(`OPEN_OPTION_INVALID ${problem.split(':')[0]}: ${problem.slice(problem.indexOf(':')+2)}`);
67
70
  if(result.compare!==undefined&&handoffFlags(result))throw new Error('OPEN_OPTION_INVALID --config: compare takes no producer handoff; open one package with --config');
package/src/front.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { interviewRefusals, interviewRequest } from './interview-routes.ts';
2
2
  import { directionStale, interviewStale } from './joined-project.ts';
3
3
  import { picksLimit } from './interview-picks.ts';
4
- import {stageDraftRefusals} from './stage-parts.ts';
4
+ import {stageDraftRefusals,stageVerdictLimit,stageVerdictRefusals} from './stage-parts.ts';
5
5
  /** Managed loopback front: one stable origin (127.0.0.1:4318 by default) routing `/instances/<key>/…` to the
6
6
  * worker named by that key's private open record. It is a router, not an authority: it never reads packages,
7
7
  * never serves or logs a capability, and forwards a mutation (rewriting Origin) only with the page capability. */
@@ -57,6 +57,8 @@ export function frontRoute(mode:'single'|'compare',method:string,path:string):Ro
57
57
  if(['/stage-parts.html','/parts.js','/parts.css'].includes(path))return read?get:null;
58
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
59
  if(mode==='single'){
60
+ if(path==='/api/stage-parts/verdict')return method==='POST'?{...get,mutation:true,limit:stageVerdictLimit}:null;
61
+ if(path==='/api/stage-parts/export/json'||path==='/api/stage-parts/export/issue')return read?get:null;
60
62
  if(['/stage-interview.html','/interview.js','/interview.css'].includes(path))return method==='GET'?get:null;
61
63
  if(interviewRequest(path))return path==='/api/interview/picks'?
62
64
  method==='POST'?{...get,mutation:true,limit:picksLimit}:null:method==='GET'?get:null;
@@ -97,7 +99,7 @@ async function boundedBody(req:Request,limit:number,timeoutMs=10000):Promise<Arr
97
99
  }
98
100
  /** Owner-only regular record for this key, or null. */
99
101
  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);}
100
- /** Worker statuses map to named front codes; worker text never reaches the client. */
102
+ /** Worker errors default to front codes unless an inspection refusal is allowlisted. */
101
103
  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'};
102
104
  const responseHeaders=['content-type','content-length','content-range','accept-ranges','content-disposition','cache-control','content-security-policy','x-content-type-options','referrer-policy'];
103
105
  /** The trusted atlas frame alone may carry this closed navigation query. */
@@ -106,6 +108,26 @@ export function stageFrameQuery(mode:'single'|'compare',search:string):boolean {
106
108
  const allowed=mode==='single'?['stageEmbed','lang']:['stageEmbed','lang','side'];
107
109
  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')??''));
108
110
  }
111
+ // The submitted Apply can supply the check line. Accept the producer's structured
112
+ // summary fields, never an arbitrary suffix after the failed-check code.
113
+ const submitCheckPrefix = 'EDIT_SUBMIT_UNCHECKED: applied build failed check — ';
114
+ const checkBarName = '(?:[A-Z][A-Z0-9_]*|gate|loop|seam)';
115
+ const submitCheckSummary = new RegExp(
116
+ String.raw`^check: FAIL — \d+ bar\(s\) not met(?:, \d+ declared requirement\(s\) not PASS)?; ` +
117
+ String.raw`\d+ of \d+ bar\(s\) measured, \d+ skipped(?: \(${checkBarName}(?:, ${checkBarName})*\))?` +
118
+ String.raw`(?:; \d+ warning\(s\) \((?:SEAM_OVER_MOTION(?:, CLOTH_SETTLES)?|CLOTH_SETTLES), not a bar\))?$`
119
+ );
120
+ const submitCheckFallback = new RegExp(String.raw`^(?:${checkBarName}: FAIL|check exited -?\d+)$`);
121
+ const fixedSubmitRefusals = new Set([
122
+ 'EDIT_SUBMIT_UNCHECKED: applied mesh has no successful producer check',
123
+ 'CORRECTION_CHECK_FAILED: the settled Apply requires a passing producer check',
124
+ ]);
125
+ function isSubmitCheckRefusal(error: string): boolean {
126
+ if(fixedSubmitRefusals.has(error))return true;
127
+ if(!error.startsWith(submitCheckPrefix))return false;
128
+ const detail=error.slice(submitCheckPrefix.length);
129
+ return submitCheckSummary.test(detail)||submitCheckFallback.test(detail);
130
+ }
109
131
  /** Preserve only closed, bounded inspection refusals. */
110
132
  async function inspectionRefusal(mode:'single'|'compare',method:string,path:string,response:Response,sameFingerprint:boolean):Promise<string|null>{
111
133
  const stageData=mode==='single'?path==='/api/stage-parts':/^\/api\/compare\/(?:a|b)\/stage-parts$/.test(path);
@@ -113,7 +135,9 @@ async function inspectionRefusal(mode:'single'|'compare',method:string,path:stri
113
135
  // Both reads race during the single-package page bootstrap.
114
136
  const direction=sameFingerprint&&mode==='single'&&method==='GET'&&response.status===409&&
115
137
  (path==='/api/review'||path==='/api/session');
116
- if(!(direction||interview||stageData&&method==='GET'&&response.status===409)||!/^application\/json(?:\s*;|$)/i.test(response.headers.get('content-type')??''))return null;
138
+ const submit=sameFingerprint&&mode==='single'&&method==='PUT'&&path==='/api/session'&&response.status===400;
139
+ 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);
140
+ if(!(submit||direction||interview||verdict||stageData&&method==='GET'&&response.status===409)||!/^application\/json(?:\s*;|$)/i.test(response.headers.get('content-type')??''))return null;
117
141
  const limit=512,declared=response.headers.get('content-length');if(declared!==null&&(!/^\d+$/.test(declared)||Number(declared)>limit))return null;
118
142
  const reader=response.body?.getReader();if(!reader)return null;
119
143
  try{
@@ -123,8 +147,9 @@ async function inspectionRefusal(mode:'single'|'compare',method:string,path:stri
123
147
  const data:unknown=JSON.parse(new TextDecoder().decode(body)),named='PARTS_ATLAS_UNAVAILABLE: the inspected package has no usable atlas or its source changed.';
124
148
  if(data===null||typeof data!=='object'||Array.isArray(data)||Object.keys(data).length!==1)return null;
125
149
  const error=(data as {error?:unknown}).error;
150
+ if(submit)return typeof error==='string'&&isSubmitCheckRefusal(error)?error:null;
126
151
  if(direction)return error===directionStale?directionStale:null;
127
- return typeof error==='string'&&(interview?[...interviewRefusals]:[named,interviewStale,...Object.values(stageDraftRefusals)] as readonly string[]).some(code=>code===error)?error:null;
152
+ 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;
128
153
  }catch{return null;}finally{reader.releaseLock();}
129
154
  }
130
155
  export const maximumUpstreamStreams=32;
@@ -182,11 +207,11 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
182
207
  body=await boundedBody(req,route.limit);
183
208
  // A stale interview worker must still prove its identity before it receives picks.
184
209
  // It revalidates the join before saving and returns the specific stale refusal.
185
- if(!await alive(record,path==='/api/interview/picks'))return refuse('FRONT_INSTANCE_EXPIRED: reopen with rig-review open',410);
210
+ if(!await alive(record,(path==='/api/interview/picks'||path==='/api/stage-parts/verdict')))return refuse('FRONT_INSTANCE_EXPIRED: reopen with rig-review open',410);
186
211
  }
187
212
  if(active>=maximumUpstreamStreams)return refuse('FRONT_BUSY: too many concurrent upstream streams',503);
188
213
  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);}
189
- if(/^\/api\/stage-parts(?:\/(?:image|page)\/\d+)?$/.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);}}
214
+ 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);}}
190
215
  if(route.mutation){headers.set('origin',record.origin);headers.set(capabilityHeader,record.capability);}
191
216
  active++;let released=false;const abort=new AbortController(),timer=setTimeout(()=>abort.abort(),route.timeoutMs);const release=()=>{if(released)return;released=true;active--;clearTimeout(timer);};
192
217
  req.signal.addEventListener('abort',()=>abort.abort(),{once:true});
@@ -43,7 +43,7 @@ export function interviewRequest(path: string) {
43
43
  }
44
44
 
45
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}) {
46
+ joined?: {opened: ReturnType<typeof readProject>; assertCurrent: () => Promise<void>; available: boolean; sourceHash: string; version?: number; draftId?:string}) {
47
47
  const opened = joined?.opened ?? readProject(root);
48
48
  const outputPath = outputDirectory(opened.root, output, opened.project);
49
49
  const openedOutput = lstatSync(outputPath);
@@ -67,7 +67,7 @@ export function interviewRoutes(root: string, output: string, capability: string
67
67
  if (req.method === 'GET' && url.pathname === '/api/interview') {
68
68
  await current();
69
69
  const dir = destination();
70
- return json({...(joined ? {binding:{projectHash:opened.hash, sourceHash:joined.sourceHash, version:joined.version}} : {}), historical:opened.historical, questions:opened.questions.map(question => ({
70
+ return json({...(joined ? {binding:{projectHash:opened.hash, sourceHash:joined.sourceHash, ...(joined.draftId===undefined?{version:joined.version}:{draftId:joined.draftId})}} : {}), historical:opened.historical, questions:opened.questions.map(question => ({
71
71
  ...question, saved:question.editable ? readPicks(dir, question) : null,
72
72
  images:question.images.map(({name}, index) => ({name, url:'/api/interview/image/' + question.ref.sha256 + '/' + index})),
73
73
  }))});
@@ -1,4 +1,4 @@
1
- import { readdirSync } from 'node:fs';
1
+ import { lstatSync, readdirSync } from 'node:fs';
2
2
  import { join, relative, sep } from 'node:path';
3
3
  import { boundBytes, checkedPath, digest, jsonObject, literalPath, object, readProject, readRegular } from './interview-project.ts';
4
4
  import { DIRECTION_MAX_BYTES, readDirectionInspection } from './direction-inspection.ts';
@@ -6,13 +6,33 @@ import { outputDirectory } from './interview-picks.ts';
6
6
  import { packagePath, type ReviewPackage } from './manifest.ts';
7
7
  import { assertReviewUnchanged, withReviewAssertion } from './reference.ts';
8
8
 
9
- export interface ProjectDesignation {root: string; version: number; postVersion?: number; picksDir: string}
9
+ export type ProjectDesignation={root:string;picksDir:string}&(
10
+ {version:number;postVersion?:number;draftId?:never;partsVerdictDir?:never} |
11
+ {draftId:string;partsVerdictDir?:string;version?:never;postVersion?:never}
12
+ );
13
+ interface DraftSource {
14
+ parts:string;
15
+ rig:string;
16
+ meshReport:string;
17
+ model:string;
18
+ files:ReadonlyMap<string,string>;
19
+ }
20
+ interface JoinedSource {
21
+ review:ReviewPackage;
22
+ opened:ReturnType<typeof readProject>;
23
+ designation:ProjectDesignation;
24
+ assertCurrent:()=>Promise<void>;
25
+ available:boolean;
26
+ draft?:DraftSource;
27
+ verdictDirectory?:()=>string;
28
+ }
10
29
  export const interviewUnavailable = 'INTERVIEW_UNAVAILABLE';
11
30
  export const interviewMismatch = 'INTERVIEW_SOURCE_MISMATCH';
12
31
  export const interviewStale = 'INTERVIEW_OPTIONS_STALE';
13
32
  export const directionStale = 'DIRECTION_SOURCE_STALE';
14
33
 
15
- export function joinProject(p: ReviewPackage, designation: ProjectDesignation) {
34
+ export function joinProject(p: ReviewPackage, designation: ProjectDesignation):JoinedSource {
35
+ if(designation.draftId!==undefined)return joinDraft(p,designation);
16
36
  const opened = readProject(designation.root);
17
37
  const {root, hash, project} = opened;
18
38
  const {version} = designation;
@@ -127,4 +147,87 @@ export function joinProject(p: ReviewPackage, designation: ProjectDesignation) {
127
147
  return {review, opened, designation:{...designation, root}, assertCurrent,
128
148
  available:opened.questions.length > 0 || opened.historical.length > 0};
129
149
  }
150
+ /** Match the draft writer's explicit parts and rig inventories, independently of a production version. */
151
+ function joinDraft(p:ReviewPackage,designation:Extract<ProjectDesignation,{draftId:string}>):JoinedSource {
152
+ const opened=readProject(designation.root);
153
+ const {root,hash,project}=opened;
154
+ const {draftId}=designation;
155
+ const path='derived/drafts/'+draftId;
156
+ const fail=():never=>{throw new Error('INTERVIEW_SOURCE_MISMATCH: expected the selected Create pre-rig draft and exact recorded files');};
157
+ if(!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(draftId)||!Array.isArray(project.versions)||project.versions.length||
158
+ !Array.isArray(project.drafts)||!Array.isArray(project.signoffs)||!p.manifest.model||!p.reviewedSource.rig||
159
+ p.direction||p.handoffInputs)return fail();
160
+ const matches=project.drafts.map(object).filter(draft=>draft.id===draftId);
161
+ const record=matches[0],parts=object(record?.parts);
162
+ if(matches.length!==1||record?.kind!=='draft-rig'||!literalPath(parts.path)||!parts.path.startsWith(path+'/')||
163
+ !Array.isArray(parts.files)||!Array.isArray(record.files)||
164
+ (record.config_inputs!==undefined&&!Array.isArray(record.config_inputs)))return fail();
165
+ const files=new Map<string,string>();
166
+ const inventory=(refs:unknown[],prefix:string)=>{
167
+ const paths:string[]=[];
168
+ for(const ref of refs){
169
+ const {path,sha256}=object(ref);
170
+ if(!literalPath(path)||!path.startsWith(prefix+'/')||typeof sha256!=='string'||!/^[a-f0-9]{64}$/.test(sha256))return fail();
171
+ packagePath(path);
172
+ if(paths.includes(path)||(files.has(path)&&files.get(path)!==sha256))return fail();
173
+ paths.push(path);
174
+ files.set(path,sha256);
175
+ }
176
+ return paths;
177
+ };
178
+ let draft:DraftSource;
179
+ try{
180
+ inventory([record.config,...(record.config_inputs??[])],path);
181
+ const input=inventory(parts.files,parts.path);
182
+ if(!input.includes(parts.path+'/parts.json')||!input.some(file=>file.startsWith(parts.path+'/parts/')))return fail();
183
+ const output=inventory(record.files,path);
184
+ const rigs=output.filter(file=>file.endsWith('/rig.json'));
185
+ if(rigs.length!==1)return fail();
186
+ const rig=rigs[0]!,dir=rig.slice(0,-'/rig.json'.length);
187
+ const meshReport=dir+'/mesh_report.json';
188
+ const model=relative(root,join(p.root,p.manifest.model)).split(sep).join('/');
189
+ const checkRoot=dir.endsWith('/rig')?dir.slice(0,-'/rig'.length):dir;
190
+ if(!output.includes(meshReport)||!output.includes(dir+'/motion.json')||
191
+ !model.startsWith(checkRoot+'/check/')||!output.includes(model)||files.get(model)!==p.reviewedSource.rig.sha256||
192
+ ![...p.files].every(file=>output.includes(relative(root,join(p.root,file)).split(sep).join('/'))))return fail();
193
+ draft={parts:checkedPath(root,parts.path,true),rig:checkedPath(root,rig),meshReport:checkedPath(root,meshReport),
194
+ model:checkedPath(root,model),files:new Map([...files].map(([file,sha])=>[checkedPath(root,file),sha]))};
195
+ for(const [path,sha256] of files)boundBytes(root,{path,sha256});
196
+ }catch{return fail();}
197
+ outputDirectory(root,designation.picksDir,project);
198
+ const assertCurrent=async()=>{
199
+ try{
200
+ await assertReviewUnchanged(p);
201
+ for(const [path,sha256] of files)boundBytes(root,{path,sha256});
202
+ if(digest(readRegular(checkedPath(root,'project.json'),8*1024*1024))!==hash)throw new Error('Project changed');
203
+ }catch{throw new Error(interviewStale+': project or draft changed; reopen the project');}
204
+ };
205
+ const dir=designation.partsVerdictDir;
206
+ // An explicit output selects the write surface. A recorded parts approval closes it.
207
+ const pending=['parts','parts-review'].includes(String(project.stage))&&
208
+ !project.signoffs.map(object).some(signoff=>signoff.stage==='parts-review');
209
+ let verdictDirectory:JoinedSource['verdictDirectory'];
210
+ if(dir!==undefined){
211
+ const locate=()=>{
212
+ const portable=(value:string)=>value.normalize('NFC').toLowerCase();
213
+ const overlaps=(a:string,b:string)=>a===b||a.startsWith(b+'/')||b.startsWith(a+'/');
214
+ if(overlaps(portable(dir),portable(path))||overlaps(portable(dir),portable(designation.picksDir)))
215
+ throw new Error('PARTS_VERDICT_OUTPUT');
216
+ try{return outputDirectory(root,dir,project);}
217
+ catch{throw new Error('PARTS_VERDICT_OUTPUT');}
218
+ };
219
+ const original=lstatSync(locate());
220
+ if(pending)verdictDirectory=()=>{
221
+ const output=locate(),stat=lstatSync(output);
222
+ if(stat.dev!==original.dev||stat.ino!==original.ino)throw new Error('PARTS_VERDICT_OUTPUT');
223
+ return output;
224
+ };
225
+ }
226
+ const review=withReviewAssertion({...p,manifest:{...p.manifest,model:undefined},handoff:null,report:null,
227
+ feedbackCatalog:{rig:p.feedbackCatalog.rig,bones:null,slots:null,animations:null,clock:null,clockAnimation:null},
228
+ sourceHash:digest(JSON.stringify({schema:'rig-review-joined-draft/1',draftId,projectHash:hash,packageSourceHash:p.sourceHash})),
229
+ },assertCurrent);
230
+ return {review,opened,designation:{...designation,root},assertCurrent,draft,verdictDirectory,
231
+ available:opened.questions.length>0||opened.historical.length>0};
232
+ }
130
233
  export type JoinedProject = ReturnType<typeof joinProject>;
package/src/open.ts CHANGED
@@ -110,6 +110,8 @@ async function openRefusal(error:unknown,inputs:OpenInputs):Promise<unknown>{
110
110
  }
111
111
  async function verifyOpenLoad(p:OpenPackage,viewOnly:boolean,cwd=process.cwd()):Promise<void>{
112
112
  if(p.mode==='single'){
113
+ // A recorded pre-rig draft has a bound model for Stage 1 mesh mapping only.
114
+ if(p.joined?.draft)return;
113
115
  try{await verifyCompiledModel(p.p.root,p.p.manifest.model,p.selection?.name,p.p.manifest.sets);}
114
116
  catch(error){throw new Error(`OPEN_MODEL_UNAVAILABLE: ${error instanceof Error?error.message:String(error)}`,{cause:error});}
115
117
  const handoffReason=await verifyHandoffReadiness(p.p,[p.p.root,cwd],viewOnly);
package/src/parts-view.ts CHANGED
@@ -532,8 +532,9 @@ async function packageVersion(): Promise<string> {
532
532
  return (JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }).version;
533
533
  }
534
534
 
535
- /** Writes the verdict atomically beside its sources. */
536
- export async function saveVerdict(pkg: PartsViewPackage, input: unknown): Promise<PartsVerdict> {
535
+ /** Writes the verdict atomically at its designated destination. */
536
+ export async function saveVerdict(pkg: PartsViewPackage, input: unknown, assertCurrent?: () => Promise<void>): Promise<PartsVerdict> {
537
+ await assertCurrent?.();
537
538
  await assertVerdictDestination(pkg);
538
539
  await assertPartsUnchanged(pkg);
539
540
  await readVerdict(pkg); // Existing read-side evidence errors must never become an implicit reset.
@@ -545,6 +546,7 @@ export async function saveVerdict(pkg: PartsViewPackage, input: unknown): Promis
545
546
  try {
546
547
  await writeFile(tmp, JSON.stringify(verdict, null, 2) + '\n', { flag: 'wx' });
547
548
  await assertVerdictDestination(pkg);
549
+ await assertCurrent?.();
548
550
  await rename(tmp, pkg.verdictPath);
549
551
  } finally { await rm(tmp, { force: true }); }
550
552
  return verdict;
package/src/server.ts CHANGED
@@ -2,7 +2,7 @@ import { interviewHeaders, interviewRequest, interviewRoutes } from './interview
2
2
  import { directionStale, interviewUnavailable, interviewStale, type JoinedProject } from './joined-project.ts';
3
3
  import {isDeepStrictEqual} from 'node:util';
4
4
  import {appliedValue,parseCorrection,projectSessionCorrection} from './correction-handoff.ts';
5
- import {stagePartsRoutes} from './stage-parts.ts';
5
+ import {stagePartsRoutes,stageVerdictLimit} from './stage-parts.ts';
6
6
  import {createControlServer,type ControlIdentity} from './control-server.ts';
7
7
  import { readFile } from 'node:fs/promises';
8
8
  import { appRoot, buildWeb } from './build.ts';
@@ -39,13 +39,18 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
39
39
  const joined = options.joined;
40
40
  if (joined && !options.capability) throw new Error('Joined interview requires an instance capability');
41
41
  const interview = joined && interviewRoutes(joined.opened.root, joined.designation.picksDir, options.capability!,
42
- {...joined, sourceHash:p.sourceHash, version:joined.designation.version});
42
+ {...joined, sourceHash:p.sourceHash, version:joined.designation.version,draftId:joined.designation.draftId});
43
43
  let interviewBundle: Promise<Blob> | undefined;
44
44
  const bundle=await buildWeb();
45
45
  const unchanged=()=>assertReviewUnchanged(p);
46
46
  const stateDir=options.stateDir??process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review'),starts=[p.root,options.cwd??process.cwd()];
47
47
  const rebuilds=createRebuilds(p,{stateDir,starts,unchanged,bones:p.feedbackCatalog.bones,...(options.stripConcurrency?{stripConcurrency:options.stripConcurrency}:{}),...(options.viewOnly??p.viewOnly?{viewOnly:true}:{})});
48
- const stageParts=stagePartsRoutes({single:p},undefined,rebuilds.stageDraft);
48
+ const stageParts=stagePartsRoutes({single:p},undefined,rebuilds.stageDraft,joined?.draft?{
49
+ joined,viewOnly:options.viewOnly??p.viewOnly??false,readInput:async req=>{
50
+ try{return await bodyJson(req,stageVerdictLimit,'PARTS_VERDICT_BODY_LIMIT');}
51
+ catch(error){if(error instanceof Error&&error.message==='PARTS_VERDICT_BODY_LIMIT')throw error;throw new Error('PARTS_VERDICT_INVALID');}
52
+ },
53
+ }:undefined);
49
54
  // Readings (#108): rigc render's readings on the inspected build and on the latest scratch build, into scratch.
50
55
  const readings=createReadings(p,{stateDir,starts,unchanged,latest:rebuilds.latest});
51
56
  // Bones check (#109): propose --from-config and compare on a scratch copy of the patched handoff config.
@@ -100,6 +105,7 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
100
105
  const controlled=await control?.(req,origin);if(controlled)return controlled;
101
106
  options.activity?.();const gate=openGate(req,options.open);if(gate){if(gate.status===200){try{await unchanged();}catch{return staleOpenStatus(options.open!);}if(!live.rearmUnopened())return json({error:'Server is closing'},503);}return gate;}
102
107
  if(req.method==='PUT'&&url.pathname==='/api/session'){
108
+ if(joined?.draft)return json({error:'MODEL_UNAVAILABLE'},409);
103
109
  if(req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
104
110
  const input=await bodyJson(req);await unchanged();
105
111
  return json(await saveSession(p,input,options.stateDir,async(session,sessionBytes,previous)=>{
@@ -170,7 +176,7 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
170
176
  return new Response(result.png?new Uint8Array(result.png):stripJson(result),{headers:{...headers,'Content-Type':result.png?'image/png':'application/json; charset=utf-8','Content-Disposition':`attachment; filename="review-strip.${result.png?'png':'json'}"`}});
171
177
  }
172
178
  if(req.method!=='GET'&&req.method!=='HEAD')return json({error:'Method not allowed'},405);
173
- if(url.pathname==='/api/review'){await unchanged();return json({manifest:p.manifest,...(p.direction?{direction:p.direction}:{}),...(p.setsHash?{setsHash:p.setsHash}:{}),initialAnimation:options.initialAnimation??null,sourceHash:p.sourceHash,reviewedSource:p.reviewedSource,...(referenceBinding(p)?{referenceBinding:referenceBinding(p),explicitReference:{...referenceBinding(p)!.reference,url:'/review-reference'}}:{}),...(p.sourcePainting?{sourcePainting:{...p.sourcePainting,url:'/review-painting'}}:{}),referenceHashes:{...p.referenceHashes,...(referenceBinding(p)?{[referenceBinding(p)!.reference.id]:referenceBinding(p)!.reference.sha256}:{})},report:p.report,feedbackCatalog:p.feedbackCatalog,assetsBase:'/assets/',capabilities:{...(joined?.available?{interview:true}:{}),playback:!!p.manifest.model,modeling:false,motion:false,feedback:true,audio:true}});}
179
+ if(url.pathname==='/api/review'){await unchanged();return json({manifest:p.manifest,...(p.direction?{direction:p.direction}:{}),...(p.setsHash?{setsHash:p.setsHash}:{}),initialAnimation:options.initialAnimation??null,sourceHash:p.sourceHash,reviewedSource:p.reviewedSource,...(referenceBinding(p)?{referenceBinding:referenceBinding(p),explicitReference:{...referenceBinding(p)!.reference,url:'/review-reference'}}:{}),...(p.sourcePainting?{sourcePainting:{...p.sourcePainting,url:'/review-painting'}}:{}),referenceHashes:{...p.referenceHashes,...(referenceBinding(p)?{[referenceBinding(p)!.reference.id]:referenceBinding(p)!.reference.sha256}:{})},report:p.report,feedbackCatalog:p.feedbackCatalog,assetsBase:'/assets/',capabilities:{...(joined?.available?{interview:true}:{}),...(joined?.draft?{preRig:true}:{}),playback:!!p.manifest.model,modeling:false,motion:false,feedback:!joined?.draft,audio:true}});}
174
180
  if(url.pathname==='/api/session'){await unchanged();return json(await readSession(p,options.stateDir));}
175
181
  if(url.pathname==='/api/rebuild')return json(await rebuilds.describe());
176
182
  if(url.pathname==='/api/rebuild/history')return json(await rebuilds.history());
@@ -1,50 +1,80 @@
1
- /** Read-only embedding of the existing atlas inspector. No browser-supplied filesystem paths or verdict writes. */
1
+ /** Embedded parts inspector. Only the designated joined source can save a verdict. */
2
2
  import {join} from 'node:path';
3
- import {readFile} from 'node:fs/promises';
3
+ import {lstat,readFile} from 'node:fs/promises';
4
4
  import {appRoot,buildWeb} from './build.ts';
5
5
  import type {ReviewPackage} from './manifest.ts';
6
- import {loadPartsAtlas,loadPartsView,assertPartsUnchanged,partsViewJson,servedImage,type PartsViewPackage} from './parts-view.ts';
6
+ import {loadPartsAtlas,loadPartsView,assertPartsUnchanged,partsViewJson,servedImage,verdictSource,readVerdict,saveVerdict,exportPartsVerdict,type PartsViewPackage} from './parts-view.ts';
7
7
  import {serveReference,assertReviewUnchanged} from './reference.ts';
8
- export function stagePartsRoutes(packages:{single:ReviewPackage}|{a:ReviewPackage;b:ReviewPackage},loadAtlas:typeof loadPartsAtlas=loadPartsAtlas,draft?:DraftReader) {
8
+ import {digest,object} from './interview-project.ts';
9
+ import {interviewStale,type JoinedProject} from './joined-project.ts';
10
+
11
+ export const stageVerdictLimit=4*1024*1024;
12
+ export const stageVerdictRefusals=[
13
+ 'PARTS_VERDICT_READ_ONLY','PARTS_VERDICT_SOURCE_MISMATCH','PARTS_VERDICT_OUTPUT','PARTS_VERDICT_UNAVAILABLE',
14
+ 'PARTS_VERDICT_BODY_LIMIT','PARTS_VERDICT_READ','PARTS_VERDICT_INVALID','PARTS_VERDICT_UNKNOWN_PART',
15
+ 'PARTS_VERDICT_MISSING_PART','PARTS_VERDICT_NOTE_REQUIRED','PARTS_MESH_OUTCOME_UNAVAILABLE','PARTS_MESH_OUTCOME',
16
+ 'PARTS_VERDICT_NOT_CLEAN','PARTS_VERDICT_NOTHING_FLAGGED','PARTS_VIEW_SOURCE_CHANGED','PARTS_VERDICT_INPUT_COLLISION',
17
+ ] as const;
18
+ interface JoinedVerdictOptions {
19
+ joined:JoinedProject;
20
+ readInput:(req:Request)=>Promise<unknown>;
21
+ viewOnly:boolean;
22
+ }
23
+
24
+ export function stagePartsRoutes(packages:{single:ReviewPackage}|{a:ReviewPackage;b:ReviewPackage},loadAtlas:typeof loadPartsAtlas=loadPartsAtlas,draft?:DraftReader,verdictOptions?:JoinedVerdictOptions) {
9
25
  const corrections=new Map<string,Promise<{pkg:PartsViewPackage;metadata:unknown}>>();
10
26
  const loaded=new Map<string,ReturnType<typeof loadPartsAtlas>>();let bundle:Promise<Blob>|undefined;
11
27
  const headers={'X-Content-Type-Options':'nosniff','Cache-Control':'no-store','Referrer-Policy':'no-referrer','Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'"};
12
28
  return async(req:Request):Promise<Response|null>=>{
13
29
  const url=new URL(req.url),path=url.pathname,read=req.method==='GET'||req.method==='HEAD';
14
- if(!read)return null;
30
+ const save=path==='/api/stage-parts/verdict'&&req.method==='POST';
31
+ const format=read&&path==='/api/stage-parts/export/json'?'json':read&&path==='/api/stage-parts/export/issue'?'issue':null;
32
+ const verdictRequest=save||format!==null;
33
+ if(!read&&!save)return null;
34
+ if(save&&req.headers.get('origin')!==url.origin)return Response.json({error:'Same-origin Origin required'},{status:403,headers});
35
+ if(verdictRequest&&(!verdictOptions?.joined.verdictDirectory||verdictOptions.viewOnly||(req.headers.get('X-Review-Stage-Build')??'inspected')!=='inspected')){
36
+ return Response.json({error:'PARTS_VERDICT_READ_ONLY'},{status:409,headers});
37
+ }
15
38
  if(['/stage-parts.html','/parts.js','/parts.css'].includes(path)){
16
39
  if(path==='/parts.js'){bundle??=buildWeb('parts');return new Response(req.method==='HEAD'?null:await bundle,{headers:{...headers,'Content-Type':'text/javascript'}});}
17
40
  return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/'+(path==='/stage-parts.html'?'parts.html':'parts.css')),{headers:{...headers,'Content-Type':path.endsWith('.css')?'text/css':'text/html; charset=utf-8'}});
18
41
  }
19
- const match=('single' in packages?/^\/api\/stage-parts(?:\/(image|page)\/(\d+))?$/:/^\/api\/compare\/(a|b)\/stage-parts(?:\/(image|page)\/(\d+))?$/).exec(path);
42
+ const match=('single' in packages?/^\/api\/stage-parts(?:\/(image|page)\/(\d+))?$/:/^\/api\/compare\/(a|b)\/stage-parts(?:\/(image|page)\/(\d+))?$/).exec(verdictRequest?'/api/stage-parts':path);
20
43
  if(!match)return null;
21
44
  const key='single' in packages?'single':match[1] as 'a'|'b',p='single' in packages?packages.single:packages[key as 'a'|'b'];
22
45
  const kind=match['single' in packages?1:2] as 'image'|'page'|undefined,index=match['single' in packages?2:3];
23
46
  try{
24
47
  // Single-package Stage 1 uses the declared handoff's real separated parts, not the atlas names.
25
- if ('single' in packages && p.handoff?.parts && p.handoff.rig) {
48
+ const recorded=verdictOptions?.joined.draft;
49
+ if ('single' in packages && (recorded||p.handoff?.parts&&p.handoff.rig)) {
26
50
  await assertReviewUnchanged(p);
27
51
  const build=req.headers.get('X-Review-Stage-Build')??'inspected';
28
52
  if(build!=='inspected'&&!/^[a-f0-9]{64}$/.test(build))throw new Error('STAGE_DRAFT_STALE');
29
53
  const applied=build==='inspected'?null:await draft?.(build);
30
54
  if(build!=='inspected'&&!applied)throw new Error('STAGE_DRAFT_UNAVAILABLE');
31
- const model=applied?.model??(p.manifest.model?join(p.root,p.manifest.model):null);
55
+ const model=recorded?.model??applied?.model??(p.manifest.model?join(p.root,p.manifest.model):null);
32
56
  if(!model)throw new Error('STAGE_DRAFT_UNAVAILABLE');
33
57
  let promise=corrections.get(build);
34
58
  if(!promise){
35
59
  promise=(async()=>{
36
- const rig=join(applied?.spec??p.handoff!.rig!,'rig.json');
37
- const pkg=await loadPartsView(p.handoff!.parts!,{rig,meshReport:join(applied?.spec??p.handoff!.rig!,'mesh_report.json')});
38
- const mappings=await draftMappings(model,rig,pkg);
60
+ const rig=recorded?.rig??join(applied?.spec??p.handoff!.rig!,'rig.json');
61
+ const meshReport=recorded?.meshReport??join(applied?.spec??p.handoff!.rig!,'mesh_report.json');
62
+ const pkg=await loadPartsView(recorded?.parts??p.handoff!.parts!,{rig,meshReport});
63
+ if(recorded&&[...pkg.files,...pkg.flagFiles].some(file=>recorded.files.get(file.abs)!==file.sha256))
64
+ throw new Error('PARTS_VERDICT_SOURCE_MISMATCH');
65
+ const mappings=await draftMappings(model,rig,pkg,recorded?.files);
39
66
  await assertReviewUnchanged(p);await assertPartsUnchanged(pkg);
40
- return {pkg,metadata:mappings.length?{label:'Draft rig · structure evidence only',buildId:build,inspectionSourceHash:p.sourceHash,mappings,evidence:applied?.evidence??null}:null};
67
+ return {pkg,metadata:mappings.length?{label:'Draft rig · structure evidence only',buildId:build,inspectionSourceHash:p.sourceHash,mappings,evidence:applied?.evidence??null,...(recorded?{inspectionOnly:true}:{})}:null};
41
68
  })();corrections.set(build,promise);
42
69
  }
43
70
  const {pkg,metadata}=await promise;
44
71
  // Every image is served against the same full pinned draft, including geometry and flags.
45
72
  await assertReviewUnchanged(p);await assertPartsUnchanged(pkg);
46
73
  if(kind){const file=servedImage(pkg,kind,Number(index));if(!file)return Response.json({error:'PARTS_IMAGE_UNAVAILABLE'},{status:404,headers});const pinned=pkg.files.find(f=>f.abs===file)!;return serveReference(req,file,pinned.sha256,headers);}
47
- return Response.json({...partsViewJson(pkg,{verdict:null,stale:null}),differenceAvailable:false,readOnly:true,inspectionSourceHash:p.sourceHash,...(metadata?{draft:metadata}:{draftUnavailable:stageDraftRefusals.STAGE_DRAFT_NO_MESH})},{headers});
74
+ const writable=build==='inspected'&&verdictOptions?.joined.verdictDirectory&&!verdictOptions.viewOnly;
75
+ const saved=writable?await joinedVerdict(req,p,pkg,verdictOptions,save,format,headers):null;
76
+ if(saved instanceof Response)return saved;
77
+ return Response.json({...partsViewJson(pkg,saved??{verdict:null,stale:null}),differenceAvailable:false,readOnly:!writable,...(recorded&&!writable?{verdictReadOnlyReason:'PARTS_VERDICT_READ_ONLY: a pending parts review and an explicit verdict output directory are required.'}:{}),inspectionSourceHash:p.sourceHash,...(saved?{joinedVerdictBinding:saved.binding,verdictFile:saved.filename}:{}),...(metadata?{draft:metadata}:{draftUnavailable:stageDraftRefusals.STAGE_DRAFT_NO_MESH})},{headers});
48
78
  }
49
79
  let promise=loaded.get(key);
50
80
  const initializing=!promise;
@@ -59,8 +89,49 @@ export function stagePartsRoutes(packages:{single:ReviewPackage}|{a:ReviewPackag
59
89
  if(kind){const model=pkg.files[0]!;await serveReference(new Request(req.url,{method:'HEAD'}),model.abs,model.sha256,headers);}
60
90
  if(kind){const file=servedImage(pkg,kind,Number(index));if(!file)return Response.json({error:'PARTS_IMAGE_UNAVAILABLE'},{status:404,headers});const pinned=pkg.files.find(f=>f.abs===file);if(!pinned)throw new Error('Unbound atlas page');return await serveReference(req,file,pinned.sha256,headers);}
61
91
  return Response.json({...partsViewJson(pkg,{verdict:null,stale:null}),differenceAvailable:false,readOnly:true,inspectionSourceHash:p.sourceHash,draftUnavailable:stageDraftRefusals.STAGE_DRAFT_UNAVAILABLE},{headers});
62
- }catch(error){const code=error instanceof Error?error.message.split(':')[0]:'';const named=stageDraftRefusals[code??'']??(code==='PARTS_MESH_IMAGE_MISMATCH'?stageDraftRefusals.STAGE_DRAFT_MISMATCH:undefined);return Response.json({error:named??'PARTS_ATLAS_UNAVAILABLE: the inspected package has no usable atlas or its source changed.'},{status:409,headers});}
92
+ }catch(error){const code=error instanceof Error?error.message.split(':')[0]??'':'';
93
+ if((verdictRequest||verdictOptions)&& (code===interviewStale||stageVerdictRefusals.some(refusal=>refusal===code))){
94
+ const invalid=save&&!['PARTS_VERDICT_SOURCE_MISMATCH','PARTS_VERDICT_OUTPUT','PARTS_VERDICT_READ_ONLY','PARTS_VIEW_SOURCE_CHANGED',interviewStale].includes(code);
95
+ return Response.json({error:code},{status:invalid?400:409,headers});
96
+ }
97
+ const named=stageDraftRefusals[code??'']??(code==='PARTS_MESH_IMAGE_MISMATCH'?stageDraftRefusals.STAGE_DRAFT_MISMATCH:undefined);return Response.json({error:named??'PARTS_ATLAS_UNAVAILABLE: the inspected package has no usable atlas or its source changed.'},{status:409,headers});}
98
+ };
99
+ }
100
+
101
+ /** The output address and request binding share the exact joined and parts identities.
102
+ * Only the standard verdict is exported, with source paths relative to the file on disk.
103
+ */
104
+ async function joinedVerdict(req:Request,p:ReviewPackage,pkg:PartsViewPackage,options:JoinedVerdictOptions,
105
+ save:boolean,format:'json'|'issue'|null,headers:Record<string,string>){
106
+ const {joined}=options,{hash}=joined.opened,{version}=joined.designation;
107
+ const binding=digest(JSON.stringify({projectHash:hash,version,sourceHash:p.sourceHash,parts:verdictSource(pkg)}));
108
+ const filename=`parts-review-${binding}.json`;
109
+ const directory=joined.verdictDirectory!();
110
+ const destination={...pkg,verdictPath:join(directory,filename)};
111
+ const assertCurrent=async()=>{
112
+ await joined.assertCurrent();
113
+ await assertPartsUnchanged(pkg);
114
+ try{
115
+ joined.verdictDirectory!();
116
+ const entry=await lstat(destination.verdictPath).catch((e:NodeJS.ErrnoException)=>{if(e.code!=='ENOENT')throw e;return null;});
117
+ if(entry&&(!entry.isFile()||entry.nlink!==1))throw new Error('Aliased output');
118
+ }catch{throw new Error('PARTS_VERDICT_OUTPUT');}
63
119
  };
120
+ const input=save?object(await options.readInput(req)):null;
121
+ if(input&&input.binding!==binding)throw new Error('PARTS_VERDICT_SOURCE_MISMATCH');
122
+ // Pointed comments use the standalone crop endpoints. Joined sign-off exposes part and mesh notes.
123
+ if(input&&input.comments!==undefined)throw new Error('PARTS_VERDICT_INVALID');
124
+ await assertCurrent();
125
+ const saved=await readVerdict(destination);
126
+ if(saved.stale)throw new Error('PARTS_VERDICT_SOURCE_MISMATCH');
127
+ if(input)return Response.json({verdict:await saveVerdict(destination,input,assertCurrent)},{headers});
128
+ if(format){
129
+ if(!saved.verdict)throw new Error('PARTS_VERDICT_UNAVAILABLE');
130
+ return new Response(req.method==='HEAD'?null:exportPartsVerdict(saved.verdict,format),{headers:{...headers,
131
+ 'Content-Type':format==='json'?'application/json':'text/markdown; charset=utf-8',
132
+ 'Content-Disposition':`attachment; filename="${format==='json'?filename:filename.replace(/\.json$/,'.md')}"`}});
133
+ }
134
+ return {...saved,binding,filename};
64
135
  }
65
136
 
66
137
  export interface DraftSnapshot {id:string;spec:string;model:string;evidence:unknown}
@@ -79,8 +150,13 @@ export const stageDraftRefusals:Record<string,string>={
79
150
  /** Same names alone cannot bind a producer operation: exact skin/slot/attachment, raster crop and mesh arrays must agree.
80
151
  * Compiler UV decimals round-trip float32; compare the represented float32 values exactly, with no numeric tolerance.
81
152
  */
82
- async function draftMappings(modelPath:string,rigPath:string,pkg:PartsViewPackage){
83
- const model=JSON.parse(await readFile(modelPath,'utf8')),rig=JSON.parse(await readFile(rigPath,'utf8'));
153
+ async function draftMappings(modelPath:string,rigPath:string,pkg:PartsViewPackage,files?:ReadonlyMap<string,string>){
154
+ const parse=async(path:string)=>{
155
+ const bytes=await readFile(path);
156
+ if(files&&digest(bytes)!==files.get(path))throw new Error('PARTS_VERDICT_SOURCE_MISMATCH');
157
+ return JSON.parse(bytes.toString('utf8'));
158
+ };
159
+ const [model,rig]=await Promise.all([parse(modelPath),parse(rigPath)]);
84
160
  const mappings:{part:string;skin:string;slot:string;attachment:string;vertices:number;triangles:number}[]=[];
85
161
  for(const item of pkg.items){
86
162
  if(!item.mesh)continue;
package/web/catalog-en.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  export const enCatalog: Readonly<Record<string, string>> = {
2
+ "RIG_VERSION_UNAVAILABLE: this draft has no recorded rig review package.": "RIG_VERSION_UNAVAILABLE: this draft has no recorded rig review package.",
3
+ "DIRECTION_VERSION_UNAVAILABLE: this draft has no recorded rig review package.": "DIRECTION_VERSION_UNAVAILABLE: this draft has no recorded rig review package.",
4
+ "PARTS_VERDICT_READ_ONLY: a pending parts review and an explicit verdict output directory are required.": "PARTS_VERDICT_READ_ONLY: a pending parts review and an explicit verdict output directory are required.",
2
5
  "INTERVIEW_OPTIONS_STALE": "INTERVIEW_OPTIONS_STALE: Project or source changed. Reopen the inspection.",
6
+ "interview.joinedDraft": "Draft {0} · project {1} · source {2}",
3
7
  "interview.joined": "Create version {0} · project SHA-256 {1} · inspection SHA-256 {2}",
4
8
  "interview.mismatch": "INTERVIEW_SOURCE_MISMATCH: The inspection does not match the designated Create package.",
5
9
  "interview.imageUnavailable": "INTERVIEW_IMAGE_INVALID: The bound image could not be displayed.",
package/web/catalog-ko.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  export const koCatalog: Readonly<Record<string, string>> = {
2
+ "RIG_VERSION_UNAVAILABLE: this draft has no recorded rig review package.": "RIG_VERSION_UNAVAILABLE: 이 초안에는 기록된 리그 검토 패키지가 없습니다.",
3
+ "DIRECTION_VERSION_UNAVAILABLE: this draft has no recorded rig review package.": "DIRECTION_VERSION_UNAVAILABLE: 이 초안에는 기록된 리그 검토 패키지가 없습니다.",
4
+ "PARTS_VERDICT_READ_ONLY: a pending parts review and an explicit verdict output directory are required.": "PARTS_VERDICT_READ_ONLY: 대기 중인 파츠 검토와 명시적으로 지정한 판정 출력 디렉터리가 필요합니다.",
2
5
  "INTERVIEW_OPTIONS_STALE": "INTERVIEW_OPTIONS_STALE: 프로젝트 또는 원본이 바뀌었어요. 검토를 다시 여세요.",
6
+ "interview.joinedDraft": "초안 {0} · 프로젝트 {1} · 원본 {2}",
3
7
  "interview.joined": "Create 버전 {0} · 프로젝트 SHA-256 {1} · 검토 SHA-256 {2}",
4
8
  "interview.mismatch": "INTERVIEW_SOURCE_MISMATCH: 검토 대상이 지정한 Create 패키지와 일치하지 않아요.",
5
9
  "interview.imageUnavailable": "INTERVIEW_IMAGE_INVALID: 바인딩된 이미지를 표시할 수 없습니다.",
@@ -33,7 +33,7 @@ async function request(access: InstanceAccess, path: string, body?: Picks) {
33
33
  }
34
34
 
35
35
  export async function mountInterview(host: HTMLElement, access: InstanceAccess) {
36
- let data: {questions:Question[];historical:HistoricalInterview[]; binding?:{projectHash:string;sourceHash:string;version:number}};
36
+ let data: {questions:Question[];historical:HistoricalInterview[]; binding?:{projectHash:string;sourceHash:string;version?:number;draftId?:string}};
37
37
  try {data = await request(access, '/api/interview');}
38
38
  catch (error) {
39
39
  const render = () => {host.textContent = t(errorKey(error));};
@@ -53,7 +53,7 @@ export async function mountInterview(host: HTMLElement, access: InstanceAccess)
53
53
  let busy = false;
54
54
  const render = () => {
55
55
  const joined = data.binding;
56
- const source = joined ? element('p', t('interview.joined', [String(joined.version), joined.projectHash, joined.sourceHash])) : null;
56
+ const source = joined ? element('p', t(joined.draftId===undefined?'interview.joined':'interview.joinedDraft', [joined.draftId??String(joined.version), joined.projectHash, joined.sourceHash])) : null;
57
57
  if (source) source.className = 'interview-binding';
58
58
  const archive = element('details');
59
59
  archive.append(element('summary', t('interview.legacy')));
package/web/main.ts CHANGED
@@ -73,7 +73,7 @@ import {assertRigFieldOps,RIG_FIELDS_READOUT_BARS,TURN_BONE} from '../src/rig-fi
73
73
  import {IDLE_READOUT_BARS,type LocalChannel} from '../src/idle-tracks.ts';
74
74
  import type {PatchOp} from '../src/config-patch.ts';
75
75
 
76
- interface ReviewResponse { direction?:DirectionInspection; setsHash?:string; referenceHashes?:Record<string,string>; initialAnimation?:string|null; manifest: ReviewManifest; referenceBinding?:ReferenceBinding; explicitReference?:{id:string;name:string;sha256:string;url:string}; sourcePainting?:{id:string;path:string;sha256:string;url:string}; sourceHash: string; reviewedSource: ReviewedSource; report: ReportSeeds | null; feedbackCatalog: FeedbackCatalog; assetsBase: string; capabilities: { interview?:true; playback: boolean; modeling: false; motion: false; feedback: boolean; audio: boolean } }
76
+ interface ReviewResponse { direction?:DirectionInspection; setsHash?:string; referenceHashes?:Record<string,string>; initialAnimation?:string|null; manifest: ReviewManifest; referenceBinding?:ReferenceBinding; explicitReference?:{id:string;name:string;sha256:string;url:string}; sourcePainting?:{id:string;path:string;sha256:string;url:string}; sourceHash: string; reviewedSource: ReviewedSource; report: ReportSeeds | null; feedbackCatalog: FeedbackCatalog; assetsBase: string; capabilities: { interview?:true; preRig?:true; playback: boolean; modeling: false; motion: false; feedback: boolean; audio: boolean } }
77
77
  interface PoseReference { schema: 'rig-review-pose/1'; coordinateSystem: 'image-pixels-y-down'; width: number; height: number; joints: { id: string; x: number; y: number; parent?: string }[] }
78
78
  interface SequenceJoint { state: 'observed' | 'occluded' | 'missing' | 'inferred'; at?: [number, number]; score?: number }
79
79
  interface PoseSequence { spec: 'rig-pose-sequence/1'; space: { units: 'picture-px'; origin: 'top-left'; y: 'down' }; width: number; height: number; source?: string; frames: { t: number; people: { id: string; joints: Record<string, SequenceJoint> }[] }[]; camera?: { s: number; tx: number; ty: number; inliers: number }[]; cameraSource?: unknown }
@@ -986,7 +986,7 @@ function bind(): void {
986
986
  const picker=select('part-set');picker.value=name;picker.dispatchEvent(new Event('change',{bubbles:true}));
987
987
  });
988
988
  viewDisposers.push(()=>directionPanel?.dispose());
989
- viewDisposers.push(bindStageNav({access,interview:data.capabilities.interview,model:!!data.manifest.model,direction:active=>directionPanel?.show(active),setup:()=>showInspector('rig'),draftBuild:()=>appliedOnStage?.buildId??'inspected',correction:openStageCorrection}));
989
+ viewDisposers.push(bindStageNav({access,interview:data.capabilities.interview,preRig:data.capabilities.preRig,model:!!data.manifest.model,direction:active=>directionPanel?.show(active),setup:()=>showInspector('rig'),draftBuild:()=>appliedOnStage?.buildId??'inspected',correction:data.capabilities.preRig?undefined:openStageCorrection}));
990
990
  workspace=bindWorkspaceUI({changed:fitCamera,defaultTheme:theme=>appearance?.set(theme),currentTheme:()=>appearance?.get()});
991
991
  viewport.state.cameraSync=workspace.defaults().defaultCameraSync;input('camera-sync').checked=viewport.state.cameraSync;input('idle-repeat').checked=workspace.defaults().defaultIdleRepeat;
992
992
  appearance=bindAppearance(select('settings-theme'),workspace.defaults().theme);
@@ -1052,6 +1052,7 @@ async function start(): Promise<void> {
1052
1052
  let writes: { capabilityRequired: boolean; control?: boolean };
1053
1053
  [data, session, writes] = await Promise.all([api<ReviewResponse>('/api/review'), api<ReviewSession>('/api/session'), api<{ capabilityRequired: boolean; control?: boolean }>('/api/access')]);
1054
1054
  readOnly = readOnlyReason(access, writes.capabilityRequired);
1055
+ if(data.capabilities.preRig)el('write-review').hidden=true;
1055
1056
  submittedBaseline=structuredClone(session);
1056
1057
  text('package-title', data.manifest.title); text('revision', data.manifest.revision); document.title = `${data.manifest.title} · rig review`; text('source-hash', `source ${data.sourceHash.slice(0, 12)}`); select('review-status').value = session.status; select('feedback-target-kind').value = 'rig'; input('feedback-target-name').value = data.manifest.id;
1057
1058
  select('reference-select').replaceChildren(); for (const reference of data.manifest.references) select('reference-select').append(option(reference.id, `${reference.label} · ${reference.type}`));
package/web/parts.css CHANGED
@@ -50,6 +50,7 @@ h2{font-size:11px;letter-spacing:.06em;color:var(--muted);margin:4px 0 8px}
50
50
  #pv-flags summary{cursor:pointer;font-size:11px;color:var(--muted)}
51
51
  #pv-flags li.pv-none{border-left-color:var(--line);background:none;color:var(--muted)}
52
52
  .pv-verdict{margin-top:16px;display:flex;flex-direction:column;gap:6px}
53
+ #pv-save-status{overflow-wrap:anywhere}
53
54
  .pv-outcomes{display:flex;gap:10px}
54
55
  .pv-label{font-size:11px;color:var(--muted);margin-top:4px}
55
56
  textarea,select{font:inherit;color:inherit;background:var(--bg);border:1px solid var(--line);border-radius:5px;padding:4px}
package/web/parts.ts CHANGED
@@ -30,7 +30,9 @@ type Flag =
30
30
  | { id: string; item: string; source: 'check'; kind: 'check'; path: string; line: string; root: string; status: string | null; entry: Record<string, unknown>; classification?: 'part' | 'pair' | 'evidence' | 'unclassified' };
31
31
  interface ViewData {
32
32
  inspectionSourceHash?:string;
33
- draft?:{label:string;buildId:string;inspectionSourceHash:string;mappings:{part:string;skin:string;slot:string;attachment:string;vertices:number;triangles:number}[];evidence:unknown};draftUnavailable?:string;
33
+ joinedVerdictBinding?:string;
34
+ verdictReadOnlyReason?:string;
35
+ draft?:{inspectionOnly?:boolean;label:string;buildId:string;inspectionSourceHash:string;mappings:{part:string;skin:string;slot:string;attachment:string;vertices:number;triangles:number}[];evidence:unknown};draftUnavailable?:string;
34
36
  differenceAvailable?:boolean;painting:{sha256:string;width:number;height:number}|null;sourceHash:string;mode: 'parts' | 'atlas'; title: string; rigSize: [number, number] | null; items: Item[]; pages: Page[]; flags: Flag[]; readings?: Flag[];
35
37
  flagSources: string[]; flagMissing: string[]; verdictFile: string;
36
38
  verdict: { comments?:PartsComment[];status: string; parts: Record<string, Entry> } | null; verdictStale: 'files' | 'flags' | null;
@@ -320,7 +322,7 @@ function renderMesh(): void {
320
322
  }
321
323
  panel.append(figures);
322
324
  const help = document.createElement('p'); help.textContent = t('Pink: art pixels outside every triangle.'); panel.append(help);
323
- if(stageEmbedded){document.querySelector('.pv-verdict')!.before(panel);return;}
325
+ if(stageEmbedded&&!state.data?.joinedVerdictBinding){document.querySelector('.pv-verdict')!.before(panel);return;}
324
326
  const entry = state.verdict.get(item.name)!;
325
327
  const select = document.createElement('select'); select.setAttribute('aria-label', t('Mesh outcome'));
326
328
  for (const [value, label] of [['pending', 'Pending'], ['clean', 'Clean'], ['flagged', 'Flagged']]) { const option = document.createElement('option'); option.value = value!; option.textContent = t(label!); select.append(option); }
@@ -384,13 +386,21 @@ async function approveAll(): Promise<void> {
384
386
  }
385
387
 
386
388
  async function save(): Promise<void> {
387
- if(stageEmbedded)return;
388
- const status = $('pv-save-status');
389
- const body = { status: $<HTMLSelectElement>('pv-overall').value, parts: Object.fromEntries(state.verdict),comments };
390
- const res = await fetch(access.route('/api/parts/verdict'), { method: 'POST', headers: access.headers({ 'Content-Type': 'application/json' }), body: JSON.stringify(body) });
391
- const out = await res.json() as { error?: string; verdict?: { source: { sha256: string } } };
392
- status.textContent = res.ok ? t('Saved {file}: source {hash}.', { file: state.data!.verdictFile, hash: out.verdict!.source.sha256.slice(0, 12) }) : out.error ?? t('Save failed.');
393
- status.dataset.result = res.ok ? 'saved' : 'refused';
389
+ const data=state.data;
390
+ if(!data||stageEmbedded&&(!data.joinedVerdictBinding||!access.capability||stageBuild!=='inspected'))return;
391
+ const status = $('pv-save-status'),button=$<HTMLButtonElement>('pv-save');
392
+ const body = { status: $<HTMLSelectElement>('pv-overall').value, parts: Object.fromEntries(state.verdict),
393
+ ...(stageEmbedded?{binding:data.joinedVerdictBinding}:{comments}) };
394
+ button.disabled=true;
395
+ try{
396
+ const headers=stageEmbedded?stageHeaders():access.headers();headers.set('Content-Type','application/json');
397
+ const res = await fetch(access.route(stageEmbedded?partsApi+'/verdict':'/api/parts/verdict'), { method: 'POST', headers, body: JSON.stringify(body) });
398
+ const out = await res.json() as { error?: string; verdict?: { source: { sha256: string } } };
399
+ status.textContent = res.ok ? t('Saved {file}: source {hash}.', { file: data.verdictFile, hash: out.verdict!.source.sha256.slice(0, 12) }) : out.error ? t(out.error) : t('Save failed.');
400
+ status.dataset.result = res.ok ? 'saved' : 'refused';
401
+ }catch{
402
+ status.textContent=t('Save failed.');status.dataset.result='refused';
403
+ }finally{button.disabled=false;}
394
404
  }
395
405
 
396
406
  async function boot(): Promise<void> {
@@ -405,7 +415,7 @@ async function boot(): Promise<void> {
405
415
  document.querySelector<HTMLElement>('.pv-layout')!.hidden=true;
406
416
  document.querySelector<HTMLElement>('.pv-verdict')!.hidden=true;
407
417
  const approveButton=$<HTMLButtonElement>('pv-approve-all');approveButton.disabled=true;
408
- const saveButton=$<HTMLButtonElement>('pv-save');saveButton.disabled=true;saveButton.title=t('Embedded atlas inspection is read-only. Use the parts command for a separate sign-off.');
418
+ const saveButton=$<HTMLButtonElement>('pv-save');saveButton.disabled=true;
409
419
  }
410
420
  window.addEventListener('message',event=>{if(event.source!==parent||event.origin!==location.origin||event.data?.type!=='review-stage-language'||!['en','ko'].includes(event.data.language))return;setLinkLanguage(null);setLanguagePreference(event.data.language);});
411
421
  connectLiveWindow(access);
@@ -414,6 +424,14 @@ async function boot(): Promise<void> {
414
424
  const data = await res.json() as ViewData & { error?: string };
415
425
  if (!res.ok) { const status=$('pv-load');status.textContent=t(data.error??'Load failed.');status.dataset.result='refused';return; }
416
426
  state.data = data;if(!data.differenceAvailable)document.querySelector('[data-pv-comparison="difference"]')?.remove();if(stageEmbedded)for(const item of data.items)if(item.mesh)state.meshShown.add(item.name);$('reference-empty').textContent=data.painting?'':t('PARTS_REFERENCE_UNAVAILABLE: supply --painting to compare the original painting');$('reference-empty').hidden=!!data.painting;if(data.painting)viewport.state.cameraSync=true;comments.push(...data.verdict?.comments??[]);setupPartsComments();viewport.bindNavigation(undefined,()=>!commentUi?.active());viewport.observeResize();
427
+ if(stageEmbedded&&data.joinedVerdictBinding){
428
+ document.querySelector<HTMLElement>('.pv-verdict')!.hidden=false;
429
+ $('pv-approve-all').hidden=true;
430
+ $('pv-comment-count').hidden=true;
431
+ const save=$<HTMLButtonElement>('pv-save');
432
+ save.disabled=!access.capability;
433
+ if(!access.capability)save.title=t('Read-only view: reopen with rig-review open to edit.');
434
+ }
417
435
  document.getElementById('parts-correction-hint')!.hidden = data.mode !== 'parts' || stageEmbedded;
418
436
  for (const item of data.items) state.verdict.set(item.name, { outcome: 'pending', note: '', ...(item.mesh ? { mesh: { outcome: 'pending' as Outcome, note: '' } } : {}) });
419
437
  if (data.verdict) { for (const [name, v] of Object.entries(data.verdict.parts)) if (state.verdict.has(name)) state.verdict.set(name, { outcome: v.outcome, note: v.note ?? '', ...(v.mesh ? { mesh: v.mesh } : {}) }); $<HTMLSelectElement>('pv-overall').value = data.verdict.status; }
@@ -421,7 +439,7 @@ async function boot(): Promise<void> {
421
439
  $('pv-title').textContent = data.title;
422
440
  $('pv-mode').textContent = data.mode === 'parts' ? t('Parts package, before rigging') : t('Atlas of a built rig');
423
441
  $('pv-list-title').textContent = data.mode === 'parts' ? t('PARTS') : t('REGIONS');
424
- $('pv-load').textContent = data.verdictStale === 'files' ? t('A saved sign-off was made on other files; this review starts fresh.') : data.verdictStale === 'flags' ? t('The saved sign-off is for different producer flags; this review starts fresh.') : data.verdict ? t('Saved sign-off loaded.') : '';
442
+ $('pv-load').textContent = data.verdictStale === 'files' ? t('A saved sign-off was made on other files; this review starts fresh.') : data.verdictStale === 'flags' ? t('The saved sign-off is for different producer flags; this review starts fresh.') : data.verdict ? t('Saved sign-off loaded.') : data.verdictReadOnlyReason?t(data.verdictReadOnlyReason):'';
425
443
  if(stageEmbedded){$('pv-load').hidden=$('pv-load').textContent==='';document.querySelector<HTMLElement>('.pv-layout')!.hidden=false;}
426
444
  $('pv-atlas-switch').hidden = data.mode !== 'atlas';
427
445
  const assemble=$<HTMLButtonElement>('pv-assemble');assemble.disabled=data.mode!=='parts'||!data.rigSize;assemble.title=assemble.disabled?t(data.mode==='atlas'?'Assembly unavailable: atlas regions carry no rig placement.':'Assembly unavailable: rig_size is not declared.'):'';
@@ -453,7 +471,7 @@ async function boot(): Promise<void> {
453
471
  $<HTMLTextAreaElement>('pv-note').oninput = e => updateEntry({ note: (e.target as HTMLTextAreaElement).value });
454
472
  $('pv-save').onclick = () => { void save(); };
455
473
  $('pv-approve-all').onclick = () => approveAll();
456
- for(const format of ['json','issue'])$('pv-export-'+format).onclick=async()=>{const res=await fetch(access.route('/api/parts/export?format='+format),{headers:access.headers()});const value=await res.text();if(!res.ok){$('pv-save-status').textContent=value;return;}const url=URL.createObjectURL(new Blob([value],{type:format==='json'?'application/json':'text/markdown'})),a=document.createElement('a');a.href=url;a.download=format==='json'?'parts-review-export.json':'parts-review-export.md';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
474
+ for(const format of ['json','issue'])$('pv-export-'+format).onclick=async()=>{const res=await fetch(access.route(stageEmbedded?partsApi+'/export/'+format:'/api/parts/export?format='+format),{headers:stageHeaders()});const value=await res.text();if(!res.ok){$('pv-save-status').textContent=JSON.parse(value).error??t('Save failed.');return;}const url=URL.createObjectURL(new Blob([value],{type:format==='json'?'application/json':'text/markdown'})),a=document.createElement('a');a.href=url;a.download=stageEmbedded?(format==='json'?data.verdictFile:data.verdictFile.replace(/\.json$/,'.md')):format==='json'?'parts-review-export.json':'parts-review-export.md';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
457
475
  onLanguageChange(() => { if (state.data) select(state.selected); });
458
476
  if(stageEmbedded)(window as StagePartsWindow).rigReviewStageParts={snapshot:stagePartsSnapshot};
459
477
  if(data.items.length){if(stageRestore)await restoreStageParts(stageRestore);else select(0);}
@@ -499,6 +517,7 @@ function renderCorrections():void {
499
517
  const label=document.createElement('p');label.textContent=t(data?.draft&&!mapping?'STAGE_DRAFT_NO_MESH: this part has no mesh attachment; direct correction is unavailable.':data?.draft?.label??data?.draftUnavailable??'STAGE_DRAFT_UNAVAILABLE: no producer-compatible draft is supplied.');host.append(label);
500
518
  if(!mapping||!data?.draft)return;
501
519
  label.textContent+=` · ${mapping.part} · ${mapping.skin}/${mapping.slot}/${mapping.attachment} · v ${mapping.vertices} t ${mapping.triangles} · ${data.draft.buildId}`;
520
+ if(data.draft.inspectionOnly)return;
502
521
  for(const [instrument,title,operation]of [['chest','Chest regions',t('rig-parts remesh --mesh')],['mesh','Mesh parameters',t('rig-parts remesh --mesh')],['delta','Edit Mesh',t('rig-parts remesh --delta')]]){
503
522
  const button=document.createElement('button');button.type='button';button.textContent=t(title!);button.title=`${mapping.part} · ${operation}`;button.onclick=()=>parent.postMessage({type:'review-stage-correction',part:mapping.part,sourceHash:data.sourceHash,buildId:data.draft!.buildId,instrument},location.origin);host.append(button);
504
523
  }
@@ -524,5 +543,5 @@ if(typeof window!=='undefined')window.addEventListener('message',event=>{if(even
524
543
 
525
544
  if(typeof window!=='undefined')window.addEventListener('message',event=>{if(event.source!==parent||event.origin!==location.origin||event.data?.type!=='review-stage-revalidate')return;void (async()=>{
526
545
  try{const response=await fetch(access.route(partsApi),{headers:stageHeaders()}),data=await response.json() as ViewData&{error?:string};if(!response.ok||data.sourceHash!==state.data?.sourceHash)throw new Error(data.error??'STAGE_DRAFT_MISMATCH: separated parts and draft mesh identity differ.');if(event.data.state)await restoreStageParts(event.data.state);}
527
- catch(error){const status=$('pv-load');status.hidden=false;status.dataset.result='refused';status.textContent=t(error instanceof Error?error.message:String(error));document.querySelector<HTMLElement>('.pv-layout')!.hidden=true;}
546
+ catch(error){document.querySelector<HTMLElement>('.pv-verdict')!.hidden=true;if(state.data)delete state.data.joinedVerdictBinding;const status=$('pv-load');status.hidden=false;status.dataset.result='refused';status.textContent=t(error instanceof Error?error.message:String(error));document.querySelector<HTMLElement>('.pv-layout')!.hidden=true;}
528
547
  })();});
package/web/stage-nav.ts CHANGED
@@ -17,13 +17,15 @@ export function stagePartsSelectionIndex(data:{inspectionSourceHash?:string;item
17
17
  if(i<0||data.inspectionSourceHash!==saved.inspectionSourceHash||!m||(['skin','slot','attachment']as const).some(k=>m[k]!==saved.mapping[k]))throw new Error('STAGE_DRAFT_MISMATCH');
18
18
  return i;
19
19
  }
20
- export function stageReason(stage:ReviewStage,model:boolean,direction=false,interview=false):string|null {
20
+ export function stageReason(stage:ReviewStage,model:boolean,direction=false,interview=false,preRig=false):string|null {
21
21
  if(stage===2&&!interview)return 'INTERVIEW_UNAVAILABLE: No interview is attached to this inspection.';
22
+ if(preRig&&stage===3)return 'RIG_VERSION_UNAVAILABLE: this draft has no recorded rig review package.';
23
+ if(preRig&&stage===4)return 'DIRECTION_VERSION_UNAVAILABLE: this draft has no recorded rig review package.';
22
24
  if(stage===4&&!direction)return 'DIRECTION_UNAVAILABLE: no direction inspection contract is installed.';
23
25
  if(stage===3&&!model)return 'MODEL_UNAVAILABLE: no compiled model is supplied in this inspection.';
24
26
  return null;
25
27
  }
26
- export function bindStageNav(options:{interviewOnly?:boolean;interview?:boolean;access?:InstanceAccess;partsOnly?:boolean;model:boolean;direction?:(active:boolean)=>void;side?:()=> 'a'|'b';setup?:()=>void;draftBuild?:()=>string;correction?:(request:{part:string;sourceHash:string;buildId:string;instrument:string})=>Promise<void>}):()=>void {
28
+ export function bindStageNav(options:{preRig?:boolean;interviewOnly?:boolean;interview?:boolean;access?:InstanceAccess;partsOnly?:boolean;model:boolean;direction?:(active:boolean)=>void;side?:()=> 'a'|'b';setup?:()=>void;draftBuild?:()=>string;correction?:(request:{part:string;sourceHash:string;buildId:string;instrument:string})=>Promise<void>}):()=>void {
27
29
  const host=document.querySelector<HTMLElement>('[data-stage-nav]');if(!host)return ()=>{};
28
30
  if(options.interviewOnly){
29
31
  const button=document.createElement('button');button.type='button';button.dataset.reviewStage='2';button.setAttribute('aria-current','step');host.append(button);
@@ -37,13 +39,13 @@ export function bindStageNav(options:{interviewOnly?:boolean;interview?:boolean;
37
39
  const status=document.createElement('p');status.setAttribute('role','status');panel.append(status);
38
40
  let interview:HTMLIFrameElement|undefined,interviewError:string|null=null,entry=0;
39
41
  const sourcePicker=document.getElementById('mode-build-picker');
40
- const frames=new Map<string,HTMLIFrameElement>();let lastFrame:HTMLIFrameElement|null=null;let current:ReviewStage=options.partsOnly?1:3;
42
+ const frames=new Map<string,HTMLIFrameElement>();let lastFrame:HTMLIFrameElement|null=null;let current:ReviewStage=(options.partsOnly||options.preRig)?1:3;
41
43
  const workspace=document.querySelector<HTMLElement>(options.partsOnly?'.pv-layout':'.layout');const wasInert=workspace?.inert??false;
42
44
  const buttons=reviewStages.map((label,index)=>{const button=document.createElement('button');button.type='button';button.dataset.reviewStage=String(index+1);button.onclick=()=>show(index+1 as ReviewStage);host.append(button);return button;});
43
45
  const mesh=document.createElement('button');mesh.type='button';mesh.onclick=()=>{show(3);options.setup?.();};panel.append(mesh);
44
46
  const render=()=>{buttons.forEach((b,i)=>{b.textContent=t(reviewStages[i]!);b.setAttribute('aria-current',current===i+1?'step':'false');});host.setAttribute('aria-label',t('Inspection stages'));if(sourcePicker)sourcePicker.setAttribute('aria-label',t(current===1?'Atlas source build':'Picked build for Setup and Animate'));mesh.textContent=t('Open setup mesh instruments');};
45
47
  const place=()=>{panel.style.top=`${(host.closest('header')??host).getBoundingClientRect().bottom}px`;};
46
- const reasonFor=(stage:ReviewStage)=>stageReason(stage,options.model,!!options.direction,!!options.interview);
48
+ const reasonFor=(stage:ReviewStage)=>stageReason(stage,options.model,!!options.direction,!!options.interview,options.preRig);
47
49
  const setFrameLanguage=(frame:HTMLIFrameElement)=>frame.contentWindow?.postMessage({type:'review-stage-language',language:getLanguage()},location.origin);
48
50
  async function showInterview(revision:number) {
49
51
  try {
@@ -70,9 +72,9 @@ export function bindStageNav(options:{interviewOnly?:boolean;interview?:boolean;
70
72
  function show(stage:ReviewStage):void {
71
73
  current=stage;document.documentElement.dataset.inspectionStage=String(stage);render();place();const reason=reasonFor(stage);const revision=++entry;interviewError=null;
72
74
  options.direction?.(stage===4);
73
- panel.hidden=!reason&&(stage===(options.partsOnly?1:3)||stage===4);
75
+ panel.hidden=!reason&&(stage===(options.partsOnly?1:3)||stage===4)&&!options.preRig;
74
76
  if(workspace)workspace.inert=!panel.hidden||wasInert;
75
- status.textContent=reason?t(reason):stage===1&&!options.partsOnly?t(options.correction?'Draft rig · structure evidence only':'Atlas inspection, read only — inspected package. Applied scratch atlas, pre-rig parts, mesh sign-off and draft corrections are unavailable here.'):'';mesh.hidden=stage!==1||!options.model||!!options.partsOnly;
77
+ status.textContent=reason?t(reason):stage===1&&!options.partsOnly?t(options.correction||options.preRig?'Draft rig · structure evidence only':'Atlas inspection, read only — inspected package. Applied scratch atlas, pre-rig parts, mesh sign-off and draft corrections are unavailable here.'):'';mesh.hidden=stage!==1||!options.model||!!options.partsOnly;
76
78
  for(const frame of frames.values())frame.hidden=true;
77
79
  if(interview)interview.hidden=true;
78
80
  panel.classList.remove('with-interview');
@@ -80,7 +82,7 @@ export function bindStageNav(options:{interviewOnly?:boolean;interview?:boolean;
80
82
  if(stage===2&&!reason){status.textContent=t('interview.loading');void showInterview(revision);}
81
83
  }
82
84
  function showParts(){
83
- const saved=(lastFrame?.contentWindow as StagePartsWindow|null)?.rigReviewStageParts?.snapshot()??null;const side=options.side?.(),key=(side??'single')+':'+(options.draftBuild?.()??'inspected');let frame=frames.get(key);if(!frame){if(options.correction){for(const old of frames.values())old.remove();frames.clear();}frame=document.createElement('iframe');frame.title=t('Parts and atlas inspection');frame.src=access.route('/stage-parts.html')+'?stageEmbed=1&lang='+getLanguage()+(side?'&side='+side:'');frame.addEventListener('load',()=>{frame!.contentWindow?.postMessage({type:'review-stage-language',language:getLanguage()},location.origin);frame!.contentWindow?.postMessage({type:'review-stage-source',buildId:options.draftBuild?.()??'inspected',state:saved},location.origin);});frames.set(key,frame);panel.append(frame);}else if(options.correction){frame.contentWindow?.postMessage({type:'review-stage-revalidate',state:lastFrame!==frame?saved:null},location.origin);}frame.hidden=false;lastFrame=frame;
85
+ const saved=(lastFrame?.contentWindow as StagePartsWindow|null)?.rigReviewStageParts?.snapshot()??null;const side=options.side?.(),key=(side??'single')+':'+(options.draftBuild?.()??'inspected');let frame=frames.get(key);if(!frame){if(options.correction){for(const old of frames.values())old.remove();frames.clear();}frame=document.createElement('iframe');frame.title=t('Parts and atlas inspection');frame.src=access.route('/stage-parts.html')+'?stageEmbed=1&lang='+getLanguage()+(side?'&side='+side:'');frame.addEventListener('load',()=>{frame!.contentWindow?.postMessage({type:'review-stage-language',language:getLanguage()},location.origin);frame!.contentWindow?.postMessage({type:'review-stage-source',buildId:options.draftBuild?.()??'inspected',state:saved},location.origin);});frames.set(key,frame);panel.append(frame);}else if(options.correction||options.preRig){frame.contentWindow?.postMessage({type:'review-stage-revalidate',state:lastFrame!==frame?saved:null},location.origin);}frame.hidden=false;lastFrame=frame;
84
86
  }
85
87
  const correction=async(event:MessageEvent)=>{if(event.origin!==location.origin||![...frames.values()].some(f=>f.contentWindow===event.source)||event.data?.type!=='review-stage-correction'||!options.correction)return;const r=event.data;if(typeof r.part!=='string'||typeof r.sourceHash!=='string'||typeof r.buildId!=='string'||!['chest','mesh','delta'].includes(r.instrument))return;try{await options.correction(r);show(3);}catch(error){status.textContent=error instanceof Error?error.message:String(error);}};
86
88
  window.addEventListener('message',correction);
@@ -91,9 +93,9 @@ export function bindStageNav(options:{interviewOnly?:boolean;interview?:boolean;
91
93
  const sourceChanged=()=>{if(current!==1)return;pickingSource=true;show(1);queueMicrotask(()=>{pickingSource=false;});};
92
94
  sourcePicker?.querySelectorAll('[data-build-side]').forEach(button=>button.addEventListener('click',sourceChanged));
93
95
  // Legacy bookmark/control restoration writes these canonical attributes even when a mode is unchanged.
94
- const canonical=new MutationObserver(()=>{if(current!==3&&!options.partsOnly&&!pickingSource)show(3);});
96
+ const canonical=new MutationObserver(()=>{if(current!==3&&!options.partsOnly&&!options.preRig&&!pickingSource)show(3);});
95
97
  document.querySelectorAll('[data-inspector]').forEach(button=>canonical.observe(button,{attributes:true,attributeFilter:['aria-selected','aria-pressed']}));
96
- const language=onLanguageChange(()=>{render();if(!panel.hidden)status.textContent=t(reasonFor(current)??(current===2?(interviewError??(interview&&!interview.hidden?'':'interview.loading')):current===1&&options.correction?'Draft rig · structure evidence only':current===1?'Atlas inspection, read only — inspected package. Applied scratch atlas, pre-rig parts, mesh sign-off and draft corrections are unavailable here.':''));for(const f of frames.values()){f.title=t('Parts and atlas inspection');setFrameLanguage(f);}if(interview){interview.title=t('interview.title');setFrameLanguage(interview);}});
98
+ const language=onLanguageChange(()=>{render();if(!panel.hidden)status.textContent=t(reasonFor(current)??(current===2?(interviewError??(interview&&!interview.hidden?'':'interview.loading')):current===1&&(options.correction||options.preRig)?'Draft rig · structure evidence only':current===1?'Atlas inspection, read only — inspected package. Applied scratch atlas, pre-rig parts, mesh sign-off and draft corrections are unavailable here.':''));for(const f of frames.values()){f.title=t('Parts and atlas inspection');setFrameLanguage(f);}if(interview){interview.title=t('interview.title');setFrameLanguage(interview);}});
97
99
  window.addEventListener('resize',place);show(current);
98
100
  return ()=>{entry++;window.removeEventListener('message',correction);language();canonical.disconnect();sourcePicker?.querySelectorAll('[data-build-side]').forEach(button=>button.removeEventListener('click',sourceChanged));delete document.documentElement.dataset.inspectionStage;if(workspace)workspace.inert=wasInert;panel.remove();window.removeEventListener('resize',place);document.querySelectorAll('[data-mode],[data-inspector]').forEach(b=>b.removeEventListener('click',legacy));};
99
101
  }