rig-review 2.11.0 → 2.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/docs/DESIGN.md +145 -74
  2. package/docs/PANELS.md +20 -12
  3. package/docs/PARTS_VIEW.md +31 -11
  4. package/docs/REVIEW_PACKAGE.md +215 -0
  5. package/docs/STABILITY.md +98 -2
  6. package/docs/WORKFLOWS.md +40 -12
  7. package/package.json +2 -1
  8. package/skills/rig-review/SKILL.md +29 -1
  9. package/src/build.ts +10 -2
  10. package/src/cli.ts +14 -12
  11. package/src/comment-crops.ts +6 -1
  12. package/src/compare-html.ts +22 -24
  13. package/src/compare-server.ts +1 -1
  14. package/src/compare-session.ts +41 -3
  15. package/src/create-pin-gate.ts +3 -0
  16. package/src/feedback-export.ts +67 -0
  17. package/src/front.ts +10 -16
  18. package/src/interview-routes.ts +1 -1
  19. package/src/job-act.ts +39 -21
  20. package/src/job-api.ts +291 -0
  21. package/src/job-cli.ts +20 -11
  22. package/src/job-contract.ts +91 -3
  23. package/src/job-front.ts +15 -7
  24. package/src/job-host.ts +15 -0
  25. package/src/job-hub.ts +4 -4
  26. package/src/job-image-set.ts +32 -9
  27. package/src/job-session.ts +19 -11
  28. package/src/job-source.ts +74 -30
  29. package/src/joined-project.ts +61 -4
  30. package/src/open-workspace.ts +12 -12
  31. package/src/open.ts +17 -9
  32. package/src/parts-comment.ts +31 -1
  33. package/src/parts-server.ts +19 -7
  34. package/src/parts-view.ts +103 -20
  35. package/src/server.ts +30 -21
  36. package/src/session.ts +58 -0
  37. package/src/stage-comment.ts +39 -0
  38. package/src/stage-parts.ts +18 -10
  39. package/web/animation-inspection.ts +1 -1
  40. package/web/bones-panel.ts +1 -3
  41. package/web/catalog-en.ts +76 -12
  42. package/web/catalog-ko.ts +76 -12
  43. package/web/cloth-panel.ts +1 -2
  44. package/web/compare.css +3 -9
  45. package/web/compare.html +3 -3
  46. package/web/compare.ts +69 -64
  47. package/web/cuts-panel.ts +1 -3
  48. package/web/density-strip-panel.ts +1 -2
  49. package/web/i18n.ts +13 -1
  50. package/web/idle-panel.ts +1 -2
  51. package/web/index.html +1 -5
  52. package/web/inspection-persistence.ts +2 -1
  53. package/web/inspector-blocks.ts +144 -39
  54. package/web/instance-access.ts +24 -5
  55. package/web/interview-panel.ts +224 -175
  56. package/web/job-hub.ts +50 -69
  57. package/web/job-rig-capture.ts +103 -10
  58. package/web/job-rig-screen.ts +317 -0
  59. package/web/job-session.ts +927 -1365
  60. package/web/main.ts +535 -129
  61. package/web/mesh-panel.ts +1 -2
  62. package/web/owner-workspace.ts +88 -109
  63. package/web/part-selection.ts +47 -6
  64. package/web/part-thumbnails.ts +20 -6
  65. package/web/parts-viewport-provider.ts +166 -9
  66. package/web/physics-panel.ts +1 -2
  67. package/web/readings-panel.ts +1 -2
  68. package/web/requirements-panel.ts +1 -3
  69. package/web/retained-frame-stage.ts +105 -0
  70. package/web/retarget-panel.ts +2 -3
  71. package/web/rig-fields-panel.ts +1 -2
  72. package/web/rig-host.ts +62 -0
  73. package/web/rig-viewport-provider.ts +63 -16
  74. package/web/stage-comments.ts +29 -26
  75. package/web/styles.css +127 -43
  76. package/web/view-controls.ts +201 -12
  77. package/web/viewport-controller.ts +97 -26
  78. package/web/viewport-pair.ts +2 -1
  79. package/web/workspace-preferences.ts +5 -4
  80. package/web/workspace-ui.ts +152 -19
  81. package/src/interview-server.ts +0 -54
  82. package/web/interview.css +0 -28
  83. package/web/interview.html +0 -17
  84. package/web/interview.ts +0 -40
  85. package/web/job-hub.css +0 -14
  86. package/web/job-hub.html +0 -5
  87. package/web/owner-workspace.css +0 -14
  88. package/web/owner-workspace.html +0 -5
  89. package/web/parts-flags.ts +0 -48
  90. package/web/parts-page.ts +0 -217
  91. package/web/parts.css +0 -116
  92. package/web/parts.html +0 -15
  93. package/web/parts.ts +0 -986
  94. package/web/stage-nav.ts +0 -136
@@ -9,7 +9,8 @@ import { assertReviewUnchanged, withReviewAssertion } from './reference.ts';
9
9
 
10
10
  export type ProjectDesignation={root:string;picksDir:string}&(
11
11
  {version:number;postVersion?:number;draftId?:never;partsVerdictDir?:never} |
12
- {draftId:string;partsVerdictDir?:string;version?:never;postVersion?:never}
12
+ {draftId:string;partsVerdictDir?:string;version?:never;postVersion?:never} |
13
+ {version?:never;draftId?:never;postVersion?:never;partsVerdictDir?:never}
13
14
  );
