rig-review 3.7.0 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/docs/DESIGN.md +145 -74
- package/docs/PANELS.md +20 -12
- package/docs/PARTS_VIEW.md +133 -76
- package/docs/REVIEW_PACKAGE.md +446 -100
- package/docs/STABILITY.md +132 -198
- package/docs/WORKFLOWS.md +41 -120
- package/package.json +4 -3
- package/skills/rig-review/SKILL.md +41 -27
- package/src/build.ts +10 -2
- package/src/cli.ts +17 -16
- package/src/comment-crops.ts +6 -1
- package/src/compare-html.ts +22 -24
- package/src/compare-server.ts +1 -1
- package/src/compare-session.ts +41 -3
- package/src/correction-handoff.ts +27 -4
- package/src/create-pin-gate.ts +3 -0
- package/src/direction-inspection.ts +6 -2
- package/src/feedback-export.ts +68 -1
- package/src/front.ts +5 -200
- package/src/handoff.ts +1 -1
- package/src/interview-routes.ts +1 -1
- package/src/interview-scene.ts +3 -3
- package/src/job-act.ts +77 -73
- package/src/job-api.ts +326 -13
- package/src/job-checkpoint-evidence.ts +113 -0
- package/src/job-cli.ts +27 -14
- package/src/job-contract.ts +284 -62
- package/src/job-front.ts +192 -61
- package/src/job-host.ts +23 -4
- package/src/job-session.ts +109 -24
- package/src/job-source.ts +227 -58
- package/src/job-store.ts +80 -6
- package/src/job-worker.ts +1 -47
- package/src/joined-project.ts +61 -4
- package/src/manifest.ts +32 -4
- package/src/open-workspace.ts +12 -12
- package/src/open.ts +19 -12
- package/src/parts-comment-crops.ts +126 -31
- package/src/parts-comment.ts +351 -28
- package/src/parts-server.ts +19 -7
- package/src/parts-view.ts +588 -109
- package/src/scene-inspection.ts +50 -0
- package/src/server.ts +31 -22
- package/src/session.ts +58 -0
- package/src/stage-comment.ts +48 -1
- package/src/stage-parts.ts +23 -11
- package/web/animation-inspection.ts +1 -1
- package/web/bones-panel.ts +1 -3
- package/web/catalog-en.ts +175 -39
- package/web/catalog-ko.ts +175 -39
- package/web/cloth-panel.ts +1 -2
- package/web/compare.css +3 -13
- package/web/compare.html +3 -3
- package/web/compare.ts +69 -64
- package/web/cuts-panel.ts +1 -3
- package/web/density-strip-panel.ts +1 -2
- package/web/direction-panel.ts +22 -6
- package/web/i18n.ts +13 -1
- package/web/idle-panel.ts +1 -2
- package/web/index.html +1 -5
- package/web/inspection-persistence.ts +2 -1
- package/web/inspector-blocks.ts +149 -40
- package/web/instance-access.ts +24 -5
- package/web/interview-panel.ts +224 -175
- package/web/job-rig-capture.ts +164 -21
- package/web/job-rig-screen.ts +344 -0
- package/web/job-session.ts +611 -1443
- package/web/main.ts +614 -151
- package/web/mesh-panel.ts +1 -2
- package/web/owner-workspace.ts +88 -109
- package/web/part-selection.ts +47 -6
- package/web/part-thumbnails.ts +20 -6
- package/web/parts-render.ts +26 -19
- package/web/parts-viewport-provider.ts +181 -7
- package/web/physics-panel.ts +1 -2
- package/web/readings-panel.ts +1 -2
- package/web/requirements-panel.ts +1 -3
- package/web/retained-frame-stage.ts +105 -0
- package/web/retarget-panel.ts +2 -3
- package/web/rig-fields-panel.ts +1 -2
- package/web/rig-host.ts +64 -0
- package/web/rig-viewport-provider.ts +65 -16
- package/web/scene-plates.ts +57 -4
- package/web/stage-comments.ts +103 -46
- package/web/styles.css +117 -63
- package/web/view-controls.ts +201 -12
- package/web/viewport-capture.ts +12 -2
- package/web/viewport-controller.ts +107 -27
- package/web/viewport-pair.ts +2 -1
- package/web/workspace-preferences.ts +5 -4
- package/web/workspace-ui.ts +151 -19
- package/src/front-worker.ts +0 -2
- package/src/interview-server.ts +0 -54
- package/src/job-hub.ts +0 -304
- package/src/job-image-set.ts +0 -50
- package/web/interview.css +0 -28
- package/web/interview.html +0 -17
- package/web/interview.ts +0 -40
- package/web/job-hub.css +0 -14
- package/web/job-hub.html +0 -5
- package/web/job-hub.ts +0 -179
- package/web/owner-workspace.css +0 -14
- package/web/owner-workspace.html +0 -5
- package/web/parts-flags.ts +0 -48
- package/web/parts.css +0 -104
- package/web/parts.html +0 -49
- package/web/parts.ts +0 -604
- package/web/stage-nav.ts +0 -136
package/src/job-worker.ts
CHANGED
|
@@ -1,8 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { createJobHostPorts } from './job-api.ts';
|
|
3
|
-
import { JobSession, type JobSessionOptions } from './job-session.ts';
|
|
4
|
-
import type { JobHostPorts } from './job-contract.ts';
|
|
5
|
-
import { JobError } from './job-store.ts';
|
|
1
|
+
import type {JobSessionOptions} from './job-session.ts';
|
|
6
2
|
|
|
7
3
|
export interface JobWorkerOptions extends JobSessionOptions {
|
|
8
4
|
readonly port?: number;
|
|
@@ -16,45 +12,3 @@ export interface JobWorkerOptions extends JobSessionOptions {
|
|
|
16
12
|
readonly fetchCapability: string;
|
|
17
13
|
}) => void | Promise<void>;
|
|
18
14
|
}
|
|
19
|
-
|
|
20
|
-
/** Backend host only. Lane B mounts these same ports in its managed front and
|
|
21
|
-
* supplies the owner UI. This listener serves semantic API requests only and
|
|
22
|
-
* never serves a private snapshot directory or starts a browser/producer.
|
|
23
|
-
*/
|
|
24
|
-
export async function startJobWorker(options: JobWorkerOptions): Promise<{
|
|
25
|
-
readonly session: JobSession;
|
|
26
|
-
readonly ports: JobHostPorts;
|
|
27
|
-
readonly origin: string;
|
|
28
|
-
readonly listenerIncarnation: string;
|
|
29
|
-
stop(): void;
|
|
30
|
-
}> {
|
|
31
|
-
const session = new JobSession(options);
|
|
32
|
-
const listenerIncarnation = randomUUID();
|
|
33
|
-
let ports: JobHostPorts;
|
|
34
|
-
let stopped = false;
|
|
35
|
-
const server = Bun.serve({
|
|
36
|
-
hostname: '127.0.0.1', port: options.port ?? 0, idleTimeout: 0,
|
|
37
|
-
fetch(request) {
|
|
38
|
-
const url = new URL(request.url);
|
|
39
|
-
if (url.pathname === `/jobs/${session.jobId}/api`) return ports.handleJobApi(request);
|
|
40
|
-
return Response.json({ error: 'JOB_REQUEST_INVALID' }, {
|
|
41
|
-
status: 404, headers: { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },
|
|
42
|
-
});
|
|
43
|
-
},
|
|
44
|
-
});
|
|
45
|
-
const origin = `http://127.0.0.1:${server.port}`;
|
|
46
|
-
ports = createJobHostPorts(session, origin);
|
|
47
|
-
const stop = () => {
|
|
48
|
-
if (stopped) return;
|
|
49
|
-
stopped = true;
|
|
50
|
-
server.stop(true);
|
|
51
|
-
session.dispose();
|
|
52
|
-
};
|
|
53
|
-
try {
|
|
54
|
-
await options.installWriterBinding?.({ ...session.writerGrant(), origin });
|
|
55
|
-
return { session, ports, origin, listenerIncarnation, stop };
|
|
56
|
-
} catch {
|
|
57
|
-
stop();
|
|
58
|
-
throw new JobError('JOB_AUTHORITY_REFUSED', 'Writer binding installation failed');
|
|
59
|
-
}
|
|
60
|
-
}
|
package/src/joined-project.ts
CHANGED
|
@@ -9,7 +9,8 @@ import { assertReviewUnchanged, withReviewAssertion } from './reference.ts';
|
|
|
9
9
|
|
|
10
10
|
export type ProjectDesignation={root:string;picksDir:string}&(
|
|
11
11
|
{version:number;postVersion?:number;draftId?:never;partsVerdictDir?:never} |
|
|
12
|
-
{draftId:string;partsVerdictDir?:string;version?:never;postVersion?:never}
|
|
12
|
+
{draftId:string;partsVerdictDir?:string;version?:never;postVersion?:never} |
|
|
13
|
+
{version?:never;draftId?:never;postVersion?:never;partsVerdictDir?:never}
|
|
13
14
|
);
|
|
14
15
|
interface DraftRecord {
|
|
15
16
|
id:string;
|
|
@@ -45,7 +46,62 @@ export const interviewMismatch = 'INTERVIEW_SOURCE_MISMATCH';
|
|
|
45
46
|
export const interviewStale = 'INTERVIEW_OPTIONS_STALE';
|
|
46
47
|
export const directionStale = 'DIRECTION_SOURCE_STALE';
|
|
47
48
|
|
|
48
|
-
|
|
49
|
+
/** Project inspection metadata; deliberately has no manifest, model or package session. */
|
|
50
|
+
export interface InterviewSubjectEntry {
|
|
51
|
+
subject:'interview';
|
|
52
|
+
project:{path:'project.json';sha256:string};
|
|
53
|
+
label:string;
|
|
54
|
+
sourceHash:string;
|
|
55
|
+
capabilities:{interview:true;playback:false;modeling:false;motion:false;feedback:false;audio:false};
|
|
56
|
+
unavailable:'MODEL_UNAVAILABLE';
|
|
57
|
+
}
|
|
58
|
+
export interface JoinedInterview {
|
|
59
|
+
interviewOnly:true;
|
|
60
|
+
opened:ReturnType<typeof readProject>;
|
|
61
|
+
designation:Extract<ProjectDesignation,{version?:never;draftId?:never}>;
|
|
62
|
+
sourceHash:string;
|
|
63
|
+
available:boolean;
|
|
64
|
+
assertCurrent:()=>Promise<void>;
|
|
65
|
+
review?:never;
|
|
66
|
+
draft?:never;
|
|
67
|
+
verdictDirectory?:never;
|
|
68
|
+
}
|
|
69
|
+
export function joinProject(p:null,designation:ProjectDesignation,options?:{starts?:readonly string[]}):JoinedInterview;
|
|
70
|
+
export function joinProject(p:ReviewPackage,designation:ProjectDesignation,options?:{starts?:readonly string[]}):JoinedSource;
|
|
71
|
+
export function joinProject(p:ReviewPackage|null,designation:ProjectDesignation,options:{starts?:readonly string[]}={}):JoinedSource|JoinedInterview {
|
|
72
|
+
if(designation.version===undefined&&designation.draftId===undefined){
|
|
73
|
+
const fail=():never=>{throw new Error(interviewMismatch+': expected an interview-stage project without a draft or recorded package');};
|
|
74
|
+
if(p!==null||designation.postVersion!==undefined||designation.partsVerdictDir!==undefined)return fail();
|
|
75
|
+
const opened=readProject(designation.root),{root,project,hash}=opened;
|
|
76
|
+
const assertStage=()=>{
|
|
77
|
+
if(project.stage!=='interview'||!Array.isArray(project.versions)||
|
|
78
|
+
project.versions.some(entry=>object(entry).review_package!=null)||
|
|
79
|
+
!(project.drafts==null||Array.isArray(project.drafts)&&project.drafts.length===0))return fail();
|
|
80
|
+
};
|
|
81
|
+
assertStage();
|
|
82
|
+
outputDirectory(root,designation.picksDir,project);
|
|
83
|
+
if(!opened.questions.length&&!opened.historical.length)throw new Error(interviewUnavailable);
|
|
84
|
+
const files=new Map<string,string>([['project.json',hash]]);
|
|
85
|
+
const retain=(ref:SetRef)=>{
|
|
86
|
+
if(!literalPath(ref.path)||typeof ref.sha256!=='string'||!/^[a-f0-9]{64}$/.test(ref.sha256))return fail();
|
|
87
|
+
if(files.has(ref.path)&&files.get(ref.path)!==ref.sha256)return fail();
|
|
88
|
+
boundBytes(root,ref);files.set(ref.path,ref.sha256);
|
|
89
|
+
};
|
|
90
|
+
if(!Array.isArray(project.inputs))return fail();
|
|
91
|
+
for(const input of project.inputs)retain(object(input) as unknown as SetRef);
|
|
92
|
+
for(const question of opened.questions){retain(question.ref);for(const image of question.images)retain(image.ref);}
|
|
93
|
+
const assertCurrent=async()=>{
|
|
94
|
+
try{
|
|
95
|
+
assertStage();
|
|
96
|
+
for(const [path,sha256]of files)boundBytes(root,{path,sha256});
|
|
97
|
+
if(readProject(root).hash!==hash)throw new Error('Project changed');
|
|
98
|
+
outputDirectory(root,designation.picksDir,project);
|
|
99
|
+
}catch{throw new Error(interviewStale+': project or interview inputs changed; reopen the project');}
|
|
100
|
+
};
|
|
101
|
+
return {interviewOnly:true,opened,designation:{root,picksDir:designation.picksDir},available:true,assertCurrent,
|
|
102
|
+
sourceHash:digest(JSON.stringify({project:{path:'project.json',sha256:hash},files:[...files].sort(([a],[b])=>a.localeCompare(b))}))};
|
|
103
|
+
}
|
|
104
|
+
if(!p)throw new Error(interviewMismatch+': expected the explicitly designated recorded package');
|
|
49
105
|
if(designation.draftId!==undefined)return joinDraft(p,designation,options);
|
|
50
106
|
const opened = readProject(designation.root);
|
|
51
107
|
const {root, hash, project} = opened;
|
|
@@ -176,7 +232,8 @@ function joinDraft(p:ReviewPackage,designation:Extract<ProjectDesignation,{draft
|
|
|
176
232
|
const producer=object(record?.producer);
|
|
177
233
|
if(matches.length!==1||record?.kind!=='draft-rig'||typeof record.at!=='string'||!Number.isFinite(Date.parse(record.at))||
|
|
178
234
|
producer.name!=='@rig-c/parts'||typeof producer.version!=='string'||!producer.version.trim()||
|
|
179
|
-
|
|
235
|
+
// Create's draft-rig records the draft directory itself when --parts is omitted (rig-create src/drafts.ts `opts['--parts'] ?? from`).
|
|
236
|
+
!literalPath(parts.path)||!(parts.path===path||parts.path.startsWith(path+'/'))||
|
|
180
237
|
!Array.isArray(parts.files)||!Array.isArray(record.files)||
|
|
181
238
|
(record.config_inputs!==undefined&&!Array.isArray(record.config_inputs)))return fail();
|
|
182
239
|
const files=new Map<string,string>();
|
|
@@ -301,4 +358,4 @@ function joinDraft(p:ReviewPackage,designation:Extract<ProjectDesignation,{draft
|
|
|
301
358
|
return {review,opened,designation:{...designation,root},assertCurrent,draft,verdictDirectory,
|
|
302
359
|
available:opened.questions.length>0||opened.historical.length>0};
|
|
303
360
|
}
|
|
304
|
-
export type JoinedProject =
|
|
361
|
+
export type JoinedProject = JoinedSource | JoinedInterview;
|
package/src/manifest.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {readSceneInspection,scenePlateBytes,type SceneInspection} from './scene-inspection.ts';
|
|
1
2
|
import {DIRECTION_MAX_BYTES, readDirectionInspection, type DirectionInspection} from './direction-inspection.ts';
|
|
2
3
|
import {discoverTurnDials} from './turn-pad.ts';
|
|
3
4
|
import { createHash } from 'node:crypto';
|
|
@@ -9,22 +10,25 @@ import { readFile, realpath, stat, lstat, readdir } from 'node:fs/promises';
|
|
|
9
10
|
import { createReadStream } from 'node:fs';
|
|
10
11
|
import { basename, dirname, isAbsolute, relative, resolve, posix } from 'node:path';
|
|
11
12
|
import { isBuildRoot, parseHandoffDeclaration, resolveHandoff, type Handoff, type HandoffDeclaration, type HandoffFlags, type HandoffRecord } from './handoff.ts';
|
|
13
|
+
import { parsePanelComposition, type JobPanelComposition } from './job-contract.ts';
|
|
14
|
+
export { isPanelComponent, parsePanelComposition } from './job-contract.ts';
|
|
12
15
|
|
|
13
16
|
export type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
|
|
14
17
|
export interface Reference { id: string; label: string; type: 'image' | 'video' | 'pose'; path: string; width?: number; height?: number }
|
|
15
18
|
export interface Checkpoint { id: string; title: string; time?: number; animation?: string; reference?: string; note?: string; workspace?: 'modeling' | 'motion'; camera?: { zoom: number; x: number; y: number }; axis?: {id:string;value:number} }
|
|
16
19
|
export interface ReviewManifest {
|
|
17
20
|
schema: 'rig-review/1'; id: string; title: string; revision: string; model?: string; motion?: string;
|
|
18
|
-
direction?: string; sets?: string;
|
|
21
|
+
direction?: string; scene?: string; sets?: string;
|
|
19
22
|
references: Reference[]; animations: { id: string; label?: string; duration?: number }[];
|
|
20
23
|
checkpoints: Checkpoint[]; authoring: { label: string; path: string }[];
|
|
21
24
|
axes: { id: string; label: string; animation: string; min: number; max: number }[];
|
|
22
25
|
audio: { clips: { id: string; label?: string; path: string }[]; cues: { id: string; clip: string; time: number; animation?: string }[] };
|
|
23
26
|
/** Optional producer handoff (#101): package-relative literal paths; checked when the package loads. */
|
|
24
27
|
producer?: HandoffDeclaration;
|
|
28
|
+
panels?: JobPanelComposition;
|
|
25
29
|
}
|
|
26
30
|
export interface ReviewedSource { readonly packageRevision:string; readonly viewerVersion:string; readonly runtimeVersion:string; readonly rig:{readonly path:string;readonly sha256:string}|null; readonly motion:{readonly path:string;readonly sha256:string}|null; readonly handoff?:HandoffRecord }
|
|
27
|
-
export interface ReviewPackage { direction?:DirectionInspection; setsHash?:string; referenceHashes?:Record<string,string>; root: string; manifestPath: string; manifest: ReviewManifest; sourceHash: string; reviewedSource:ReviewedSource; files: Set<string>; report:ReportSeeds|null; feedbackCatalog:FeedbackCatalog;
|
|
31
|
+
export interface ReviewPackage { scene?:SceneInspection; direction?:DirectionInspection; setsHash?:string; referenceHashes?:Record<string,string>; root: string; manifestPath: string; manifest: ReviewManifest; sourceHash: string; reviewedSource:ReviewedSource; files: Set<string>; report:ReportSeeds|null; feedbackCatalog:FeedbackCatalog;
|
|
28
32
|
/** The resolved producer handoff (#101) and, when there is none, the refusal line naming where it was looked for. */
|
|
29
33
|
handoff: Handoff|null; handoffReason: string|null; handoffInputs?: HandoffFlags;
|
|
30
34
|
/** #187: the rig-parts build root ({@link isBuildRoot}) whose `check/` this package is, however it was opened; review state stays outside it. */
|
|
@@ -64,10 +68,16 @@ export async function safeFile(root: string, path: string): Promise<string> {
|
|
|
64
68
|
export function parseManifest(input: unknown): ReviewManifest {
|
|
65
69
|
const m = object(input, 'review'); if (m.schema !== 'rig-review/1') fail('schema', 'rig-review/1');
|
|
66
70
|
const audio = m.audio === undefined ? {} : object(m.audio, 'audio');
|
|
71
|
+
let panels: JobPanelComposition | undefined;
|
|
72
|
+
if (m.panels !== undefined) {
|
|
73
|
+
try { panels = parsePanelComposition(m.panels); }
|
|
74
|
+
catch { panels = undefined; }
|
|
75
|
+
}
|
|
67
76
|
const manifest: ReviewManifest = {
|
|
68
77
|
schema: 'rig-review/1', id: id(m.id, 'id'), title: string(m.title, 'title'), revision: string(m.revision, 'revision'),
|
|
69
78
|
model: m.model === undefined ? undefined : packagePath(m.model, 'model'),
|
|
70
79
|
...(m.direction===undefined?{}:{direction:packagePath(m.direction,'direction')}),
|
|
80
|
+
...(m.scene===undefined?{}:{scene:packagePath(m.scene,'scene')}),
|
|
71
81
|
...(m.sets===undefined?{}:{sets:packagePath(m.sets,'sets')}),
|
|
72
82
|
motion:m.motion===undefined?undefined:packagePath(m.motion,'motion'),
|
|
73
83
|
references: list(m.references, 'references', (v,f) => ({ id:id(v.id,f+'.id'), label:string(v.label,f+'.label'), type:choice(v.type,['image','video','pose'],f+'.type'), path:packagePath(v.path,f+'.path'), width:v.width===undefined?undefined:number(v.width,f+'.width',Number.EPSILON), height:v.height===undefined?undefined:number(v.height,f+'.height',Number.EPSILON) })),
|
|
@@ -76,10 +86,12 @@ export function parseManifest(input: unknown): ReviewManifest {
|
|
|
76
86
|
authoring:list(m.authoring,'authoring',(v,f)=>({label:string(v.label,f+'.label'),path:packagePath(v.path,f+'.path')})),
|
|
77
87
|
axes:list(m.axes,'axes',(v,f)=>({id:id(v.id,f+'.id'),label:string(v.label,f+'.label'),animation:string(v.animation,f+'.animation'),min:number(v.min,f+'.min',-Number.MAX_VALUE),max:number(v.max,f+'.max',-Number.MAX_VALUE)})),
|
|
78
88
|
...(m.producer===undefined?{}:{producer:parseHandoffDeclaration(m.producer)}),
|
|
89
|
+
...(panels===undefined?{}:{panels}),
|
|
79
90
|
audio:{clips:list(audio.clips,'audio.clips',(v,f)=>({id:id(v.id,f+'.id'),label:optionalString(v.label,f+'.label'),path:packagePath(v.path,f+'.path')})),cues:list(audio.cues,'audio.cues',(v,f)=>({id:id(v.id,f+'.id'),clip:string(v.clip,f+'.clip'),time:number(v.time,f+'.time'),animation:optionalString(v.animation,f+'.animation')}))}
|
|
80
91
|
};
|
|
81
92
|
if(manifest.model&&!manifest.model.endsWith('.model.json'))fail('model','compiled model path ending .model.json (the play runtime input)');
|
|
82
93
|
if(manifest.sets&&!manifest.model)fail('sets','compiled model declaration');
|
|
94
|
+
if(manifest.scene&&!manifest.direction)throw new Error('SCENE_REQUIRED: scene requires direction');
|
|
83
95
|
if(manifest.direction&&!manifest.model)fail('direction','compiled model declaration');
|
|
84
96
|
for (const c of manifest.checkpoints) { if(c.reference && !manifest.references.some(r=>r.id===c.reference)) fail(`checkpoint ${c.id}.reference`,'declared reference id'); if(c.animation && !manifest.animations.some(a=>a.id===c.animation)) fail(`checkpoint ${c.id}.animation`,'declared animation id'); }
|
|
85
97
|
for (const c of manifest.audio.cues) { if(!manifest.audio.clips.some(a=>a.id===c.clip)) fail(`cue ${c.id}.clip`,'declared audio clip id'); if(c.animation && !manifest.animations.some(a=>a.id===c.animation)) fail(`cue ${c.id}.animation`,'declared animation id'); }
|
|
@@ -123,9 +135,25 @@ export async function loadReview(input: string, options: { handoff?: HandoffFlag
|
|
|
123
135
|
const {handoff,reason:handoffReason}=await resolveHandoff(root,manifest.producer,options.handoff,{starts:[options.cwd??process.cwd()]});
|
|
124
136
|
// #329: the source painting the handoff knows is the first reference, outside the package's own files.
|
|
125
137
|
const painting=sourcePainting(manifest,handoff,directory);
|
|
138
|
+
let scene:SceneInspection|undefined;
|
|
139
|
+
const sceneBytes=new Map<string,Buffer>();
|
|
140
|
+
if(manifest.scene){
|
|
141
|
+
let bytes:Buffer;try{bytes=await readFile(await safeFile(root,manifest.scene));}catch{throw new Error('SCENE_REQUIRED: '+manifest.scene);}
|
|
142
|
+
if(bytes.length>DIRECTION_MAX_BYTES)throw new Error('SCENE_SOURCE_MISMATCH: '+manifest.scene);
|
|
143
|
+
const dirBytes=await readFile(await safeFile(root,manifest.direction!));
|
|
144
|
+
const direction=readDirectionInspection(JSON.parse(dirBytes.toString()),{path:manifest.direction!,sha256:createHash('sha256').update(dirBytes).digest('hex')},{path:manifest.model!,sha256:modelBytesHash!});
|
|
145
|
+
const sha256=createHash('sha256').update(bytes).digest('hex');
|
|
146
|
+
if(direction.scene?.path!==manifest.scene||direction.scene.sha256!==sha256)throw new Error('SCENE_SOURCE_MISMATCH: '+manifest.scene);
|
|
147
|
+
const model=object(JSON.parse((await readFile(await safeFile(root,manifest.model!))).toString()),'model');
|
|
148
|
+
let sceneInput:unknown;try{sceneInput=JSON.parse(bytes.toString());}catch{throw new Error('SCENE_SOURCE_MISMATCH: '+manifest.scene);}
|
|
149
|
+
scene=readSceneInspection(sceneInput,{path:manifest.scene,sha256},direction,model);
|
|
150
|
+
sceneBytes.set(manifest.scene,bytes);sceneBytes.set(manifest.direction!,dirBytes);
|
|
151
|
+
for(const [path,bytes] of await scenePlateBytes(root,scene))sceneBytes.set(path,bytes);
|
|
152
|
+
for(const path of sceneBytes.keys())files.add(path);
|
|
153
|
+
}
|
|
126
154
|
const hash = createHash('sha256');hash.update(JSON.stringify(manifest));hash.update('\0');const fileHashes=new Map<string,string>();
|
|
127
155
|
for(const p of [...files].sort()) { const full=await safeFile(root,p); const before=await stat(full); hash.update(p);hash.update('\0');hash.update(String(before.size));hash.update('\0'); const fileHash=createHash('sha256');const metadataChunks:Buffer[]=[];const isDirection=p===manifest.direction;let bytesRead=0;
|
|
128
|
-
if(isDirection&&before.size>DIRECTION_MAX_BYTES)throw new Error('DIRECTION_SIZE: direction exceeds 256 KiB');for await(const chunk of createReadStream(full)){hash.update(chunk);fileHash.update(chunk);if(isDirection&&(bytesRead+=chunk.length)>DIRECTION_MAX_BYTES)throw new Error('DIRECTION_SIZE: direction exceeds 256 KiB');if(p===reportPath||p===manifest.model||isDirection)metadataChunks.push(chunk);}fileHashes.set(p,fileHash.digest('hex')); const after=await stat(full); if(before.size!==after.size||before.mtimeMs!==after.mtimeMs) throw new Error(`Asset ${p} changed while hashing; retry with stable package inputs`);
|
|
156
|
+
if(isDirection&&before.size>DIRECTION_MAX_BYTES)throw new Error('DIRECTION_SIZE: direction exceeds 256 KiB');for await(const chunk of createReadStream(full)){hash.update(chunk);fileHash.update(chunk);if(isDirection&&(bytesRead+=chunk.length)>DIRECTION_MAX_BYTES)throw new Error('DIRECTION_SIZE: direction exceeds 256 KiB');if(p===reportPath||p===manifest.model||isDirection)metadataChunks.push(chunk);}fileHashes.set(p,fileHash.digest('hex'));if(sceneBytes.has(p)&&createHash('sha256').update(sceneBytes.get(p)!).digest('hex')!==fileHashes.get(p))throw new Error('SCENE_SOURCE_MISMATCH: '+p); const after=await stat(full); if(before.size!==after.size||before.mtimeMs!==after.mtimeMs) throw new Error(`Asset ${p} changed while hashing; retry with stable package inputs`);
|
|
129
157
|
// The parser and package hash consume the same bytes, never two file reads.
|
|
130
158
|
if(p===manifest.model){if(fileHashes.get(p)!==modelBytesHash)throw new Error(`Model ${p} changed while hashing; retry with stable package inputs`);modelMetadata=object(JSON.parse(Buffer.concat(metadataChunks).toString('utf8')),'model');}
|
|
131
159
|
if(isDirection)directionInput=JSON.parse(Buffer.concat(metadataChunks).toString('utf8'));
|
|
@@ -137,7 +165,7 @@ export async function loadReview(input: string, options: { handoff?: HandoffFlag
|
|
|
137
165
|
const reviewedSource:ReviewedSource={packageRevision:manifest.revision,...await toolVersions(),rig:rigPath?{path:rigPath,sha256:fileHashes.get(rigPath)!}:null,motion:motionPath?{path:motionPath,sha256:fileHashes.get(motionPath)!}:null,...(handoff?{handoff:handoff.record}:{})};
|
|
138
166
|
const direction=manifest.direction?readDirectionInspection(directionInput,{path:manifest.direction,sha256:fileHashes.get(manifest.direction)!},reviewedSource.rig):undefined;
|
|
139
167
|
const feedbackCatalog:FeedbackCatalog={rig:manifest.id,bones:modelNames(modelMetadata,'bones'),slots:modelNames(modelMetadata,'slots'),animations:modelAnimations(modelMetadata),clock:report?.clock??null,clockAnimation:report?.animation??null,...(discoverTurnDials(modelMetadata).length?{turnDials:discoverTurnDials(modelMetadata)}:{})};
|
|
140
|
-
return {...(direction?{direction}:{}),...(manifest.sets?{setsHash:fileHashes.get(manifest.sets)!}:{}),referenceHashes:Object.fromEntries(manifest.references.map(r=>[r.id,r.id===painting?.id?painting.sha256:fileHashes.get(r.path)!])),root,manifestPath,manifest,sourceHash:hash.digest('hex'),reviewedSource,files,report,feedbackCatalog,handoff,handoffReason,...(handoff?.flags?{handoffInputs:handoff.flags}:{}),...(buildRoot?{buildRoot}:{}),...(painting?{sourcePainting:painting}:{}),...(options.cwd?{cwd:options.cwd}:{})};
|
|
168
|
+
return {...(scene?{scene}:{}),...(direction?{direction}:{}),...(manifest.sets?{setsHash:fileHashes.get(manifest.sets)!}:{}),referenceHashes:Object.fromEntries(manifest.references.map(r=>[r.id,r.id===painting?.id?painting.sha256:fileHashes.get(r.path)!])),root,manifestPath,manifest,sourceHash:hash.digest('hex'),reviewedSource,files,report,feedbackCatalog,handoff,handoffReason,...(handoff?.flags?{handoffInputs:handoff.flags}:{}),...(buildRoot?{buildRoot}:{}),...(painting?{sourcePainting:painting}:{}),...(options.cwd?{cwd:options.cwd}:{})};
|
|
141
169
|
}
|
|
142
170
|
|
|
143
171
|
/** #329: the reference id and served path of the handoff's source painting; the path is a name, never a package file. */
|
package/src/open-workspace.ts
CHANGED
|
@@ -7,7 +7,7 @@ import {createCompareRequestContext} from './compare-server.ts';
|
|
|
7
7
|
import {createLiveLifecycle, type UpgradableServer} from './live-lifecycle.ts';
|
|
8
8
|
import {prepareOpenTarget} from './open.ts';
|
|
9
9
|
import {sameSecret} from './open-protocol.ts';
|
|
10
|
-
import {boundedBody, frontRoute, maximumUpstreamStreams
|
|
10
|
+
import {boundedBody, frontRoute, maximumUpstreamStreams} from './front.ts';
|
|
11
11
|
import {assertCompareUnchanged} from './compare.ts';
|
|
12
12
|
import {assertReviewUnchanged} from './reference.ts';
|
|
13
13
|
import {parseDesignation, parseRegistry, readPrivate, targetCapability, workspaceDirectory, workspaceError, writePrivate} from './open-workspace-state.ts';
|
|
@@ -71,24 +71,25 @@ export async function startOpenWorkspace(options: OpenWorkspaceOptions) {
|
|
|
71
71
|
}, options.fingerprint);
|
|
72
72
|
const loaded = prepared.package;
|
|
73
73
|
if (prepared.key !== designation.key || loaded.contentHash !== designation.contentHash) throw workspaceError('WORKSPACE_SOURCE_CHANGED');
|
|
74
|
-
|
|
75
|
-
|
|
74
|
+
const bundleMode=loaded.mode==='interview'?'single':loaded.mode;
|
|
75
|
+
let bundle = bundles.get(bundleMode);
|
|
76
|
+
if (!bundle) {bundle = buildWeb(bundleMode); bundles.set(bundleMode, bundle);}
|
|
76
77
|
const controlToken = loaded.inputs.control ? randomUUID() : undefined;
|
|
77
78
|
const contextOptions = {stateDir: options.stateDir, cwd: designation.cwd, lifecycle: live, bundle: await bundle,
|
|
78
79
|
capability: targetCapability(ownerCapability, incarnation, designation.key),
|
|
79
80
|
open: {key: designation.key, contentHash: designation.contentHash, nonce: incarnation, fingerprint: options.fingerprint},
|
|
80
81
|
...(controlToken ? {control: {token: controlToken, instanceKey: designation.key}} : {}),
|
|
81
82
|
};
|
|
82
|
-
const context = loaded.mode
|
|
83
|
+
const context = loaded.mode !== 'compare'
|
|
83
84
|
? await createReviewRequestContext(loaded.p, {...contextOptions, joined: loaded.joined,
|
|
84
85
|
initialAnimation: loaded.selection?.name, viewOnly: designation.viewOnly})
|
|
85
86
|
: await createCompareRequestContext(loaded.p, contextOptions);
|
|
86
|
-
const check = () => loaded.mode === 'single' ? assertReviewUnchanged(loaded.p) : assertCompareUnchanged(loaded.p);
|
|
87
|
+
const check = () => loaded.mode === 'interview' ? loaded.joined.assertCurrent() : loaded.mode === 'single' ? assertReviewUnchanged(loaded.p) : assertCompareUnchanged(loaded.p);
|
|
87
88
|
await check();
|
|
88
89
|
return {stored: {designation, ...(controlToken ? {controlToken} : {})}, context, check,
|
|
89
90
|
view: {key: designation.key, contentHash: designation.contentHash,
|
|
90
|
-
title: (loaded.mode === 'single' ? loaded.p.manifest.title : loaded.p.response.title).slice(0, 256),
|
|
91
|
-
mode: loaded.mode, animation: loaded.selection?.name ?? null, viewOnly: designation.viewOnly, unavailable: null,
|
|
91
|
+
title: (loaded.mode === 'interview' ? String(loaded.joined.opened.project.name??loaded.joined.opened.root.split('/').at(-1)) : loaded.mode === 'single' ? loaded.p.manifest.title : loaded.p.response.title).slice(0, 256),
|
|
92
|
+
mode: loaded.mode==='interview'?'single' as const:loaded.mode, animation: loaded.selection?.name ?? null, viewOnly: designation.viewOnly, unavailable: null,
|
|
92
93
|
entry: `/instances/${designation.key}/?input=${designation.contentHash}&handoff=${designation.key}&workspace=${incarnation}`}};
|
|
93
94
|
}
|
|
94
95
|
|
|
@@ -185,7 +186,7 @@ export async function startOpenWorkspace(options: OpenWorkspaceOptions) {
|
|
|
185
186
|
if (live.connections >= WORKSPACE_SOCKET_LIMIT) return refused('WORKSPACE_BUSY', 503);
|
|
186
187
|
return live.upgrade(request, server, securityHeaders);
|
|
187
188
|
}
|
|
188
|
-
if (['/', '/
|
|
189
|
+
if (['/', '/main.js', '/styles.css'].includes(url.pathname)) {
|
|
189
190
|
if (!['GET', 'HEAD'].includes(request.method)) return refused('WORKSPACE_REQUEST_INVALID', 400);
|
|
190
191
|
if (url.pathname === '/') {
|
|
191
192
|
const keys = [...url.searchParams.keys()];
|
|
@@ -199,8 +200,8 @@ export async function startOpenWorkspace(options: OpenWorkspaceOptions) {
|
|
|
199
200
|
} else if (url.search && !['?lang=en', '?lang=ko'].includes(url.search)) {
|
|
200
201
|
return refused('WORKSPACE_REQUEST_INVALID', 400);
|
|
201
202
|
}
|
|
202
|
-
const body = url.pathname === '/
|
|
203
|
-
: await readFile(appRoot + (url.pathname === '/' ? 'web/
|
|
203
|
+
const body = url.pathname === '/main.js' ? await (ownerScript ??= ownerBundle())
|
|
204
|
+
: await readFile(appRoot + (url.pathname === '/' ? 'web/index.html' : 'web/styles.css'));
|
|
204
205
|
return new Response(request.method === 'HEAD' ? null : body, {headers: {...securityHeaders,
|
|
205
206
|
'Content-Type': url.pathname.endsWith('.js') ? 'text/javascript' : url.pathname.endsWith('.css') ? 'text/css' : 'text/html; charset=utf-8'}});
|
|
206
207
|
}
|
|
@@ -212,8 +213,7 @@ export async function startOpenWorkspace(options: OpenWorkspaceOptions) {
|
|
|
212
213
|
const agentControl = path === '/api/control' || path === '/api/control/commands' || /^\/api\/control\/receipts\/[a-f0-9-]+$/.test(path);
|
|
213
214
|
if (!frontRoute(target.view.mode, request.method, path) && !(agentControl && target.stored.controlToken)) return refused('WORKSPACE_ROUTE_REFUSED', 404);
|
|
214
215
|
const landing = path === '/' || path === '/index.html';
|
|
215
|
-
|
|
216
|
-
if (stageFrame ? !stageFrameQuery(target.view.mode, url.search) : !landing && !!url.search) return refused('FRONT_QUERY_REFUSED', 400);
|
|
216
|
+
if (!landing && !!url.search) return refused('FRONT_QUERY_REFUSED', 400);
|
|
217
217
|
if (request.method !== 'GET' && request.method !== 'HEAD' && sentOrigin !== record.origin) return refused('WORKSPACE_SAME_ORIGIN_REQUIRED', 403);
|
|
218
218
|
if (path === '/api/live' && live.connections >= WORKSPACE_SOCKET_LIMIT) return refused('WORKSPACE_BUSY', 503);
|
|
219
219
|
if (activeStreams >= maximumUpstreamStreams) return refused('WORKSPACE_BUSY', 503);
|
package/src/open.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { joinProject, type JoinedProject, type ProjectDesignation } from './joined-project.ts';
|
|
1
|
+
import { joinProject, type JoinedProject, type JoinedInterview, type ProjectDesignation } from './joined-project.ts';
|
|
2
2
|
import {parseControlCommand,type ControlCommand,type ControlReceipt} from './control.ts';
|
|
3
3
|
/** One fixed-package worker per exact binding. There is no general daemon API. */
|
|
4
4
|
import {createHash,randomBytes,randomUUID} from 'node:crypto';
|
|
@@ -15,7 +15,6 @@ import {startServer} from './server.ts';
|
|
|
15
15
|
import {startCompareServer} from './compare-server.ts';
|
|
16
16
|
import {selectAnimation,AnimationSelectionError,type AnimationSelection} from './animation-selection.ts';
|
|
17
17
|
import {capabilityHeader,capabilityPattern,type OpenIdentity} from './open-protocol.ts';
|
|
18
|
-
import {ensureFront,frontPort} from './front.ts';
|
|
19
18
|
import {playBuildConditions} from './build.ts';
|
|
20
19
|
import {playPackagePath} from './versions.ts';
|
|
21
20
|
import {HandoffError,HANDOFF_FLAGS,isBuildRoot,type HandoffFlags,type HandoffRecord} from './handoff.ts';
|
|
@@ -35,7 +34,7 @@ export function buildOpenDiagnostic(build:BuildOpen):string{
|
|
|
35
34
|
export interface OpenInputs {input:string;project?:ProjectDesignation;compare?:string;reference?:string;animation?:string;control?:boolean;direct?:boolean;viewOnly?:boolean;config?:string;parts?:string;source?:string;full?:string;head?:string;keypoints?:string}
|
|
36
35
|
/** The producer handoff flags (#101) among the inputs, or undefined when none was given. */
|
|
37
36
|
export function handoffFlags(inputs:OpenInputs):HandoffFlags|undefined{const present=HANDOFF_FLAGS.filter(f=>inputs[f]!==undefined);if(!present.length)return undefined;return Object.fromEntries(present.map(f=>[f,inputs[f]])) as unknown as HandoffFlags;}
|
|
38
|
-
export type OpenPackage=({mode:'single';p:ReviewPackage;joined?:JoinedProject;inputs:OpenInputs;contentHash:string}|{mode:'compare';p:ComparePackage;inputs:OpenInputs;contentHash:string})&{selection:AnimationSelection|null};
|
|
37
|
+
export type OpenPackage=({mode:'single';p:ReviewPackage;joined?:Exclude<JoinedProject,JoinedInterview>;inputs:OpenInputs;contentHash:string}|{mode:'interview';joined:JoinedInterview;p:null;inputs:OpenInputs;contentHash:string}|{mode:'compare';p:ComparePackage;inputs:OpenInputs;contentHash:string})&{selection:AnimationSelection|null};
|
|
39
38
|
/** Private 0600 record. `capability` is the 256-bit page write capability, handed out only in the printed `#cap=` fragment. */
|
|
40
39
|
export interface RecordFile extends OpenIdentity {schema:'rig-review-open-instance/1';pid:number;origin:string;mode:'single'|'compare';capability:string;controlToken?:string}
|
|
41
40
|
/** `cwd` is the launcher's working directory: the worker runs in the state directory, so Apply · Rebuild looks for the producer from here after the package's own directories. */
|
|
@@ -45,6 +44,13 @@ const digest=(value:unknown)=>createHash('sha256').update(JSON.stringify(value))
|
|
|
45
44
|
const sleep=(ms:number)=>new Promise(resolveSleep=>setTimeout(resolveSleep,ms));
|
|
46
45
|
export const defaultStateDir=()=>process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review');
|
|
47
46
|
export async function loadOpenPackage(inputs:OpenInputs,options:{cwd?:string}={}):Promise<OpenPackage>{
|
|
47
|
+
if(inputs.project&&inputs.project.version===undefined&&inputs.project.draftId===undefined){
|
|
48
|
+
if(inputs.compare!==undefined||inputs.reference!==undefined||inputs.animation!==undefined||inputs.control||inputs.direct||inputs.viewOnly||handoffFlags(inputs))throw new Error('OPEN_OPTION_INVALID --project: interview-only open takes only the project root, --project and --picks-dir');
|
|
49
|
+
const joined=joinProject(null,inputs.project);
|
|
50
|
+
if(await realpath(resolve(inputs.input))!==joined.opened.root)throw new Error('INTERVIEW_SOURCE_MISMATCH: interview input must be the designated project root');
|
|
51
|
+
await joined.assertCurrent();
|
|
52
|
+
return {mode:'interview',p:null,joined,selection:null,contentHash:joined.sourceHash,inputs:{input:joined.opened.root,project:joined.designation}};
|
|
53
|
+
}
|
|
48
54
|
// Handoff flags become canonical absolute paths here, so the worker and every reload read exactly these files.
|
|
49
55
|
if(!inputs.compare){const base=await loadReferencedReview(inputs.input,inputs.reference,handoffFlags(inputs),options.cwd);const joined=inputs.project?joinProject(base,inputs.project,{starts:[options.cwd??process.cwd()]}):undefined;const p=joined?.review??base,selection=selectAnimation([{label:'single',catalog:p.feedbackCatalog,report:p.report}],inputs.animation,true);if(inputs.viewOnly)p.viewOnly=true;return {mode:'single',p,selection,contentHash:p.sourceHash,...(joined?{joined}:{}),inputs:{input:p.manifestPath,...(joined?{project:joined.designation}:{}),...(selectedReference(p)?{reference:selectedReference(p)!.path}:{}),...(selection?{animation:selection.name}:{}),...(inputs.control?{control:true}:{}),...(p.handoffInputs??{})}};}
|
|
50
56
|
if(inputs.project)throw new Error('INTERVIEW_SOURCE_MISMATCH: compare takes no joined project');
|
|
@@ -63,7 +69,7 @@ export async function openFingerprint():Promise<string>{
|
|
|
63
69
|
hash.update('bun.lock\0');try{hash.update(await readFile(join(appRoot,'bun.lock')));}catch(e){if((e as NodeJS.ErrnoException).code!=='ENOENT')throw e;hash.update('(absent)');}
|
|
64
70
|
hash.update('@rig-c/play/package.json\0');hash.update(await readFile(playPackagePath()));return hash.digest('hex');
|
|
65
71
|
}
|
|
66
|
-
export function openKey(p:OpenPackage,fingerprint:string):string {return digest({fingerprint,installation:appRoot,mode:p.mode,inputs:p.inputs,content:p.contentHash,identity:p.mode==='single'?p.p.reviewedSource:p.p.response.binding,...(p.mode==='single'&&p.joined?{projectHash:p.joined.opened.hash}:{})});}
|
|
72
|
+
export function openKey(p:OpenPackage,fingerprint:string):string {return digest({fingerprint,installation:appRoot,mode:p.mode,inputs:p.inputs,content:p.contentHash,identity:p.mode==='interview'?{projectHash:p.joined.opened.hash}:p.mode==='single'?p.p.reviewedSource:p.p.response.binding,...(p.mode==='single'&&p.joined?{projectHash:p.joined.opened.hash}:{})});}
|
|
67
73
|
/** Handoff URL: the managed front's `/instances/<key>/` path (or the worker's own origin when direct). The
|
|
68
74
|
* capability rides in the fragment, which browsers never send to a server; the page stores and strips it. */
|
|
69
75
|
export function openUrl(record:Pick<RecordFile,'origin'|'key'|'contentHash'|'capability'>,front?:string):string {const url=new URL(front?`${front}/instances/${record.key}/`:record.origin);url.searchParams.set('input',record.contentHash);url.searchParams.set('handoff',record.key);url.hash='cap='+record.capability;return url.href;}
|
|
@@ -110,6 +116,7 @@ async function openRefusal(error:unknown,inputs:OpenInputs):Promise<unknown>{
|
|
|
110
116
|
return new Error(`${name}: ${detail}`,{cause:error});
|
|
111
117
|
}
|
|
112
118
|
async function verifyOpenLoad(p:OpenPackage,viewOnly:boolean,cwd=process.cwd()):Promise<void>{
|
|
119
|
+
if(p.mode==='interview'){await p.joined.assertCurrent();return;}
|
|
113
120
|
if(p.mode==='single'){
|
|
114
121
|
// A recorded pre-rig draft has a bound model for Stage 1 mesh mapping only.
|
|
115
122
|
if(p.joined?.draft)return;
|
|
@@ -134,26 +141,26 @@ export async function prepareOpenTarget(inputs: OpenInputs, options: OpenOptions
|
|
|
134
141
|
let p:OpenPackage;try{p=await loadOpenPackage(inputs,{cwd:options.cwd});}catch(error){throw await openRefusal(error,inputs);}
|
|
135
142
|
fingerprint??=await openFingerprint();const key=openKey(p,fingerprint);
|
|
136
143
|
// #187: canonical (symlinks and ancestors resolved) and outside every supplied folder: the package, the build root a check package belongs to, the handoff root.
|
|
137
|
-
const stateDir=destinationDirectory(options.stateDir??defaultStateDir(),'OPEN_STATE_INVALID: the state directory path has a non-directory component or a symlink loop'),roots=p.mode==='single'?stateRoots(p.p):[...stateRoots(p.p.a),...stateRoots(p.p.b)];
|
|
138
|
-
if(p.mode
|
|
144
|
+
const stateDir=destinationDirectory(options.stateDir??defaultStateDir(),'OPEN_STATE_INVALID: the state directory path has a non-directory component or a symlink loop'),roots=p.mode==='interview'?[{kind:'package' as const,path:p.joined.opened.root}]:p.mode==='single'?stateRoots(p.p):[...stateRoots(p.p.a),...stateRoots(p.p.b)];
|
|
145
|
+
if(p.mode!=='compare'&&p.joined&&stateDirInside(stateDir,[{kind:'package',path:p.joined.opened.root}]))throw new Error('OPEN_STATE_INSIDE_PACKAGE: review state must be outside the joined project');
|
|
139
146
|
const inside=stateDirInside(stateDir,roots);if(inside)throw new Error(`OPEN_STATE_INSIDE_PACKAGE ${inside.kind}: the review state directory must be outside input packages; it is inside the ${inside.kind}; set RIG_REVIEW_STATE_DIR outside it`);
|
|
140
147
|
await verifyOpenLoad(p,viewOnly,options.cwd);
|
|
141
148
|
const build=p.mode==='single'&&basename(p.p.root)==='check'&&await isBuildRoot(dirname(p.p.root))?{package:p.p.root,handoff:p.p.reviewedSource.handoff??null,reason:p.p.handoffReason}:null;
|
|
142
149
|
return {package:p,key,fingerprint,stateDir,viewOnly,cwd:resolve(options.cwd??process.cwd()),build};
|
|
143
150
|
}
|
|
144
151
|
export async function openReview(inputs:OpenInputs,options:OpenOptions={}):Promise<{url:string;reused:boolean;nonce:string;inputs:OpenInputs;selection:AnimationSelection|null;direct:boolean;build:BuildOpen|null}>{
|
|
145
|
-
const direct=
|
|
152
|
+
const direct=true;
|
|
146
153
|
const prepared=await prepareOpenTarget(inputs,options);
|
|
147
154
|
const {package:p,key,fingerprint,stateDir,viewOnly,build}=prepared;
|
|
148
155
|
const control=join(stateDir,'open');await mkdir(control,{recursive:true,mode:0o700});const canonicalControl=await realpath(control);if((await lstat(control)).isSymbolicLink())throw new Error('open.state: control directory cannot be a symlink');
|
|
149
156
|
const worker=await ensureWorker(p,key,fingerprint,stateDir,canonicalControl,options.idleMs??DEFAULT_UNOPENED_TIMEOUT_MS,options.graceMs,viewOnly,options.cwd);
|
|
150
|
-
const url=
|
|
157
|
+
const url=openUrl(worker.row);
|
|
151
158
|
// #149: the check package of a rig-parts build root says which package it opened and which config the handoff took.
|
|
152
159
|
return {url,reused:worker.reused,nonce:worker.row.nonce,inputs:p.inputs,selection:p.selection,direct,build};
|
|
153
160
|
}
|
|
154
161
|
async function ensureWorker(p:OpenPackage,key:string,fingerprint:string,stateDir:string,canonicalControl:string,idleMs:number,graceMs?:number,viewOnly=false,cwd=process.cwd()):Promise<{row:RecordFile;reused:boolean}>{
|
|
155
162
|
const registry=join(canonicalControl,key+'.json'),claim=join(canonicalControl,key+'.claim'),nonce=randomUUID(),deadline=performance.now()+20000;
|
|
156
|
-
const reuse=async()=>{const row=await readRecord(registry,key);return row&&row.fingerprint===fingerprint&&row.contentHash===p.contentHash&&row.mode===p.mode&&await alive(row)?row:null;};
|
|
163
|
+
const reuse=async()=>{const row=await readRecord(registry,key);return row&&row.fingerprint===fingerprint&&row.contentHash===p.contentHash&&row.mode===(p.mode==='interview'?'single':p.mode)&&await alive(row)?row:null;};
|
|
157
164
|
const ready=await reuse();if(ready)return {row:ready,reused:true};
|
|
158
165
|
const claimed=await acquireClaim(canonicalControl,key,nonce,reuse,deadline,'OPEN_BUSY: instance startup claim did not become ready');if('row' in claimed)return {row:claimed.row,reused:true};
|
|
159
166
|
let request:string|undefined,spawned:ReturnType<typeof spawn>|undefined,handedOff=false;
|
|
@@ -175,9 +182,9 @@ export async function runOpenWorker(requestPath:string):Promise<void>{
|
|
|
175
182
|
// The worker mints its own page capability; it lives only in this process and the private record.
|
|
176
183
|
const removeRecord=async()=>{const current=await readRecord(spec.registry,spec.identity.key);if(current?.nonce===spec.identity.nonce)await unlink(spec.registry).catch(()=>{});};
|
|
177
184
|
const capability=randomBytes(32).toString('hex');const options={port:0,stateDir:spec.stateDir,open:spec.identity,capability,unopenedTimeoutMs:spec.idleMs,...(spec.graceMs!==undefined?{graceMs:spec.graceMs}:{}),exitOnClose:true,onClose:removeRecord,...(spec.inputs.control?{control:{token:spec.controlToken!,instanceKey:spec.identity.key}}:{})};
|
|
178
|
-
const server=p.mode
|
|
179
|
-
const check=()=>p.mode==='single'?assertReviewUnchanged(p.p):assertCompareUnchanged(p.p);
|
|
180
|
-
await check();const record:RecordFile={schema:'rig-review-open-instance/1',...spec.identity,pid:process.pid,origin:`http://127.0.0.1:${server.port}`,mode:p.mode,capability,...(spec.inputs.control?{controlToken:spec.controlToken}:{})};const tmp=spec.registry+'.'+spec.identity.nonce+'.tmp';await writeFile(tmp,JSON.stringify(record),{mode:0o600,flag:'wx'});await rename(tmp,spec.registry);
|
|
185
|
+
const server=p.mode!=='compare'?await startServer(p.p,{...options,joined:p.joined,initialAnimation:p.selection?.name,...(typeof spec.cwd==='string'&&isAbsolute(spec.cwd)?{cwd:spec.cwd}:{}),...(spec.viewOnly?{viewOnly:true}:{})}):await startCompareServer(p.p,options);
|
|
186
|
+
const check=()=>p.mode==='interview'?p.joined.assertCurrent():p.mode==='single'?assertReviewUnchanged(p.p):assertCompareUnchanged(p.p);
|
|
187
|
+
await check();const record:RecordFile={schema:'rig-review-open-instance/1',...spec.identity,pid:process.pid,origin:`http://127.0.0.1:${server.port}`,mode:p.mode==='interview'?'single':p.mode,capability,...(spec.inputs.control?{controlToken:spec.controlToken}:{})};const tmp=spec.registry+'.'+spec.identity.nonce+'.tmp';await writeFile(tmp,JSON.stringify(record),{mode:0o600,flag:'wx'});await rename(tmp,spec.registry);
|
|
181
188
|
await unlink(requestPath).catch(e=>{if(e.code!=='ENOENT')throw e;});
|
|
182
189
|
let stopped=false;const stop=async(signal:string)=>{if(stopped)return;stopped=true;await removeRecord();server.stop(true);console.log(`review: exiting — received ${signal}.`);process.exit(0);};
|
|
183
190
|
process.on('SIGTERM',()=>{void stop('SIGTERM');});process.on('SIGINT',()=>{void stop('SIGINT');});
|
|
@@ -1,33 +1,128 @@
|
|
|
1
1
|
/** Native evidence is cut from the bound original PNG, never from a displayed alpha mask. */
|
|
2
|
-
import {createHash} from 'node:crypto';
|
|
3
|
-
import {readFile} from 'node:fs/promises';
|
|
4
|
-
import {PNG} from 'pngjs';
|
|
5
|
-
import {
|
|
6
|
-
import {validatePngCrop,storePngCrop,readPngCrop} from './comment-crops.ts';
|
|
7
|
-
import {assertPartsUnchanged,partsDifference,verdictSource,type PartsViewPackage} from './parts-view.ts';
|
|
8
|
-
|
|
9
|
-
export
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
return
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { PNG } from 'pngjs';
|
|
5
|
+
import { parsePartsIssue, assertPartsIssueBinding, type PartsIssue } from './parts-comment.ts';
|
|
6
|
+
import { validatePngCrop, storePngCrop, readPngCrop, type PngCrop } from './comment-crops.ts';
|
|
7
|
+
import { assertPartsUnchanged, partsDifference, verdictSource, type PartsViewPackage } from './parts-view.ts';
|
|
8
|
+
|
|
9
|
+
export interface PartsCommentBindingOptions {
|
|
10
|
+
readonly sourceHash?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function preparePartsComment(
|
|
14
|
+
pkg: PartsViewPackage,
|
|
15
|
+
raw: unknown,
|
|
16
|
+
requireNative = false,
|
|
17
|
+
options?: PartsCommentBindingOptions,
|
|
18
|
+
): Promise<PartsIssue> {
|
|
19
|
+
return resolvePartsComment(pkg, raw, requireNative, true, false, options);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function validateStoredPartsComment(
|
|
23
|
+
pkg: PartsViewPackage,
|
|
24
|
+
raw: unknown,
|
|
25
|
+
allowLegacy = false,
|
|
26
|
+
options?: PartsCommentBindingOptions,
|
|
27
|
+
): Promise<PartsIssue> {
|
|
28
|
+
return resolvePartsComment(pkg, raw, true, false, allowLegacy, options);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function resolvePartsComment(
|
|
32
|
+
pkg: PartsViewPackage,
|
|
33
|
+
raw: unknown,
|
|
34
|
+
requireNative: boolean,
|
|
35
|
+
persist: boolean,
|
|
36
|
+
allowLegacy = false,
|
|
37
|
+
options?: PartsCommentBindingOptions,
|
|
38
|
+
): Promise<PartsIssue> {
|
|
39
|
+
const c = parsePartsIssue(raw, requireNative, allowLegacy, persist && !requireNative);
|
|
40
|
+
if (pkg.mode !== 'parts') {
|
|
41
|
+
throw new Error('PARTS_COMMENT_UNAVAILABLE: original part image required');
|
|
42
|
+
}
|
|
43
|
+
const itemMap = new Map<
|
|
44
|
+
string,
|
|
45
|
+
{ name: string; index: number; x: number; y: number; w: number; h: number; imageHash: string; path: string }
|
|
46
|
+
>();
|
|
47
|
+
for (const item of pkg.items) {
|
|
48
|
+
const path = pkg.imagePaths[item.index];
|
|
49
|
+
const file = path ? pkg.files.find(f => f.abs === path) : undefined;
|
|
50
|
+
if (!path || !file) {
|
|
51
|
+
throw new Error('PARTS_COMMENT_UNAVAILABLE: bound original PNG required');
|
|
52
|
+
}
|
|
53
|
+
itemMap.set(item.name, { ...item, imageHash: file.sha256, path });
|
|
54
|
+
}
|
|
55
|
+
const expectedSourceHash = options?.sourceHash ?? verdictSource(pkg).sha256;
|
|
56
|
+
assertPartsIssueBinding(c, itemMap, expectedSourceHash);
|
|
57
|
+
if (c.view.comparison?.mode === 'overlay' && !pkg.painting) {
|
|
58
|
+
throw new Error('PARTS_COMPARISON_UNAVAILABLE: original painting required');
|
|
59
|
+
}
|
|
60
|
+
if (c.view.comparison?.mode === 'difference') {
|
|
61
|
+
for (const part of c.parts) {
|
|
62
|
+
const item = itemMap.get(part.name)!;
|
|
63
|
+
await partsDifference(pkg, item.index, c.view.comparison.threshold, c.view.footprints);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const partBuffers = new Map<string, Buffer>();
|
|
67
|
+
for (const part of c.parts) {
|
|
68
|
+
const item = itemMap.get(part.name)!;
|
|
69
|
+
const bytes = await readFile(item.path);
|
|
70
|
+
if (createHash('sha256').update(bytes).digest('hex') !== item.imageHash) {
|
|
71
|
+
throw new Error('PARTS_COMMENT_STALE_SOURCE: original PNG changed');
|
|
72
|
+
}
|
|
73
|
+
partBuffers.set(part.name, bytes);
|
|
74
|
+
}
|
|
75
|
+
await assertPartsUnchanged(pkg);
|
|
76
|
+
if (c.crop.png !== undefined) {
|
|
77
|
+
validatePngCrop(c.crop as PngCrop);
|
|
78
|
+
}
|
|
79
|
+
if (c.view.mode !== 'item') {
|
|
80
|
+
if (persist && c.crop.png !== undefined) {
|
|
81
|
+
await storePngCrop(c.crop as PngCrop);
|
|
82
|
+
} else {
|
|
83
|
+
await readPngCrop(c.crop);
|
|
84
|
+
}
|
|
85
|
+
await assertPartsUnchanged(pkg);
|
|
86
|
+
return { ...c, nativeCrop: null };
|
|
87
|
+
}
|
|
88
|
+
const primary = itemMap.get(c.parts[0]!.name)!;
|
|
89
|
+
const r = c.imageRegion!;
|
|
90
|
+
if (r.width * r.height > 16777216) {
|
|
91
|
+
throw new Error('PARTS_COMMENT_CROP_LIMIT: native crop exceeds 16 million pixels');
|
|
92
|
+
}
|
|
93
|
+
const bytes = partBuffers.get(primary.name)!;
|
|
94
|
+
const original = PNG.sync.read(bytes);
|
|
95
|
+
if (original.width !== primary.w || original.height !== primary.h) {
|
|
96
|
+
throw new Error('PARTS_COMMENT_IMAGE_SIZE: original dimensions differ from placement');
|
|
97
|
+
}
|
|
98
|
+
const native = new PNG({ width: r.width, height: r.height });
|
|
99
|
+
for (let y = 0; y < r.height; y++) {
|
|
100
|
+
original.data.copy(
|
|
101
|
+
native.data,
|
|
102
|
+
y * r.width * 4,
|
|
103
|
+
((r.y + y) * original.width + r.x) * 4,
|
|
104
|
+
((r.y + y) * original.width + r.x + r.width) * 4,
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
if (requireNative) {
|
|
108
|
+
const stored = await readPngCrop(c.nativeCrop!);
|
|
109
|
+
const decoded = PNG.sync.read(stored);
|
|
110
|
+
if (decoded.width !== r.width || decoded.height !== r.height || !decoded.data.equals(native.data)) {
|
|
111
|
+
throw new Error('PARTS_COMMENT_NATIVE_CROP_TAMPERED: native crop differs from bound original');
|
|
112
|
+
}
|
|
113
|
+
if (persist && c.crop.png !== undefined) {
|
|
114
|
+
await storePngCrop(c.crop as PngCrop);
|
|
115
|
+
} else {
|
|
116
|
+
await readPngCrop(c.crop);
|
|
117
|
+
}
|
|
118
|
+
await assertPartsUnchanged(pkg);
|
|
119
|
+
return c;
|
|
120
|
+
}
|
|
121
|
+
const png = PNG.sync.write(native);
|
|
122
|
+
const sha256 = createHash('sha256').update(png).digest('hex');
|
|
123
|
+
const nativeCrop = { path: `comment-crops/${sha256}.png`, sha256, width: r.width, height: r.height };
|
|
124
|
+
await storePngCrop(c.crop as PngCrop);
|
|
125
|
+
await storePngCrop({ ...nativeCrop, png: 'data:image/png;base64,' + png.toString('base64') });
|
|
126
|
+
await assertPartsUnchanged(pkg);
|
|
127
|
+
return { ...c, nativeCrop };
|
|
33
128
|
}
|