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,6 +9,73 @@ import { environmentSummary, parseEnvironmentContext } from './environment.ts';
9
9
  import { appliedSummary } from './applied-context.ts';
10
10
  import { requirementsSummaryLine } from './requirements.ts';
11
11
  import { scheduleContextLine } from './environment-schedule.ts';
12
+ import {parseCommentsSession} from './session.ts';
13
+ import {projectComments} from './stage-comment.ts';
14
+ import type {ReviewCommentsSession, JobCommentFeedbackAnchor, JobCommentPartsAnchor} from './job-contract.ts';
15
+ import type {PartsIssue} from './parts-comment.ts';
16
+ import type {JobComment, JobActValues, ActV3, JobCommentsAct} from './job-contract.ts';
17
+ import type {CompareFeedback} from './compare-session.ts';
18
+ import {parseRecordAct} from './job-api.ts';
19
+
20
+ /** Browser-safe mappers live beside projectComments; this module keeps exporting them. */
21
+ export {feedbackItemComments, checkpointNoteComments} from './stage-comment.ts';
22
+
23
+ /** Per-ask feedback has no ask anchor in act@6. */
24
+ export function feedbackWordsComments(words: string): JobComment[] {
25
+ return [{text: words}];
26
+ }
27
+
28
+ export {partsIssueComments} from './parts-comment.ts';
29
+
30
+ /** A blank note has no comment form: it maps to no comments, never to a padded entry. */
31
+ export function noteComments(words: string): JobComment[] {
32
+ return words.trim() ? feedbackWordsComments(words) : [];
33
+ }
34
+
35
+ /** Named-image notes retain sealed image names; no region evidence is manufactured. */
36
+ export function imageNoteComments(notes: readonly {readonly name: string; readonly words: string}[]): JobComment[] {
37
+ return notes.map(({name, words}) => ({text: words, anchor: {name}}));
38
+ }
39
+
40
+ /** Display only over decoded legacy sessions: historical fields are general comments. */
41
+ export function legacySessionComments(session: Pick<ReviewSession, 'feedback'> & Partial<Pick<ReviewSession, 'checkpoints'>>): {text: string}[] {
42
+ return legacyFeedbackComments([
43
+ ...Object.values(session.checkpoints ?? {}).map(checkpoint => checkpoint.note),
44
+ ...session.feedback.map(item => item.summary),
45
+ ]);
46
+ }
47
+
48
+ /** Reuse the record decoder; survey answers must never become feedback. */
49
+ export function legacyRecordActComments(raw: unknown): {text: string}[] {
50
+ return legacyActComments(parseRecordAct(raw));
51
+ }
52
+
53
+ /** Display projection of already-decoded @2–@5 acts, without upgrading their envelopes. */
54
+ export function legacyActComments(act: Exclude<ActV3, JobCommentsAct>): {text: string}[] {
55
+ if (act.kind === 'interview-picks') return [];
56
+ const value = act.value;
57
+ const fields = [value.words];
58
+ if ('imageNotes' in value) fields.push(...(value.imageNotes ?? []).map(note => note.words));
59
+ if ('issues' in value) fields.push(...value.issues.map(issue => issue.summary));
60
+ else if ('parts' in value) fields.push(...value.parts.flatMap(part => [part.part.note, part.mesh.note]));
61
+ return legacyFeedbackComments(fields);
62
+ }
63
+
64
+ /** A display view over explicitly selected legacy feedback fields, including empty strings. */
65
+ export function legacyFeedbackComments(fields: readonly string[]): {text: string}[] {
66
+ if (!Array.isArray(fields) || fields.some(value => typeof value !== 'string')) throw new Error('JOB_ACT_INVALID');
67
+ return fields.map(text => ({text}));
68
+ }
69
+
70
+ /** Pure adapter arguments. The source session/2 bytes stay in the consumer's receipt. */
71
+ export function projectSelectedCommentsFeedback(session: ReviewCommentsSession, itemId: string): {
72
+ anchor: JobCommentFeedbackAnchor; summary: string;
73
+ } {
74
+ const parsed = parseCommentsSession(session);
75
+ const matches = parsed.comments.filter(comment => comment.anchor && 'frameStart' in comment.anchor && comment.anchor.id === itemId);
76
+ if (matches.length !== 1) throw new Error('JOB_ACT_INVALID');
77
+ return {anchor: matches[0]!.anchor as JobCommentFeedbackAnchor, summary: projectComments(matches)};
78
+ }
12
79
  type Category = Feedback['category'];
13
80
  type Side = 'single' | 'a' | 'b';
14
81
  type ParsedFeedbackSession = FeedbackHistory<ReviewSession | CompareSession>;
package/src/front.ts CHANGED
@@ -24,11 +24,12 @@ const uuid=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,hex6
24
24
  const frontName=(port:number)=>`front-${port}`;
25
25
  const noStore={'Cache-Control':'no-store','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer'};
26
26
  const refuse=(error:string,status:number)=>Response.json({error},{status,headers:noStore});
27
- export function frontPort(value?:number):number{const raw=value??(process.env.RIG_REVIEW_FRONT_PORT===undefined?defaultFrontPort:Number(process.env.RIG_REVIEW_FRONT_PORT));if(!Number.isSafeInteger(raw)||raw<1||raw>65535)throw new Error('FRONT_PORT: RIG_REVIEW_FRONT_PORT expects an integer 1..65535');return raw;}
28
- function frontValue(value:unknown,port:number):FrontRecord|null{if(!value||typeof value!=='object'||Array.isArray(value))return null;const v=value as Partial<FrontRecord>;return v.schema==='rig-review-front/1'&&v.port===port&&v.origin===`http://127.0.0.1:${port}`&&uuid.test(v.nonce??'')&&hex64.test(v.fingerprint??'')&&Number.isSafeInteger(v.pid)&&v.pid!>0?v as FrontRecord:null;}
27
+ export function frontPort(value?:number):number{const raw=value??(process.env.RIG_REVIEW_FRONT_PORT===undefined?defaultFrontPort:Number(process.env.RIG_REVIEW_FRONT_PORT));if(!Number.isSafeInteger(raw)||raw<(value===0?0:1)||raw>65535)throw new Error('FRONT_PORT: RIG_REVIEW_FRONT_PORT expects an integer 1..65535');return raw;}
28
+ function frontValue(value:unknown,port:number):FrontRecord|null{if(!value||typeof value!=='object'||Array.isArray(value))return null;const v=value as Partial<FrontRecord>;return v.schema==='rig-review-front/1'&&Number.isSafeInteger(v.port)&&v.port!>=1&&v.port!<=65535&&(port===0||v.port===port)&&v.origin===`http://127.0.0.1:${v.port}`&&uuid.test(v.nonce??'')&&hex64.test(v.fingerprint??'')&&Number.isSafeInteger(v.pid)&&v.pid!>0?v as FrontRecord:null;}
29
29
  async function readFront(file:string,port:number):Promise<FrontRecord|null>{try{return frontValue(await smallJson(file),port);}catch(e){if(['ENOENT','ELOOP'].includes((e as NodeJS.ErrnoException).code??'')||e instanceof SyntaxError)return null;throw e;}}
