rig-review 1.11.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -37,9 +37,9 @@ The illustrative `look` animation in `axes` must also be declared in `animations
37
37
 
38
38
  ## Files and references
39
39
 
40
- Every path is a literal relative path, including `model`, optional read-only `motion`, each reference `path`, authoring `path`, clip `path`, and every page name in the compiled model. Manifest paths accept no absolute paths, URL schemes, colon, percent encoding, traversal, backslash, query, fragment, empty segment, or symlink escape. Compiled-model page names are resolved relative to the model directory: a page such as `../parts/page.png` is accepted only when its normalized destination remains inside the review package. This permits portable local builds without letting a page escape the package. All declared files must exist as regular files. The asset endpoint serves only declared files, the manifest, and compiled-model page images. There is no arbitrary directory endpoint. Keep a package focused on the files intended for inspection.
40
+ Every path is a literal relative path, including `model`, optional `direction` and `sets`, optional read-only `motion`, each reference `path`, authoring `path`, clip `path`, and every page name in the compiled model. Manifest paths accept no absolute paths, URL schemes, colon, percent encoding, traversal, backslash, query, fragment, empty segment, or symlink escape. Compiled-model page names are resolved relative to the model directory: a page such as `../parts/page.png` is accepted only when its normalized destination remains inside the review package. This permits portable local builds without letting a page escape the package. All declared files must exist as regular files. The asset endpoint serves only declared files, the manifest, and compiled-model page images. There is no arbitrary directory endpoint. Keep a package focused on the files intended for inspection.
41
41
 
42
- `model` is optional and must point to `rigc-compiled/3` under a filename ending `.model.json`, produced by an upstream gated rigc build. Review uses the public `@rig-c/play` loader and player; Spine JSON/skel is not its input. Its pages are resolved relative to the model document. Missing model means unavailable playback, never a mock playback success. The runtime's optional attachment-set sidecar is not part of v1; attachment presets must remain unavailable rather than guessed.
42
+ `model` is optional and must point to `rigc-compiled/3` under a filename ending `.model.json`, produced by an upstream gated rigc build. Review uses the public `@rig-c/play` loader and player; Spine JSON/skel is not its input. Its pages are resolved relative to the model document. Missing model means unavailable playback, never a mock playback success. The optional `sets` path declares an attachment-set sidecar for single-package playback. Without that declaration, attachment presets are unavailable. See [Direction inspection](#direction-inspection).
43
43
 
44
44
  Reference `type` is `image`, `video`, or `pose`. `width` and `height` optionally state image pixel dimensions. The primary animated pose input is the canonical `rig-pose-sequence/1` format documented by `@rig-c/pose`, consumed directly:
45
45
 
@@ -904,6 +904,38 @@ explicit handoff data. The package revision and inspector navigation do not
904
904
  supply it. The named model path is data for Create and is never opened by
905
905
  Review. Only explicitly marked correction rows can carry multiline text.
906
906
 
907
+ For a described request on a package with authored direction, use the
908
+ inspected compiled model's relative path as `modelFile` and explicitly select
909
+ the Create post number. Review checks the model path against the package and
910
+ refuses a described direction request captured on a scratch Apply. A promoted
911
+ stage comment keeps its original camera, inspection time and marked screen and
912
+ world regions. For unmarked feedback the export carries the saved inspection
913
+ view and a null marked region.
914
+
915
+ Use `rig-review feedback <package> --correction <item-id> --format issue`.
916
+ The issue JSON carries the exact human `verbatim`, `selectorArgs` and a
917
+ `createSource` string (JSON, at most 32 KiB) with the post number, inspected
918
+ model and direction path/hash pairs, package revision and source hash, and
919
+ inspection context. To import into Create:
920
+
921
+ 1. With Create at [76a96dc](https://github.com/rig-c/create/commit/76a96dc528e07804a4df5e6c6e99ec5fc66b751c),
922
+ run `rig-create direction check <post> <project> --json`. Compare its
923
+ `post`, `direction` and `document.rig.model` to the matching fields in
924
+ the decoded `createSource`. Stop on any mismatch, including a different
925
+ post that uses the same compiled model.
926
+ 2. Write the decoded `verbatim` to a UTF-8 file without trimming or appending
927
+ a newline. Run `rig-create correction record <project> --id <item-id>
928
+ --path described --stage direction-review --version <post>
929
+ --model-file <model-path> --by <reviewer> --verbatim-file <words>
930
+ --source <createSource> --json`. Pass the decoded `createSource` string
931
+ as one argument. The writer returns `rig-create/correction@2` with
932
+ `on.model` and `on.direction`, and an open description (`outcome: null`).
933
+ Create retains `source` as opaque text. Review runs no Create command.
934
+
935
+ Packages without authored direction continue to use their explicit legacy
936
+ selector. Direction patch Apply is unavailable. Existing supported rig and
937
+ draft Apply records keep their producer and result evidence.
938
+
907
939
  A supported made item must match the server-owned settled Apply seal and
908
940
  retained scratch model and pages when the item is added or changed and on
909
941
  selected export. Older unchanged items remain saved as historical evidence
@@ -920,3 +952,26 @@ file's path and byte hash in the handoff. Apply copies those bytes into its
920
952
  private scratch directory and points the scratch config at that copy. The
921
953
  copied input is checked with the retained result. A missing or redirected
922
954
  requirements file refuses the handoff or Apply by name.
955
+
956
+ ### Direction inspection
957
+
958
+ In a single-package inspection, **4 Direction** keeps the stage, reference picker
959
+ and Turn Pad visible. The panel names the current model and its SHA-256, the
960
+ package revision and source SHA-256, and the installed Play version. It reports
961
+ the compiled sliders available through the Turn Pad and the attachment sets
962
+ loaded through Play. Independent depth control is unavailable on this surface.
963
+
964
+ A manifest may declare `direction` as the literal package-relative path to a
965
+ retained Create `rig-create/direction@1` document (up to 256 KiB). Preserve the
966
+ document's model path relative to the Review package root. Review requires that
967
+ path and SHA-256 to match the inspected compiled model and includes the direction
968
+ file in the package source hash. The panel shows authored camera keys and timing
969
+ read-only while that inspected model is on stage. Create remains responsible
970
+ for validating project history and citations. Viewport pan and zoom affect only
971
+ inspection. Authored camera playback and camera Apply are unavailable.
972
+
973
+ The optional `sets` manifest path names a package-local Play attachment-set
974
+ sidecar for the inspected single-package build. Review includes it in the
975
+ source hash and loads its sets through the published runtime. Scratch builds
976
+ use their own model and do not inherit the inspected build's sidecar. Compare
977
+ and standalone parts retain their existing inspection surfaces.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-review",
3
- "version": "1.11.0",
3
+ "version": "1.13.0",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
package/src/cli.ts CHANGED
@@ -174,7 +174,7 @@ export async function main(args:string[],options:{stateDir?:string}={}){
174
174
  await assertReviewUnchanged(p);
175
175
  const rebuilds=createRebuilds(p,{stateDir,starts:[p.root,process.cwd()],unchanged:()=>assertReviewUnchanged(p),bones:p.feedbackCatalog.bones});
176
176
  const settled=correction.path==='made'&&correction.selector.kind!=='post'?await rebuilds.correctionEvidence(appliedValue(item)):undefined;
177
- const projected=projectSessionCorrection({...correction,session,sessionBytes:bytes,source,itemId:item.id,settled});
177
+ const projected=projectSessionCorrection({...correction,session,sessionBytes:bytes,source,itemId:item.id,settled,direction:p.direction});
178
178
  if(projected.kind==='unsupported')console.error('CORRECTION_OPERATION_UNSUPPORTED: '+projected.operation);
179
179
  process.stdout.write(format==='json'?bytes:formatCorrectionIssue(projected,item.context)+'\n');
180
180
  return;
@@ -4,6 +4,8 @@ import { APPLIED_ANIMATION_SCHEMA, APPLIED_DELTA_SCHEMA, APPLIED_PATCH_SCHEMA, A
4
4
  import { patchSha256, patchText } from './config-patch.ts';
5
5
  import type { PartsVerdict } from './parts-view.ts';
6
6
  import type { Feedback, ReviewSession } from './session.ts';
7
+ import type { DirectionInspection } from './direction-inspection.ts';
8
+ import { hasStageComment, parseStageComment } from './stage-comment.ts';
7
9
 
8
10
  type Selector =
9
11
  | { stage: 'parts-review'; kind: 'parts'; inventory: string }
@@ -34,6 +36,7 @@ type SessionInput = {
34
36
  source: SessionSource;
35
37
  selector: SessionSelector;
36
38
  itemId: string;
39
+ direction?: DirectionInspection;
37
40
  } & ({ path: 'described' } | { path: 'made'; settled?: SettledEvidence });
38
41
 
39
42
  const hash = (value: string) => /^[a-f0-9]{64}$/.test(value);
@@ -116,7 +119,33 @@ export function projectSessionCorrection(input: SessionInput) {
116
119
  if (matches.length !== 1 || !item) return refuse('CORRECTION_ITEM_INVALID', 'expected one saved feedback item');
117
120
  const verbatim = itemWords(itemId, item.summary);
118
121
  const common = { itemId, verbatim, stage: selector.stage, on, source, target: item.target };
119
- if (input.path === 'described') return { ...common, kind: 'described' as const, outcome: null };
122
+ if (input.path === 'described') {
123
+ const direction = input.direction?.file;
124
+ if (selector.kind !== 'post' || !direction) return { ...common, kind: 'described' as const, outcome: null };
125
+ const model = source.reviewedSource.rig;
126
+ if (!model || selector.modelFile !== model.path || appliedValue(item) != null) {
127
+ return refuse('CORRECTION_DIRECTION_SOURCE', 'select the inspected compiled model and its authored direction');
128
+ }
129
+ const context = item.context as Record<string, unknown> | undefined;
130
+ const comment = hasStageComment(context?.comment) ? parseStageComment(context?.comment) : null;
131
+ const createSource = JSON.stringify({
132
+ source, post: selector.version, model, direction,
133
+ animation: comment ? comment.animation : context?.animation,
134
+ time: comment ? comment.time : context?.time,
135
+ sourceTime: context?.sourceTime,
136
+ frame: comment ? comment.frame : context?.frame,
137
+ interval: comment?.frame === null ? null : { frameStart: item.frameStart, frameEnd: item.frameEnd, inclusive: true },
138
+ target: item.target,
139
+ camera: comment ? comment.camera : context?.camera,
140
+ region: comment ? { viewport: comment.viewport, screen: comment.screen, world: comment.world } : null,
141
+ reference: comment ? { id: comment.referenceId, sha256: comment.referenceHash } : context?.reference,
142
+ view: context?.view,
143
+ });
144
+ if (Buffer.byteLength(createSource) > 32 * 1024) {
145
+ return refuse('CORRECTION_DIRECTION_CONTEXT_SIZE', 'direction correction source exceeds 32 KiB');
146
+ }
147
+ return { ...common, kind: 'described' as const, outcome: null, createSource };
148
+ }
120
149
 
121
150
  const value = appliedValue(item);
122
151
  if (value == null) return refuse('CORRECTION_APPLY_PENDING', 'no settled Apply in the saved item');
@@ -0,0 +1,65 @@
1
+ import { numberField, object, packagePath } from './manifest.ts';
2
+
3
+ export const DIRECTION_MAX_BYTES = 256 * 1024;
4
+
5
+ type Binding = { path: string; sha256: string };
6
+ export interface DirectionInspection {
7
+ file: Binding;
8
+ rigVersion: number;
9
+ camera: { space: 'rig-world-y-up'; keys: { time: number; easing: string; box: { x: number; y: number; width: number; height: number } }[] };
10
+ take: { duration: number; loop: boolean };
11
+ timing: { time: number; source_time: number; easing: string }[];
12
+ }
13
+
14
+ /** Read the inspection subset of Create's direction@1. Create validates project history and citations. */
15
+ export function readDirectionInspection(value: unknown, file: Binding, model: Binding | null): DirectionInspection {
16
+ const doc = object(value, 'direction');
17
+ if (doc.schema !== 'rig-create/direction@1') throw new Error('DIRECTION_SCHEMA: expected rig-create/direction@1');
18
+ const rig = object(doc.rig, 'direction.rig');
19
+ const binding = object(rig.model, 'direction.rig.model');
20
+ const path = packagePath(binding.path, 'direction.rig.model.path');
21
+ if (!model || path !== model.path || binding.sha256 !== model.sha256)
22
+ throw new Error('DIRECTION_MODEL_MISMATCH: expected the inspected model path and SHA-256');
23
+ const rigVersion = numberField(rig.version, 'direction.rig.version', 1);
24
+ if (!Number.isSafeInteger(rigVersion)) throw new Error('DIRECTION_SCHEMA: expected integer rig version');
25
+ const take = object(doc.take, 'direction.take');
26
+ const duration = numberField(take.duration, 'direction.take.duration');
27
+ if (duration === 0 || typeof take.loop !== 'boolean') throw new Error('DIRECTION_SCHEMA: expected positive duration and loop boolean');
28
+ const camera = object(doc.camera, 'direction.camera');
29
+ const timing = object(doc.timing, 'direction.timing');
30
+ if (camera.space !== 'rig-world-y-up') throw new Error('DIRECTION_SCHEMA: expected rig-world-y-up camera');
31
+ function keys<T>(value: unknown, section: string, min: number, parse: (key: Record<string, unknown>, field: string) => T) {
32
+ if (!Array.isArray(value) || value.length < min || value.length > 256)
33
+ throw new Error(`DIRECTION_SCHEMA: invalid ${section} key count`);
34
+ let previous = -Infinity;
35
+ return value.map((raw, index) => {
36
+ const field = `direction.${section}.keys[${index}]`;
37
+ const key = object(raw, field);
38
+ const time = numberField(key.time, field + '.time');
39
+ if (time <= previous || time > duration || (index === 0 && time !== 0))
40
+ throw new Error('DIRECTION_SCHEMA: expected increasing keys within the take starting at zero');
41
+ previous = time;
42
+ const easing = key.easing;
43
+ if (easing !== 'linear' && easing !== 'hold' && easing !== 'smoothstep')
44
+ throw new Error('DIRECTION_SCHEMA: unknown easing');
45
+ return { time, easing, ...parse(key, field) };
46
+ });
47
+ }
48
+ const cameraKeys = keys(camera.keys, 'camera', 1, (key, field) => {
49
+ const box = object(key.box, field + '.box');
50
+ const x = numberField(box.x, field + '.box.x', -Infinity);
51
+ const y = numberField(box.y, field + '.box.y', -Infinity);
52
+ const width = numberField(box.width, field + '.box.width');
53
+ const height = numberField(box.height, field + '.box.height');
54
+ if (width === 0 || height === 0) throw new Error('DIRECTION_SCHEMA: expected positive camera box dimensions');
55
+ return { box: { x, y, width, height } };
56
+ });
57
+ let previousSource = 0;
58
+ const timingKeys = keys(timing.keys, 'timing', 2, (key, field) => {
59
+ const source_time = numberField(key.source_time, field + '.source_time', previousSource);
60
+ previousSource = source_time;
61
+ return { source_time };
62
+ });
63
+ if (timingKeys.at(-1)?.time !== duration) throw new Error('DIRECTION_SCHEMA: timing must end at take duration');
64
+ return { file, rigVersion, camera: { space: camera.space, keys: cameraKeys }, take: { duration, loop: take.loop }, timing: timingKeys };
65
+ }
@@ -247,7 +247,7 @@ export function formatFeedbackIssues(input: ParsedFeedbackSession): string {
247
247
 
248
248
  /** Selected handoff uses the existing issue export surface with exact JSON-escaped words and evidence. */
249
249
  export function formatCorrectionIssue(
250
- correction: {kind:string;itemId:string;stage:string;on:readonly string[];verbatim:string;source:unknown;operation?:string;patchBytes?:string;target?:unknown;part?:string;imageHash?:string;comment?:import('./parts-comment.ts').PartsComment},
250
+ correction: {kind:string;itemId:string;stage:string;on:readonly string[];verbatim:string;source:unknown;createSource?:string;operation?:string;patchBytes?:string;target?:unknown;part?:string;imageHash?:string;comment?:import('./parts-comment.ts').PartsComment},
251
251
  context?:Json,
252
252
  ): string {
253
253
  const state=correction.kind==='described'?'Unresolved request':
@@ -256,5 +256,5 @@ export function formatCorrectionIssue(
256
256
  const evidence=comment?{...comment,crop:{...comment.crop,png:undefined}}:undefined;
257
257
  return ['## Correction handoff','',state,'',
258
258
  jsonBlock({itemId:correction.itemId,stage:correction.stage,selectorArgs:correction.on,
259
- source:correction.source,verbatim:correction.verbatim,target:correction.target,part:correction.part,imageHash:correction.imageHash,comment:evidence,...(correction.patchBytes===undefined?{}:{patchBytes:correction.patchBytes}),context})].join('\n');
259
+ source:correction.source,verbatim:correction.verbatim,target:correction.target,part:correction.part,imageHash:correction.imageHash,comment:evidence,...(correction.patchBytes===undefined?{}:{patchBytes:correction.patchBytes}),createSource:correction.createSource,context})].join('\n');
260
260
  }
package/src/manifest.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import {DIRECTION_MAX_BYTES, readDirectionInspection, type DirectionInspection} from './direction-inspection.ts';
1
2
  import {discoverTurnDials} from './turn-pad.ts';
2
3
  import { createHash } from 'node:crypto';
3
4
  import { toolVersions } from './versions.ts';
@@ -14,6 +15,7 @@ export interface Reference { id: string; label: string; type: 'image' | 'video'
14
15
  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} }
15
16
  export interface ReviewManifest {
16
17
  schema: 'rig-review/1'; id: string; title: string; revision: string; model?: string; motion?: string;
18
+ direction?: string; sets?: string;
17
19
  references: Reference[]; animations: { id: string; label?: string; duration?: number }[];
18
20
  checkpoints: Checkpoint[]; authoring: { label: string; path: string }[];
19
21
  axes: { id: string; label: string; animation: string; min: number; max: number }[];
@@ -22,7 +24,7 @@ export interface ReviewManifest {
22
24
  producer?: HandoffDeclaration;
23
25
  }
24
26
  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 }
25
- export interface ReviewPackage { referenceHashes?:Record<string,string>; root: string; manifestPath: string; manifest: ReviewManifest; sourceHash: string; reviewedSource:ReviewedSource; files: Set<string>; report:ReportSeeds|null; feedbackCatalog:FeedbackCatalog;
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;
26
28
  /** The resolved producer handoff (#101) and, when there is none, the refusal line naming where it was looked for. */
27
29
  handoff: Handoff|null; handoffReason: string|null; handoffInputs?: HandoffFlags;
28
30
  /** #187: the rig-parts build root ({@link isBuildRoot}) whose `check/` this package is, however it was opened; review state stays outside it. */
@@ -37,6 +39,7 @@ export function string(value: unknown, field: string): string { if (typeof value
37
39
  function id(value: unknown, field: string): string { const s = string(value, field); if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(s)) fail(field, 'identifier [A-Za-z0-9][A-Za-z0-9._-], at most 128 characters'); return s; }
38
40
  export function choice<T extends string>(value: unknown, choices: readonly T[], field: string): T { if (!choices.includes(value as T)) fail(field, choices.join(' | ')); return value as T; }
39
41
  function number(value: unknown, field: string, min = 0): number { if (typeof value !== 'number' || !Number.isFinite(value) || value < min) fail(field, `finite number >= ${min}`); return value; }
42
+ export { number as numberField };
40
43
  function optionalString(value: unknown, field: string): string | undefined { return value === undefined ? undefined : string(value, field); }
41
44
  function optionalNumber(value: unknown, field: string): number | undefined { return value === undefined ? undefined : number(value, field); }
42
45
  function list<T>(value: unknown, field: string, parse: (v: Record<string, unknown>, field: string) => T): T[] {
@@ -62,6 +65,8 @@ export function parseManifest(input: unknown): ReviewManifest {
62
65
  const manifest: ReviewManifest = {
63
66
  schema: 'rig-review/1', id: id(m.id, 'id'), title: string(m.title, 'title'), revision: string(m.revision, 'revision'),
64
67
  model: m.model === undefined ? undefined : packagePath(m.model, 'model'),
68
+ ...(m.direction===undefined?{}:{direction:packagePath(m.direction,'direction')}),
69
+ ...(m.sets===undefined?{}:{sets:packagePath(m.sets,'sets')}),
65
70
  motion:m.motion===undefined?undefined:packagePath(m.motion,'motion'),
66
71
  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) })),
67
72
  animations: list(m.animations,'animations',(v,f) => ({id:id(v.id,f+'.id'),label:optionalString(v.label,f+'.label'),duration:optionalNumber(v.duration,f+'.duration')})),
@@ -72,6 +77,8 @@ export function parseManifest(input: unknown): ReviewManifest {
72
77
  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')}))}
73
78
  };
74
79
  if(manifest.model&&!manifest.model.endsWith('.model.json'))fail('model','compiled model path ending .model.json (the play runtime input)');
80
+ if(manifest.sets&&!manifest.model)fail('sets','compiled model declaration');
81
+ if(manifest.direction&&!manifest.model)fail('direction','compiled model declaration');
75
82
  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'); }
76
83
  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'); }
77
84
  for (const a of manifest.axes) { if(a.min >= a.max) fail(`axis ${a.id}`,'min < max'); if(!manifest.animations.some(v=>v.id===a.animation)) fail(`axis ${a.id}.animation`,'declared animation id'); }
@@ -87,6 +94,8 @@ export async function loadReview(input: string, options: { handoff?: HandoffFlag
87
94
  const manifestPath=inputPath;const root=directory?inputPath:await realpath(dirname(inputPath));
88
95
  const manifest=directory?await folderManifest(root):parseManifest(JSON.parse(await readFile(manifestPath,'utf8')));
89
96
  const files = new Set([...(directory?[]:[relative(root,manifestPath)]),...manifest.references.map(v=>v.path),...manifest.authoring.map(v=>v.path),...manifest.audio.clips.map(v=>v.path)]);
97
+ if(manifest.direction)files.add(manifest.direction);
98
+ if(manifest.sets)files.add(manifest.sets);
90
99
  const rootFile=async(name:string):Promise<string|undefined>=>{try{await safeFile(root,name);return name;}catch(e){if((e as NodeJS.ErrnoException).code==='ENOENT')return undefined;throw e;}};
91
100
  const authoringPath=(name:string):string|undefined=>{const paths=manifest.authoring.filter(v=>posix.basename(v.path)===name);return paths.length===1?paths[0].path:undefined;};
92
101
  const rigPath=manifest.model??await rootFile('skeleton.json')??authoringPath('skeleton.json')??await rootFile('skeleton.skel')??authoringPath('skeleton.skel');
@@ -107,23 +116,26 @@ export async function loadReview(input: string, options: { handoff?: HandoffFlag
107
116
  const joints=list(pose.joints,`pose ${r.id}.joints`,(v,f)=>({id:id(v.id,f+'.id'),x:number(v.x,f+'.x',-Number.MAX_VALUE),y:number(v.y,f+'.y',-Number.MAX_VALUE),parent:optionalString(v.parent,f+'.parent')}));
108
117
  for(const j of joints) if(j.parent&&!joints.some(v=>v.id===j.parent&&v.id!==j.id)) fail(`pose ${r.id} joint ${j.id}.parent`,'another declared joint id');
109
118
  }
110
- const reportPath=files.has('report.json')?'report.json':authoringPath('report.json');let report:ReportSeeds|null=null;let modelMetadata:Record<string,unknown>|null=null;
119
+ const reportPath=files.has('report.json')?'report.json':authoringPath('report.json');let report:ReportSeeds|null=null;let modelMetadata:Record<string,unknown>|null=null;let directionInput:unknown;
111
120
  // The handoff files are hashed beside the package: their record joins the reviewed identity (and so the session file).
112
121
  const {handoff,reason:handoffReason}=await resolveHandoff(root,manifest.producer,options.handoff);
113
122
  // #329: the source painting the handoff knows is the first reference, outside the package's own files.
114
123
  const painting=sourcePainting(manifest,handoff,directory);
115
124
  const hash = createHash('sha256');hash.update(JSON.stringify(manifest));hash.update('\0');const fileHashes=new Map<string,string>();
116
- 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[]=[];for await(const chunk of createReadStream(full)){hash.update(chunk);fileHash.update(chunk);if(p===reportPath||p===manifest.model)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`);
125
+ 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;
126
+ 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`);
117
127
  // The parser and package hash consume the same bytes, never two file reads.
118
128
  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');}
129
+ if(isDirection)directionInput=JSON.parse(Buffer.concat(metadataChunks).toString('utf8'));
119
130
  if(p===reportPath){let value:unknown;try{value=JSON.parse(Buffer.concat(metadataChunks).toString('utf8'));}catch(e){throw new Error(`${p}: ${e instanceof Error?e.message:String(e)}`);}report=parseReport(value,p);}
120
131
  }
121
132
  if(painting){hash.update(SOURCE_PAINTING_ID);hash.update('\0');hash.update(painting.sha256);hash.update('\0');}
122
133
  // #192: the root is `check/` whether the folder or its review.json was opened, so the build root is kept either way.
123
134
  const buildRoot=basename(root)==='check'&&await isBuildRoot(dirname(root))?dirname(root):undefined;
124
135
  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}:{})};
136
+ const direction=manifest.direction?readDirectionInspection(directionInput,{path:manifest.direction,sha256:fileHashes.get(manifest.direction)!},reviewedSource.rig):undefined;
125
137
  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)}:{})};
126
- return {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}:{})};
138
+ 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}:{})};
127
139
  }
128
140
 
129
141
  /** #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.ts CHANGED
@@ -108,7 +108,7 @@ async function openRefusal(error:unknown,inputs:OpenInputs):Promise<unknown>{
108
108
  }
109
109
  async function verifyOpenLoad(p:OpenPackage,viewOnly:boolean,cwd=process.cwd()):Promise<void>{
110
110
  if(p.mode==='single'){
111
- try{await verifyCompiledModel(p.p.root,p.p.manifest.model,p.selection?.name);}
111
+ try{await verifyCompiledModel(p.p.root,p.p.manifest.model,p.selection?.name,p.p.manifest.sets);}
112
112
  catch(error){throw new Error(`OPEN_MODEL_UNAVAILABLE: ${error instanceof Error?error.message:String(error)}`,{cause:error});}
113
113
  const handoffReason=await verifyHandoffReadiness(p.p,[p.p.root,cwd],viewOnly);
114
114
  if(handoffReason)throw new Error(`OPEN_MODEL_UNAVAILABLE: ${handoffReason}`);
package/src/server.ts CHANGED
@@ -87,8 +87,9 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
87
87
  const applied=appliedValue(feedback);
88
88
  await rebuilds.validateApplied(applied);
89
89
  if(correction){
90
+ if(correction.path==='described'&&isDeepStrictEqual(previousRows.get(feedback.id),feedback))continue;
90
91
  const settled=correction.path==='made'&&correction.selector.kind!=='post'?await rebuilds.correctionEvidence(applied):undefined;
91
- projectSessionCorrection({...correction,source,session,sessionBytes,itemId:feedback.id,settled});
92
+ projectSessionCorrection({...correction,source,session,sessionBytes,itemId:feedback.id,settled,direction:p.direction});
92
93
  }
93
94
  }
94
95
  await unchanged();
@@ -144,7 +145,7 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
144
145
  return new Response(result.png?new Uint8Array(result.png):stripJson(result),{headers:{...headers,'Content-Type':result.png?'image/png':'application/json; charset=utf-8','Content-Disposition':`attachment; filename="review-strip.${result.png?'png':'json'}"`}});
145
146
  }
146
147
  if(req.method!=='GET'&&req.method!=='HEAD')return json({error:'Method not allowed'},405);
147
- if(url.pathname==='/api/review'){await unchanged();return json({manifest:p.manifest,initialAnimation:options.initialAnimation??null,sourceHash:p.sourceHash,reviewedSource:p.reviewedSource,...(referenceBinding(p)?{referenceBinding:referenceBinding(p),explicitReference:{...referenceBinding(p)!.reference,url:'/review-reference'}}:{}),...(p.sourcePainting?{sourcePainting:{...p.sourcePainting,url:'/review-painting'}}:{}),referenceHashes:{...p.referenceHashes,...(referenceBinding(p)?{[referenceBinding(p)!.reference.id]:referenceBinding(p)!.reference.sha256}:{})},report:p.report,feedbackCatalog:p.feedbackCatalog,assetsBase:'/assets/',capabilities:{playback:!!p.manifest.model,modeling:false,motion:false,feedback:true,audio:true}});}
148
+ if(url.pathname==='/api/review'){await unchanged();return json({manifest:p.manifest,...(p.direction?{direction:p.direction}:{}),...(p.setsHash?{setsHash:p.setsHash}:{}),initialAnimation:options.initialAnimation??null,sourceHash:p.sourceHash,reviewedSource:p.reviewedSource,...(referenceBinding(p)?{referenceBinding:referenceBinding(p),explicitReference:{...referenceBinding(p)!.reference,url:'/review-reference'}}:{}),...(p.sourcePainting?{sourcePainting:{...p.sourcePainting,url:'/review-painting'}}:{}),referenceHashes:{...p.referenceHashes,...(referenceBinding(p)?{[referenceBinding(p)!.reference.id]:referenceBinding(p)!.reference.sha256}:{})},report:p.report,feedbackCatalog:p.feedbackCatalog,assetsBase:'/assets/',capabilities:{playback:!!p.manifest.model,modeling:false,motion:false,feedback:true,audio:true}});}
148
149
  if(url.pathname==='/api/session'){await unchanged();return json(await readSession(p,options.stateDir));}
149
150
  if(url.pathname==='/api/rebuild')return json(await rebuilds.describe());
150
151
  if(url.pathname==='/api/rebuild/history')return json(await rebuilds.history());
@@ -97,7 +97,7 @@ async function openRig(input:StripRenderInput['rigs'][number],images:Map<string,
97
97
  }catch(error){assets.dispose();throw error;}
98
98
  }
99
99
  /** Verify that a package's compiled model and its page images load and pose in headless `@rig-c/play` (#305). */
100
- export async function verifyCompiledModel(root:string,modelRelPath:string|undefined,animation?:string):Promise<void>{
100
+ export async function verifyCompiledModel(root:string,modelRelPath:string|undefined,animation?:string,setsPath?:string):Promise<void>{
101
101
  if(!modelRelPath)throw new Error('package has no compiled model (manifest.model is absent)');
102
102
  const previous=hostQueue;let release=()=>{};hostQueue=new Promise<void>(done=>{release=done;});await previous;
103
103
  let restore=()=>{};
@@ -117,11 +117,14 @@ export async function verifyCompiledModel(root:string,modelRelPath:string|undefi
117
117
  urls.set(page.name,url);images.set(url,await readFile(path));
118
118
  }
119
119
  const modelUrl=`https://strip.invalid/open/${encodeURIComponent(modelRelPath)}`;
