rig-review 4.0.0 → 4.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,7 +18,7 @@ The app provides one inspection workspace for setup geometry and motion, compile
18
18
 
19
19
  ## Place in the toolchain
20
20
 
21
- [Parts](https://github.com/rig-c/parts) → [Pose](https://github.com/rig-c/pose) →
21
+ [Create](https://github.com/rig-c/create) → [Parts](https://github.com/rig-c/parts) → [Pose](https://github.com/rig-c/pose) →
22
22
  [Core / rigc](https://github.com/rig-c/core) → **Review** →
23
23
  [Play](https://github.com/rig-c/play) → **Adapter** (consumer integration).
24
24
 
@@ -81,7 +81,7 @@ http://127.0.0.1:4318/?workspace=<incarnation>#cap=…
81
81
  | <a id="control-the-current-inspection-page"></a>Control an opted-in inspection | `control` | [Inspection control — WORKFLOWS](docs/WORKFLOWS.md#control-the-current-inspection-page) |
82
82
  | <a id="keep-and-share-an-inspection"></a>Restore a view link or local draft | View link, draft | [Keep and share — WORKFLOWS](docs/WORKFLOWS.md#keep-and-share-an-inspection) |
83
83
  | <a id="launcher-contract"></a>Start or reuse the launcher | `open` | [Launcher contract — WORKFLOWS](docs/WORKFLOWS.md#launcher-contract) |
84
- | <a id="managed-front-and-write-capability"></a>Use the managed front and write capability | `open` | [Managed front — WORKFLOWS](docs/WORKFLOWS.md#managed-front-and-write-capability) |
84
+ | <a id="managed-front-and-write-capability"></a>Use the owner workspace and write capability | `open` | [Owner workspace — WORKFLOWS](docs/WORKFLOWS.md#managed-front-and-write-capability) |
85
85
 
86
86
  ## License
87
87
 
@@ -1,6 +1,6 @@
1
1
  # Review package and existing-folder adapter v1
2
2
 
3
- The toolchain delivery flow is **Parts → Pose → Core (rigc) → Review → Play →
3
+ The toolchain delivery flow is **Create → Parts → Pose → Core (rigc) → Review → Play →
4
4
  Adapter**. Review supplies human inspection and feedback bound to the exact
5
5
  reviewed sources; it neither replaces Core's build validation nor authors motion.
6
6
  The app uses the published `@rig-c/play` loader/player to preview artifacts during
package/docs/STABILITY.md CHANGED
@@ -412,7 +412,7 @@ preserve capability, origin, size, cancellation and replay checks.
412
412
 
413
413
  ## Changelog
414
414
 
415
- - Breaking, next cut 4.0.0 (#806): remove `startJobHub` and its `JobHubOptions`, `JobHubJobOptions`, `JobHubJob` and `JobOwnerHub` types; the uncalled semantic-job hub is deleted.
415
+ - Breaking, 4.0.0 (#806): remove `startJobHub` and its `JobHubOptions`, `JobHubJobOptions`, `JobHubJob` and `JobOwnerHub` types; the uncalled semantic-job hub is deleted.
416
416
 
417
417
  ## Named export inventory
418
418
 
package/docs/WORKFLOWS.md CHANGED
@@ -496,7 +496,7 @@ On the view you are inspecting, choose **Comment · C (n)**, drag over the detai
496
496
 
497
497
  The four-stage navigator preserves this entry and its explicit save behavior. Compiled sessions reuse the atlas surface read-only; see [Four inspection stages](PANELS.md#four-inspection-stages).
498
498
 
499
- The managed front forwards a query only to the landing page; every other route refuses one. Stage navigation never changes CLI arguments or package bindings.
499
+ The current owner workspace accepts optional, nonduplicated `workspace` (matching the host incarnation) and `lang=en|ko` queries at `/`; `/main.js` and `/styles.css` accept only an optional `?lang=en` or `?lang=ko`, while workspace API and live routes reject queries. For allowed `/instances/<key>/…` routes, it passes landing-page queries (`/` or `/index.html`) to the in-process target handler and refuses queries on other target routes. Stage navigation never changes CLI arguments or package bindings.
500
500
 
501
501
  ## Standing live job workflow
502
502
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-review",
3
- "version": "4.0.0",
3
+ "version": "4.0.2",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
package/src/job-front.ts CHANGED
@@ -224,7 +224,7 @@ export function jobWindowResources() {
224
224
  }
225
225
 
226
226
  interface RetainedView {
227
- review: ReviewPackage;
227
+ review: ReviewPackage | null;
228
228
  parts: PartsViewPackage | null;
229
229
  }
230
230
 
@@ -238,6 +238,12 @@ export function retainedPublicationRoutes(session: JobSession) {
238
238
  if (crop) session.authorize('ui', request.headers.get('X-Review-Capability'));
239
239
  return await session.readPublicationResponse(publicationId, async retained => {
240
240
  const display = session.displayPublication(publicationId);
241
+ // Retain history, but expose images only for this publication's declared questions.
242
+ const questions = retained.questions.map(question => ({...question,
243
+ images: retained.subjects.some(subject => subject.kind === 'interview-picks' &&
244
+ subject.setId === question.set.id && subject.questionId === question.set.question)
245
+ ? question.images : [],
246
+ }));
241
247
  if (key !== display.publication.instanceKey) return failure('JOB_DISPLAY_MISMATCH', 409);
242
248
  if (crop && session.status().publication?.publicationId !== publicationId)
243
249
  return failure('JOB_ACT_SOURCE_STALE', 409);
@@ -264,6 +270,31 @@ export function retainedPublicationRoutes(session: JobSession) {
264
270
  return await sealedFile(member.path);
265
271
  }
266
272
  if (isRetainedRecordSource(retained)) {
273
+ // hasParts is projected only after validating the option's sealed draft closure.
274
+ const question = retained.questions.find(question => question.hasParts);
275
+ if (question && (path === 'api/stage-parts' || /^api\/stage-parts\/(image|page)\/(0|[1-9]\d*)$/.test(path))) {
276
+ let pending = views.get(publicationId);
277
+ if (!pending) {
278
+ pending = (async () => {
279
+ const context = (question.set as unknown as {context:{parts:{path:string;files:{path:string;sha256:string}[]}}}).context;
280
+ const root = join(retained.snapshotRoot, context.parts.path);
281
+ const parts = await loadPartsView(root);
282
+ for (const file of [...parts.files, ...parts.flagFiles]) {
283
+ const path = relative(retained.snapshotRoot, file.abs).split('\\').join('/');
284
+ if (!context.parts.files.some(bound => bound.path === path && bound.sha256 === file.sha256)) throw new JobError('JOB_SOURCE_UNRETAINABLE');
285
+ }
286
+ return {review:null, parts};
287
+ })();
288
+ views.set(publicationId, pending);
289
+ }
290
+ const {parts} = await pending;
291
+ if (!parts) throw new JobError('JOB_SOURCE_UNRETAINABLE');
292
+ if (path === 'api/stage-parts') return json({...partsViewJson(parts, {verdict:null,stale:null}),
293
+ sourceHash:retained.source.sourceHash,inspectionSourceHash:retained.source.sourceHash,readOnly:true});
294
+ const image = /^api\/stage-parts\/(image|page)\/(0|[1-9]\d*)$/.exec(path)!;
295
+ const file = servedImage(parts, image[1] as 'image'|'page', Number(image[2]));
296
+ return file ? await sealedFile(relative(retained.snapshotRoot,file).split('\\').join('/')) : failure('JOB_SOURCE_UNRETAINABLE',404);
297
+ }
267
298
  if (path === 'api/review') {
268
299
  return json({
269
300
  ...checkpointEvidenceMetadata(retained.snapshotRoot, retained.source.checkpointEvidence),
@@ -283,7 +314,7 @@ export function retainedPublicationRoutes(session: JobSession) {
283
314
  });
284
315
  }
285
316
  if (path === 'api/interview') {
286
- return json({questions: retained.questions.map(question => ({...question,
317
+ return json({questions: questions.map(question => ({...question,
287
318
  images: question.images.map((image, index) => ({name: image.name,
288
319
  url: `/api/interview/image/${question.ref.sha256}/${index}`})),
289
320
  }))});
@@ -331,6 +362,7 @@ export function retainedPublicationRoutes(session: JobSession) {
331
362
  views.set(publicationId, pending);
332
363
  }
333
364
  const {review, parts} = await pending;
365
+ if (!review) throw new JobError('JOB_SOURCE_MISMATCH');
334
366
  await assertReviewUnchanged(review);
335
367
  if (retained.checkpointEvidencePackageHash !== undefined && retained.checkpointEvidencePackageHash !== review.sourceHash) {
336
368
  throw new JobError('JOB_SOURCE_MISMATCH');
@@ -359,7 +391,7 @@ export function retainedPublicationRoutes(session: JobSession) {
359
391
  if (path === 'api/interview') {
360
392
  const interview = retained.interview !== undefined ? retained.interview : display.publication.interview;
361
393
  return json({
362
- questions: retained.questions.map(question => ({...question,
394
+ questions: questions.map(question => ({...question,
363
395
  images: question.images.map((image, index) => ({name: image.name,
364
396
  url: `/api/interview/image/${question.ref.sha256}/${index}`})),
365
397
  })),
package/src/job-source.ts CHANGED
@@ -922,13 +922,30 @@ function decodeRetainedRecordProject(
922
922
  }
923
923
  }
924
924
  }
925
+ // Older record readers retained only inputs/evidence. Keep those records usable,
926
+ // but expose a parts picture only when the option's entire draft closure is sealed.
927
+ let hasBoundParts = false;
928
+ const boundParts = ctx?.kind === 'parts' ? asPlainObject(ctx.parts) : null;
929
+ if (boundParts && typeof boundParts.path === 'string' && Array.isArray(boundParts.files)) {
930
+ try {
931
+ const root = jobPath(boundParts.path), paths = new Set<string>();
932
+ hasBoundParts = boundParts.files.every(value => {
933
+ const file = asPlainObject(value);
934
+ if (!file) return false;
935
+ const path = jobPath(file.path), sha = jobSha(file.sha256);
936
+ if (!path.startsWith(root + '/') || paths.has(path) || sealMap.get(path) !== sha) return false;
937
+ paths.add(path);
938
+ return true;
939
+ }) && paths.has(root + '/parts.json');
940
+ } catch {hasBoundParts = false;}
941
+ }
925
942
  return {
926
943
  questions: [{
927
944
  ref,
928
945
  set,
929
946
  editable: true,
930
947
  images,
931
- hasParts: false,
948
+ hasParts: hasBoundParts,
932
949
  }],
933
950
  optionSetFile: ref,
934
951
  };
@@ -154,6 +154,30 @@ export function recoverSession<T extends {id:string;revision:string;sourceHash:s
154
154
  /** Drafts kept per origin before least-recently-written eviction; recent drafts are never evicted. */
155
155
  export const maximumDrafts=32,protectedDraftMs=24*60*60*1000;
156
156
  const draftPrefix='rig-review-draft/1:',draftIndex='rig-review-draft-index/1';
157
+ const cropDatabase='rig-review-inspection-drafts',cropStore='crops',cropReference='draft-crop:';
158
+ /** Only existing stage-comment crops in inspection sessions belong to this private transport. */
159
+ function draftCrops(session:unknown):{row:{id:string};crop:Record<string,unknown>}[] {
160
+ if(!session||typeof session!=='object'||!Array.isArray((session as PersistenceSession).feedback))return [];
161
+ return (session as PersistenceSession).feedback.flatMap(item=>{
162
+ const comment=(item as {context?:{comment?:unknown}}|null)?.context?.comment;
163
+ if(!hasStageComment(comment))return [];
164
+ const row=record(item,'draft');if(typeof row.id!=='string')throw new Error('Draft review state invalid');
165
+ return [{row:row as {id:string},crop:record((comment as {crop:unknown}).crop,'crop')}];
166
+ });
167
+ }
168
+ /** Browser counterpart of comment-crops.ts's signature/dimension/digest boundary (no Node imports). */
169
+ async function draftPng(blob:Blob,crop:Record<string,unknown>):Promise<string|null> {
170
+ if(!(blob instanceof Blob)||blob.size>150000)return null;
171
+ const bytes=new Uint8Array(await blob.arrayBuffer()),view=new DataView(bytes.buffer);
172
+ if(bytes.length<33||[137,80,78,71,13,10,26,10].some((value,i)=>bytes[i]!==value)||
173
+ view.getUint32(8)!==13||String.fromCharCode(...bytes.slice(12,16))!=='IHDR'||
174
+ ![crop.width,crop.height].every(n=>Number.isSafeInteger(n)&&Number(n)>0&&Number(n)<=1024)||
175
+ view.getUint32(16)!==crop.width||view.getUint32(20)!==crop.height)return null;
176
+ const digest=[...new Uint8Array(await crypto.subtle.digest('SHA-256',bytes))].map(n=>n.toString(16).padStart(2,'0')).join('');
177
+ if(digest!==crop.sha256||crop.path!==`comment-crops/${digest}.png`)return null;
178
+ let binary='';for(const byte of bytes)binary+=String.fromCharCode(byte);
179
+ const png='data:image/png;base64,'+btoa(binary);if(png.length>200000)return null;return png;
180
+ }
157
181
  /** Storage is confined to this app; the scope carries the source identity (`single:<id>:<sourceHash>`), so
158
182
  * revisions of one package opened on one origin keep separate drafts. Opening deletes nothing; writing evicts
159
183
  * the least-recently-written drafts beyond 32, except any written within the last 24 hours. */
@@ -162,9 +186,11 @@ export class InspectionDraftStore {
162
186
  private blocked=false;
163
187
  private rawRecovery:string|null=null;
164
188
  private priorKey:string|null=null;
189
+ private pending:Promise<void>=Promise.resolve();
165
190
  recovery():string|null{return this.rawRecovery;}
166
191
  readonly key:string;
167
- constructor(private readonly scope:string,private readonly binding:InspectionBinding,private readonly warn:(message:string)=>void,storage?:Storage,private readonly now:()=>number=Date.now){
192
+ constructor(private readonly scope:string,private readonly binding:InspectionBinding,private readonly warn:(message:string)=>void,storage?:Storage,private readonly now:()=>number=Date.now,private readonly factory?:IDBFactory|null){
193
+ this.binding=structuredClone(binding);
168
194
  this.key=`${draftPrefix}${scope}:${binding.sourceHash}`;
169
195
  try{this.storage=storage??localStorage;this.storage.getItem(draftIndex);}catch{this.storage=null;warn('Local draft storage unavailable. Keep this page open or export feedback before leaving.');}
170
196
  }
@@ -175,7 +201,7 @@ export class InspectionDraftStore {
175
201
  return times;
176
202
  }
177
203
  private evict():void{
178
- const storage=this.storage!,now=this.now(),times=this.written();if(this.priorKey&&this.priorKey!==this.key){storage.removeItem(this.priorKey);times.delete(this.priorKey);this.priorKey=null;}times.set(this.key,now);
204
+ const storage=this.storage!,now=this.now(),times=this.written();if(this.priorKey&&this.priorKey!==this.key){storage.removeItem(this.priorKey);times.delete(this.priorKey);}times.set(this.key,now);
179
205
  const old=[...times].filter(([key,time])=>key!==this.key&&now-time>protectedDraftMs).sort((a,b)=>a[1]-b[1]);
180
206
  for(const [key]of old){if(times.size<=maximumDrafts)break;storage.removeItem(key);times.delete(key);}
181
207
  storage.setItem(draftIndex,JSON.stringify(Object.fromEntries(times)));
@@ -183,21 +209,105 @@ export class InspectionDraftStore {
183
209
  private parseDraft(raw:string,expectedBinding:InspectionBinding):LocalInspectionDraft{
184
210
  if(new TextEncoder().encode(raw).length>maximumDraftBytes)throw new Error('Draft exceeds 512 KiB');const o=record(JSON.parse(raw),'draft');keys(o,['schema','sourceHash','baseline','savedAt','reviewDirty','bookmark','inputs','session','ui'],'draft');if(o.schema!=='rig-review-local-draft/1'||o.sourceHash!==expectedBinding.sourceHash)throw new Error('Draft binding/version differs');if(typeof o.reviewDirty!=='boolean')throw new Error('Draft review state invalid');const bookmark=parseBookmark(o.bookmark,expectedBinding),baseline=hash(o.baseline);if(typeof o.savedAt!=='string'||!Number.isFinite(Date.parse(o.savedAt)))throw new Error('Draft timestamp invalid');const ui=record(o.ui,'draft UI');for(const [k,v]of Object.entries(ui)){text(k,'draft UI key');if(v!==null&&typeof v!=='string'&&typeof v!=='number'||typeof v==='number'&&!Number.isFinite(v))throw new Error('Draft UI value invalid');}return {schema:o.schema,sourceHash:this.binding.sourceHash,baseline,savedAt:o.savedAt,reviewDirty:o.reviewDirty,bookmark:{...bookmark,binding:{...bookmark.binding,sourceHash:this.binding.sourceHash}},inputs:parseInputs(o.inputs),session:o.session,ui:ui as LocalInspectionDraft['ui']};
185
211
  }
186
- read(canRecover?:(session:unknown)=>boolean):LocalInspectionDraft|null {
187
- if(!this.storage)return null;try{const raw=this.storage.getItem(this.key);if(!raw){
188
- if(this.binding.mode==='compare'&&canRecover){
189
- const prefix=`${draftPrefix}${this.scope}:`,candidates=[...this.written().entries()].filter(([k])=>k!==this.key&&k.startsWith(prefix)).sort((a,b)=>b[1]-a[1]);
190
- for(const [candidateKey]of candidates){
191
- try{const candidateRaw=this.storage.getItem(candidateKey);if(!candidateRaw)continue;const sourceHash=hash(candidateKey.slice(prefix.length)),parsed=this.parseDraft(candidateRaw,{...this.binding,sourceHash});if(!canRecover(parsed.session))continue;this.priorKey=candidateKey;this.rawRecovery=candidateRaw;return parsed;}catch{}
192
- }
212
+ private ordered<T>(operation:()=>Promise<T>):Promise<T> {
213
+ const result=this.pending.then(operation);this.pending=result.then(()=>{},()=>{});return result;
214
+ }
215
+ private openCrops():Promise<IDBDatabase> {
216
+ return new Promise<IDBDatabase>((resolve,reject)=>{
217
+ const factory=this.factory===undefined?globalThis.indexedDB:this.factory;
218
+ if(!factory){reject(new Error('COMMENT_CROP_STATE_UNAVAILABLE: stored crop cannot be read'));return;}
219
+ const request=factory.open(cropDatabase,1);let blocked=false;
220
+ request.onupgradeneeded=()=>request.result.createObjectStore(cropStore);
221
+ request.onerror=()=>reject(request.error);
222
+ request.onblocked=()=>{blocked=true;reject(new Error('COMMENT_CROP_STATE_UNAVAILABLE: stored crop cannot be read'));};
223
+ request.onsuccess=()=>{if(blocked)request.result.close();else resolve(request.result);};
224
+ });
225
+ }
226
+ /** Resolve only on transaction completion, never an individual request's success. */
227
+ private async crops(mode:IDBTransactionMode,visit:(store:IDBObjectStore)=>void):Promise<void> {
228
+ const db=await this.openCrops();
229
+ try{await new Promise<void>((resolve,reject)=>{
230
+ const transaction=db.transaction(cropStore,mode);
231
+ transaction.oncomplete=()=>resolve();transaction.onabort=()=>reject(transaction.error);
232
+ transaction.onerror=()=>{};
233
+ try{visit(transaction.objectStore(cropStore));}catch(error){transaction.abort();reject(error);}
234
+ });}finally{db.close();}
235
+ }
236
+ private async unpack(raw:string,key:string,expected:InspectionBinding):Promise<LocalInspectionDraft> {
237
+ if(new TextEncoder().encode(raw).length>maximumDraftBytes)throw new Error('Draft exceeds 512 KiB');
238
+ const packed=record(JSON.parse(raw),'draft');
239
+ if(packed.schema!=='rig-review-local-draft/2')return this.parseDraft(raw,expected);
240
+ // Check the bounded envelope/binding before touching IDB; validate the full session only after hydration.
241
+ const draft=this.parseDraft(JSON.stringify({...packed,schema:'rig-review-local-draft/1'}),expected);
242
+ const crops=draftCrops(draft.session),blobs=new Map<{id:string},Blob>();
243
+ if(crops.length)await this.crops('readonly',store=>{
244
+ for(const {row,crop}of crops){
245
+ if(crop.png!==cropReference+crop.sha256)throw new Error('COMMENT_CROP_STATE_UNAVAILABLE: stored crop cannot be read');
246
+ const request=store.get([key,row.id,hash(crop.sha256)]);request.onsuccess=()=>blobs.set(row,request.result);
193
247
  }
194
- return null;
195
- }this.rawRecovery=raw;return this.parseDraft(raw,this.binding);}catch(error){this.blocked=true;this.warn(`Saved local draft was not restored: ${error instanceof Error?error.message:String(error)}. It remains in storage for recovery.`);return null;}
248
+ });
249
+ // A completed read with missing/corrupt bytes loses only that image comment; transport failures still throw.
250
+ const unavailable=new Set<unknown>();
251
+ for(const {row,crop}of crops){const png=await draftPng(blobs.get(row)!,crop);if(png===null)unavailable.add(row);else crop.png=png;}
252
+ if(unavailable.size){const session=record(draft.session,'draft');session.feedback=(session.feedback as unknown[]).filter(row=>!unavailable.has(row));}
253
+ return draft;
196
254
  }
197
- write(draft:LocalInspectionDraft):boolean {
198
- if(!this.storage||this.blocked)return false;try{const value=JSON.stringify(draft);if(new TextEncoder().encode(value).length>maximumDraftBytes)throw new Error('Draft exceeds 512 KiB');this.storage.setItem(this.key,value);try{this.evict();}catch{}return true;}catch(error){this.warn(`Local draft could not be saved: ${error instanceof Error?error.message:String(error)}. Export feedback before leaving.`);return false;}
255
+ read(canRecover?:(session:unknown)=>boolean):Promise<LocalInspectionDraft|null> {
256
+ return this.ordered(async()=>{
257
+ if(!this.storage)return null;try{const raw=this.storage.getItem(this.key);if(!raw){
258
+ if(this.binding.mode==='compare'&&canRecover){
259
+ const prefix=`${draftPrefix}${this.scope}:`,candidates=[...this.written().entries()].filter(([k])=>k!==this.key&&k.startsWith(prefix)).sort((a,b)=>b[1]-a[1]);
260
+ for(const [candidateKey]of candidates){
261
+ const candidateRaw=this.storage.getItem(candidateKey);if(!candidateRaw)continue;
262
+ let parsed:LocalInspectionDraft;
263
+ try{const sourceHash=hash(candidateKey.slice(prefix.length));parsed=await this.unpack(candidateRaw,candidateKey,{...this.binding,sourceHash});}
264
+ catch(error){let referenced=false;try{referenced=JSON.parse(candidateRaw).schema==='rig-review-local-draft/2';}catch{}if(!referenced)continue;this.priorKey=candidateKey;this.rawRecovery=candidateRaw;throw error;}
265
+ if(!canRecover(parsed.session))continue;this.priorKey=candidateKey;this.rawRecovery=JSON.parse(candidateRaw).schema==='rig-review-local-draft/2'?JSON.stringify(parsed):candidateRaw;return parsed;
266
+ }
267
+ }
268
+ return null;
269
+ }this.rawRecovery=raw;const parsed=await this.unpack(raw,this.key,this.binding);this.rawRecovery=JSON.parse(raw).schema==='rig-review-local-draft/2'?JSON.stringify(parsed):raw;return parsed;}catch(error){this.blocked=true;this.warn(`Saved local draft was not restored: ${error instanceof Error?error.message:String(error)}. It remains in storage for recovery.`);return null;}
270
+ });
271
+ }
272
+ write(draft:LocalInspectionDraft):Promise<boolean> {
273
+ // Snapshot at invocation, before any await or queued storage operation can observe later edits.
274
+ const snapshot=JSON.stringify(draft);
275
+ return this.ordered(async()=>{
276
+ if(!this.storage||this.blocked)return false;
277
+ try{
278
+ const packed=JSON.parse(snapshot) as LocalInspectionDraft;
279
+ // Clean sessions are already durable on the server and are never restored as unsent feedback.
280
+ if(!packed.reviewDirty&&packed.session&&typeof packed.session==='object'){
281
+ packed.session={...packed.session,feedback:[]};
282
+ }
283
+ const crops=draftCrops(packed.session),blobs:{key:IDBValidKey;blob:Blob}[]=[];
284
+ for(const {row,crop}of crops){
285
+ if(typeof crop.png!=='string'||crop.png.length>200000||!/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(crop.png))throw new Error('COMMENT_CROP_STATE_UNAVAILABLE: stored crop cannot be read');
286
+ blobs.push({key:[this.key,row.id,hash(crop.sha256)],blob:new Blob([Uint8Array.from(atob(crop.png.slice(22)),c=>c.charCodeAt(0))],{type:'image/png'})});
287
+ crop.png=cropReference+crop.sha256;
288
+ }
289
+ let value=JSON.stringify({...packed,schema:'rig-review-local-draft/2'});
290
+ if(new TextEncoder().encode(value).length>maximumDraftBytes)throw new Error('Draft exceeds 512 KiB');
291
+ try{if(blobs.length)await this.crops('readwrite',store=>{for(const {key,blob}of blobs)store.put(blob,key);});}
292
+ catch{value=snapshot;if(new TextEncoder().encode(value).length>maximumDraftBytes)throw new Error('Draft exceeds 512 KiB');}
293
+ // IDB has committed before localStorage can publish a crop reference. Failure retains the old draft.
294
+ this.storage.setItem(this.key,value);try{this.evict();}catch{}return true;
295
+ }catch(error){this.warn(`Local draft could not be saved: ${error instanceof Error?error.message:String(error)}. Export feedback before leaving.`);return false;}
296
+ });
297
+ }
298
+ clear():Promise<void> {
299
+ return this.ordered(async()=>{
300
+ const keys=[this.key,...(this.priorKey&&this.priorKey!==this.key?[this.priorKey]:[])];
301
+ try{
302
+ for(const key of keys)this.storage?.removeItem(key);
303
+ this.priorKey=null;this.blocked=false;this.rawRecovery=null;
304
+ // Only explicit clear/submission reclaims blobs, never opening, autosave or draft-index eviction.
305
+ try{await this.crops('readwrite',store=>{
306
+ const request=store.openCursor();request.onsuccess=()=>{const cursor=request.result;if(cursor){if(Array.isArray(cursor.key)&&keys.includes(String(cursor.key[0])))cursor.delete();cursor.continue();}};
307
+ });}catch{} // Unavailable IDB must not prevent clearing the local draft.
308
+ }catch{this.warn('Local draft could not be cleared.');}
309
+ });
199
310
  }
200
- clear():void {try{this.storage?.removeItem(this.key);if(this.priorKey&&this.priorKey!==this.key){this.storage?.removeItem(this.priorKey);this.priorKey=null;}this.blocked=false;this.rawRecovery=null;}catch{this.warn('Local draft could not be cleared.');}}
201
311
  }
202
312
 
203
313
  interface PersistenceSession {id:string;revision:string;sourceHash:string;status:string;feedback:unknown[]}
@@ -218,7 +328,7 @@ export async function connectInspectionPersistence<T extends PersistenceSession>
218
328
  const holdRestore=(value:boolean)=>{restoring=value;const body=document.body;if(value){if(body&&previousInert===null){previousInert=body.inert;body.inert=true;}}else if(body&&previousInert!==null){body.inert=previousInert;previousInert=null;}};
219
329
  let baseline=await sessionFingerprint(adapter.baseline);const status=adapter.onStatus,initialInputs=captureInputs();
220
330
  const store=new InspectionDraftStore(adapter.scope,adapter.binding,status);
221
- let draft=store.read(session=>recoverSession(session,adapter.baseline)!==null);
331
+ let draft=await store.read(session=>recoverSession(session,adapter.baseline)!==null);
222
332
  const notices=[document.getElementById('draft-recovery'),document.getElementById('review-draft-recovery')].filter((node):node is HTMLElement=>node!==null);
223
333
  const clearNotices=()=>{for(const node of notices)node.replaceChildren();};
224
334
  const appendAction=(label:string,onclick:()=>void)=>{for(const node of notices){const button=actionButton(label,onclick);node.append(button);}};
@@ -231,7 +341,7 @@ export async function connectInspectionPersistence<T extends PersistenceSession>
231
341
  recovered=recoverSession(draft.session,adapter.baseline);
232
342
  const prior=recovered?recoverSession(adapter.baseline,draft.session as T):null;
233
343
  sameBaseline=draft.baseline===baseline||(prior!==null&&draft.baseline===await sessionFingerprint(prior));
234
- if(!draft.reviewDirty&&(!sameBaseline||!recovered||draft.baseline!==baseline)){store.clear();draft=null;recovered=null;}
344
+ if(!draft.reviewDirty&&(!sameBaseline||!recovered||draft.baseline!==baseline)){await store.clear();draft=null;recovered=null;}
235
345
  }
236
346
  const raw=store.recovery();
237
347
  if(draft){
@@ -245,7 +355,7 @@ export async function connectInspectionPersistence<T extends PersistenceSession>
245
355
  }
246
356
  if(raw&&(conflict||!draft))appendAction('Download saved local draft',()=>download(raw));
247
357
  if(conflict&&recovered)appendAction('Recover local draft as pending',()=>{try{adapter.restoreSession({...recovered,status:'pending'},true);conflict=false;adapter.onConflict(false);clearNotices();status('Recovered local draft as pending · not submitted');save();}catch(error){status(`Local draft recovery refused: ${error instanceof Error?error.message:String(error)}`);}});
248
- if(conflict)appendAction('Discard conflicting local draft',()=>{adapter.restoreSession(structuredClone(adapter.baseline),false);restoreInputs(initialInputs,viewInputIds);adapter.afterInputs();store.clear();conflict=false;adapter.onConflict(false);clearNotices();status('Local draft discarded · current submitted review retained.');save();});
358
+ if(conflict)appendAction('Discard conflicting local draft',async()=>{adapter.restoreSession(structuredClone(adapter.baseline),false);restoreInputs(initialInputs,viewInputIds);adapter.afterInputs();await store.clear();conflict=false;adapter.onConflict(false);clearNotices();status('Local draft discarded · current submitted review retained.');save();});
249
359
  const selected=location.hash.startsWith('#review=')?explicit:draft?.bookmark;
250
360
  let restored=location.hash.startsWith('#review=')||!!draft;
251
361
  if(selected){try{await adapter.restoreBookmark(selected,new AbortController().signal);restored=true;}catch(error){status(`Inspection was not restored: ${error instanceof Error?error.message:String(error)}`);}}
@@ -253,13 +363,20 @@ export async function connectInspectionPersistence<T extends PersistenceSession>
253
363
  const excluded=new Set(viewInputIds);if(conflict||!draft.reviewDirty){excluded.add('review-status');excluded.add('status');excluded.add('checkpoint-note');for(const key of Object.keys(draft.inputs))if(key.startsWith('radio:outcome:'))excluded.add(key);}
254
364
  restoreInputs(draft.inputs,excluded);adapter.afterInputs();
255
365
  }
256
- if(raw&&!draft)appendAction('Discard unusable local draft',()=>{store.clear();clearNotices();status('Unusable local draft discarded for this review only.');save();});
366
+ if(raw&&!draft)appendAction('Discard unusable local draft',async()=>{await store.clear();clearNotices();status('Unusable local draft discarded for this review only.');save();});
367
+ let writes=Promise.resolve();
257
368
  restoring=false;
258
369
  if(draft&&!conflict&&draft.baseline!==baseline)save();
370
+ function snapshot():LocalInspectionDraft {
371
+ return structuredClone<LocalInspectionDraft>({schema:'rig-review-local-draft/1',sourceHash:adapter.binding.sourceHash,baseline,savedAt:new Date().toISOString(),reviewDirty:adapter.reviewDirty(),bookmark:parseBookmark(adapter.bookmark(),adapter.binding),inputs:captureInputs(),session:adapter.session(),ui:adapter.ui()});
372
+ }
373
+ async function persist(value:LocalInspectionDraft,navigation:number):Promise<void> {
374
+ value.baseline=baseline;
375
+ if(await store.write(value)&&!closed&&!restoring&&navigation===navigationGeneration){const url=new URL(location.href);url.hash=encodeBookmark(value.bookmark);history.replaceState(null,'',url);lastNavigationHash=url.hash;}
376
+ }
259
377
  function save():void {
260
378
  if(closed||restoring||conflict)return;
261
- try{const bookmark=parseBookmark(adapter.bookmark(),adapter.binding);const value:LocalInspectionDraft={schema:'rig-review-local-draft/1',sourceHash:adapter.binding.sourceHash,baseline,savedAt:new Date().toISOString(),reviewDirty:adapter.reviewDirty(),bookmark,inputs:captureInputs(),session:adapter.session(),ui:adapter.ui()};
262
- if(store.write(value)){const url=new URL(location.href);url.hash=encodeBookmark(bookmark);history.replaceState(null,'',url);lastNavigationHash=url.hash;}
379
+ try{const value=snapshot(),navigation=navigationGeneration;writes=writes.then(()=>persist(value,navigation)).catch(error=>{status(`Local view was not saved: ${error instanceof Error?error.message:String(error)}`);});
263
380
  }catch(error){status(`Local view was not saved: ${error instanceof Error?error.message:String(error)}`);}
264
381
  }
265
382
  function navigateView():void {
@@ -285,5 +402,9 @@ export async function connectInspectionPersistence<T extends PersistenceSession>
285
402
  const events=['input','change','click','pointerup','wheel'] as const;for(const event of events)window.addEventListener(event,schedule,{passive:true});
286
403
  const interval=setInterval(()=>{if(!document.hidden)save();},1000);
287
404
  const copy=document.getElementById('copy-view');const copyView=async()=>{if(closed)return;try{const url=inspectionLink(location.href,adapter.bookmark());await navigator.clipboard.writeText(url.href);history.replaceState(null,'',url);lastNavigationHash=url.hash;status('View link copied · source-bound numeric region, no review decisions.');}catch(error){status(`View link was not copied: ${error instanceof Error?error.message:String(error)}`);}};if(copy)copy.onclick=copyView;
288
- return {restored,restoring:()=>restoring,save,submitted:async session=>{baseline=await sessionFingerprint(session);save();},dispose:()=>{save();closed=true;++navigationGeneration;navigationAbort?.abort();holdRestore(false);window.removeEventListener('hashchange',navigateView);window.removeEventListener('popstate',navigateView);if(copy?.onclick===copyView)copy.onclick=null;if(timer)clearTimeout(timer);clearInterval(interval);for(const event of events)window.removeEventListener(event,schedule);}};
405
+ return {restored,restoring:()=>restoring,save,submitted:session=>{
406
+ if(closed)return Promise.resolve();
407
+ const submitted=structuredClone(session),value=snapshot(),navigation=navigationGeneration;
408
+ writes=writes.then(async()=>{baseline=await sessionFingerprint(submitted);await store.clear();await persist(value,navigation);});return writes;
409
+ },dispose:()=>{save();closed=true;++navigationGeneration;navigationAbort?.abort();holdRestore(false);window.removeEventListener('hashchange',navigateView);window.removeEventListener('popstate',navigateView);if(copy?.onclick===copyView)copy.onclick=null;if(timer)clearTimeout(timer);clearInterval(interval);for(const event of events)window.removeEventListener(event,schedule);}};
289
410
  }
@@ -132,6 +132,13 @@ export function createJobRigScreen(options: {
132
132
  if (jobRigScreenSubject(candidate.publication.source)) {picture = await prepare(candidate, signal, true);break;}
133
133
  previous = candidate.publication.previousPublicationId;
134
134
  }
135
+ if (!picture && inspection.interview?.questions.some(question => question.hasParts)) {
136
+ const response = await fetch(options.routes(display).api('stage-parts'), {signal});
137
+ if (!response.ok) throw new Error('JOB_VISUAL_UNAVAILABLE');
138
+ const parts = await response.json() as PartsSubjectData;
139
+ if (parts.sourceHash !== source.sourceHash || parts.mode !== 'parts') throw new Error('JOB_DISPLAY_MISMATCH');
140
+ picture = {jobRigScreen:true,display,entry:options.routes(display).entry,checkpoints:new Set(),parts};
141
+ }
135
142
  if(signal.aborted)throw new Error('JOB_PRELOAD_CANCELLED');
136
143
  return {jobRigScreen:true,display,entry:options.routes(display).entry,checkpoints:new Set(),record:{inspection,forms,picture}};
137
144
  } catch(error) {inspection.dispose();throw error;}
@@ -164,7 +171,8 @@ export function createJobRigScreen(options: {
164
171
  let modals:JobRigScreenPrepared['modals'];
165
172
  const asks=options.window.state().pending.filter(ask=>ask.publicationId===display.publication.publicationId&&ask.subject.kind!=='review-verdict'&&ask.subject.kind!=='parts-verdict'&&jobRigScreenAsk(display,ask,checkpoints));
166
173
  if(!backdropOnly&&options.formDependencies){
167
- const inspection=await prepareJobInspection(display,signal,true);
174
+ // The shared main workspace loads visuals; modal forms keep data and checkpoint evidence.
175
+ const inspection=await prepareJobInspection(display,signal,true,false);
168
176
  try{modals={inspection,forms:prepareJobForms(display,asks,ask=>formFor(ask,inspection,options.formDependencies!))};}
169
177
  catch(error){inspection.dispose();throw error;}
170
178
  }
@@ -241,7 +249,7 @@ export function createJobRigScreen(options: {
241
249
  attach:value=>{screen=value;screen.pendingSubjects?.(pendingSubjects());refreshRecordForms();},
242
250
  displayed:()=>ready.resolve(),failed:error=>ready.reject(error)};
243
251
  }
244
- if(!review)throw new Error('JOB_DISPLAY_MISMATCH');
252
+ if(!review&&!prepared.parts)throw new Error('JOB_DISPLAY_MISMATCH');
245
253
  return {access,pendingSubjects,navigation,...prepared.refusal?{unavailable:prepared.refusal}:{},...prepared.display.publication.source.direction?{direction:{publicationId:prepared.display.publication.publicationId,sourceHash:prepared.display.publication.source.sourceHash}}:{},
246
254
  reviewState(issues,sending) {
247
255
  if(sending)return options.translate('job.parts.sending');
@@ -261,10 +269,10 @@ export function createJobRigScreen(options: {
261
269
  if(path==='/api/session'){const act=options.window.state().pending.filter(ask=>ask.publicationId===prepared.display.publication.publicationId&&ask.subject.kind==='parts-verdict').at(-1)?.act;return Promise.resolve({subject:'parts',issues:act?.kind==='parts-verdict'&&act.schema==='rig-review/act@6'?commentPartsIssues(act.value.comments):act?.kind==='parts-verdict'&&act.schema==='rig-review/act@5'?act.value.issues:[]});}
262
270
  return undefined;
263
271
  }
264
- if (path === '/api/review') return Promise.resolve(structuredClone(review));
272
+ if (path === '/api/review') return Promise.resolve(structuredClone(review!));
265
273
  if (path === '/api/access') return Promise.resolve({capabilityRequired: true, control: false});
266
- if (path === '/api/session') return Promise.resolve({schema: 'rig-review-session/1', id: review.manifest.id, revision: review.manifest.revision,
267
- sourceHash: review.sourceHash, reviewedSource: structuredClone(review.reviewedSource), status: 'pending', checkpoints: {}, feedback: [],
274
+ if (path === '/api/session') return Promise.resolve({schema: 'rig-review-session/1', id: review!.manifest.id, revision: review!.manifest.revision,
275
+ sourceHash: review!.sourceHash, reviewedSource: structuredClone(review!.reviewedSource), status: 'pending', checkpoints: {}, feedback: [],
268
276
  feedbackWarnings: [], updatedAt: null} satisfies ReviewSession);
269
277
  return Promise.reject(new Error('JOB_REVIEW_READ_ONLY'));
270
278
  },
@@ -792,7 +792,6 @@ export interface JobPreparedInspection {
792
792
  parts: JobPartsInventory | null;
793
793
  partImages: Map<string, HTMLImageElement>;
794
794
  partPages?: Map<number, HTMLImageElement>;
795
- interviewImages: Map<string, HTMLImageElement>;
796
795
  checkpointEvidence?: readonly {
797
796
  packet: JobCheckpointEvidence;
798
797
  table: JobCheckpointTable;
@@ -867,8 +866,8 @@ export function mediaReady(media: HTMLVideoElement, name: 'loadeddata' | 'seeked
867
866
  failed();
868
867
  });
869
868
  }
870
- /** Prepare the real published Play model, references and every form dependency off-stage. */
871
- export async function prepareJobInspection(display: DisplayPublicationV3, signal: AbortSignal, formsOnly=false): Promise<JobPreparedInspection> {
869
+ /** Prepare off-stage; modal-only callers may skip workspace visuals, never checkpoint evidence. */
870
+ export async function prepareJobInspection(display: DisplayPublicationV3, signal: AbortSignal, formsOnly=false, preloadVisuals=true): Promise<JobPreparedInspection> {
872
871
  const routes = jobPublicationRoutes(display, location.origin);
873
872
  const metadata = await jobJson<JobInspectionMetadataV3>(routes.api('review'), signal);
874
873
  const publishedSource = display.publication.source;
@@ -962,7 +961,6 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
962
961
  throw new Error('JOB_SOURCE_MISMATCH');
963
962
  const references: JobReferenceView[] = [];
964
963
  const partImages = new Map<string, HTMLImageElement>();
965
- const interviewImages = new Map<string, HTMLImageElement>();
966
964
  const partPages = new Map<number, HTMLImageElement>();
967
965
  const preload: Promise<void>[] = [];
968
966
  const source = display.publication.source;
@@ -1008,7 +1006,7 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
1008
1006
  checkpointEvidence[index] = {packet, table, images};
1009
1007
  })());
1010
1008
  }
1011
- for (const reference of metadata.manifest?.references ?? []) {
1009
+ for (const reference of preloadVisuals ? metadata.manifest?.references ?? [] : []) {
1012
1010
  if (reference.id === metadata.sourcePainting?.id) continue;
1013
1011
  preload.push((async () => {
1014
1012
  if (reference.type === 'image') {
@@ -1107,7 +1105,7 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
1107
1105
  }
1108
1106
  })());
1109
1107
  }
1110
- if (metadata.sourcePainting) {
1108
+ if (preloadVisuals && metadata.sourcePainting) {
1111
1109
  const source = metadata.sourcePainting;
1112
1110
  preload.push(image(routes.instance(source.url), source.sha256).then(element => {
1113
1111
  element.alt = source.path;
@@ -1115,18 +1113,14 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
1115
1113
  width: element.naturalWidth, height: element.naturalHeight, seek: async () => { } });
1116
1114
  }));
1117
1115
  }
1118
- for (const part of parts?.items ?? []) {
1116
+ for (const part of preloadVisuals ? parts?.items ?? [] : []) {
1119
1117
  preload.push(image(routes.api('stage-parts/image/' + part.index), part.imageHash)
1120
1118
  .then(element => { element.alt = part.name; partImages.set(part.name, element); }));
1121
1119
  }
1122
- for (const page of parts?.pages ?? []) {
1120
+ for (const page of preloadVisuals ? parts?.pages ?? [] : []) {
1123
1121
  preload.push(image(routes.api('stage-parts/page/' + page.index))
1124
1122
  .then(element => { partPages.set(page.index, element); }));
1125
1123
  }
1126
- for (const question of interview?.questions ?? [])
1127
- for (const asset of question.images) {
1128
- preload.push(image(routes.instance(asset.url)).then(element => { element.alt = asset.name; interviewImages.set(asset.url, element); }));
1129
- }
1130
1124
  const preloaded = await Promise.allSettled(preload);
1131
1125
  const failed = preloaded.find(result => result.status === 'rejected');
1132
1126
  if (failed?.status === 'rejected')
@@ -1171,7 +1165,7 @@ export async function prepareJobInspection(display: DisplayPublicationV3, signal
1171
1165
  const order = [metadata.sourcePainting?.id, ...(metadata.manifest?.references.map(reference => reference.id) ?? [])];
1172
1166
  references.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
1173
1167
  return {
1174
- display, metadata, interview, parts, partImages, partPages, interviewImages, checkpointEvidence, references, assets, rigRoot,
1168
+ display, metadata, interview, parts, partImages, partPages, checkpointEvidence, references, assets, rigRoot,
1175
1169
  get rigPresentation() { return rigPresentation; },
1176
1170
  set rigPresentation(value) {
1177
1171
  clearRigPresentation();
@@ -1400,7 +1394,7 @@ export interface JobFormDependencies {
1400
1394
  fields.prepend(legacyNotice);
1401
1395
  }
1402
1396
  interviewForm=createInterviewForm({question,id:'interview-answer-'+ask.askId,node,form,fieldset:fields,source,
1403
- images:question.images.map(image=>{const visual=prepared.interviewImages.get(image.url);if(!visual)throw new Error('JOB_VISUAL_UNAVAILABLE');return {name:image.name,src:visual.src};}),answered:ask.status==='answered'});
1397
+ images:question.images.map(image=>({name:image.name,src:jobPublicationRoutes(prepared.display,location.origin).instance(image.url)})),answered:ask.status==='answered'});
1404
1398
  disposeInterview=interviewForm.dispose;read=interviewForm.read;
1405
1399
  submitKey = 'interview.save';
1406
1400
  }