30
30
  async function frontAlive(row:FrontRecord):Promise<boolean>{try{const response=await fetch(row.origin+'/api/front-status',{headers:{authorization:'Bearer '+row.nonce},redirect:'error',signal:AbortSignal.timeout(1500)});if(!response.ok){void response.body?.cancel();return false;}const v=await response.json() as {schema?:string;nonce?:string;fingerprint?:string};return v.schema==='rig-review-front-status/1'&&v.nonce===row.nonce&&v.fingerprint===row.fingerprint;}catch{return false;}}
31
- /** Ensure this state directory's front on `port`; reuse a verified live one. A front from another tool
31
+ /** Ensure this state directory's front on `port`; reuse a verified live one.
32
+ * Port 0 binds an OS-assigned port and stores its actual origin in front-0.json. A front from another tool
32
33
  * build is ours (verified nonce) and is replaced. Any other listener is FRONT_PORT_BUSY, never a fallback. */
33
34
  export async function ensureFront(options:{control:string;port:number;fingerprint:string;idleMs?:number}):Promise<string>{
34
35
  const {control,port,fingerprint}=options,name=frontName(port),recordPath=join(control,name+'.json'),nonce=randomUUID(),deadline=performance.now()+20000,idleMs=options.idleMs??DEFAULT_CLOSE_GRACE_MS;
@@ -55,12 +56,10 @@ export function frontRoute(mode:'single'|'compare',method:string,path:string):Ro
55
56
  const read=method==='GET'||method==='HEAD',get:Route={mutation:false,limit:0,timeoutMs:30000,control:false};
56
57
  if(path===LIVE_PATH)return method==='GET'?{...get,live:true}:null;
57
58
  if(['/','/index.html','/main.js','/styles.css','/api/access'].includes(path))return read?get:null;
58
- if(['/stage-parts.html','/parts.js','/parts.css'].includes(path))return read?get:null;
59
59
  if((mode==='single'?/^\/api\/stage-parts(?:\/(?:image|page)\/\d+)?$/:/^\/api\/compare\/(?:a|b)\/stage-parts(?:\/(?:image|page)\/\d+)?$/).test(path))return read?get:null;
60
60
  if(mode==='single'){
61
61
  if(path==='/api/stage-parts/verdict')return method==='POST'?{...get,mutation:true,limit:stageVerdictLimit}:null;
62
62
  if(path==='/api/stage-parts/export/json'||path==='/api/stage-parts/export/issue')return read?get:null;
63
- if(['/stage-interview.html','/interview.js','/interview.css'].includes(path))return method==='GET'?get:null;
64
63
  if(interviewRequest(path))return path==='/api/interview/picks'?
65
64
  method==='POST'?{...get,mutation:true,limit:picksLimit}:null:method==='GET'?get:null;
66
65
  }
@@ -103,12 +102,6 @@ async function instanceRecord(control:string,key:string):Promise<RecordFile|null
103
102
  /** Worker errors default to front codes unless an inspection refusal is allowlisted. */
104
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'};
105
104
  const responseHeaders=['content-type','content-length','content-range','accept-ranges','content-disposition','cache-control','content-security-policy','x-content-type-options','referrer-policy'];
106
- /** The trusted atlas frame alone may carry this closed navigation query. */
107
- export function stageFrameQuery(mode:'single'|'compare',search:string):boolean {
108
- const params=new URLSearchParams(search),keys=[...params.keys()];
109
- const allowed=mode==='single'?['stageEmbed','lang']:['stageEmbed','lang','side'];
110
- return keys.length===allowed.length&&new Set(keys).size===keys.length&&keys.every(k=>allowed.includes(k))&&params.get('stageEmbed')==='1'&&['en','ko'].includes(params.get('lang')??'')&&(mode==='single'||['a','b'].includes(params.get('side')??''));
111
- }
112
105
  // The submitted Apply can supply the check line. Accept the producer's structured
113
106
  // summary fields, never an arbitrary suffix after the failed-check code.
114
107
  const submitCheckPrefix = 'EDIT_SUBMIT_UNCHECKED: applied build failed check — ';
@@ -156,7 +149,7 @@ async function inspectionRefusal(mode:'single'|'compare',method:string,path:stri
156
149
  export const maximumUpstreamStreams=32;
157
150
  interface FrontLiveRelay {upstream:WebSocket;client:ServerWebSocket<FrontLiveRelay>|null}
158
151
  export function startFront(options:{control:string;port:number;nonce:string;fingerprint:string}){
159
- const origin=`http://127.0.0.1:${options.port}`;let active=0,last=performance.now();
152
+ let origin:string;let active=0,last=performance.now();
160
153
  const server=Bun.serve<FrontLiveRelay>({hostname:'127.0.0.1',port:options.port,websocket:{
161
154
  idleTimeout:0,
162
155
  open(ws){last=performance.now();ws.data.client=ws;if(ws.data.upstream.readyState!==WebSocket.OPEN){try{ws.close();}catch{}return;}try{ws.send('live');}catch{}},
@@ -172,7 +165,7 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
172
165
  if(req.headers.get('sec-fetch-site')==='cross-site'||sentOrigin!==null&&sentOrigin!==origin)return refuse('FRONT_SAME_ORIGIN_REQUIRED',403);
173
166
  const record=await instanceRecord(options.control,key);if(!record)return refuse('FRONT_INSTANCE_UNKNOWN: reopen with rig-review open',404);
174
167
  const route=frontRoute(record.mode,req.method,path);if(!route)return refuse('FRONT_ROUTE_REFUSED',404);
175
- const landing=path==='/'||path==='/index.html',stageFrame=path==='/stage-parts.html'||path==='/stage-interview.html';if(stageFrame?!stageFrameQuery(record.mode,url.search):!landing&&!!url.search)return refuse('FRONT_QUERY_REFUSED',400);
168
+ const landing=path==='/'||path==='/index.html';if(!landing&&!!url.search)return refuse('FRONT_QUERY_REFUSED',400);
176
169
  if(route.live){
177
170
  if(sentOrigin!==origin)return refuse('FRONT_SAME_ORIGIN_REQUIRED',403);
178
171
  if(req.headers.get('upgrade')?.toLowerCase()!=='websocket')return refuse('FRONT_UPGRADE_REQUIRED',426);
@@ -217,7 +210,7 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
217
210
  active++;let released=false;const abort=new AbortController(),timer=setTimeout(()=>abort.abort(),route.timeoutMs);const release=()=>{if(released)return;released=true;active--;clearTimeout(timer);};
218
211
  req.signal.addEventListener('abort',()=>abort.abort(),{once:true});
219
212
  let upstream:Response;
220
- try{upstream=await fetch(record.origin+path+(landing||stageFrame?url.search:''),{method:req.method,headers,...(body?{body}:{}),redirect:'manual',signal:abort.signal});}
213
+ try{upstream=await fetch(record.origin+path+(landing?url.search:''),{method:req.method,headers,...(body?{body}:{}),redirect:'manual',signal:abort.signal});}
221
214
  catch{release();return abort.signal.aborted&&!req.signal.aborted?refuse('FRONT_UPSTREAM_TIMEOUT',504):refuse('FRONT_INSTANCE_EXPIRED: reopen with rig-review open',410);}
222
215
  if(upstream.headers.get(openKeyHeader)!==key){void upstream.body?.cancel().catch(()=>{});release();return refuse('FRONT_INSTANCE_REPLACED: reopen with rig-review open',410);}
223
216
  if(upstream.status>=400&&upstream.status!==416){const named=await inspectionRefusal(record.mode,req.method,path,upstream,record.fingerprint===options.fingerprint);void upstream.body?.cancel().catch(()=>{});release();if(named)return refuse(named,upstream.status);const code=upstreamFailure[upstream.status];return refuse(code??'FRONT_UPSTREAM_FAILED',code?upstream.status:502);}
@@ -229,18 +222,19 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
229
222
  return new Response(stream,{status:upstream.status,headers:out});
230
223
  }catch(error){const message=error instanceof Error?error.message:'';return refuse(message.startsWith('FRONT_')?message:'FRONT_REQUEST_FAILED',message==='FRONT_BODY_LIMIT'?413:message==='FRONT_BODY_TIMEOUT'?408:400);}
231
224
  }});
225
+ origin=`http://127.0.0.1:${server.port}`;
232
226
  return {origin,stop:()=>server.stop(true),idleMs:()=>performance.now()-last,active:()=>active};
233
227
  }
234
228
  /** A missing directory or record means gone; any other read error (readdir or a record) throws, and the caller keeps
235
229
  * the front up. A record read that failed with EACCES or ENOTDIR used to count as gone and stopped the front (#354). */
236
230
  async function liveInstances(control:string):Promise<boolean>{let names:string[];try{names=await readdir(control);}catch(e){if((e as NodeJS.ErrnoException).code==='ENOENT')return false;throw e;}for(const name of names){if(/^[a-f0-9]{64}\.claim$/.test(name))return true;if(/^[a-f0-9]{64}\.json$/.test(name)){const row=await readRecord(join(control,name),name.slice(0,64));if(row&&running(row.pid))return true;}}return false;}
237
231
  export async function runFront(requestPath:string):Promise<void>{
238
- const spec=await smallJson(requestPath) as FrontRequest;if(spec?.schema!=='rig-review-front-request/1'||!uuid.test(spec.nonce??'')||!hex64.test(spec.fingerprint??'')||!Number.isSafeInteger(spec.port)||spec.port<1||spec.port>65535||!Number.isSafeInteger(spec.idleMs)||spec.idleMs<100)throw new Error('front: invalid request');
232
+ const spec=await smallJson(requestPath) as FrontRequest;if(spec?.schema!=='rig-review-front-request/1'||!uuid.test(spec.nonce??'')||!hex64.test(spec.fingerprint??'')||!Number.isSafeInteger(spec.port)||spec.port<0||spec.port>65535||!Number.isSafeInteger(spec.idleMs)||spec.idleMs<100)throw new Error('front: invalid request');
239
233
  const control=await realpath(spec.control);if(dirname(await realpath(requestPath))!==control||spec.request!==requestPath||spec.record!==join(control,frontName(spec.port)+'.json'))throw new Error('front: invalid state locations');
240
234
  if(await openFingerprint()!==spec.fingerprint)throw new Error('front: tool changed before startup');
241
235
  let front:ReturnType<typeof startFront>;
242
236
  try{front=startFront({control,port:spec.port,nonce:spec.nonce,fingerprint:spec.fingerprint});}catch(error){if((error as NodeJS.ErrnoException).code==='EADDRINUSE'||/in use/i.test(error instanceof Error?error.message:''))throw new Error(`FRONT_PORT_BUSY: 127.0.0.1:${spec.port}`);throw error;}
243
- const record:FrontRecord={schema:'rig-review-front/1',origin:front.origin,port:spec.port,nonce:spec.nonce,fingerprint:spec.fingerprint,pid:process.pid},tmp=spec.record+'.'+spec.nonce+'.tmp';await writeFile(tmp,JSON.stringify(record),{mode:0o600,flag:'wx'});await rename(tmp,spec.record);
237
+ const record:FrontRecord={schema:'rig-review-front/1',origin:front.origin,port:Number(new URL(front.origin).port),nonce:spec.nonce,fingerprint:spec.fingerprint,pid:process.pid},tmp=spec.record+'.'+spec.nonce+'.tmp';await writeFile(tmp,JSON.stringify(record),{mode:0o600,flag:'wx'});await rename(tmp,spec.record);
244
238
  await unlink(requestPath).catch(e=>{if(e.code!=='ENOENT')throw e;});
245
239
  let stopped=false;const stop=async(reason:string)=>{if(stopped)return;stopped=true;clearInterval(timer);front.stop();const current=await readFront(spec.record,spec.port).catch(()=>null);if(current?.nonce===spec.nonce)await unlink(spec.record).catch(()=>{});console.log(`review front: exiting — ${reason}.`);process.exit(0);};
246
240
  // Idle exit only once no request arrived for idleMs and no live worker record remains.
@@ -70,7 +70,7 @@ export function interviewRoutes(root: string, output: string, capability: string
70
70
  if (req.method === 'GET' && url.pathname === '/api/interview') {
71
71
  const validated = await current();
72
72
  const dir = destination();
73
- return json({...(joined ? {binding:{projectHash:opened.hash, sourceHash:joined.sourceHash, ...(joined.draftId===undefined?{version:joined.version}:{draftId:joined.draftId})}} : {}), historical:validated.historical, diagnostics:validated.diagnostics, questions:validated.questions.map(question => ({
73
+ return json({...(joined && (joined.version!==undefined||joined.draftId!==undefined) ? {binding:{projectHash:opened.hash, sourceHash:joined.sourceHash, ...(joined.draftId===undefined?{version:joined.version}:{draftId:joined.draftId})}} : {}), historical:validated.historical, diagnostics:validated.diagnostics, questions:validated.questions.map(question => ({
74
74
  ...question, saved:question.editable ? readPicks(dir, question) : null,
75
75
  images:question.images.map(({name}, index) => ({name, url:'/api/interview/image/' + question.ref.sha256 + '/' + index})),
76
76
  }))});
package/src/job-act.ts CHANGED
@@ -1,15 +1,17 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import {
3
- JOB_ACT_SCHEMA, JOB_API_SCHEMA, JOB_API_V3_SCHEMA, JOB_PARTS_VERDICT_ACT_SCHEMA, JOB_RECORD_ACT_KINDS, JOB_RECORD_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, jobStillByteLimit, JOB_ENABLED_ACT_KINDS, JOB_PLAN_BOUND_SIGNOFF_STAGES, JOB_RESERVED_ACT_KINDS,
4
- type ActV3, type JobAct, type JobActValues, type JobApiSchema, type JobPendingAsk, type JobPublicationMode, type JobReviewerBinding,
3
+ JOB_ACT_SCHEMA, JOB_API_SCHEMA, JOB_COMMENTS_ACT_SCHEMA, JOB_API_V3_SCHEMA, JOB_RECORD_ACT_KINDS, JOB_RECORD_ACT_SCHEMA, jobStillByteLimit, JOB_ENABLED_ACT_KINDS, JOB_PLAN_BOUND_SIGNOFF_STAGES, JOB_RESERVED_ACT_KINDS,
4
+ type ActV3, type JobAct, type JobCommentsAct, type JobApiSchema, type JobPendingAsk, type JobPublicationMode, type JobReviewerBinding,
5
5
  type JobSourceBinding, type JobSubject, type JobUISubmission, type JobRigCapture, type JobRigStill,
6
6
  type PendingAskV3, type RecordAct, type RecordSource, type RecordSubject, type SourceV3, type UISubmissionV3,
7
7
  } from './job-contract.ts';
8
8
  import { parsePartsIssue, type PartsIssue } from './parts-comment.ts';
9
9
  import {
10
10
  isRecordSource, jobHash, jobId, jobInteger, jobObject,
11
- parseRecordAct, parseRecordSource, requestDigest, validateRecordAskSubject,
11
+ parseCommentsAct, parseRecordAct, parseRecordSource, requestDigest, validateRecordAskSubject,
12
12
  } from './job-api.ts';
13
+ import { checkpointNoteComments, feedbackItemComments, noteComments, partsIssueComments } from './feedback-export.ts';
14
+ import type { Feedback } from './session.ts';
13
15
  import { validatePicks } from './interview-picks.ts';
14
16
  import {
15
17
  isRetainedRecordSource,
@@ -27,6 +29,12 @@ function words(value: unknown): string {
27
29
  return value;
28
30
  }
29
31
 
32
+ /** The writer's output must decode through the public @6 decoder; its refusal is JOB_ACT_INVALID. */
33
+ function commentsAct(act: JobCommentsAct): JobCommentsAct {
34
+ parseCommentsAct(act);
35
+ return act;
36
+ }
37
+
30
38
  function choice<Value extends string>(value: unknown, allowed: readonly Value[]): Value {
31
39
  if (!allowed.includes(value as Value)) throw new JobError('JOB_ACT_INVALID');
32
40
  return value as Value;
@@ -504,6 +512,8 @@ export function finalizeJobAct(options: {
504
512
  authority: { actor: 'human' as const, channel: 'review-ui' as const, reviewer: structuredClone(reviewer) },
505
513
  at,
506
514
  };
515
+ // Image-review and interview-picks keep act@2: Create refuses both under act@6.
516
+ const comments = {...envelope, schema: JOB_COMMENTS_ACT_SCHEMA};
507
517
  if (source.subject === 'image-set') {
508
518
  if (submission.kind !== 'review-verdict' || ask.subject.kind !== 'review-verdict' ||
509
519
  ask.subject.stage !== 'image-review') throw new JobError('JOB_ACT_INVALID');
@@ -553,10 +563,12 @@ export function finalizeJobAct(options: {
553
563
  const value = jobObject(submission.value, ['checkpointId', 'outcome', 'words']);
554
564
  const subject = ask.subject;
555
565
  if (subject.kind !== 'checkpoint' || value.checkpointId !== subject.checkpointId) throw new JobError('JOB_ACT_INVALID');
556
- return { ...envelope, kind: 'checkpoint', source: { ...source, plan: source.plan! }, value: {
557
- checkpointId: subject.checkpointId, planStepId: subject.planStepId ?? subject.checkpointId,
558
- outcome: choice(value.outcome, ['pass', 'fail'] as const), words: words(value.words),
559
- } };
566
+ const planStepId = subject.planStepId ?? subject.checkpointId, note = words(value.words);
567
+ return commentsAct({ ...comments, kind: 'checkpoint', source: { ...source, plan: source.plan! }, value: {
568
+ checkpointId: subject.checkpointId, planStepId,
569
+ outcome: choice(value.outcome, ['pass', 'fail'] as const),
570
+ comments: note.trim() ? checkpointNoteComments({checkpointId: subject.checkpointId, planStepId, note}) : [],
571
+ } });
560
572
  }
561
573
  case 'parts-verdict': {
562
574
  const value = jobObject(submission.value, ['verdict', 'issues', 'words']);
@@ -590,9 +602,8 @@ export function finalizeJobAct(options: {
590
602
  }
591
603
  return structuredClone(issue);
592
604
  });
593
- return {
594
- ...envelope,
595
- schema: JOB_PARTS_VERDICT_ACT_SCHEMA,
605
+ return commentsAct({
606
+ ...comments,
596
607
  kind: 'parts-verdict',
597
608
  source: {
598
609
  ...source,
@@ -600,31 +611,38 @@ export function finalizeJobAct(options: {
600
611
  selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, { kind: 'draft' }>,
601
612
  parts: source.parts!,
602
613
  },
603
- value: { verdict, issues, words: words(value.words) },
604
- };
614
+ value: { verdict, comments: [...partsIssueComments(issues), ...noteComments(words(value.words))] },
615
+ });
605
616
  }
606
617
  case 'review-verdict': {
607
- const value = jobObject(submission.value, ['stage', 'verdict', 'words']);
618
+ const value = jobObject(submission.value, ['stage', 'verdict', 'words',
619
+ ...(ask.subject.kind === 'review-verdict' && ask.subject.stage === 'rig-review' ? ['feedback'] : [])]);
608
620
  if (ask.subject.kind !== 'review-verdict' || ask.subject.stage === 'image-review' || value.stage !== ask.subject.stage) throw new JobError('JOB_ACT_INVALID');
609
621
  if (ask.subject.stage === 'rig-review') {
610
622
  if (!options.still) throw new JobError('JOB_STILL_CAPTURE_FAILED');
611
- return {...envelope, schema: JOB_RIG_REVIEW_ACT_SCHEMA, kind: 'review-verdict',
623
+ const note = words(value.words);
624
+ if (value.feedback !== undefined && !Array.isArray(value.feedback)) throw new JobError('JOB_ACT_INVALID');
625
+ let verdictComments: ReturnType<typeof noteComments>;
626
+ try {
627
+ verdictComments = value.feedback === undefined ? noteComments(note) : feedbackItemComments(value.feedback as Feedback[]);
628
+ } catch { throw new JobError('JOB_ACT_INVALID'); }
629
+ return commentsAct({...comments, kind: 'review-verdict',
612
630
  source: {...source, model: source.model!, selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, {kind: 'rig'}>},
613
- value: {stage: 'rig-review', verdict: choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const), words: words(value.words)},
614
- still: options.still};
631
+ value: {stage: 'rig-review', verdict: choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const), comments: verdictComments},
632
+ still: options.still});
615
633
  }
616
- return { ...envelope, kind: 'review-verdict', source: { ...source, model: source.model!,
634
+ return commentsAct({ ...comments, kind: 'review-verdict', source: { ...source, model: source.model!,
617
635
  selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, { kind: 'rig' | 'post' }> }, value: {
618
- stage: ask.subject.stage, verdict: choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const), words: words(value.words),
619
- } };
636
+ stage: ask.subject.stage, verdict: choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const), comments: noteComments(words(value.words)),
637
+ } });
620
638
  }
621
639
  case 'signoff': {
622
640
  const value = jobObject(submission.value, ['stage', 'decision', 'words']);
623
641
  if (ask.subject.kind !== 'signoff' || value.stage !== ask.subject.stage || value.decision !== 'approved') {
624
642
  throw new JobError('JOB_ACT_INVALID');
625
643
  }
626
- const result: JobActValues['signoff'] = { stage: ask.subject.stage, decision: 'approved', words: words(value.words) };
627
- return { ...envelope, kind: 'signoff', source, value: result };
644
+ return commentsAct({ ...comments, kind: 'signoff', source,
645
+ value: { stage: ask.subject.stage, decision: 'approved', comments: noteComments(words(value.words)) } });
628
646
  }
629
647
  }
630
648
  }
package/src/job-api.ts CHANGED
@@ -17,6 +17,17 @@ import {
17
17
  } from './job-contract.ts';
18
18
  import { JobError } from './job-store.ts';
19
19
  import type { JobSession } from './job-session.ts';
20
+ import { JOB_COMMENTS_ACT_SCHEMA, JOB_COMMENT_CONTEXT_ACT_SCHEMA, type JobCommentContext, type JobContextComment,
21
+ type JobContextCommentsAct, type JobComment, type JobCommentAnchor, type JobCommentsAct,
22
+ type SourceV3, type JobRigStill } from './job-contract.ts';
23
+ import { parseFeedback } from './session.ts';
24
+ import { parsePartsIssue } from './parts-comment.ts';
25
+ import { parseStageComment, hasStageComment, projectComments, commentModes } from './stage-comment.ts';
26
+ import { validatePngCrop, validatePngCropMetadata } from './comment-crops.ts';
27
+ import {parseJobImageSetBinding} from './job-image-set.ts';
28
+ import {parseJobPartsIdentity} from './job-source.ts';
29
+ import {parseControlPart, parseControlView} from './control.ts';
30
+ import {EMIT_UNPINNED_CREATE_FIELDS} from './create-pin-gate.ts';
20
31
 
21
32
  export type {
22
33
  JobInterviewJson,
@@ -1181,6 +1192,286 @@ export function parseRecordAct(value: unknown): RecordAct {
1181
1192
  throw new JobError('JOB_ACT_INVALID');
1182
1193
  }
1183
1194
 
1195
+ /** Shared closed object reader for the comments contract; legacy readers retain their rules. */
1196
+ export function commentsObject(value: unknown, keys: readonly string[], optional: readonly string[] = []): Record<string, unknown> {
1197
+ if (!value || typeof value !== 'object' || Object.getPrototypeOf(value) !== Object.prototype) throw new JobError('JOB_ACT_INVALID');
1198
+ return exactObject(value, keys, 'JOB_ACT_INVALID', optional);
1199
+ }
1200
+
1201
+ function commentCrop(value: unknown): void {
1202
+ const crop = commentsObject(value, ['path', 'sha256', 'width', 'height'], ['png']);
1203
+ jobSha(crop.sha256);
1204
+ validatePngCropMetadata(crop as unknown as Parameters<typeof validatePngCropMetadata>[0]);
1205
+ if (Object.hasOwn(crop, 'png')) validatePngCrop(crop as unknown as Parameters<typeof validatePngCrop>[0]);
1206
+ }
1207
+
1208
+ /** Both checkpoint values and pins obey the source's declared checkpoint mapping. */
1209
+ function assertCommentsCheckpointBinding(source: SourceV3, checkpointId: string, planStepId: string): void {
1210
+ if (!source.plan?.steps.some(step => step.id === planStepId) ||
1211
+ 'record' in source && checkpointId !== planStepId) throw new JobError('JOB_ACT_INVALID');
1212
+ const evidence = source.checkpointEvidence?.find(packet => packet.checkpointId === checkpointId);
1213
+ if (evidence && evidence.planStepId !== planStepId) throw new JobError('JOB_ACT_INVALID');
1214
+ }
1215
+
1216
+ function parseCommentAnchor(raw: unknown, text: string, source?: SourceV3 | string): JobCommentAnchor {
1217
+ const item = commentsObject(raw, [], Object.keys(raw && typeof raw === 'object' ? raw : {}));
1218
+ const sourceHash = typeof source === 'string' ? source : source?.sourceHash;
1219
+ if ('schema' in item) {
1220
+ commentsObject(item, ['schema', 'id', 'parts', 'sourceHash', 'rigRegion', 'imageRegion', 'view', 'crop', 'nativeCrop']);
1221
+ const issue = parsePartsIssue({...item, summary: text}, true, false, false);
1222
+ if (issue.crop.png !== undefined) validatePngCrop(issue.crop as Parameters<typeof validatePngCrop>[0]);
1223
+ if (sourceHash && issue.sourceHash !== sourceHash) throw new JobError('JOB_ACT_SOURCE_STALE');
1224
+ if (source && typeof source !== 'string' && !('record' in source)) {
1225
+ if (!source.parts || issue.parts.some(part => !source.parts!.images.some(image =>
1226
+ image.role === 'part' && image.path === `parts/${part.name}.png` && image.sha256 === part.imageHash))) throw new JobError('JOB_ACT_SOURCE_STALE');
1227
+ }
1228
+ const {summary: _summary, ...anchor} = issue;
1229
+ return anchor;
1230
+ }
1231
+ if ('frameStart' in item) {
1232
+ commentsObject(item, ['id', 'frameStart', 'frameEnd', 'target', 'category'], ['context', 'side']);
1233
+ commentsObject(item.target, ['kind', 'name']);
1234
+ jobId(item.id);
1235
+ if ('side' in item && item.side !== 'a' && item.side !== 'b') throw new JobError('JOB_ACT_INVALID');
1236
+ const feedback = parseFeedback({...item, summary: text});
1237
+ const context = feedback.context as Record<string, unknown> | undefined;
1238
+ if (hasStageComment(context?.comment)) {
1239
+ const mark = parseStageComment(context!.comment);
1240
+ validatePngCrop(mark.crop);
1241
+ if (sourceHash && mark.sourceHash !== sourceHash) throw new JobError('JOB_ACT_SOURCE_STALE');
1242
+ if (source && typeof source !== 'string' && !('record' in source) &&
1243
+ mark.viewport !== 'reference' && mark.modelHash !== source.model?.sha256) throw new JobError('JOB_ACT_SOURCE_STALE');
1244
+ }
1245
+ const {summary: _summary, ...anchor} = feedback;
1246
+ return {...anchor, ...('side' in item ? {side: item.side as 'a' | 'b'} : {})};
1247
+ }
1248
+ if ('checkpointId' in item) {
1249
+ commentsObject(item, ['checkpointId', 'planStepId']);
1250
+ const checkpointId = jobId(item.checkpointId), planStepId = jobId(item.planStepId);
1251
+ if (source && typeof source !== 'string') assertCommentsCheckpointBinding(source, checkpointId, planStepId);
1252
+ return {checkpointId, planStepId};
1253
+ }
1254
+ if ('name' in item) {
1255
+ commentsObject(item, ['name'], ['imageRegion', 'crop', 'nativeCrop']);
1256
+ const name = jobText(item.name);
1257
+ if (source && (typeof source === 'string' || source.subject !== 'image-set' ||
1258
+ !source.imageSet.images.some(image => image.name === name))) throw new JobError('JOB_ACT_SOURCE_STALE');
1259
+ if (Object.keys(item).length === 1) return {name};
1260
+ commentsObject(item, ['name', 'imageRegion', 'crop', 'nativeCrop']);
1261
+ const region = commentsObject(item.imageRegion, ['x', 'y', 'width', 'height']);
1262
+ for (const axis of ['x', 'y', 'width', 'height']) jobInteger(region[axis]);
1263
+ if (!region.width || !region.height || Number(region.width) * Number(region.height) > 16777216) throw new JobError('JOB_ACT_INVALID');
1264
+ commentsObject(item.nativeCrop, ['path', 'sha256', 'width', 'height']);
1265
+ commentCrop(item.crop); commentCrop(item.nativeCrop);
1266
+ if ((item.nativeCrop as {width: number}).width !== region.width ||
1267
+ (item.nativeCrop as {height: number}).height !== region.height) throw new JobError('JOB_ACT_INVALID');
1268
+ return structuredClone(item) as unknown as JobCommentAnchor;
1269
+ }
1270
+ throw new JobError('JOB_ACT_INVALID');
1271
+ }
1272
+
1273
+ /** Structural/source-identity decoding only. Original asset freshness remains with the retained-source owner. */
1274
+ export function parseComments(value: unknown, source?: SourceV3 | string): JobComment[] {
1275
+ return decodeComments(value, source, false);
1276
+ }
1277
+
1278
+ function decodeComments(value: unknown, source: SourceV3 | string | undefined, withContext: false): JobComment[];
1279
+ function decodeComments(value: unknown, source: SourceV3 | string | undefined, withContext: true): JobContextComment[];
1280
+ function decodeComments(value: unknown, source: SourceV3 | string | undefined, withContext: boolean): JobContextComment[] {
1281
+ return asCode(() => {
1282
+ if (!Array.isArray(value) || value.length > 1000) throw new JobError('JOB_ACT_INVALID');
1283
+ const ids = new Set<string>();
1284
+ const comments: JobContextComment[] = value.map(raw => {
1285
+ const item = commentsObject(raw, ['text'], withContext ? ['anchor', 'context'] : ['anchor']);
1286
+ const text = parseActWords(item.text, 'JOB_ACT_INVALID');
1287
+ if (!text.trim()) throw new JobError('JOB_ACT_INVALID');
1288
+ const context = Object.hasOwn(item, 'context') ? {context: parseCommentContext(item.context, source)} : {};
1289
+ if (!Object.hasOwn(item, 'anchor')) return {text, ...context};
1290
+ const anchor = parseCommentAnchor(item.anchor, text, source);
1291
+ if ('id' in anchor) {
1292
+ if (ids.has(anchor.id)) throw new JobError('JOB_ACT_INVALID');
1293
+ ids.add(anchor.id);
1294
+ }
1295
+ return {text, anchor, ...context};
1296
+ });
1297
+ // The signed projection covers text and anchor only; context restores a view and is not signed text.
1298
+ projectComments(comments.map(({text, anchor}) => anchor === undefined ? {text} : {text, anchor}));
1299
+ return comments;
1300
+ }, 'JOB_ACT_INVALID');
1301
+ }
1302
+
1303
+ /** act@7 comment context. Each field reuses the decoder of the pin or restore path it copies. */
1304
+ function parseCommentContext(raw: unknown, source?: SourceV3 | string): JobCommentContext {
1305
+ const item = commentsObject(raw, [], ['subject', 'mode', 'tab', 'part', 'region', 'viewMode', 'camera', 'frame']);
1306
+ if (!Object.keys(item).length) throw new JobError('JOB_ACT_INVALID');
1307
+ const out: Record<string, unknown> = {};
1308
+ if ('subject' in item) {
1309
+ const subject = commentsObject(item.subject, ['ask', 'sourceHash'], ['selector']);
1310
+ const ask = parseJobSubject(subject.ask), sourceHash = jobSha(subject.sourceHash);
1311
+ const selector = 'selector' in subject ? parseJobSelector(subject.selector) : undefined;
1312
+ if (selector === null) throw new JobError('JOB_ACT_INVALID');
1313
+ const bound = typeof source === 'string' ? source : source?.sourceHash;
1314
+ if (bound && sourceHash !== bound) throw new JobError('JOB_ACT_SOURCE_STALE');
1315
+ if (selector && source && typeof source !== 'string' && !('record' in source) && source.subject !== 'image-set' &&
1316
+ JSON.stringify(selector) !== JSON.stringify(source.selector)) throw new JobError('JOB_ACT_SOURCE_STALE');
1317
+ out.subject = {ask, sourceHash, ...(selector ? {selector} : {})};
1318
+ }
1319
+ if ('mode' in item) {
1320
+ if (!(commentModes as readonly unknown[]).includes(item.mode)) throw new JobError('JOB_ACT_INVALID');
1321
+ out.mode = item.mode;
1322
+ }
1323
+ if ('tab' in item) {
1324
+ // The inspector values parseBookmark accepts (web/inspection-persistence.ts).
1325
+ if (!['view', 'rig', 'playback', 'feedback'].includes(item.tab as string)) throw new JobError('JOB_ACT_INVALID');
1326
+ out.tab = item.tab;
1327
+ }
1328
+ if ('part' in item) {
1329
+ const part = parseControlPart(item.part);
1330
+ if (!part) throw new JobError('JOB_ACT_INVALID');
1331
+ out.part = part;
1332
+ }
1333
+ if ('region' in item) {
1334
+ const region = commentsObject(item.region, ['x', 'y', 'width', 'height']);
1335
+ for (const axis of ['x', 'y', 'width', 'height']) {
1336
+ const n = region[axis];
1337
+ if (typeof n !== 'number' || !Number.isFinite(n) || Math.abs(n) > Number.MAX_SAFE_INTEGER) throw new JobError('JOB_ACT_INVALID');
1338
+ }
1339
+ if ((region.width as number) < 0 || (region.height as number) < 0) throw new JobError('JOB_ACT_INVALID');
1340
+ out.region = {x: region.x, y: region.y, width: region.width, height: region.height};
1341
+ }
1342
+ if ('viewMode' in item) {
1343
+ if (item.viewMode !== 'item' && item.viewMode !== 'assembled') throw new JobError('JOB_ACT_INVALID');
1344
+ out.viewMode = item.viewMode;
1345
+ }
1346
+ if ('camera' in item) {
1347
+ const space = (item.camera as {space?: unknown} | null)?.space;
1348
+ if (space !== 'world' && space !== 'image') throw new JobError('JOB_ACT_INVALID');
1349
+ const cameras = {rig: null, a: null, b: null, reference: null, [space === 'world' ? 'rig' : 'reference']: item.camera};
1350
+ const view = parseControlView({schema: 'rig-review-view/1', cameras});
1351
+ out.camera = space === 'world' ? view.cameras.rig : view.cameras.reference;
1352
+ }
1353
+ if ('frame' in item) {
1354
+ const frame = commentsObject(item.frame, ['index', 'basis']);
1355
+ if (!Number.isSafeInteger(frame.index) || (frame.index as number) < 0 ||
1356
+ (frame.basis !== 'producer' && frame.basis !== 'reference')) throw new JobError('JOB_ACT_INVALID');
1357
+ out.frame = {index: frame.index, basis: frame.basis};
1358
+ }
1359
+ return out as JobCommentContext;
1360
+ }
1361
+
1362
+ function commentsSource(raw: unknown): Exclude<SourceV3, OptionSource> {
1363
+ if (isRecordSource(raw)) {
1364
+ const record = parseRecordSource(raw);
1365
+ if (record.subject !== 'plan') throw new JobError('JOB_ACT_INVALID');
1366
+ return record;
1367
+ }
1368
+ const image = !!raw && typeof raw === 'object' && (raw as {subject?: unknown}).subject === 'image-set';
1369
+ const common = ['sourceHash', 'projectHash', 'package', 'direction', 'optionSet', 'appliedResult', 'plan', 'parts'];
1370
+ const item = commentsObject(raw, image ? [...common, 'subject', 'imageSet', 'imageSetDigest', 'duplicateHashes'] :
1371
+ [...common, 'selector', 'model'], image ? [] : ['checkpointEvidence']);
1372
+ jobSha(item.sourceHash); if (item.projectHash !== null) jobSha(item.projectHash);
1373
+ const pkg = commentsObject(item.package, ['id', 'revision']); jobText(pkg.id); jobText(pkg.revision);
1374
+ for (const key of image ? ['direction'] : ['direction', 'model']) if (item[key] !== null) parseFileRow(item[key], 'JOB_ACT_INVALID');
1375
+ if (!image) parseJobSelector(item.selector);
1376
+ if (item.optionSet !== null) {
1377
+ const set = commentsObject(item.optionSet, ['id', 'sha256']); jobId(set.id); jobSha(set.sha256);
1378
+ }
1379
+ if (item.appliedResult !== null) {
1380
+ const applied = commentsObject(item.appliedResult, ['id', 'modelHash']); jobId(applied.id); jobSha(applied.modelHash);
1381
+ }
1382
+ if (item.plan !== null) parsePlanIdentity(item.plan, 'JOB_ACT_INVALID');
1383
+ if (item.parts !== null) parseJobPartsIdentity(item.parts);
1384
+ if ('checkpointEvidence' in item) {
1385
+ if (!Array.isArray(item.checkpointEvidence)) throw new JobError('JOB_ACT_INVALID');
1386
+ // Validate the declared packet with the existing codec. Actual closure seals remain
1387
+ // with the retained-source owner; a decoder has neither files nor source authority.
1388
+ const declarations = item.checkpointEvidence.map(raw => commentsObject(raw,
1389
+ ['schema', 'checkpointId', 'planStepId', 'tiles', 'table', 'routesText', 'recommendationText']));
1390
+ const subjects = declarations.map(row => ({kind: 'checkpoint' as const, checkpointId: jobId(row.checkpointId), planStepId: jobId(row.planStepId)}));
1391
+ const files = declarations.flatMap(row => {
1392
+ if (!Array.isArray(row.tiles)) throw new JobError('JOB_ACT_INVALID');
1393
+ return [...row.tiles, row.table].map(file => parseFileRow(
1394
+ {path: (file as JobFileIdentity)?.path, sha256: (file as JobFileIdentity)?.sha256}, 'JOB_ACT_INVALID'));
1395
+ });
1396
+ checkpointEvidenceFields(item, item.plan as JobPlanIdentity | null, subjects, files);
1397
+ }
1398
+ if (image) parseJobImageSetBinding({imageSet: item.imageSet, imageSetDigest: item.imageSetDigest, duplicateHashes: item.duplicateHashes});
1399
+ return structuredClone(item) as unknown as Exclude<SourceV3, OptionSource>;
1400
+ }
1401
+
1402
+ /** Public @6 decoder. The UI finalizers write checkpoint, parts, rig/post verdict and signoff acts at @6 (#713). */
1403
+ export function parseCommentsAct(raw: unknown): JobCommentsAct {
1404
+ return decodeCommentsAct(raw, false) as JobCommentsAct;
1405
+ }
1406
+
1407
+ /** Public @7 decoder: the @6 rules plus an optional `context` on each comment. @6 input refuses. */
1408
+ export function parseContextCommentsAct(raw: unknown): JobContextCommentsAct {
1409
+ return decodeCommentsAct(raw, true) as JobContextCommentsAct;
1410
+ }
1411
+
1412
+ /** The comments act a writer sends. With EMIT_UNPINNED_CREATE_FIELDS off, contexts are dropped and @6 goes out. */
1413
+ export function commentsActForEmission(act: JobCommentsAct | JobContextCommentsAct,
1414
+ emitUnpinned: boolean = EMIT_UNPINNED_CREATE_FIELDS): JobCommentsAct | JobContextCommentsAct {
1415
+ const value = act.value as {comments: readonly JobContextComment[]};
1416
+ const comments = value.comments.map(({context, ...comment}) => emitUnpinned && context ? {...comment, context} : comment);
1417
+ const schema = emitUnpinned && comments.some(comment => 'context' in comment) ? JOB_COMMENT_CONTEXT_ACT_SCHEMA : JOB_COMMENTS_ACT_SCHEMA;
1418
+ const next = {...structuredClone(act), schema, value: {...structuredClone(act.value), comments: structuredClone(comments)}};
1419
+ return schema === JOB_COMMENTS_ACT_SCHEMA ? parseCommentsAct(next) : parseContextCommentsAct(next);
1420
+ }
1421
+
1422
+ function decodeCommentsAct(raw: unknown, withContext: boolean): JobCommentsAct | JobContextCommentsAct {
1423
+ return asCode(() => {
1424
+ const item = commentsObject(raw, ['schema', 'actId', 'jobId', 'askId', 'publicationId', 'kind', 'authority', 'at', 'source', 'value'], ['still']);
1425
+ if (item.schema !== (withContext ? JOB_COMMENT_CONTEXT_ACT_SCHEMA : JOB_COMMENTS_ACT_SCHEMA)) throw new JobError('JOB_ACT_INVALID');
1426
+ for (const key of ['actId', 'jobId', 'askId', 'publicationId']) jobId(item[key]);
1427
+ parseHumanAuthority(item.authority, 'JOB_ACT_INVALID');
1428
+ if (typeof item.at !== 'string' || !Number.isFinite(Date.parse(item.at))) throw new JobError('JOB_ACT_INVALID');
1429
+ const source = commentsSource(item.source);
1430
+ const fields: Record<string, readonly string[]> = {
1431
+ checkpoint: ['checkpointId', 'planStepId', 'outcome', 'comments'],
1432
+ 'parts-verdict': ['verdict', 'comments'], 'review-verdict': ['stage', 'verdict', 'comments'],
1433
+ signoff: ['stage', 'decision', 'comments'], reopen: ['stage', 'comments'],
1434
+ };
1435
+ const keys = typeof item.kind === 'string' && Object.hasOwn(fields, item.kind) ? fields[item.kind] : undefined;
1436
+ if (!keys) throw new JobError('JOB_ACT_INVALID');
1437
+ if (source.subject === 'image-set' && item.kind !== 'review-verdict') throw new JobError('JOB_ACT_INVALID');
1438
+ const value = commentsObject(item.value, keys);
1439
+ const comments = withContext ? decodeComments(value.comments, source, true) : parseComments(value.comments, source);
1440
+ if (comments.some(comment => comment.anchor && 'side' in comment.anchor)) throw new JobError('JOB_ACT_INVALID');
1441
+ if ((comments as readonly JobContextComment[]).some(comment => comment.context?.subject &&
1442
+ comment.context.subject.ask.kind !== item.kind)) throw new JobError('JOB_ACT_INVALID');
1443
+ if (item.kind === 'checkpoint') {
1444
+ const checkpointId = jobId(value.checkpointId), planStepId = jobId(value.planStepId);
1445
+ if (typeof value.outcome !== 'string' || !['pass', 'fail'].includes(value.outcome)) throw new JobError('JOB_ACT_INVALID');
1446
+ assertCommentsCheckpointBinding(source, checkpointId, planStepId);
1447
+ } else if (item.kind === 'parts-verdict') {
1448
+ if ('record' in source || source.subject === 'image-set' || source.selector?.kind !== 'draft' || !source.parts || !source.projectHash ||
1449
+ typeof value.verdict !== 'string' || !['approved', 'changes-requested'].includes(value.verdict)) throw new JobError('JOB_ACT_INVALID');
1450
+ const issues = comments.filter(comment => comment.anchor && 'schema' in comment.anchor).length;
1451
+ if ((value.verdict === 'approved') !== (issues === 0)) throw new JobError('JOB_ACT_INVALID');
1452
+ } else if (item.kind === 'review-verdict') {
1453
+ if ('record' in source || typeof value.verdict !== 'string' || !['pending', 'approved', 'changes-requested'].includes(value.verdict)) throw new JobError('JOB_ACT_INVALID');
1454
+ if (source.subject === 'image-set' ? value.stage !== 'image-review' :
1455
+ !source.model || (value.stage === 'rig-review' ? source.selector?.kind !== 'rig' : value.stage !== 'direction-review' || source.selector?.kind !== 'post' || !source.direction)) throw new JobError('JOB_ACT_INVALID');
1456
+ } else {
1457
+ const stage = jobId(value.stage);
1458
+ if (item.kind === 'signoff' && value.decision !== 'approved') throw new JobError('JOB_ACT_INVALID');
1459
+ if (item.kind === 'reopen' && !('record' in source)) throw new JobError('JOB_ACT_INVALID');
1460
+ if (item.kind === 'signoff' && JOB_PLAN_BOUND_SIGNOFF_STAGES.includes(stage as RecordSignoffStage) && !source.plan?.steps.length) throw new JobError('JOB_ACT_INVALID');
1461
+ }
1462
+ if ('record' in source) validateRecordAskSubject(item.kind === 'checkpoint' ? {kind: item.kind, checkpointId: value.checkpointId} :
1463
+ {kind: item.kind, stage: value.stage}, source);
1464
+ const rig = item.kind === 'review-verdict' && value.stage === 'rig-review';
1465
+ if (rig) {
1466
+ const still = commentsObject(item.still, ['path', 'sha256', 'camera', 'frame'], ['animation']);
1467
+ if (still.path !== jobSha(still.sha256) + '.png' || still.camera !== 'fixed' ||
1468
+ (still.frame === 'setup' ? 'animation' in still : typeof still.frame !== 'number' || !Number.isFinite(still.frame) ||
1469
+ still.frame < 0 || typeof still.animation !== 'string' || !still.animation)) throw new JobError('JOB_ACT_INVALID');
1470
+ } else if ('still' in item) throw new JobError('JOB_ACT_INVALID');
1471
+ return {...structuredClone(item), source, value: {...value, comments}} as unknown as JobCommentsAct | JobContextCommentsAct;
1472
+ }, 'JOB_ACT_INVALID');
1473
+ }
1474
+
1184
1475
  export async function jobBody(request: Request, maximum = jobBodyLimit): Promise<unknown> {
1185
1476
  if (!/^application\/json(?:\s*;|$)/i.test(request.headers.get('content-type') ?? '')) {
1186
1477
  throw new JobError('JOB_REQUEST_INVALID');