120
+ const setsUrl=setsPath?'https://strip.invalid/open/sets.json':null;
121
+ const setBytes=setsPath?await readFile(await safeFile(root,setsPath)):null;
120
122
  const fileFetch=new Proxy(fetch,{apply:(_target,_this,args:Parameters<typeof fetch>)=>{
123
+ if(setsUrl&&String(args[0])===setsUrl&&setBytes)return Promise.resolve(new Response(new Uint8Array(setBytes)));
121
124
  if(String(args[0])!==modelUrl)return Promise.reject(new Error('undeclared model URL'));
122
125
  return Promise.resolve(new Response(new Uint8Array(bytes)));
123
126
  }});
124
- const assets=await loadModel({modelUrl,fetch:fileFetch,setsUrl:null,regions:'none',resolvePage:name=>{const url=urls.get(name);if(!url)throw new Error(`undeclared page ${name}`);return url;}});
127
+ const assets=await loadModel({modelUrl,fetch:fileFetch,setsUrl,regions:'none',resolvePage:name=>{const url=urls.get(name);if(!url)throw new Error(`undeclared page ${name}`);return url;}});
125
128
  try{
126
129
  const clip=animation??assets.animations[0]?.name;
127
130
  if(clip!==undefined&&!assets.animations.some(a=>a.name===clip))throw new Error(`missing animation ${JSON.stringify(clip)}`);
package/web/catalog-en.ts CHANGED
@@ -79,6 +79,24 @@ export const enCatalog: Readonly<Record<string, string>> = {
79
79
  "Open setup mesh instruments": "Open setup mesh instruments",
80
80
  "Parts and atlas inspection": "Parts and atlas inspection",
81
81
  "INTERVIEW_UNAVAILABLE: Open a designated create project with rig-review interview.": "INTERVIEW_UNAVAILABLE: Open a designated create project with rig-review interview.",
82
+ "DIRECTION_SOURCE_CHANGED: undeclared playback input": "DIRECTION_SOURCE_CHANGED: undeclared playback input",
83
+ "DIRECTION_SOURCE_CHANGED: playback bytes differ from the bound SHA-256": "DIRECTION_SOURCE_CHANGED: playback bytes differ from the bound SHA-256",
84
+ "direction.title": "Direction inspection",
85
+ "direction.inspected": "Inspected model · {0} · SHA-256 {1}",
86
+ "direction.scratch": "Scratch model · {0} · SHA-256 {1}",
87
+ "direction.modelUnavailable": "MODEL_UNAVAILABLE · No compiled model loaded.",
88
+ "direction.package": "Package revision {0} · source SHA-256 {1} · @rig-c/play {2}",
89
+ "direction.turn": "2.5D turn · {0} · Use the Turn Pad to inspect the compiled sliders.",
90
+ "direction.turnUnavailable": "TURN_UNAVAILABLE · No supported compiled turn dials loaded.",
91
+ "direction.depthUnavailable": "DEPTH_UNAVAILABLE · No independent depth control in this playback surface.",
92
+ "direction.sets": "Attachment sets · {0}",
93
+ "direction.chooseSet": "Inspect attachment set",
94
+ "direction.setsUnavailable": "SETS_UNAVAILABLE · No attachment sets loaded.",
95
+ "direction.authored": "Authored direction · rig v{0} · {1} · SHA-256 {2}",
96
+ "direction.authoredUnavailable": "DIRECTION_METADATA_UNAVAILABLE · No authored direction bound to this model on stage.",
97
+ "direction.runtimeCameraUnavailable": "CAMERA_PLAYBACK_UNAVAILABLE · Authored camera and timing are read-only here. Pan and zoom adjust the inspection viewport.",
98
+ "direction.cameraApplyUnavailable": "CAMERA_APPLY_UNSUPPORTED · Camera Apply is unavailable.",
99
+ "direction.keys": "Authored camera and timing keys",
82
100
  "DIRECTION_UNAVAILABLE: no direction inspection contract is installed.": "DIRECTION_UNAVAILABLE: no direction inspection contract is installed.",
83
101
  "MODEL_UNAVAILABLE: no compiled model is supplied in this inspection.": "MODEL_UNAVAILABLE: no compiled model is supplied in this inspection.",
84
102
  "Atlas inspection, read only — inspected package. Applied scratch atlas, pre-rig parts, mesh sign-off and draft corrections are unavailable here.": "Atlas inspection, read only — inspected package. Applied scratch atlas, pre-rig parts, mesh sign-off and draft corrections are unavailable here.",
@@ -3234,6 +3252,8 @@ export const enCatalog: Readonly<Record<string, string>> = {
3234
3252
  "Declared post model path": "Declared post model path",
3235
3253
  "Exact correction text (optional UTF-8 file)": "Exact correction text (optional UTF-8 file)",
3236
3254
  "Choose the explicit Create source identity.": "Choose the explicit Create source identity.",
3255
+ "Direction request · bound to inspected model and direction": "Direction request · bound to inspected model and direction",
3256
+ "Use the inspected compiled model path for an authored direction request.": "Use the inspected compiled model path for an authored direction request.",
3237
3257
  "Unresolved correction request": "Unresolved correction request",
3238
3258
  "Made correction evidence": "Made correction evidence",
3239
3259
  "Use as described correction": "Use as described correction",
package/web/catalog-ko.ts CHANGED
@@ -79,6 +79,24 @@ export const koCatalog: Readonly<Record<string, string>> = {
79
79
  "Open setup mesh instruments": "Setup 메시 도구 열기",
80
80
  "Parts and atlas inspection": "파츠 및 아틀라스 검사",
81
81
  "INTERVIEW_UNAVAILABLE: Open a designated create project with rig-review interview.": "INTERVIEW_UNAVAILABLE: rig-review interview로 지정한 create 프로젝트를 여세요.",
82
+ "DIRECTION_SOURCE_CHANGED: undeclared playback input": "DIRECTION_SOURCE_CHANGED: 선언되지 않은 재생 입력입니다.",
83
+ "DIRECTION_SOURCE_CHANGED: playback bytes differ from the bound SHA-256": "DIRECTION_SOURCE_CHANGED: 재생 입력의 SHA-256이 기록된 값과 다릅니다.",
84
+ "direction.title": "연출 검사",
85
+ "direction.inspected": "검사 모델 · {0} · SHA-256 {1}",
86
+ "direction.scratch": "임시 빌드 모델 · {0} · SHA-256 {1}",
87
+ "direction.modelUnavailable": "MODEL_UNAVAILABLE · 불러온 컴파일 모델이 없습니다.",
88
+ "direction.package": "패키지 리비전 {0} · 소스 SHA-256 {1} · @rig-c/play {2}",
89
+ "direction.turn": "2.5D 회전 · {0} · 회전 패드에서 컴파일된 슬라이더를 확인하세요.",
90
+ "direction.turnUnavailable": "TURN_UNAVAILABLE · 불러온 모델에 지원되는 회전 다이얼이 없습니다.",
91
+ "direction.depthUnavailable": "DEPTH_UNAVAILABLE · 이 재생 화면에서는 깊이를 별도로 제어할 수 없습니다.",
92
+ "direction.sets": "부착물 세트 · {0}",
93
+ "direction.chooseSet": "부착물 세트 검사",
94
+ "direction.setsUnavailable": "SETS_UNAVAILABLE · 불러온 부착물 세트가 없습니다.",
95
+ "direction.authored": "작성된 연출 · 리그 v{0} · {1} · SHA-256 {2}",
96
+ "direction.authoredUnavailable": "DIRECTION_METADATA_UNAVAILABLE · 화면의 모델에 연결된 연출 데이터가 없습니다.",
97
+ "direction.runtimeCameraUnavailable": "CAMERA_PLAYBACK_UNAVAILABLE · 작성된 카메라와 타이밍은 여기서 읽기 전용입니다. 이동과 확대는 검사 화면에만 적용됩니다.",
98
+ "direction.cameraApplyUnavailable": "CAMERA_APPLY_UNSUPPORTED · 카메라 적용을 지원하지 않습니다.",
99
+ "direction.keys": "작성된 카메라 및 타이밍 키",
82
100
  "DIRECTION_UNAVAILABLE: no direction inspection contract is installed.": "DIRECTION_UNAVAILABLE: 연출 검사 계약이 설치되어 있지 않습니다.",
83
101
  "MODEL_UNAVAILABLE: no compiled model is supplied in this inspection.": "MODEL_UNAVAILABLE: 이 검사에 컴파일된 모델이 제공되지 않았습니다.",
84
102
  "Atlas inspection, read only — inspected package. Applied scratch atlas, pre-rig parts, mesh sign-off and draft corrections are unavailable here.": "검사 입력 패키지의 아틀라스 · 읽기 전용. 적용된 임시 빌드의 아틀라스, 리깅 전 파츠, 메시 승인, 초안 수정 기능은 이 화면에서 사용할 수 없습니다.",
@@ -3234,6 +3252,8 @@ export const koCatalog: Readonly<Record<string, string>> = {
3234
3252
  "Declared post model path": "선언된 후반 작업 모델 경로",
3235
3253
  "Exact correction text (optional UTF-8 file)": "수정 원문 (UTF-8 파일 선택)",
3236
3254
  "Choose the explicit Create source identity.": "Create의 소스 식별자를 지정해 주세요.",
3255
+ "Direction request · bound to inspected model and direction": "연출 수정 요청 · 검사한 모델과 연출 문서에 연결됨",
3256
+ "Use the inspected compiled model path for an authored direction request.": "작성된 연출에 대한 수정 요청에는 검사한 컴파일 모델 경로를 사용하세요.",
3237
3257
  "Unresolved correction request": "미해결 수정 요청",
3238
3258
  "Made correction evidence": "직접 적용한 수정의 근거",
3239
3259
  "Use as described correction": "이 댓글을 수정 요청으로 사용",
@@ -0,0 +1,88 @@
1
+ import type { DirectionInspection } from '../src/direction-inspection.ts';
2
+ import type { TurnDial } from '../src/turn-pad.ts';
3
+ import { onLanguageChange, t } from './i18n.ts';
4
+
5
+ export interface DirectionView {
6
+ model: { path: string; sha256: string; inspected: boolean } | null;
7
+ revision: string;
8
+ sourceHash: string;
9
+ runtime: string;
10
+ dials: readonly TurnDial[];
11
+ sets: readonly string[];
12
+ activeSet?: string;
13
+ authored?: DirectionInspection;
14
+ }
15
+
16
+ export function directionRows(view: DirectionView): { key: string; values?: string[] }[] {
17
+ const model = view.model;
18
+ return [
19
+ model ? { key: model.inspected ? 'direction.inspected' : 'direction.scratch', values: [model.path, model.sha256] }
20
+ : { key: 'direction.modelUnavailable' },
21
+ { key: 'direction.package', values: [view.revision, view.sourceHash, view.runtime] },
22
+ view.dials.length ? { key: 'direction.turn', values: [view.dials.map(d => d.axis).join(', ')] }
23
+ : { key: 'direction.turnUnavailable' },
24
+ { key: 'direction.depthUnavailable' },
25
+ view.sets.length ? { key: 'direction.sets', values: [view.sets.join(', ')] } : { key: 'direction.setsUnavailable' },
26
+ model?.inspected && view.authored
27
+ ? { key: 'direction.authored', values: [String(view.authored.rigVersion), view.authored.file.path, view.authored.file.sha256] }
28
+ : { key: 'direction.authoredUnavailable' },
29
+ { key: 'direction.runtimeCameraUnavailable' },
30
+ { key: 'direction.cameraApplyUnavailable' },
31
+ ];
32
+ }
33
+
34
+ /** The adjacent viewport, reference picker and Turn Pad keep their normal input and rendering paths. */
35
+ export function bindDirectionPanel(before: HTMLElement, read: () => DirectionView, set: (name: string) => void) {
36
+ const host = document.createElement('details');
37
+ host.id = 'direction-panel';
38
+ host.open = true;
39
+ host.hidden = true;
40
+ const title = document.createElement('summary');
41
+ const body = document.createElement('div');
42
+ host.append(title, body);
43
+ before.before(host);
44
+ function refresh() {
45
+ if (host.hidden) return;
46
+ const view = read();
47
+ title.textContent = t('direction.title');
48
+ const rows = directionRows(view).map(({ key, values }) => {
49
+ const row = document.createElement('li');
50
+ row.textContent = t(key, values);
51
+ return row;
52
+ });
53
+ const list = document.createElement('ul');
54
+ list.append(...rows);
55
+ body.replaceChildren(list);
56
+ if (view.sets.length) {
57
+ const label = document.createElement('label');
58
+ label.textContent = t('direction.chooseSet');
59
+ const picker = document.createElement('select');
60
+ for (const name of ['', ...view.sets]) {
61
+ const option = document.createElement('option');
62
+ option.value = name;
63
+ option.textContent = name || t('Original set');
64
+ picker.append(option);
65
+ }
66
+ picker.value = view.activeSet ?? '';
67
+ picker.onchange = () => set(picker.value);
68
+ label.append(picker);
69
+ body.append(label);
70
+ }
71
+ if (view.model?.inspected && view.authored) {
72
+ const { camera, timing, take } = view.authored;
73
+ const details = document.createElement('details');
74
+ const summary = document.createElement('summary');
75
+ summary.textContent = t('direction.keys');
76
+ const keys = document.createElement('pre');
77
+ keys.textContent = JSON.stringify({ camera, timing, take }, null, 2);
78
+ details.append(summary, keys);
79
+ body.append(details);
80
+ }
81
+ }
82
+ const language = onLanguageChange(refresh);
83
+ return {
84
+ refresh,
85
+ show(active: boolean) { host.hidden = !active; refresh(); },
86
+ dispose() { language(); host.remove(); },
87
+ };
88
+ }
package/web/main.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import {bindDirectionPanel} from './direction-panel.ts';
2
+ import type {DirectionInspection} from '../src/direction-inspection.ts';
1
3
  import {bindStageNav} from './stage-nav.ts';
2
4
  import {timeOnlyBasis,feedbackTimingLabel,requireFeedbackFrames,isTimeOnlyFeedback} from '../src/stage-comment.ts';
3
5
  import {bindStageComments,type CommentPose} from './stage-comments.ts';
@@ -71,7 +73,7 @@ import {assertRigFieldOps,RIG_FIELDS_READOUT_BARS,TURN_BONE} from '../src/rig-fi
71
73
  import {IDLE_READOUT_BARS,type LocalChannel} from '../src/idle-tracks.ts';
72
74
  import type {PatchOp} from '../src/config-patch.ts';
73
75
 
74
- interface ReviewResponse { referenceHashes?:Record<string,string>; initialAnimation?:string|null; manifest: ReviewManifest; referenceBinding?:ReferenceBinding; explicitReference?:{id:string;name:string;sha256:string;url:string}; sourcePainting?:{id:string;path:string;sha256:string;url:string}; sourceHash: string; reviewedSource: ReviewedSource; report: ReportSeeds | null; feedbackCatalog: FeedbackCatalog; assetsBase: string; capabilities: { playback: boolean; modeling: false; motion: false; feedback: boolean; audio: boolean } }
76
+ interface ReviewResponse { direction?:DirectionInspection; setsHash?:string; referenceHashes?:Record<string,string>; initialAnimation?:string|null; manifest: ReviewManifest; referenceBinding?:ReferenceBinding; explicitReference?:{id:string;name:string;sha256:string;url:string}; sourcePainting?:{id:string;path:string;sha256:string;url:string}; sourceHash: string; reviewedSource: ReviewedSource; report: ReportSeeds | null; feedbackCatalog: FeedbackCatalog; assetsBase: string; capabilities: { playback: boolean; modeling: false; motion: false; feedback: boolean; audio: boolean } }
75
77
  interface PoseReference { schema: 'rig-review-pose/1'; coordinateSystem: 'image-pixels-y-down'; width: number; height: number; joints: { id: string; x: number; y: number; parent?: string }[] }
76
78
  interface SequenceJoint { state: 'observed' | 'occluded' | 'missing' | 'inferred'; at?: [number, number]; score?: number }
77
79
  interface PoseSequence { spec: 'rig-pose-sequence/1'; space: { units: 'picture-px'; origin: 'top-left'; y: 'down' }; width: number; height: number; source?: string; frames: { t: number; people: { id: string; joints: Record<string, SequenceJoint> }[] }[]; camera?: { s: number; tx: number; ty: number; inliers: number }[]; cameraSource?: unknown }
@@ -97,6 +99,7 @@ const access = pageInstanceAccess();
97
99
  connectLiveWindow(access);
98
100
  let readOnly: string | null = null;
99
101
  let data: ReviewResponse;
102
+ let directionPanel:ReturnType<typeof bindDirectionPanel>|undefined;
100
103
  let session: ReviewSession;
101
104
  let dirty = false;
102
105
  let saving = false;
@@ -666,6 +669,30 @@ function configureTurnPad(model:unknown):void {
666
669
  if(previous&&turnPad){try{turnPad.restore(previous);}catch{message('TURN_STATE_MODEL_MISMATCH: turn values reset for this build.',true);}}
667
670
  workspace?.refresh();
668
671
  }
672
+ /** Verify the same response consumed by Play, rather than a second read of its source. */
673
+ function stageLoadInputs(modelUrl:string, modelHash:string) {
674
+ const setsUrl=modelUrl===inspectedModel?.url&&data.manifest.sets&&data.setsHash
675
+ ?new URL(assetUrl(data.manifest.sets),location.href).href:null;
676
+ const checkedFetch=new Proxy(fetch,{apply:async(_target,_this,args:Parameters<typeof fetch>)=>{
677
+ const expected=String(args[0])===modelUrl?modelHash:String(args[0])===setsUrl?data.setsHash:null;
678
+ if(!expected)throw new Error('DIRECTION_SOURCE_CHANGED: undeclared playback input');
679
+ const response=await fetch(...args);
680
+ if(!response.ok)return response;
681
+ const bytes=await response.clone().arrayBuffer();
682
+ const sha256=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),v=>v.toString(16).padStart(2,'0')).join('');
683
+ if(sha256!==expected)throw new Error('DIRECTION_SOURCE_CHANGED: playback bytes differ from the bound SHA-256');
684
+ return response;
685
+ }});
686
+ return {setsUrl,fetch:checkedFetch};
687
+ }
688
+
689
+ function configurePartSets(keep=''):void {
690
+ const picker=select('part-set'),presets=player?.sets()??[];
691
+ picker.replaceChildren(option('', 'Original set'),...presets.map(set=>option(set.name,set.name)));
692
+ picker.disabled=!presets.length;
693
+ if(keep&&presets.some(set=>set.name===keep)){player!.setSet(keep);picker.value=keep;}
694
+ }
695
+
669
696
  async function initPlayer(initialCheckpoint?:Checkpoint): Promise<void> {
670
697
  text('renderer-state',rendererStatus(null,'pending').label);
671
698
  if (!data.manifest.model) { text('player-state', 'No rig supplied · reference review is available'); return; }
@@ -673,7 +700,7 @@ async function initPlayer(initialCheckpoint?:Checkpoint): Promise<void> {
673
700
  try {
674
701
  const modelUrl = new URL(assetUrl(data.manifest.model), location.href).href;
675
702
  inspectedModel={url:modelUrl,prefix:access.route('/assets/'),sha256:data.reviewedSource.rig?.sha256??''};stageModelHash=inspectedModel.sha256||null;
676
- assets = await loadModel({ modelUrl, setsUrl: null, resolvePage: (name, url) => {
703
+ assets = await loadModel({ modelUrl, ...stageLoadInputs(modelUrl,inspectedModel.sha256), resolvePage: (name, url) => {
677
704
  const target = new URL(name, url); if (target.origin !== location.origin || !target.pathname.startsWith(access.route('/assets/'))) throw new Error(`Model page escapes local package: ${name}`); return target.href;
678
705
  } });
679
706
  player = new RigPlayer(el('rig-root'), assets);
@@ -687,7 +714,7 @@ async function initPlayer(initialCheckpoint?:Checkpoint): Promise<void> {
687
714
  const names=assets.animations.map(clip=>clip.name),initial=initialIdleAnimation(names,initialPlayerAnimation(names,data.initialAnimation??undefined,initialCheckpoint),!!data.initialAnimation||!!initialCheckpoint?.animation||!!initialCheckpoint?.axis);
688
715
  if(initial)chooseAnimation(initial);else drawRig(()=>player!.draw());
689
716
  el('rig-empty').hidden = true; text('player-state', '@rig-c/play · Actual rig');
690
- const presets = player.sets(); if (presets.length) { select('part-set').replaceChildren(option('', 'Original set')); for (const set of presets) select('part-set').append(option(set.name, set.name)); select('part-set').disabled = false; }
717
+ configurePartSets();
691
718
  const validAxes = data.manifest.axes.filter(axis => assets?.animations.some(item => item.name === axis.animation));
692
719
  text('axis-state', validAxes.length ? `${validAxes.length} axes` : 'No inspection axes supplied');
693
720
  select('axis-select').replaceChildren(); for (const axis of validAxes) select('axis-select').append(option(axis.id, axis.label));
@@ -697,6 +724,7 @@ async function initPlayer(initialCheckpoint?:Checkpoint): Promise<void> {
697
724
  describeLayerToggles(document,el('layer-state').textContent??'');
698
725
  fitCamera();
699
726
  } catch (error) { turnPad?.dispose();turnPad=null;document.getElementById('turn-pad-host')?.remove();text('renderer-state',rendererStatus(null,'failed').label);player?.dispose(); player = null; assets?.dispose(); assets = null; text('player-state', 'Rig load failed'); text('rig-empty', `Could not open rig: ${errorText(error)}`); message(errorText(error), true); }
727
+ directionPanel?.refresh();
700
728
  }
701
729
 
702
730
  function chooseAxis(): void {
@@ -728,7 +756,11 @@ function renderProposals(): void {
728
756
  const label = document.createElement('p');
729
757
  const schema=(context?.applied as {schema?:string}|undefined)?.schema;
730
758
  const unsupported=correction.selector?.kind==='post'||schema!=='rig-review-applied/2';
731
- setSourceText(label, correction.path === 'described' ? 'Unresolved correction request' :
759
+ setSourceText(label, correction.path === 'described'
760
+ ? correction.selector?.kind === 'post' && data.direction && !context?.applied
761
+ ? 'Direction request · bound to inspected model and direction'
762
+ : 'Unresolved correction request'
763
+ :
732
764
  unsupported ? 'Unsupported correction operation' : 'Made correction evidence');
733
765
  item.append(label);
734
766
  }
@@ -764,7 +796,12 @@ function correctionSelection(path: 'described' | 'made'): Json {
764
796
  if (/^[1-9][0-9]*$/.test(identity) && Number.isSafeInteger(version)) {
765
797
  if (stage === 'rig-review') return { path, selector: { stage, kind: 'rig', version } };
766
798
  const modelFile = input('correction-model').value;
767
- if (stage === 'direction-review' && modelFile) return { path, selector: { stage, kind: 'post', version, modelFile } };
799
+ if (stage === 'direction-review') {
800
+ if (path === 'described' && data.direction && modelFile !== data.reviewedSource.rig?.path) {
801
+ throw new Error(tr('Use the inspected compiled model path for an authored direction request.'));
802
+ }
803
+ if (modelFile) return { path, selector: { stage, kind: 'post', version, modelFile } };
804
+ }
768
805
  }
769
806
  throw new Error(tr('Choose the explicit Create source identity.'));
770
807
  }
@@ -930,7 +967,16 @@ function bind(): void {
930
967
  } catch (error) { message(`Submission failed: ${errorText(error)}`, true); } finally { saving = false; updateSavedState(); }
931
968
  };
932
969
  // Saved browser defaults seed a new inspection; explicit links and source drafts restore over them.
933
- viewDisposers.push(bindStageNav({model:!!data.manifest.model,setup:()=>showInspector('rig'),draftBuild:()=>appliedOnStage?.buildId??'inspected',correction:openStageCorrection}));
970
+ directionPanel=bindDirectionPanel(el('stage-layout'),()=>{
971
+ const inspected=!!inspectedModel&&(!stageSource||stageSource.url===inspectedModel.url);
972
+ const model=player&&stageModelHash?{path:inspected?data.manifest.model!:new URL(stageSource!.url).pathname,sha256:stageModelHash,inspected}:null;
973
+ return {model,revision:data.manifest.revision,sourceHash:data.sourceHash,runtime:data.reviewedSource.runtimeVersion,
974
+ dials:player?turnPad?.state.dials??[]:[],sets:player?.sets().map(set=>set.name)??[],activeSet:select('part-set').value,authored:data.direction};
975
+ },name=>{
976
+ const picker=select('part-set');picker.value=name;picker.dispatchEvent(new Event('change',{bubbles:true}));
977
+ });
978
+ viewDisposers.push(()=>directionPanel?.dispose());
979
+ viewDisposers.push(bindStageNav({model:!!data.manifest.model,direction:active=>directionPanel?.show(active),setup:()=>showInspector('rig'),draftBuild:()=>appliedOnStage?.buildId??'inspected',correction:openStageCorrection}));
934
980
  workspace=bindWorkspaceUI({changed:fitCamera,defaultTheme:theme=>appearance?.set(theme),currentTheme:()=>appearance?.get()});
935
981
  viewport.state.cameraSync=workspace.defaults().defaultCameraSync;input('camera-sync').checked=viewport.state.cameraSync;input('idle-repeat').checked=workspace.defaults().defaultIdleRepeat;
936
982
  appearance=bindAppearance(select('settings-theme'),workspace.defaults().theme);
@@ -2181,14 +2227,14 @@ async function swapRig(modelUrl:string,prefix:string,sha256:string,world:StageWo
2181
2227
  const keepPart=stageCorrectionPart?parts?.value():null;
2182
2228
  const keepAnimation=animation,keepTime=time,wasPlaying=playing,keepSet=select('part-set').disabled?'':select('part-set').value;
2183
2229
  inspectionSourceState='pending';partModel=null;pause();refreshAnimationInspection();
2184
- const next=await loadModel({modelUrl,setsUrl:null,resolvePage:(name,url)=>{const target=new URL(name,url);if(target.origin!==location.origin||!target.pathname.startsWith(prefix))throw new Error(`Model page escapes its build: ${name}`);return target.href;}}).catch(error=>{inspectionSourceState='failed';refreshAnimationInspection();throw error;});
2230
+ const next=await loadModel({modelUrl,...stageLoadInputs(modelUrl,sha256),resolvePage:(name,url)=>{const target=new URL(name,url);if(target.origin!==location.origin||!target.pathname.startsWith(prefix))throw new Error(`Model page escapes its build: ${name}`);return target.href;}}).catch(error=>{inspectionSourceState='failed';refreshAnimationInspection();throw error;});
2185
2231
  physicsPanel?.clearPreview();
2186
2232
  pause();player?.dispose();assets?.dispose();assets=next;player=new RigPlayer(el('rig-root'),assets);setupChestWorld=readSetupChest(player);stageModelHash=sha256;stageSource={url:modelUrl,prefix,hash:sha256};
2187
2233
  // A scratch build may hold another set of animations (a retarget adds one, #114): the picker lists what this build has.
2188
2234
  {const animations=select('animation-select');animations.replaceChildren(...assets.animations.map(item=>option(item.name,data.manifest.animations.find(a=>a.id===item.name)?.label??item.name)));animations.disabled=assets.animations.length===0;}
2189
2235
  player.on('event',event=>{text('event-log',`Runtime event: ${event.name} · ${event.time.toFixed(2)} s`);});
2190
2236
  try{const catalog=await loadPartModel(modelUrl,sha256,data.feedbackCatalog.slots??[]);inspectionSourceState='ready';partModel=catalog.model;configureTurnPad(catalog.model);refreshAnimationInspection();weightsView?.refresh();meshEditor?.selectionChanged();parts?.register('single',catalog.entries,player,new PartThumbnails(pageRegionTable(catalog.model),assets.pageImages));}catch(error){inspectionSourceState='failed';partModel=null;refreshAnimationInspection();parts?.refuseCatalog('single',error);}
2191
- if(keepSet){try{player.setSet(keepSet);}catch{select('part-set').value='';player.setSet(null);}}
2237
+ configurePartSets(keepSet);
2192
2238
  // The same world before the first pose: a physics Apply resumes the wind (clock and pulse), the pending jolts, gravity and
2193
2239
  // whether the controls are engaged as they stood when Apply was pressed; then the seek re-poses under that world.
2194
2240
  if(world){wind.resume(world.wind);joltQueue=world.jolts.map(step=>({...step}));input('environment-applied').checked=world.applied;input('gravity').value=String(world.gravity);syncEnvironmentInputs();}
@@ -2205,7 +2251,7 @@ async function swapRig(modelUrl:string,prefix:string,sha256:string,world:StageWo
2205
2251
  // The preview (#104) drives the new player once its bone setups are read (an idle Apply cleared it first).
2206
2252
  stageDocumentSet=true;void loadModelDocument(modelUrl,sha256).then(loaded=>{if(loaded.ok&&stageModelHash===sha256)idlePanel?.model(boneSetup(loaded.document));});
2207
2253
  if(wasPlaying)void playPreview();
2208
- }finally{stageCorrectionRebinding--;}
2254
+ }finally{stageCorrectionRebinding--;directionPanel?.refresh();}
2209
2255
  }
2210
2256
  /**
2211
2257
  * Mesh Apply (#106): the pending `meshes.<part>` entry becomes one config patch — `replace /meshes/<part>` and nothing
package/web/stage-nav.ts CHANGED
@@ -16,13 +16,13 @@ export function stagePartsSelectionIndex(data:{inspectionSourceHash?:string;item
16
16
  if(i<0||data.inspectionSourceHash!==saved.inspectionSourceHash||!m||(['skin','slot','attachment']as const).some(k=>m[k]!==saved.mapping[k]))throw new Error('STAGE_DRAFT_MISMATCH');
17
17
  return i;
18
18
  }
19
- export function stageReason(stage:ReviewStage,model:boolean):string|null {
19
+ export function stageReason(stage:ReviewStage,model:boolean,direction=false):string|null {
20
20
  if(stage===2)return 'INTERVIEW_UNAVAILABLE: Open a designated create project with rig-review interview.';
21
- if(stage===4)return 'DIRECTION_UNAVAILABLE: no direction inspection contract is installed.';
21
+ if(stage===4&&!direction)return 'DIRECTION_UNAVAILABLE: no direction inspection contract is installed.';
22
22
  if(stage===3&&!model)return 'MODEL_UNAVAILABLE: no compiled model is supplied in this inspection.';
23
23
  return null;
24
24
  }
25
- export function bindStageNav(options:{interviewOnly?:boolean;partsOnly?:boolean;model:boolean;side?:()=> 'a'|'b';setup?:()=>void;draftBuild?:()=>string;correction?:(request:{part:string;sourceHash:string;buildId:string;instrument:string})=>Promise<void>}):()=>void {
25
+ export function bindStageNav(options:{interviewOnly?:boolean;partsOnly?:boolean;model:boolean;direction?:(active:boolean)=>void;side?:()=> 'a'|'b';setup?:()=>void;draftBuild?:()=>string;correction?:(request:{part:string;sourceHash:string;buildId:string;instrument:string})=>Promise<void>}):()=>void {
26
26
  const host=document.querySelector<HTMLElement>('[data-stage-nav]');if(!host)return ()=>{};
27
27
  if(options.interviewOnly){
28
28
  const button=document.createElement('button');button.type='button';button.dataset.reviewStage='2';button.setAttribute('aria-current','step');host.append(button);
@@ -42,8 +42,9 @@ export function bindStageNav(options:{interviewOnly?:boolean;partsOnly?:boolean;
42
42
  const render=()=>{buttons.forEach((b,i)=>{b.textContent=t(reviewStages[i]!);b.setAttribute('aria-current',current===i+1?'step':'false');});host.setAttribute('aria-label',t('Inspection stages'));if(sourcePicker)sourcePicker.setAttribute('aria-label',t(current===1?'Atlas source build':'Picked build for Setup and Animate'));mesh.textContent=t('Open setup mesh instruments');};
43
43
  const place=()=>{panel.style.top=`${(host.closest('header')??host).getBoundingClientRect().bottom}px`;};
44
44
  function show(stage:ReviewStage):void {
45
- current=stage;document.documentElement.dataset.inspectionStage=String(stage);render();place();const reason=stageReason(stage,options.model);
46
- panel.hidden=stage===(options.partsOnly?1:3)&&!reason;
45
+ current=stage;document.documentElement.dataset.inspectionStage=String(stage);render();place();const reason=stageReason(stage,options.model,!!options.direction);
46
+ options.direction?.(stage===4);
47
+ panel.hidden=!reason&&(stage===(options.partsOnly?1:3)||stage===4);
47
48
  if(workspace)workspace.inert=!panel.hidden||wasInert;
48
49
  status.textContent=reason?t(reason):stage===1&&!options.partsOnly?t(options.correction?'Draft rig · structure evidence only':'Atlas inspection, read only — inspected package. Applied scratch atlas, pre-rig parts, mesh sign-off and draft corrections are unavailable here.'):'';mesh.hidden=stage!==1||!options.model||!!options.partsOnly;
49
50
  for(const frame of frames.values())frame.hidden=true;
@@ -60,7 +61,7 @@ export function bindStageNav(options:{interviewOnly?:boolean;partsOnly?:boolean;
60
61
  // Legacy bookmark/control restoration writes these canonical attributes even when a mode is unchanged.
61
62
  const canonical=new MutationObserver(()=>{if(current!==3&&!options.partsOnly&&!pickingSource)show(3);});
62
63
  document.querySelectorAll('[data-inspector]').forEach(button=>canonical.observe(button,{attributes:true,attributeFilter:['aria-selected','aria-pressed']}));
63
- const language=onLanguageChange(()=>{render();if(!panel.hidden)status.textContent=t(stageReason(current,options.model)??(current===1&&options.correction?'Draft rig · structure evidence only':current===1?'Atlas inspection, read only — inspected package. Applied scratch atlas, pre-rig parts, mesh sign-off and draft corrections are unavailable here.':''));for(const f of frames.values()){f.title=t('Parts and atlas inspection');f.contentWindow?.postMessage({type:'review-stage-language',language:getLanguage()},location.origin);}});
64
+ const language=onLanguageChange(()=>{render();if(!panel.hidden)status.textContent=t(stageReason(current,options.model,!!options.direction)??(current===1&&options.correction?'Draft rig · structure evidence only':current===1?'Atlas inspection, read only — inspected package. Applied scratch atlas, pre-rig parts, mesh sign-off and draft corrections are unavailable here.':''));for(const f of frames.values()){f.title=t('Parts and atlas inspection');f.contentWindow?.postMessage({type:'review-stage-language',language:getLanguage()},location.origin);}});
64
65
  window.addEventListener('resize',place);show(current);
65
66
  return ()=>{window.removeEventListener('message',correction);language();canonical.disconnect();sourcePicker?.querySelectorAll('[data-build-side]').forEach(button=>button.removeEventListener('click',sourceChanged));delete document.documentElement.dataset.inspectionStage;if(workspace)workspace.inert=wasInert;panel.remove();window.removeEventListener('resize',place);document.querySelectorAll('[data-mode],[data-inspector]').forEach(b=>b.removeEventListener('click',legacy));};
66
67
  }
package/web/styles.css CHANGED
@@ -412,3 +412,6 @@ main{position:relative}.toolbar{anchor-name:--stage-comment-bar}#stage-comment{w
412
412
  :root[data-inspection-stage="1"] #mode-build-picker{display:flex!important}
413
413
  :root[data-inspection-stage="1"] #mode-build-picker>.eyebrow{display:none}
414
414
  :root[data-inspection-stage="2"] #mode-build-picker,:root[data-inspection-stage="4"] #mode-build-picker{display:none!important}
415
+ #direction-panel{flex:none;max-height:40%;overflow:auto;padding:.5rem .75rem;overflow-wrap:anywhere}
416
+ #direction-panel ul{margin:.4rem 0;padding-inline-start:1.4rem}
417
+ #direction-panel pre{max-height:12rem;overflow:auto}