14
15
  interface DraftRecord {
15
16
  id:string;
@@ -45,7 +46,62 @@ export const interviewMismatch = 'INTERVIEW_SOURCE_MISMATCH';
45
46
  export const interviewStale = 'INTERVIEW_OPTIONS_STALE';
46
47
  export const directionStale = 'DIRECTION_SOURCE_STALE';
47
48
 
48
- export function joinProject(p: ReviewPackage, designation: ProjectDesignation, options: { starts?: readonly string[] } = {}):JoinedSource {
49
+ /** Project inspection metadata; deliberately has no manifest, model or package session. */
50
+ export interface InterviewSubjectEntry {
51
+ subject:'interview';
52
+ project:{path:'project.json';sha256:string};
53
+ label:string;
54
+ sourceHash:string;
55
+ capabilities:{interview:true;playback:false;modeling:false;motion:false;feedback:false;audio:false};
56
+ unavailable:'MODEL_UNAVAILABLE';
57
+ }
58
+ export interface JoinedInterview {
59
+ interviewOnly:true;
60
+ opened:ReturnType<typeof readProject>;
61
+ designation:Extract<ProjectDesignation,{version?:never;draftId?:never}>;
62
+ sourceHash:string;
63
+ available:boolean;
64
+ assertCurrent:()=>Promise<void>;
65
+ review?:never;
66
+ draft?:never;
67
+ verdictDirectory?:never;
68
+ }
69
+ export function joinProject(p:null,designation:ProjectDesignation,options?:{starts?:readonly string[]}):JoinedInterview;
70
+ export function joinProject(p:ReviewPackage,designation:ProjectDesignation,options?:{starts?:readonly string[]}):JoinedSource;
71
+ export function joinProject(p:ReviewPackage|null,designation:ProjectDesignation,options:{starts?:readonly string[]}={}):JoinedSource|JoinedInterview {
72
+ if(designation.version===undefined&&designation.draftId===undefined){
73
+ const fail=():never=>{throw new Error(interviewMismatch+': expected an interview-stage project without a draft or recorded package');};
74
+ if(p!==null||designation.postVersion!==undefined||designation.partsVerdictDir!==undefined)return fail();
75
+ const opened=readProject(designation.root),{root,project,hash}=opened;
76
+ const assertStage=()=>{
77
+ if(project.stage!=='interview'||!Array.isArray(project.versions)||
78
+ project.versions.some(entry=>object(entry).review_package!=null)||
79
+ !(project.drafts==null||Array.isArray(project.drafts)&&project.drafts.length===0))return fail();
80
+ };
81
+ assertStage();
82
+ outputDirectory(root,designation.picksDir,project);
83
+ if(!opened.questions.length&&!opened.historical.length)throw new Error(interviewUnavailable);
84
+ const files=new Map<string,string>([['project.json',hash]]);
85
+ const retain=(ref:SetRef)=>{
86
+ if(!literalPath(ref.path)||typeof ref.sha256!=='string'||!/^[a-f0-9]{64}$/.test(ref.sha256))return fail();
87
+ if(files.has(ref.path)&&files.get(ref.path)!==ref.sha256)return fail();
88
+ boundBytes(root,ref);files.set(ref.path,ref.sha256);
89
+ };
90
+ if(!Array.isArray(project.inputs))return fail();
91
+ for(const input of project.inputs)retain(object(input) as unknown as SetRef);
92
+ for(const question of opened.questions){retain(question.ref);for(const image of question.images)retain(image.ref);}
93
+ const assertCurrent=async()=>{
94
+ try{
95
+ assertStage();
96
+ for(const [path,sha256]of files)boundBytes(root,{path,sha256});
97
+ if(readProject(root).hash!==hash)throw new Error('Project changed');
98
+ outputDirectory(root,designation.picksDir,project);
99
+ }catch{throw new Error(interviewStale+': project or interview inputs changed; reopen the project');}
100
+ };
101
+ return {interviewOnly:true,opened,designation:{root,picksDir:designation.picksDir},available:true,assertCurrent,
102
+ sourceHash:digest(JSON.stringify({project:{path:'project.json',sha256:hash},files:[...files].sort(([a],[b])=>a.localeCompare(b))}))};
103
+ }
104
+ if(!p)throw new Error(interviewMismatch+': expected the explicitly designated recorded package');
49
105
  if(designation.draftId!==undefined)return joinDraft(p,designation,options);
50
106
  const opened = readProject(designation.root);
51
107
  const {root, hash, project} = opened;
@@ -176,7 +232,8 @@ function joinDraft(p:ReviewPackage,designation:Extract<ProjectDesignation,{draft
176
232
  const producer=object(record?.producer);
177
233
  if(matches.length!==1||record?.kind!=='draft-rig'||typeof record.at!=='string'||!Number.isFinite(Date.parse(record.at))||
178
234
  producer.name!=='@rig-c/parts'||typeof producer.version!=='string'||!producer.version.trim()||
179
- !literalPath(parts.path)||!parts.path.startsWith(path+'/')||
235
+ // Create's draft-rig records the draft directory itself when --parts is omitted (rig-create src/drafts.ts `opts['--parts'] ?? from`).
236
+ !literalPath(parts.path)||!(parts.path===path||parts.path.startsWith(path+'/'))||
180
237
  !Array.isArray(parts.files)||!Array.isArray(record.files)||
181
238
  (record.config_inputs!==undefined&&!Array.isArray(record.config_inputs)))return fail();
182
239
  const files=new Map<string,string>();
@@ -301,4 +358,4 @@ function joinDraft(p:ReviewPackage,designation:Extract<ProjectDesignation,{draft
301
358
  return {review,opened,designation:{...designation,root},assertCurrent,draft,verdictDirectory,
302
359
  available:opened.questions.length>0||opened.historical.length>0};
303
360
  }
304
- export type JoinedProject = ReturnType<typeof joinProject>;
361
+ export type JoinedProject = JoinedSource | JoinedInterview;
@@ -7,7 +7,7 @@ import {createCompareRequestContext} from './compare-server.ts';
7
7
  import {createLiveLifecycle, type UpgradableServer} from './live-lifecycle.ts';
8
8
  import {prepareOpenTarget} from './open.ts';
9
9
  import {sameSecret} from './open-protocol.ts';
10
- import {boundedBody, frontRoute, maximumUpstreamStreams, stageFrameQuery} from './front.ts';
10
+ import {boundedBody, frontRoute, maximumUpstreamStreams} from './front.ts';
11
11
  import {assertCompareUnchanged} from './compare.ts';
12
12
  import {assertReviewUnchanged} from './reference.ts';
13
13
  import {parseDesignation, parseRegistry, readPrivate, targetCapability, workspaceDirectory, workspaceError, writePrivate} from './open-workspace-state.ts';
@@ -71,24 +71,25 @@ export async function startOpenWorkspace(options: OpenWorkspaceOptions) {
71
71
  }, options.fingerprint);
72
72
  const loaded = prepared.package;
73
73
  if (prepared.key !== designation.key || loaded.contentHash !== designation.contentHash) throw workspaceError('WORKSPACE_SOURCE_CHANGED');
74
- let bundle = bundles.get(loaded.mode);
75
- if (!bundle) {bundle = buildWeb(loaded.mode); bundles.set(loaded.mode, bundle);}
74
+ const bundleMode=loaded.mode==='interview'?'single':loaded.mode;
75
+ let bundle = bundles.get(bundleMode);
76
+ if (!bundle) {bundle = buildWeb(bundleMode); bundles.set(bundleMode, bundle);}
76
77
  const controlToken = loaded.inputs.control ? randomUUID() : undefined;
77
78
  const contextOptions = {stateDir: options.stateDir, cwd: designation.cwd, lifecycle: live, bundle: await bundle,
78
79
  capability: targetCapability(ownerCapability, incarnation, designation.key),
79
80
  open: {key: designation.key, contentHash: designation.contentHash, nonce: incarnation, fingerprint: options.fingerprint},
80
81
  ...(controlToken ? {control: {token: controlToken, instanceKey: designation.key}} : {}),
81
82
  };
82
- const context = loaded.mode === 'single'
83
+ const context = loaded.mode !== 'compare'
83
84
  ? await createReviewRequestContext(loaded.p, {...contextOptions, joined: loaded.joined,
84
85
  initialAnimation: loaded.selection?.name, viewOnly: designation.viewOnly})
85
86
  : await createCompareRequestContext(loaded.p, contextOptions);
86
- const check = () => loaded.mode === 'single' ? assertReviewUnchanged(loaded.p) : assertCompareUnchanged(loaded.p);
87
+ const check = () => loaded.mode === 'interview' ? loaded.joined.assertCurrent() : loaded.mode === 'single' ? assertReviewUnchanged(loaded.p) : assertCompareUnchanged(loaded.p);
87
88
  await check();
88
89
  return {stored: {designation, ...(controlToken ? {controlToken} : {})}, context, check,
89
90
  view: {key: designation.key, contentHash: designation.contentHash,
90
- title: (loaded.mode === 'single' ? loaded.p.manifest.title : loaded.p.response.title).slice(0, 256),
91
- mode: loaded.mode, animation: loaded.selection?.name ?? null, viewOnly: designation.viewOnly, unavailable: null,
91
+ title: (loaded.mode === 'interview' ? String(loaded.joined.opened.project.name??loaded.joined.opened.root.split('/').at(-1)) : loaded.mode === 'single' ? loaded.p.manifest.title : loaded.p.response.title).slice(0, 256),
92
+ mode: loaded.mode==='interview'?'single' as const:loaded.mode, animation: loaded.selection?.name ?? null, viewOnly: designation.viewOnly, unavailable: null,
92
93
  entry: `/instances/${designation.key}/?input=${designation.contentHash}&handoff=${designation.key}&workspace=${incarnation}`}};
93
94
  }
94
95
 
@@ -185,7 +186,7 @@ export async function startOpenWorkspace(options: OpenWorkspaceOptions) {
185
186
  if (live.connections >= WORKSPACE_SOCKET_LIMIT) return refused('WORKSPACE_BUSY', 503);
186
187
  return live.upgrade(request, server, securityHeaders);
187
188
  }
188
- if (['/', '/workspace.js', '/workspace.css', '/styles.css'].includes(url.pathname)) {
189
+ if (['/', '/main.js', '/styles.css'].includes(url.pathname)) {
189
190
  if (!['GET', 'HEAD'].includes(request.method)) return refused('WORKSPACE_REQUEST_INVALID', 400);
190
191
  if (url.pathname === '/') {
191
192
  const keys = [...url.searchParams.keys()];
@@ -199,8 +200,8 @@ export async function startOpenWorkspace(options: OpenWorkspaceOptions) {
199
200
  } else if (url.search && !['?lang=en', '?lang=ko'].includes(url.search)) {
200
201
  return refused('WORKSPACE_REQUEST_INVALID', 400);
201
202
  }
202
- const body = url.pathname === '/workspace.js' ? await (ownerScript ??= ownerBundle())
203
- : await readFile(appRoot + (url.pathname === '/' ? 'web/owner-workspace.html' : url.pathname === '/styles.css' ? 'web/styles.css' : 'web/owner-workspace.css'));
203
+ const body = url.pathname === '/main.js' ? await (ownerScript ??= ownerBundle())
204
+ : await readFile(appRoot + (url.pathname === '/' ? 'web/index.html' : 'web/styles.css'));
204
205
  return new Response(request.method === 'HEAD' ? null : body, {headers: {...securityHeaders,
205
206
  'Content-Type': url.pathname.endsWith('.js') ? 'text/javascript' : url.pathname.endsWith('.css') ? 'text/css' : 'text/html; charset=utf-8'}});
206
207
  }
@@ -212,8 +213,7 @@ export async function startOpenWorkspace(options: OpenWorkspaceOptions) {
212
213
  const agentControl = path === '/api/control' || path === '/api/control/commands' || /^\/api\/control\/receipts\/[a-f0-9-]+$/.test(path);
213
214
  if (!frontRoute(target.view.mode, request.method, path) && !(agentControl && target.stored.controlToken)) return refused('WORKSPACE_ROUTE_REFUSED', 404);
214
215
  const landing = path === '/' || path === '/index.html';
215
- const stageFrame = path === '/stage-parts.html' || path === '/stage-interview.html';
216
- if (stageFrame ? !stageFrameQuery(target.view.mode, url.search) : !landing && !!url.search) return refused('FRONT_QUERY_REFUSED', 400);
216
+ if (!landing && !!url.search) return refused('FRONT_QUERY_REFUSED', 400);
217
217
  if (request.method !== 'GET' && request.method !== 'HEAD' && sentOrigin !== record.origin) return refused('WORKSPACE_SAME_ORIGIN_REQUIRED', 403);
218
218
  if (path === '/api/live' && live.connections >= WORKSPACE_SOCKET_LIMIT) return refused('WORKSPACE_BUSY', 503);
219
219
  if (activeStreams >= maximumUpstreamStreams) return refused('WORKSPACE_BUSY', 503);
package/src/open.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { joinProject, type JoinedProject, type ProjectDesignation } from './joined-project.ts';
1
+ import { joinProject, type JoinedProject, type JoinedInterview, type ProjectDesignation } from './joined-project.ts';
2
2
  import {parseControlCommand,type ControlCommand,type ControlReceipt} from './control.ts';
3
3
  /** One fixed-package worker per exact binding. There is no general daemon API. */
4
4
  import {createHash,randomBytes,randomUUID} from 'node:crypto';
@@ -35,7 +35,7 @@ export function buildOpenDiagnostic(build:BuildOpen):string{
35
35
  export interface OpenInputs {input:string;project?:ProjectDesignation;compare?:string;reference?:string;animation?:string;control?:boolean;direct?:boolean;viewOnly?:boolean;config?:string;parts?:string;source?:string;full?:string;head?:string;keypoints?:string}
36
36
  /** The producer handoff flags (#101) among the inputs, or undefined when none was given. */
37
37
  export function handoffFlags(inputs:OpenInputs):HandoffFlags|undefined{const present=HANDOFF_FLAGS.filter(f=>inputs[f]!==undefined);if(!present.length)return undefined;return Object.fromEntries(present.map(f=>[f,inputs[f]])) as unknown as HandoffFlags;}
38
- export type OpenPackage=({mode:'single';p:ReviewPackage;joined?:JoinedProject;inputs:OpenInputs;contentHash:string}|{mode:'compare';p:ComparePackage;inputs:OpenInputs;contentHash:string})&{selection:AnimationSelection|null};
38
+ export type OpenPackage=({mode:'single';p:ReviewPackage;joined?:Exclude<JoinedProject,JoinedInterview>;inputs:OpenInputs;contentHash:string}|{mode:'interview';joined:JoinedInterview;p:null;inputs:OpenInputs;contentHash:string}|{mode:'compare';p:ComparePackage;inputs:OpenInputs;contentHash:string})&{selection:AnimationSelection|null};
39
39
  /** Private 0600 record. `capability` is the 256-bit page write capability, handed out only in the printed `#cap=` fragment. */
40
40
  export interface RecordFile extends OpenIdentity {schema:'rig-review-open-instance/1';pid:number;origin:string;mode:'single'|'compare';capability:string;controlToken?:string}
41
41
  /** `cwd` is the launcher's working directory: the worker runs in the state directory, so Apply · Rebuild looks for the producer from here after the package's own directories. */
@@ -45,6 +45,13 @@ const digest=(value:unknown)=>createHash('sha256').update(JSON.stringify(value))
45
45
  const sleep=(ms:number)=>new Promise(resolveSleep=>setTimeout(resolveSleep,ms));
46
46
  export const defaultStateDir=()=>process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review');
47
47
  export async function loadOpenPackage(inputs:OpenInputs,options:{cwd?:string}={}):Promise<OpenPackage>{
48
+ if(inputs.project&&inputs.project.version===undefined&&inputs.project.draftId===undefined){
49
+ if(inputs.compare!==undefined||inputs.reference!==undefined||inputs.animation!==undefined||inputs.control||inputs.direct||inputs.viewOnly||handoffFlags(inputs))throw new Error('OPEN_OPTION_INVALID --project: interview-only open takes only the project root, --project and --picks-dir');
50
+ const joined=joinProject(null,inputs.project);
51
+ if(await realpath(resolve(inputs.input))!==joined.opened.root)throw new Error('INTERVIEW_SOURCE_MISMATCH: interview input must be the designated project root');
52
+ await joined.assertCurrent();
53
+ return {mode:'interview',p:null,joined,selection:null,contentHash:joined.sourceHash,inputs:{input:joined.opened.root,project:joined.designation}};
54
+ }
48
55
  // Handoff flags become canonical absolute paths here, so the worker and every reload read exactly these files.
49
56
  if(!inputs.compare){const base=await loadReferencedReview(inputs.input,inputs.reference,handoffFlags(inputs),options.cwd);const joined=inputs.project?joinProject(base,inputs.project,{starts:[options.cwd??process.cwd()]}):undefined;const p=joined?.review??base,selection=selectAnimation([{label:'single',catalog:p.feedbackCatalog,report:p.report}],inputs.animation,true);if(inputs.viewOnly)p.viewOnly=true;return {mode:'single',p,selection,contentHash:p.sourceHash,...(joined?{joined}:{}),inputs:{input:p.manifestPath,...(joined?{project:joined.designation}:{}),...(selectedReference(p)?{reference:selectedReference(p)!.path}:{}),...(selection?{animation:selection.name}:{}),...(inputs.control?{control:true}:{}),...(p.handoffInputs??{})}};}
50
57
  if(inputs.project)throw new Error('INTERVIEW_SOURCE_MISMATCH: compare takes no joined project');
@@ -63,7 +70,7 @@ export async function openFingerprint():Promise<string>{
63
70
  hash.update('bun.lock\0');try{hash.update(await readFile(join(appRoot,'bun.lock')));}catch(e){if((e as NodeJS.ErrnoException).code!=='ENOENT')throw e;hash.update('(absent)');}
64
71
  hash.update('@rig-c/play/package.json\0');hash.update(await readFile(playPackagePath()));return hash.digest('hex');
65
72
  }
66
- export function openKey(p:OpenPackage,fingerprint:string):string {return digest({fingerprint,installation:appRoot,mode:p.mode,inputs:p.inputs,content:p.contentHash,identity:p.mode==='single'?p.p.reviewedSource:p.p.response.binding,...(p.mode==='single'&&p.joined?{projectHash:p.joined.opened.hash}:{})});}
73
+ export function openKey(p:OpenPackage,fingerprint:string):string {return digest({fingerprint,installation:appRoot,mode:p.mode,inputs:p.inputs,content:p.contentHash,identity:p.mode==='interview'?{projectHash:p.joined.opened.hash}:p.mode==='single'?p.p.reviewedSource:p.p.response.binding,...(p.mode==='single'&&p.joined?{projectHash:p.joined.opened.hash}:{})});}
67
74
  /** Handoff URL: the managed front's `/instances/<key>/` path (or the worker's own origin when direct). The
68
75
  * capability rides in the fragment, which browsers never send to a server; the page stores and strips it. */
69
76
  export function openUrl(record:Pick<RecordFile,'origin'|'key'|'contentHash'|'capability'>,front?:string):string {const url=new URL(front?`${front}/instances/${record.key}/`:record.origin);url.searchParams.set('input',record.contentHash);url.searchParams.set('handoff',record.key);url.hash='cap='+record.capability;return url.href;}
@@ -110,6 +117,7 @@ async function openRefusal(error:unknown,inputs:OpenInputs):Promise<unknown>{
110
117
  return new Error(`${name}: ${detail}`,{cause:error});
111
118
  }
112
119
  async function verifyOpenLoad(p:OpenPackage,viewOnly:boolean,cwd=process.cwd()):Promise<void>{
120
+ if(p.mode==='interview'){await p.joined.assertCurrent();return;}
113
121
  if(p.mode==='single'){
114
122
  // A recorded pre-rig draft has a bound model for Stage 1 mesh mapping only.
115
123
  if(p.joined?.draft)return;
@@ -134,8 +142,8 @@ export async function prepareOpenTarget(inputs: OpenInputs, options: OpenOptions
134
142
  let p:OpenPackage;try{p=await loadOpenPackage(inputs,{cwd:options.cwd});}catch(error){throw await openRefusal(error,inputs);}
135
143
  fingerprint??=await openFingerprint();const key=openKey(p,fingerprint);
136
144
  // #187: canonical (symlinks and ancestors resolved) and outside every supplied folder: the package, the build root a check package belongs to, the handoff root.
137
- const stateDir=destinationDirectory(options.stateDir??defaultStateDir(),'OPEN_STATE_INVALID: the state directory path has a non-directory component or a symlink loop'),roots=p.mode==='single'?stateRoots(p.p):[...stateRoots(p.p.a),...stateRoots(p.p.b)];
138
- if(p.mode==='single'&&p.joined&&stateDirInside(stateDir,[{kind:'package',path:p.joined.opened.root}]))throw new Error('OPEN_STATE_INSIDE_PACKAGE: review state must be outside the joined project');
145
+ const stateDir=destinationDirectory(options.stateDir??defaultStateDir(),'OPEN_STATE_INVALID: the state directory path has a non-directory component or a symlink loop'),roots=p.mode==='interview'?[{kind:'package' as const,path:p.joined.opened.root}]:p.mode==='single'?stateRoots(p.p):[...stateRoots(p.p.a),...stateRoots(p.p.b)];
146
+ if(p.mode!=='compare'&&p.joined&&stateDirInside(stateDir,[{kind:'package',path:p.joined.opened.root}]))throw new Error('OPEN_STATE_INSIDE_PACKAGE: review state must be outside the joined project');
139
147
  const inside=stateDirInside(stateDir,roots);if(inside)throw new Error(`OPEN_STATE_INSIDE_PACKAGE ${inside.kind}: the review state directory must be outside input packages; it is inside the ${inside.kind}; set RIG_REVIEW_STATE_DIR outside it`);
140
148
  await verifyOpenLoad(p,viewOnly,options.cwd);
141
149
  const build=p.mode==='single'&&basename(p.p.root)==='check'&&await isBuildRoot(dirname(p.p.root))?{package:p.p.root,handoff:p.p.reviewedSource.handoff??null,reason:p.p.handoffReason}:null;
@@ -153,7 +161,7 @@ export async function openReview(inputs:OpenInputs,options:OpenOptions={}):Promi
153
161
  }
154
162
  async function ensureWorker(p:OpenPackage,key:string,fingerprint:string,stateDir:string,canonicalControl:string,idleMs:number,graceMs?:number,viewOnly=false,cwd=process.cwd()):Promise<{row:RecordFile;reused:boolean}>{
155
163
  const registry=join(canonicalControl,key+'.json'),claim=join(canonicalControl,key+'.claim'),nonce=randomUUID(),deadline=performance.now()+20000;
156
- const reuse=async()=>{const row=await readRecord(registry,key);return row&&row.fingerprint===fingerprint&&row.contentHash===p.contentHash&&row.mode===p.mode&&await alive(row)?row:null;};
164
+ const reuse=async()=>{const row=await readRecord(registry,key);return row&&row.fingerprint===fingerprint&&row.contentHash===p.contentHash&&row.mode===(p.mode==='interview'?'single':p.mode)&&await alive(row)?row:null;};
157
165
  const ready=await reuse();if(ready)return {row:ready,reused:true};
158
166
  const claimed=await acquireClaim(canonicalControl,key,nonce,reuse,deadline,'OPEN_BUSY: instance startup claim did not become ready');if('row' in claimed)return {row:claimed.row,reused:true};
159
167
  let request:string|undefined,spawned:ReturnType<typeof spawn>|undefined,handedOff=false;
@@ -175,9 +183,9 @@ export async function runOpenWorker(requestPath:string):Promise<void>{
175
183
  // The worker mints its own page capability; it lives only in this process and the private record.
176
184
  const removeRecord=async()=>{const current=await readRecord(spec.registry,spec.identity.key);if(current?.nonce===spec.identity.nonce)await unlink(spec.registry).catch(()=>{});};
177
185
  const capability=randomBytes(32).toString('hex');const options={port:0,stateDir:spec.stateDir,open:spec.identity,capability,unopenedTimeoutMs:spec.idleMs,...(spec.graceMs!==undefined?{graceMs:spec.graceMs}:{}),exitOnClose:true,onClose:removeRecord,...(spec.inputs.control?{control:{token:spec.controlToken!,instanceKey:spec.identity.key}}:{})};
178
- const server=p.mode==='single'?await startServer(p.p,{...options,joined:p.joined,initialAnimation:p.selection?.name,...(typeof spec.cwd==='string'&&isAbsolute(spec.cwd)?{cwd:spec.cwd}:{}),...(spec.viewOnly?{viewOnly:true}:{})}):await startCompareServer(p.p,options);
179
- const check=()=>p.mode==='single'?assertReviewUnchanged(p.p):assertCompareUnchanged(p.p);
180
- await check();const record:RecordFile={schema:'rig-review-open-instance/1',...spec.identity,pid:process.pid,origin:`http://127.0.0.1:${server.port}`,mode:p.mode,capability,...(spec.inputs.control?{controlToken:spec.controlToken}:{})};const tmp=spec.registry+'.'+spec.identity.nonce+'.tmp';await writeFile(tmp,JSON.stringify(record),{mode:0o600,flag:'wx'});await rename(tmp,spec.registry);
186
+ const server=p.mode!=='compare'?await startServer(p.p,{...options,joined:p.joined,initialAnimation:p.selection?.name,...(typeof spec.cwd==='string'&&isAbsolute(spec.cwd)?{cwd:spec.cwd}:{}),...(spec.viewOnly?{viewOnly:true}:{})}):await startCompareServer(p.p,options);
187
+ const check=()=>p.mode==='interview'?p.joined.assertCurrent():p.mode==='single'?assertReviewUnchanged(p.p):assertCompareUnchanged(p.p);
188
+ await check();const record:RecordFile={schema:'rig-review-open-instance/1',...spec.identity,pid:process.pid,origin:`http://127.0.0.1:${server.port}`,mode:p.mode==='interview'?'single':p.mode,capability,...(spec.inputs.control?{controlToken:spec.controlToken}:{})};const tmp=spec.registry+'.'+spec.identity.nonce+'.tmp';await writeFile(tmp,JSON.stringify(record),{mode:0o600,flag:'wx'});await rename(tmp,spec.registry);
181
189
  await unlink(requestPath).catch(e=>{if(e.code!=='ENOENT')throw e;});
182
190
  let stopped=false;const stop=async(signal:string)=>{if(stopped)return;stopped=true;await removeRecord();server.stop(true);console.log(`review: exiting — received ${signal}.`);process.exit(0);};
183
191
  process.on('SIGTERM',()=>{void stop('SIGTERM');});process.on('SIGINT',()=>{void stop('SIGINT');});
@@ -1,6 +1,7 @@
1
1
  /** Closed parts evidence. No synthetic model, frame, slot or package identity. */
2
2
  import { parsePartsComparison, type PartsComparison } from './parts-comparison.ts';
3
3
  import type { MarkRegion } from './stage-comment.ts';
4
+ import type { JobCommentPartsAnchor, JobComment } from './job-contract.ts';
4
5
 
5
6
  export const PARTS_COMMENT_SCHEMA = 'rig-review-parts-comment/1' as const;
6
7
  export const PARTS_ISSUE_SCHEMA = 'rig-review-parts-comment/2' as const;
@@ -43,7 +44,7 @@ export interface PartsIssue {
43
44
  sourceHash: string;
44
45
  rigRegion: MarkRegion;
45
46
  imageRegion: MarkRegion | null;
46
- view: PartsComment['view'] & { mode: 'item' | 'assembled' };
47
+ view: PartsComment['view'] & { mode: 'item' | 'assembled'; visibleLayers?: { name: string; imageHash: string }[] };
47
48
  crop: PartsCrop & { png?: string };
48
49
  nativeCrop: PartsCrop | null;
49
50
  }
@@ -97,10 +98,23 @@ function parseView(raw: unknown, withMode: boolean): Record<string, any> {
97
98
  'footprints',
98
99
  'mesh',
99
100
  ...(Object.hasOwn(view, 'comparison') ? ['comparison'] : []),
101
+ ...(withMode && Object.hasOwn(view, 'visibleLayers') ? ['visibleLayers'] : []),
100
102
  ]);
101
103
  if (withMode && view.mode !== 'item' && view.mode !== 'assembled') {
102
104
  fail('PARTS_COMMENT_INVALID', 'view mode');
103
105
  }
106
+ if (Object.hasOwn(view, 'visibleLayers')) {
107
+ if (!withMode || view.mode !== 'assembled' || !Array.isArray(view.visibleLayers) || view.visibleLayers.length > 1000) {
108
+ fail('PARTS_COMMENT_INVALID', 'assembled visible layers required');
109
+ }
110
+ const seen = new Set<string>();
111
+ for (const rawLayer of view.visibleLayers) {
112
+ const layer = obj(rawLayer);
113
+ exact(layer, ['name', 'imageHash']);
114
+ if (!token(layer.name) || !hash(layer.imageHash) || seen.has(layer.name)) fail('PARTS_COMMENT_INVALID', 'visible layer binding');
115
+ seen.add(layer.name);
116
+ }
117
+ }
104
118
  if (Object.hasOwn(view, 'comparison')) {
105
119
  parsePartsComparison(view.comparison);
106
120
  }
@@ -284,6 +298,11 @@ export function assertPartsIssueBinding(
284
298
  if (c.sourceHash !== sourceHash) {
285
299
  fail('PARTS_COMMENT_STALE_SOURCE', 'original image or package source hash differs');
286
300
  }
301
+ for (const layer of c.view.visibleLayers ?? []) {
302
+ const item = items.get(layer.name);
303
+ if (!item) fail('PARTS_COMMENT_PART_MISMATCH', 'visible layer belongs to another part');
304
+ if (item!.imageHash !== layer.imageHash) fail('PARTS_COMMENT_STALE_SOURCE', 'visible layer image hash differs');
305
+ }
287
306
  const matchedItems: { name: string; x: number; y: number; w: number; h: number; imageHash: string }[] = [];
288
307
  for (const p of c.parts) {
289
308
  const item = items.get(p.name);
@@ -324,3 +343,14 @@ export function assertPartsIssueBinding(
324
343
  fail('PARTS_COMMENT_OUT_OF_BOUNDS', 'region exceeds union of issue parts');
325
344
  }
326
345
  }
346
+
347
+ /** The pointed issues of an act@6 Parts verdict: its comments with Parts anchors, in stored order. */
348
+ export function commentPartsIssues(comments: readonly JobComment[]): PartsIssue[] {
349
+ return comments.flatMap(comment => comment.anchor && 'schema' in comment.anchor ?
350
+ [{...structuredClone(comment.anchor), summary: comment.text} as PartsIssue] : []);
351
+ }
352
+
353
+ /** Pointed Parts issues keep their source-bound anchor; the summary becomes the comment text. */
354
+ export function partsIssueComments(issues: readonly PartsIssue[]): {text: string; anchor: JobCommentPartsAnchor}[] {
355
+ return issues.map(({summary, ...anchor}) => ({text: summary, anchor: structuredClone(anchor)}));
356
+ }
@@ -1,12 +1,12 @@
1
- /** Serves the parts and atlas view (#348): the page, its bundle, the part and page images by index, and the sign-off. */
1
+ /** Serves the parts workspace: the page, its bundle, indexed images, and the sign-off. */
2
2
  import { PNG } from 'pngjs';
3
3
  import { readFile } from 'node:fs/promises';
4
- import { appRoot, buildWeb } from './build.ts';
4
+ import { appRoot, buildWeb, setupEntryHtml } from './build.ts';
5
5
  import { accessGate } from './open-protocol.ts';
6
6
  import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
7
7
  import {preparePartsComment} from './parts-comment-crops.ts';
8
8
  import {serveReference} from './reference.ts';
9
- import { partsDifference, partsViewJson, exportPartsVerdict, assertPartsUnchanged, readVerdict, saveVerdictWithReceipt, servedImage, type PartsViewPackage, type PartsSaveReceipt } from './parts-view.ts';
9
+ import { partsDifference, partsViewJson, exportPartsVerdict, assertPartsUnchanged, assertPartsCanOpen, readVerdict, saveVerdictWithReceipt, servedImage, type PartsViewPackage, type PartsSaveReceipt } from './parts-view.ts';
10
10
 
11
11
  const headers = { 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" };
12
12
  const json = (value: unknown, status = 200) => Response.json(value, { status, headers });
@@ -47,9 +47,11 @@ export interface PartsServerOptions {
47
47
  }
48
48
 
49
49
  export async function startPartsServer(pkg: PartsViewPackage, options: PartsServerOptions = {}) {
50
+ assertPartsCanOpen(pkg);
50
51
  const by = options.by;
51
52
  if (by !== undefined && (typeof by !== 'string' || !by.trim())) throw new Error('PARTS_VERDICT_INVALID: reviewer name must be nonblank');
52
- const bundle = await buildWeb('parts');
53
+ const bundle = await buildWeb();
54
+ const page = await setupEntryHtml('parts');
53
55
  let rawStop: ((closeActiveConnections?: boolean) => void) | null = null;
54
56
  let pendingSaves = 0, saveCount = 0;
55
57
  let saveQueue: Promise<void> = Promise.resolve();
@@ -89,6 +91,14 @@ export async function startPartsServer(pkg: PartsViewPackage, options: PartsServ
89
91
  }
90
92
  live.onRequestStart(url.pathname);
91
93
  try {
94
+ // A parts subject has its own identity and verdict; never synthesize a rig manifest or session.
95
+ if (req.method === 'GET' && ['/api/review','/api/session','/api/access'].includes(url.pathname)) {
96
+ await assertPartsUnchanged(pkg);
97
+ if(url.pathname==='/api/access')return json({capabilityRequired:!!options.capability,control:false});
98
+ const saved=await readVerdict(pkg);
99
+ if(url.pathname==='/api/session')return json({subject:'parts',issues:saved.verdict?.issues??saved.legacy?.issues??[]});
100
+ return json({subject:'parts',parts:partsViewJson(pkg,saved)});
101
+ }
92
102
  if (url.pathname === '/api/parts' && req.method === 'GET'){await assertPartsUnchanged(pkg);return json(partsViewJson(pkg,await readVerdict(pkg)));}
93
103
  if(url.pathname==='/api/parts/comment'&&req.method==='POST'){if(req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);await assertPartsUnchanged(pkg);return json({comment:await preparePartsComment(pkg,await bodyJson(req))});}
94
104
  if(url.pathname==='/api/parts/export'&&req.method==='GET'){await assertPartsUnchanged(pkg);const saved=await readVerdict(pkg);if(!saved.verdict)return json({error:'PARTS_VERDICT_UNAVAILABLE: save a verdict first'},409);return new Response(exportPartsVerdict(saved.verdict,url.searchParams.get('format')==='issue'?'issue':'json'),{headers:{...headers,'Content-Type':url.searchParams.get('format')==='issue'?'text/markdown':'application/json'}});}
@@ -112,9 +122,11 @@ export async function startPartsServer(pkg: PartsViewPackage, options: PartsServ
112
122
  const pinned=pkg.files.find(f=>f.abs===path);if(!pinned)return json({error:'PARTS_IMAGE_UNBOUND'},409);return serveReference(req,path,pinned.sha256,headers);
113
123
 
114
124
  }
115
- if (url.pathname === '/parts.js') return new Response(req.method === 'HEAD' ? null : bundle, { headers: { ...headers, 'Content-Type': 'text/javascript' } });
116
- if (url.pathname === '/' || url.pathname === '/parts.html') return new Response(req.method === 'HEAD' ? null : await readFile(appRoot + 'web/parts.html'), { headers: { ...headers, 'Content-Type': 'text/html; charset=utf-8' } });
117
- if (url.pathname === '/parts.css') return new Response(req.method === 'HEAD' ? null : await readFile(appRoot + 'web/parts.css'), { headers: { ...headers, 'Content-Type': 'text/css' } });
125
+ const read=req.method==='GET'||req.method==='HEAD';
126
+ if(read&&url.pathname==='/parts.html')return new Response(null,{status:302,headers:{...headers,Location:'/'+url.search}});
127
+ if(read&&url.pathname==='/main.js')return new Response(req.method==='HEAD'?null:bundle,{headers:{...headers,'Content-Type':'text/javascript'}});
128
+ if(read&&(url.pathname==='/'||url.pathname==='/index.html'))return new Response(req.method==='HEAD'?null:page,{headers:{...headers,'Content-Type':'text/html; charset=utf-8'}});
129
+ if(read&&url.pathname==='/styles.css')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/styles.css'),{headers:{...headers,'Content-Type':'text/css'}});
118
130
  return json({ error: 'Not found' }, 404);
119
131
  } finally { live.onRequestEnd(url.pathname); }
120
132
  } catch (e) {
package/src/parts-view.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The parts and atlas view (#348): every part as an image, before any rig is built, and the atlas a built rig ships.
3
3
  *
4
- * Two inputs open it:
4
+ * Two inputs can be read (only parts mode opens the parts workspace):
5
5
  * - **parts mode** — a parts package as rig-parts assemble writes it: `parts.json` (draw order, back first) beside
6
6
  * `parts/<name>.png`, each PNG cropped to its own box at `x`/`y` in rig pixels;
7
7
  * - **atlas mode** — a review package (or rig-parts build root) whose compiled model declares `pages[].regions[]`.
@@ -21,11 +21,13 @@ import {preparePartsComment,validateStoredPartsComment} from './parts-comment-cr
21
21
  import {resolvedCropPath} from './comment-crops.ts';
22
22
  import { createHash } from 'node:crypto';
23
23
  import { existsSync } from 'node:fs';
24
- import { mkdir, open, readFile, realpath, rename, rm, stat } from 'node:fs/promises';
24
+ import { mkdir, open, readFile, realpath, rename, rm, stat, lstat } from 'node:fs/promises';
25
25
  import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
26
26
  import { PNG } from 'pngjs';
27
27
  import { loadReview, safeFile, packagePath, type ReviewPackage } from './manifest.ts';
28
28
  import { destinationDirectory } from './destination-directory.ts';
29
+ import {commentsObject, jobSha, jobInteger, parseComments} from './job-api.ts';
30
+ import {PARTS_COMMENTS_VERDICT_SCHEMA, type PartsCommentsVerdict} from './job-contract.ts';
29
31
 
30
32
  export const PARTS_VERDICT_SCHEMA = 'rig-review-parts-verdict/4';
31
33
  const LEGACY_VERDICT_SCHEMAS = ['rig-review-parts-verdict/1', 'rig-review-parts-verdict/2', 'rig-review-parts-verdict/3'] as const;
@@ -39,7 +41,7 @@ export type LegacyVerdictStatus = 'pending' | 'approved' | 'changes-requested';
39
41
 
40
42
  /** One file the verdict rests on: `path` relative to the verdict file's directory, POSIX separators. */
41
43
  export interface HashedFile { path: string; bytes: number; sha256: string }
42
- interface LocalFile { abs: string; bytes: number; sha256: string }
44
+ interface LocalFile { abs: string; bytes: number; sha256: string; declaredPath?: string }
43
45
 
44
46
  /** A part (parts mode) or a named region (atlas mode). Boxes are rig px (parts) or page px (atlas). */
45
47
  export interface PartMesh { vertices: number[]; triangles: number[]; figures: Record<string, unknown>; width: number; height: number; image: string }
@@ -341,6 +343,66 @@ async function locateMeshRasters(rig: unknown, root: string, items: ViewItem[],
341
343
  }
342
344
  }
343
345
 
346
+ /** Resolve the existing inline declaration, or the frozen adjacent sidecar only when absent. */
347
+ export async function resolvePartsPaintingInRig(root: string, manifestBytes: Buffer,
348
+ read: (absolute: string, kind: 'sidecar' | 'painting') => Promise<Buffer> = absolute => readFile(absolute),
349
+ ): Promise<{paintingInRig?: PartsViewPackage['paintingInRig']; files: LocalFile[]; sidecar?: true}> {
350
+ const doc = record(JSON.parse(manifestBytes.toString('utf8')));
351
+ if (!doc) return refuse('PARTS_JSON_MALFORMED', 'parts.json must be an object');
352
+ const size = doc.rig_size;
353
+ const rigSize = Array.isArray(size) && size.length === 2 && size.every(n => finite(n, 1)) ? size : null;
354
+ const files: LocalFile[] = [];
355
+ let d = record(doc.painting_in_rig), sidecar: true | undefined;
356
+ if (Object.hasOwn(doc, 'painting_in_rig')) {
357
+ if (!d || Object.keys(d).length !== 3) refuse('PARTS_DIFFERENCE_PROVENANCE', 'declared path, lowercase SHA-256 and lanczos3-rgb-opaque required');
358
+ } else {
359
+ const declaredPath = join(root, 'painting_in_rig.json');
360
+ const info = await lstat(declaredPath).catch(error => {
361
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
362
+ return refuse('PARTS_DIFFERENCE_PATH', 'sidecar must be readable inside the package');
363
+ });
364
+ if (!info) return {files};
365
+ const abs = await safeFile(root, 'painting_in_rig.json').catch(() => refuse('PARTS_DIFFERENCE_PATH', 'sidecar must be readable inside the package'));
366
+ const bytes = await read(abs, 'sidecar').catch(error => {
367
+ if (['ENOENT', 'EACCES', 'EPERM', 'EISDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) return refuse('PARTS_DIFFERENCE_PATH', 'sidecar must be readable inside the package');
368
+ throw error;
369
+ });
370
+ try { d = record(JSON.parse(bytes.toString('utf8'))); }
371
+ catch { refuse('PARTS_DIFFERENCE_PROVENANCE', 'sidecar must be a JSON declaration'); }
372
+ const keys = ['schema', 'manifest_sha256', 'path', 'sha256', 'resample', 'rig_size'];
373
+ if (!d || Object.keys(d).length !== keys.length || !keys.every(key => Object.hasOwn(d!, key)) ||
374
+ d.schema !== 'rig-parts-painting-reference/1' || typeof d.manifest_sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(d.manifest_sha256)) {
375
+ refuse('PARTS_DIFFERENCE_PROVENANCE', 'sidecar requires the six frozen painting reference fields');
376
+ }
377
+ if (d!.manifest_sha256 !== hashBytes(join(root, 'parts.json'), manifestBytes).sha256) refuse('PARTS_DIFFERENCE_HASH', 'sidecar manifest hash differs');
378
+ const declaredSize = d!.rig_size;
379
+ if (!Array.isArray(declaredSize) || declaredSize.length !== 2 || !declaredSize.every(n => Number.isSafeInteger(n) && n > 0) ||
380
+ !rigSize || declaredSize.some((n, i) => n !== rigSize[i])) refuse('PARTS_DIFFERENCE_SIZE', 'sidecar rig_size must equal parts.json rig_size');
381
+ files.push({...hashBytes(abs, bytes), declaredPath});
382
+ sidecar = true;
383
+ }
384
+ if (!d || typeof d.path !== 'string' || typeof d.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(d.sha256) || d.resample !== 'lanczos3-rgb-opaque') {
385
+ refuse('PARTS_DIFFERENCE_PROVENANCE', 'declared path, lowercase SHA-256 and lanczos3-rgb-opaque required');
386
+ }
387
+ try { packagePath(d!.path, 'painting_in_rig'); } catch { refuse('PARTS_DIFFERENCE_PATH', 'literal portable inside-package path required'); }
388
+ const declaredPath = join(root, d!.path as string);
389
+ const unreadable = () => refuse('PARTS_DIFFERENCE_PATH', 'declared painting must be readable inside the package');
390
+ const abs = await safeFile(root, d!.path as string).catch(unreadable);
391
+ const bytes = await read(abs, 'painting').catch(error => {
392
+ if (['ENOENT', 'EACCES', 'EPERM', 'EISDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) return unreadable();
393
+ throw error;
394
+ }), sha256 = hashBytes(abs, bytes).sha256;
395
+ if (sha256 !== d!.sha256) refuse('PARTS_DIFFERENCE_HASH', 'declared painting hash differs');
396
+ let png: PNG;
397
+ try { png = PNG.sync.read(bytes); } catch { return refuse('PARTS_DIFFERENCE_PNG', 'declared painting must be RGBA8 PNG'); }
398
+ if (bytes[24] !== 8 || bytes[25] !== 6) refuse('PARTS_DIFFERENCE_PNG', 'declared painting must be RGBA8 PNG');
399
+ if (!rigSize || !rigSize.every(Number.isSafeInteger) || png.width !== rigSize[0] || png.height !== rigSize[1]) refuse('PARTS_DIFFERENCE_SIZE', 'declared painting dimensions must equal integer rig_size');
400
+ for (let i = 3; i < png.data.length; i += 4) if (png.data[i] !== 255) refuse('PARTS_DIFFERENCE_ALPHA', 'declared painting must have alpha 255');
401
+ const paintingInRig = {abs, declaredPath, bytes: bytes.length, sha256, width: png.width, height: png.height};
402
+ files.push(paintingInRig);
403
+ return {paintingInRig, files, ...(sidecar ? {sidecar} : {})};
404
+ }
405
+
344
406
  async function loadPartsMode(root: string, options: PartsViewOptions): Promise<PartsViewPackage> {
345
407
  const partsJson = await insideRoot(root, join(root, 'parts.json'), 'PARTS_FILE_OUTSIDE', 'parts.json');
346
408
  const { bytes: partsBytes, value: partsRaw } = await readJsonBytes(partsJson, 'parts.json');
@@ -365,23 +427,8 @@ async function loadPartsMode(root: string, options: PartsViewOptions): Promise<P
365
427
  imagePaths.push(real);
366
428
  items.push({ name: part.name, index, x: part.x, y: part.y, w: part.w, h: part.h, image: true });
367
429
  }
368
- let paintingInRig:PartsViewPackage['paintingInRig'];
369
- if(Object.hasOwn(doc,'painting_in_rig')){
370
- const d=record(doc.painting_in_rig);
371
- if(!d||Object.keys(d).length!==3||typeof d.path!=='string'||typeof d.sha256!=='string'||!/^[a-f0-9]{64}$/.test(d.sha256)||d.resample!=='lanczos3-rgb-opaque')refuse('PARTS_DIFFERENCE_PROVENANCE','declared path, lowercase SHA-256 and lanczos3-rgb-opaque required');
372
- try{packagePath(d!.path,'painting_in_rig');}catch{refuse('PARTS_DIFFERENCE_PATH','literal portable inside-package path required');}
373
- const declaredPath=join(root,d!.path as string);
374
- const unreadable=()=>refuse('PARTS_DIFFERENCE_PATH','declared painting must be readable inside the package');
375
- const abs=await safeFile(root,d!.path as string).catch(unreadable);
376
- const bytes=await readFile(abs).catch(unreadable);
377
- const sha256=createHash('sha256').update(bytes).digest('hex');
378
- if(sha256!==d!.sha256)refuse('PARTS_DIFFERENCE_HASH','declared painting hash differs');
379
- let png:PNG;try{png=PNG.sync.read(bytes);}catch{refuse('PARTS_DIFFERENCE_PNG','declared painting must be RGBA8 PNG');}
380
- if(bytes[24]!==8||bytes[25]!==6)refuse('PARTS_DIFFERENCE_PNG','declared painting must be RGBA8 PNG');
381
- if(!rigSize||!rigSize.every(Number.isSafeInteger)||png!.width!==rigSize[0]||png!.height!==rigSize[1])refuse('PARTS_DIFFERENCE_SIZE','declared painting dimensions must equal integer rig_size');
382
- for(let i=3;i<png!.data.length;i+=4)if(png!.data[i]!==255)refuse('PARTS_DIFFERENCE_ALPHA','declared painting must have alpha 255');
383
- paintingInRig={abs,declaredPath,bytes:bytes.length,sha256,width:png!.width,height:png!.height};files.push(paintingInRig);
384
- }
430
+ const {paintingInRig, files: paintingFiles} = await resolvePartsPaintingInRig(root, partsBytes);
431
+ files.push(...paintingFiles);
385
432
  let painting:PartsViewPackage['painting'];if(options.painting){
386
433
  // Both paths are physical: a user-designated alias to an inside file is valid,
387
434
  // while a link reaching outside is refused before any painting bytes are read.
@@ -473,6 +520,11 @@ export async function loadPartsView(input: string, options: PartsViewOptions = {
473
520
  return checkedVerdict(await loadAtlasMode(input, options));
474
521
  }
475
522
 
523
+ /** Opening is narrower than loading: keep embedded atlas inspection and saved verdict reads available. */
524
+ export function assertPartsCanOpen(pkg: Pick<PartsViewPackage, 'mode'>): void {
525
+ if (pkg.mode === 'atlas') refuse('PARTS_ATLAS_NOT_CARRIED', 'atlas inspection is not available in the parts workspace; open the rig review instead.');
526
+ }
527
+
476
528
  /** Compare names, real paths (including parent links), and filesystem identities before creating output. */
477
529
  async function assertVerdictDestination(pkg: Pick<PartsViewPackage, 'files' | 'flagFiles' | 'protectedPaths' | 'verdictPath'>): Promise<void> {
478
530
  const target = resolve(pkg.verdictPath);
@@ -511,6 +563,36 @@ export interface PartsVerdict {
511
563
  by?: string;
512
564
  }
513
565
 
566
+ /** The standalone comments envelope is a decoder until the consumer activation receipt. */
567
+ export function parseCommentsPartsVerdict(value: unknown): PartsCommentsVerdict {
568
+ const raw = commentsObject(value, ['schema', 'mode', 'tool', 'source', 'status', 'comments', 'updatedAt'], ['by']);
569
+ if (raw.schema !== PARTS_COMMENTS_VERDICT_SCHEMA || typeof raw.mode !== 'string' || !['parts', 'atlas'].includes(raw.mode) ||
570
+ typeof raw.status !== 'string' || !['approved', 'changes-requested'].includes(raw.status)) throw new Error('JOB_ACT_INVALID');
571
+ const tool = commentsObject(raw.tool, ['name', 'version']);
572
+ if (tool.name !== '@rig-c/review' || typeof tool.version !== 'string' || !tool.version) throw new Error('JOB_ACT_INVALID');
573
+ const source = commentsObject(raw.source, ['sha256', 'files', 'flags']);
574
+ jobSha(source.sha256);
575
+ if (!Array.isArray(source.files) || !source.files.length || !Array.isArray(source.flags)) throw new Error('JOB_ACT_INVALID');
576
+ for (const file of source.files) {
577
+ const row = commentsObject(file, ['path', 'sha256', 'bytes']);
578
+ if (typeof row.path !== 'string' || !row.path) throw new Error('JOB_ACT_INVALID');
579
+ jobSha(row.sha256); jobInteger(row.bytes);
580
+ }
581
+ for (const file of source.flags) {
582
+ const row = commentsObject(file, ['path', 'sha256']);
583
+ if (typeof row.path !== 'string' || !row.path) throw new Error('JOB_ACT_INVALID');
584
+ jobSha(row.sha256);
585
+ }
586
+ if (sourceSha256(source.files as HashedFile[]) !== source.sha256) throw new Error('JOB_ACT_INVALID');
587
+ if (typeof raw.updatedAt !== 'string' || !Number.isFinite(Date.parse(raw.updatedAt)) ||
588
+ 'by' in raw && (typeof raw.by !== 'string' || !raw.by)) throw new Error('JOB_ACT_INVALID');
589
+ const comments = parseComments(raw.comments, source.sha256 as string);
590
+ const issues = comments.filter(comment => comment.anchor && 'schema' in comment.anchor).length;
591
+ if (comments.some(comment => comment.anchor && !('schema' in comment.anchor)) ||
592
+ (raw.status === 'approved') !== (issues === 0)) throw new Error('JOB_ACT_INVALID');
593
+ return {...structuredClone(raw), comments} as unknown as PartsCommentsVerdict;
594
+ }
595
+
514
596
  export interface LegacyPartsVerdictView {
515
597
  schema: LegacyVerdictSchema;
516
598
  status: LegacyVerdictStatus;
@@ -761,6 +843,7 @@ async function decodeLegacyVerdict(
761
843
  export async function assertPartsUnchanged(pkg: Pick<PartsViewPackage, 'files' | 'flagFiles' | 'paintingInRig'>): Promise<void> {
762
844
  if(pkg.paintingInRig&&await realpath(pkg.paintingInRig.declaredPath).catch(()=>null)!==pkg.paintingInRig.abs)refuse('PARTS_VIEW_SOURCE_CHANGED','declared painting path changed');
763
845
  for (const f of [...pkg.files, ...pkg.flagFiles]) {
846
+ if (f.declaredPath && await realpath(f.declaredPath).catch(() => null) !== f.abs) refuse('PARTS_VIEW_SOURCE_CHANGED', 'declared input path changed');
764
847
  const now = await hashFile(f.abs).catch(() => null);
765
848
  if (!now || now.sha256 !== f.sha256) refuse('PARTS_VIEW_SOURCE_CHANGED', `${basename(f.abs)} changed after the view opened; reopen it to review what is on disk`);
766
849
  }