@rig-c/review 1.4.3 → 1.5.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.
package/docs/PANELS.md CHANGED
@@ -30,6 +30,12 @@ body. A drawer keeps its title and close button in place while its body
30
30
  scrolls. The per-inspection **Repeat idle** toggle sits in the Animate
31
31
  transport row.
32
32
 
33
+ Animate plays in fixed 1/60 s steps taken from wall-clock time
34
+ (`web/playback-clock.ts`), so the clip and its physics advance the same way at
35
+ any display refresh rate; a frame with less than one step's worth of time draws
36
+ nothing new. A repeating clip wraps without a seek, so physics carries across
37
+ the loop seam; only **Reset physics**, a seek or choosing a clip restarts it.
38
+
33
39
  **Settings** (`#workspace-settings`) stores workspace-level preferences across
34
40
  tabs under `rig-review.workspace.v1` (`web/workspace-preferences.ts`):
35
41
  **Appearance** (`system`, `dark`, `light`), **Language** (`system`, `en`, `ko`),
@@ -265,7 +271,7 @@ This explorer is inspection. Producer-backed optimization and candidate Apply/un
265
271
 
266
272
  In **Setup**, the view bar's **Chest regions** button (pressed state; hidden in Animate) opens the chest-region editor bar directly under the view bar and enables editing on the rig pane. The bar has an **R** and an **L** group, each with **X**, **Y**, **R** (core radius, 6–120) and **Band** (4–120) in crop pixels, x screen-right and y down; **Mirror R → L** copies R's y, core radius and band to L; **Download JSON**; and **Apply · Rebuild**.
267
273
 
268
- On the rig pane each region is drawn as two circles: the core (full weight) and a dashed outer circle at core + band, R in one colour and L in another (two theme tokens per side), with a centre handle, a core handle on the right edge, a band handle on the top edge and a label `R (x,y) r:… b:…` under the outer circle. Dragging the centre moves the region, dragging the core edge sets r and dragging the band handle sets the band, all in crop pixels through the current camera scale. Each drag and each committed bar value is clamped live with the public example rebuild script's non-overlap rule: integer values, both cores plus 8 px must fit the centre distance minus a 2 px margin (both shrink by one factor) and the bands share what remains. A side the rule changed flashes its label and the footer says `CHEST_REGIONS_CLAMPED`. A handle drag never moves the camera; a drag anywhere else, or with Space held, still pans, and the wheel still zooms.
274
+ Nothing chest-related is drawn on the rig pane until the toggle is on (#345): the regions, the circles and the landmark markers appear only while **Chest regions** is pressed, and go when it is released. While it is on, each region is drawn as two circles: the core (full weight) and a dashed outer circle at core + band, R in one colour and L in another (two theme tokens per side), with a centre handle, a core handle on the right edge, a band handle on the top edge and a label `R (x,y) r:… b:…` under the outer circle. Dragging the centre moves the region, dragging the core edge sets r and dragging the band handle sets the band, all in crop pixels through the current camera scale. Each drag and each committed bar value is clamped live with the public example rebuild script's non-overlap rule: integer values, both cores plus 8 px must fit the centre distance minus a 2 px margin (both shrink by one factor) and the bands share what remains. A side the rule changed flashes its label and the footer says `CHEST_REGIONS_CLAMPED`. A handle drag never moves the camera; a drag anywhere else, or with Space held, still pans, and the wheel still zooms.
269
275
 
270
276
  The bar opens on **Circles** (the R / L groups above); **Landmarks** beside it (#105) states the chest the way the producer's `meshes.<part>.contour.bust` does. Three clicks on the part place the **right apex**, the **left apex** and the **cleavage** (each pick button arms the point its click places, then the next unplaced one; a placed marker drags), with **X** / **Y** fields for each in rig pixels, an **α** slider (core ratio, the producer's default 0.22), a **Clearance** slider (rig px, default 3.8) and optional **Bone R** / **Bone L** (empty is the producer's default, `boob_r` / `boob_l`). The two circles are drawn live with the producer's own derivation (`@rig-c/parts` `deriveBustRegions`): with `d` the distance from an apex to the cleavage, `R = round(d − clearance)`, `r = round(alpha × R)` and `band = R − r`, centred on the apex, named `bust_r` / `bust_l`, spacing 14. Review pre-checks the producer's one geometric refusal on the same numbers — `CONFIG_BUST_CLEARANCE` when `clearance <= 0`, `R_r + R_l >= |apex_r − apex_l|` or a radius is not positive — draws both circles in the overlap colour, shows the producer's detail, and Apply sends nothing. Otherwise Apply · Rebuild sends `{part, bust, configHash}`: the part's entry with `contour.bust` in place of `contour.regions` (the hand-written regions are dropped; every other field as written) goes to the same `rig-parts remesh --mesh` run as Circles, and the producer derives the circles again and judges the bones (`CONFIG_NAME_RESOLVES`) and a region declared twice (`CONFIG_REGION_NAME_UNIQUE`), verbatim. The part is the contour part whose entry already states `contour.bust`, else the one the bones name, else the only contour part. A config entry that states `contour.bust` seeds an untouched Landmarks mode.
271
277
 
@@ -281,7 +287,7 @@ Rig pixels are the whole figure's frame, which is the crop frame the model's sta
281
287
  - **Record.** The last applied state (`rig-review-applied/1`: part, regions, for a Landmarks Apply also `bust` — the entry as sent, with `regions` its two derived circles — config hash, entry SHA-256, producer and compiler versions, the producer's line and the scratch model's SHA-256) stays in the inspection draft, and feedback added while that build is on the stage carries it as `context.applied`. The review's `reviewedSource` still names the inspected build.
282
288
  - **Config patch.** The same loop takes any config edit as data: `POST /api/rebuild {patch}` with a `rig-review-config-patch/1` document (JSON Pointer ops over the handoff config, refused `EDIT_PATCH_STALE` when made against other config bytes) rebuilds the whole rig (`rig`) or one part (`remesh`) into scratch, compiles it and runs `rig-parts check` on it; the page's `window.rigReviewEditor.applyPatch(patch)` streams, reloads and resets like Apply, and the draft and `context.applied` carry `rig-review-applied/2` (the patch, its hash, the producer's line, check's summary and the diff of every document the producer writes, per file, with the images by hash). Schema and refusals: `docs/REVIEW_PACKAGE.md`, *Config patch and Apply*.
283
289
 
284
- The editor's values are the fields of Setup's **Chest regions · detail** block (R is region 1, L is region 2), which also holds what the bar does not: per region a name, a bone chosen from the loaded model's actual bones, the two semi-axes, a spacing and an optional medial clip x, plus the contour settings (tolerance, margin, spacing, max edge, stray, bridges). Max edge and stray may be left empty and bridges unchecked: as in the producer's contour block, each is then absent (no edge is cut, no island is left out, the one-island rule), and the export omits it rather than writing a default; `bridges` is written only as `true`, the one value the producer takes, and a written max edge must be above 0 (#318). Setting R in the bar writes both semi-axes. A region with equal semi-axes and no clip exports as the examples' circle, `{"name", "shape": "circle", "cx", "cy", "r", "bone", "spacing", "band"}`; unequal semi-axes or a clip export as the generator's 32-sample polygon on its 1/256-pixel grid and are drawn filled, without handles.
290
+ The editor's values are the fields of Setup's **Chest regions · detail** block (R is region 1, L is region 2), which also holds what the bar does not. Its **Markers** button is the same toggle as the view bar's (both show its On/Off state, and on a rig with no contour mesh both are disabled with the reason written under it); the crop width × height sit beside it; the two regions are one table, a row per region in its overlay colour and a column per value; the contour settings are one row (#345). Per region it holds a name, a bone chosen from the loaded model's actual bones, the two semi-axes, a spacing and an optional medial clip x, plus the contour settings (tolerance, margin, spacing, max edge, stray, bridges). Max edge and stray may be left empty and bridges unchecked: as in the producer's contour block, each is then absent (no edge is cut, no island is left out, the one-island rule), and the export omits it rather than writing a default; `bridges` is written only as `true`, the one value the producer takes, and a written max edge must be above 0 (#318). Setting R in the bar writes both semi-axes. A region with equal semi-axes and no clip exports as the examples' circle, `{"name", "shape": "circle", "cx", "cy", "r", "bone", "spacing", "band"}`; unequal semi-axes or a clip export as the generator's 32-sample polygon on its 1/256-pixel grid and are drawn filled, without handles.
285
291
 
286
292
  The overlay needs the loaded model to fix the crop: its declared stage must be the crop frame with the root at its bottom centre (`x = -width/2`, `y = 0`) and the drawn root bone must sit at the world origin, so crop `(x, y)` is world `(x - width/2, height - y)`. Otherwise the editor bar and the detail block show `CHEST_REGION_MAPPING_UNAVAILABLE: <what is missing>`, nothing is drawn, and the values still edit numerically and export from a crop size you enter.
287
293
 
@@ -0,0 +1,85 @@
1
+ # Parts and atlas view
2
+
3
+ `rig-review parts` shows a rig's parts as images, before any rig is built, so a part with missing material, a faint
4
+ island or a ragged rim is caught before rigging rather than in motion after it. The same view reads a built rig's atlas
5
+ to check what ships.
6
+
7
+ ```sh
8
+ npx rig-review parts <out> # a rig-parts build root: opens <out>/rig/parts.json
9
+ npx rig-review parts <out>/rig # the same package, named directly
10
+ npx rig-review parts <out>/check # a built rig's atlas (any review package with a compiled model)
11
+ ```
12
+
13
+ Options: `--mesh-report <file>`, `--check <file>` (producer flags; see below), `--verdict <file>` (where the sign-off
14
+ is written), `--port <n>`. Like `review`, it serves in the foreground and exits 3 s after its last tab closes.
15
+
16
+ ## Inputs
17
+
18
+ | Mode | Opens on | Items |
19
+ | --- | --- | --- |
20
+ | parts | a directory holding `parts.json` beside `parts/<name>.png`, as `rig-parts assemble` writes it, or a build root whose `rig/` holds them | every part, in `parts.json` order (draw order, back first) |
21
+ | atlas | a review package or build `check/` folder whose compiled model declares `pages[].regions[]` | every region, by page |
22
+
23
+ ## What it shows
24
+
25
+ - **Every part on its own**, on a sentinel background (green, magenta, black, white or checker), at native scale with
26
+ 2× and 4× nearest-neighbour zoom. **Alpha only** shows the alpha channel as grey (white is opaque).
27
+ - **Footprints of parts in front** (parts mode): the alpha of every part later in `parts.json` whose box meets the
28
+ selected part's box, placed by its rig box and tinted cyan at 50 %. Where the selected part has no pixel under its
29
+ occluder, the tint lands on the bare sentinel, so a back part that stops exactly at its occluder's edge shows the
30
+ occluder's shape at a glance. Nothing is measured; the tint is the front parts' own alpha.
31
+ - **Atlas mode**: the pages as packed, with each region's box and name; the background shows through padding, and a
32
+ region's own view keeps 4 page pixels around its box (dashed) so bleed is visible. Clicking a region opens it.
33
+ - **Producer flags**, read from the files rig-parts writes and shown on the part they name. None is re-measured here. Each reads as one labelled line (an opening's parts, animation, frame and cells; a seam pair's pixel counts; a gate's name, status and readings), with the producer's object verbatim under a collapsed **Producer line**.
34
+
35
+ | Flag | Read from | When |
36
+ | --- | --- | --- |
37
+ | `faint:<i>` | `mesh_report.json` beside `parts.json` (`rig` writes it there): a row's `contour.bridges.faint[i]` | a faint island the mesh left out (rig-parts #326) |
38
+ | `check:<path>` | `check/check.json` beside `rig/` | a gate whose `status` is `FAIL` or `WARN` (not `PASS`, `CLEAR`, `SKIP` or `REPORTED`), or a `seam_pairs` / `figure_openings` entry, that names the part by a string field; bone fields (`bone`, `root`, `tip`, `link`) never attribute |
39
+
40
+ The occlusion-coverage report (rig-c/parts#998) is not read yet; the footprint toggle stands without it.
41
+
42
+ ## The sign-off
43
+
44
+ Each item is **pending**, **clean** or **flagged** with a note (a note is optional on clean). **Save sign-off**
45
+ writes `parts-review.json` beside `parts.json` (atlas mode: beside the model), or to `--verdict`:
46
+
47
+ ```json
48
+ {
49
+ "schema": "rig-review-parts-verdict/1",
50
+ "mode": "parts",
51
+ "tool": { "name": "@rig-c/review", "version": "1.4.3" },
52
+ "source": {
53
+ "sha256": "…",
54
+ "files": [{ "path": "parts.json", "bytes": 1234, "sha256": "…" }, { "path": "parts/hair_back.png", "bytes": 5678, "sha256": "…" }],
55
+ "flags": [{ "path": "mesh_report.json", "sha256": "…" }]
56
+ },
57
+ "status": "pending",
58
+ "parts": { "hair_back": { "outcome": "flagged", "note": "no material under the arm", "flags": ["faint:0"] } },
59
+ "updatedAt": "2026-11-04T00:00:00.000Z"
60
+ }
61
+ ```
62
+
63
+ - `mode` is `parts` or `atlas`. rig-c/create gates its `parts-review` stage on `parts` only.
64
+ - `source.files` is `parts.json` and every part PNG (atlas mode: the model and every page), each path **relative to the
65
+ verdict file's directory**, POSIX separators. A part added, removed or repainted after sign-off changes the hash.
66
+ - `source.sha256` is the SHA-256 of the UTF-8 lines `<path>\t<sha256>\n`, one per `source.files` entry, sorted by path
67
+ bytewise. Consumers recompute it from the files on disk.
68
+ - `source.flags` lists the producer files the flags were read from; `parts.<name>.flags` the flag ids shown on that part.
69
+ - `status`: `approved` only when every part is clean; `changes-requested` only with at least one part flagged;
70
+ otherwise `pending`.
71
+
72
+ Refusals, by name: `PARTS_VERDICT_MISSING_PART`, `PARTS_VERDICT_UNKNOWN_PART`, `PARTS_VERDICT_NOTE_REQUIRED`,
73
+ `PARTS_VERDICT_NOT_CLEAN`, `PARTS_VERDICT_NOTHING_FLAGGED`, `PARTS_VERDICT_INVALID`, and `PARTS_VIEW_SOURCE_CHANGED`
74
+ when a file changed after the view opened.
75
+
76
+ On reopen, a saved sign-off is offered only when both `source.sha256` and `source.flags` match the files on disk. When
77
+ only the producer flags differ, the page says the saved sign-off is for different producer flags and starts fresh.
78
+ Consumers that gate on the sign-off (rig-c/create) check `source.sha256`.
79
+
80
+ Every file the view reads from a package resolves inside it: a part PNG or `parts.json` that symlinks out is refused
81
+ as `PARTS_IMAGE_OUTSIDE` / `PARTS_FILE_OUTSIDE`, and a discovered `mesh_report.json` or `check.json` as
82
+ `PARTS_FLAGS_OUTSIDE`. Atlas pages go through the review package's own `safeFile`. A file named on the command line
83
+ (`--mesh-report`, `--check`) is read where it is.
84
+
85
+ Editing parts is out of scope: repairs go through the producer's source ladder, never the browser.
package/docs/WORKFLOWS.md CHANGED
@@ -27,6 +27,9 @@ The server prints the exact link, for example `http://127.0.0.1:4317/?checkpoint
27
27
 
28
28
  Add `lang=en` or `lang=ko` to a review link's query to open it in that language, ahead of the fragment: `…/?checkpoint=silhouette&lang=en#cap=…`. It outranks the browser and the saved choice and stores nothing, so a shared link cannot change a reader's setting. Picking a language in the settings menu takes over for the rest of the page.
29
29
 
30
+ ## Review parts before rigging
31
+ `rig-review parts <out>` opens a rig-parts build root's parts (`rig/parts.json` and `rig/parts/*.png`) before any rig is built: each part on a sentinel background, the footprints of the parts in front of it, the producer's flags on it, and a per-part sign-off written to `parts-review.json` for the create pipeline. `rig-review parts <out>/check` shows a built rig's atlas. See [Parts and atlas view](PARTS_VIEW.md).
32
+
30
33
  ## Compare two outputs
31
34
 
32
35
  Open two compiled packages against one explicitly selected local reference video:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/review",
3
- "version": "1.4.3",
3
+ "version": "1.5.0",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -41,6 +41,7 @@
41
41
  "docs/DESIGN.md",
42
42
  "docs/ANIMATION_INSPECTION.md",
43
43
  "docs/LIVE_FIXTURE.md",
44
+ "docs/PARTS_VIEW.md",
44
45
  "skills",
45
46
  "README.md",
46
47
  "LICENSE"
package/src/build.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { fileURLToPath } from 'node:url';
2
2
  export const appRoot=fileURLToPath(new URL('..',import.meta.url));
3
- export async function buildWeb(mode:'single'|'compare'='single'):Promise<Blob> {
4
- const result=await Bun.build({entrypoints:[appRoot+(mode==='compare'?'web/compare.ts':'web/main.ts')],target:'browser',format:'esm',minify:false});
3
+ export async function buildWeb(mode:'single'|'compare'|'parts'='single'):Promise<Blob> {
4
+ const result=await Bun.build({entrypoints:[appRoot+(mode==='compare'?'web/compare.ts':mode==='parts'?'web/parts.ts':'web/main.ts')],target:'browser',format:'esm',minify:false});
5
5
  if(!result.success)throw new Error(result.logs.map(v=>v.message).join('\n'));
6
6
  const output=result.outputs.find(v=>v.path.endsWith('.js'));if(!output)throw new Error('frontend bundle: JavaScript output missing');return output;
7
7
  }
8
- if(import.meta.main){await buildWeb();await buildWeb('compare');console.log('Frontend bundles built successfully (single and compare).');}
8
+ if(import.meta.main){await buildWeb();await buildWeb('compare');await buildWeb('parts');console.log('Frontend bundles built successfully (single, compare and parts).');}
package/src/cli.ts CHANGED
@@ -15,12 +15,14 @@ import { readFeedbackSession, readFeedbackCompareSession } from './session-histo
15
15
  import { startServer } from './server.ts';
16
16
  import { loadCompare } from './compare.ts';
17
17
  import { startCompareServer } from './compare-server.ts';
18
+ import { loadPartsView, type PartsViewOptions } from './parts-view.ts';
19
+ import { startPartsServer } from './parts-server.ts';
18
20
  import { readSession, type Feedback } from './session.ts';
19
21
  import { readCompareSession } from './compare-session.ts';
20
22
  import { exportReviewStrip, exportCompareStrip, stripJson, writeStripOutput, validateStripOutput } from './strip-export.ts';
21
23
  import type { StripInterval, StripRequest } from './strip.ts';
22
24
  const handoffUsage='[--config <path> [--parts <dir>] [--source <png> --full <dir> [--head <dir>]] [--keypoints <file>]]';
23
- const usage='Usage: rig-review open <dir> [--reference <video>] [--compare <dir>] [--animation <name>] [--control] [--direct] [--view-only] '+handoffUsage+'\n --config declares the producer handoff (wins over the review.json "producer" block and discovery of config.json, rig/config.json, ../config.json beside an opened out/); feedback and control take the same flags; --view-only opens without a producer handoff.\n open is managed by default: one loopback front at 127.0.0.1:4318 (RIG_REVIEW_FRONT_PORT overrides) serves /instances/<key>/; --direct serves the worker on its own port.\n rig-review control <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--page <id> --expected-revision <n> --command <JSON> --wait-ms <n>]\n rig-review feedback <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--format json|issue]\n Usage: bun run review -- <review.json|output-directory> [--port 4317] [--checkpoint ID] [--view-only]\n bun run check -- <review.json|output-directory>\n bun run feedback -- <review.json|output-directory>\n bun run review -- compare <a> <b> --reference <video> --animation <name> [--port 4317]\n bun run check -- compare <a> <b> --reference <video> --animation <name>\n bun run feedback -- compare <a> <b> --reference <video> --animation <name>\n rig-review --version';
25
+ const usage='Usage: rig-review open <dir> [--reference <video>] [--compare <dir>] [--animation <name>] [--control] [--direct] [--view-only] '+handoffUsage+'\n --config declares the producer handoff (wins over the review.json "producer" block and discovery of config.json, rig/config.json, ../config.json beside an opened out/); feedback and control take the same flags; --view-only opens without a producer handoff.\n open is managed by default: one loopback front at 127.0.0.1:4318 (RIG_REVIEW_FRONT_PORT overrides) serves /instances/<key>/; --direct serves the worker on its own port.\n rig-review control <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--page <id> --expected-revision <n> --command <JSON> --wait-ms <n>]\n rig-review feedback <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--format json|issue]\n Usage: bun run review -- <review.json|output-directory> [--port 4317] [--checkpoint ID] [--view-only]\n bun run check -- <review.json|output-directory>\n bun run feedback -- <review.json|output-directory>\n bun run review -- compare <a> <b> --reference <video> --animation <name> [--port 4317]\n bun run check -- compare <a> <b> --reference <video> --animation <name>\n bun run feedback -- compare <a> <b> --reference <video> --animation <name>\n rig-review parts <build root | parts dir | review package> [--mesh-report <file>] [--check <file>] [--verdict <file>] [--port <n>]\n rig-review --version';
24
26
  async function stripCommand(args:string[],options:{stateDir?:string}){
25
27
  const compare=args[0]==='compare';if(compare)args.shift();const a=args.shift(),b=compare?args.shift():undefined;if(!a||compare&&!b)throw new Error('strip: expected package input(s)');
26
28
  let reference:string|undefined,referenceVideo:string|undefined,animation:string|undefined,basis:'a'|'b'|undefined,range:string|undefined,output:string|undefined,jsonOnly=false,all=false;
@@ -93,12 +95,27 @@ function commandHelpRequested(args:readonly string[],command:'open'|'review'|'ch
93
95
  }
94
96
  return false;
95
97
  }
98
+ const partsUsage='Usage: rig-review parts <build root | parts dir | review package> [--mesh-report <file>] [--check <file>] [--verdict <file>] [--port <n>]\n A directory holding parts.json (or a build root whose rig/ holds it) opens in parts mode, before rigging; a review package or check/ folder opens its atlas.\n The sign-off is written to parts-review.json beside parts.json (or the model), or to --verdict.';
99
+ /** `rig-review parts` (#348): the parts and atlas view, served in the foreground; exits when its last tab closes. */
100
+ async function partsCommand(args:string[]){
101
+ const input=args.shift();if(!input||input==='--help'||input==='-h'){console.log(partsUsage);return;}
102
+ const options:PartsViewOptions={};let port=4317;const seen=new Set<string>();
103
+ while(args.length){const flag=args.shift()!;if(flag==='--help'||flag==='-h'){console.log(partsUsage);return;}if(seen.has(flag))throw new Error(`parts: duplicate option ${flag}`);seen.add(flag);const value=args.shift();if(!value)throw new Error(`Missing value for ${flag}`);
104
+ if(flag==='--mesh-report')options.meshReport=value;else if(flag==='--check')options.check=value;else if(flag==='--verdict')options.verdict=value;
105
+ else if(flag==='--port'){port=Number(value);if(!Number.isInteger(port)||port<0||port>65535)throw new Error('--port: expected integer 0..65535');}
106
+ else throw new Error(`Unknown option ${flag}\n${partsUsage}`);}
107
+ const pkg=await loadPartsView(input,options);
108
+ const capability=randomBytes(32).toString('hex'),server=await startPartsServer(pkg,{port,capability,exitOnClose:true});
109
+ const stop=(sig:string)=>{server.stop(true);console.log(`review parts: exiting — received ${sig}.`);process.exit(0);};process.once('SIGINT',()=>stop('SIGINT'));process.once('SIGTERM',()=>stop('SIGTERM'));
110
+ console.log(`Parts view ready: http://127.0.0.1:${server.port}/#cap=${capability}\nMode: ${pkg.mode} · ${pkg.items.length} ${pkg.mode==='parts'?'parts':'regions'} · ${pkg.flags.length} producer flags\nSign-off: ${pkg.verdictPath}\nPress Ctrl+C to stop.`);
111
+ }
96
112
  export async function main(args:string[],options:{stateDir?:string}={}){
97
113
  options={stateDir:options.stateDir??defaultStateDir()};if(args[0]==='--')args.shift();
98
114
  if(args[0]==='--version'||args[0]==='-v'){console.log((JSON.parse(await readFile(new URL('../package.json',import.meta.url),'utf8')) as {version:string}).version);return;}
99
115
  if(args[0]==='control')return controlCommand(args.slice(1),options.stateDir);
100
116
  if(args[0]==='open'){const openArgs=args.slice(1);if(commandHelpRequested(openArgs,'open')){console.log(usage);return;}const inputs=parseOpenInputs(openArgs);const result=await openReview(inputs,options);// Launcher contract (README): stdout is the URL line alone; stderr is diagnostic, control notice, retrieval, in that order.
101
117
  console.log(result.url);if(result.build)console.error(buildOpenDiagnostic(result.build));if(result.selection)console.error(animationDiagnostic(result.selection));if(inputs.control)console.error('Inspection control enabled; query the current connected page with rig-review control and the same inputs.');console.error(`Review ${result.reused?'reused':'started'}; feedback: rig-review feedback ${[result.inputs.input,...(result.inputs.compare?['--compare',result.inputs.compare]:[]),...(result.inputs.reference?['--reference',result.inputs.reference]:[]),...(result.inputs.animation?['--animation',result.inputs.animation]:[]),...handoffWords(result.inputs)].map(shellWord).join(' ')}`);return;}
118
+ if(args[0]==='parts')return partsCommand(args.slice(1));
102
119
  if(args[0]==='strip'){args.shift();if(args.includes('--help')){console.log(usage+'\nStrip: strip <package> --reference <declared-video-id> --animation <name> (--frames FIRST:LAST | --all-feedback) [--json] [--out path]\n strip compare <a> <b> --reference <video> --animation <name> --basis a|b (--frames FIRST:LAST | --all-feedback) [--json] [--out path]');return;}return stripCommand(args,options);}let command:'review'|'check'|'feedback'='review';if(args[0]==='check'||args[0]==='feedback'){command=args.shift() as 'check'|'feedback';}
103
120
  if(args[0]==='--help'||args[0]==='-h'){console.log(usage);return;}
104
121
  let format:'json'|'issue'='json';if(command==='feedback'){const parsed=feedbackFormat(args);args=parsed.args;format=parsed.format;}
@@ -0,0 +1,65 @@
1
+ /** Serves the parts and atlas view (#348): the page, its bundle, the part and page images by index, and the sign-off. */
2
+ import { readFile } from 'node:fs/promises';
3
+ import { appRoot, buildWeb } from './build.ts';
4
+ import { accessGate } from './open-protocol.ts';
5
+ import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
6
+ import { partsViewJson, readVerdict, saveVerdict, servedImage, type PartsViewPackage } from './parts-view.ts';
7
+
8
+ const headers = { 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" };
9
+ const json = (value: unknown, status = 200) => Response.json(value, { status, headers });
10
+ const BODY_LIMIT = 4 * 1024 * 1024;
11
+
12
+ async function bodyJson(req: Request): Promise<unknown> {
13
+ if (!/^application\/json(?:\s*;|$)/i.test(req.headers.get('content-type') ?? '')) throw new Error('Expected application/json');
14
+ const text = await req.text();
15
+ if (text.length > BODY_LIMIT) throw new Error('Verdict payload exceeds 4 MiB');
16
+ return JSON.parse(text);
17
+ }
18
+
19
+ export interface PartsServerOptions { port?: number; capability?: string; exitOnClose?: boolean; graceMs?: number; unopenedTimeoutMs?: number; onClose?: (info: LiveExitInfo) => void | Promise<void>; log?: (line: string) => void }
20
+
21
+ export async function startPartsServer(pkg: PartsViewPackage, options: PartsServerOptions = {}) {
22
+ const bundle = await buildWeb('parts');
23
+ let rawStop: ((closeActiveConnections?: boolean) => void) | null = null;
24
+ let saving = false;
25
+ const live = createLiveLifecycle({ label: 'review parts', graceMs: options.graceMs, unopenedTimeoutMs: options.unopenedTimeoutMs, exitOnClose: options.exitOnClose, onClose: options.onClose, log: options.log, busy: () => saving, stopServer: () => { rawStop?.(true); } });
26
+ const handle = async (req: Request, port: number | undefined, srv: UpgradableServer): Promise<Response | undefined> => {
27
+ try {
28
+ const url = new URL(req.url), origin = `http://127.0.0.1:${port}`;
29
+ if (url.origin !== origin) return json({ error: 'Loopback host required' }, 403);
30
+ const refused = accessGate(req, options.capability);
31
+ if (refused) return refused;
32
+ if (req.method === 'GET' && url.pathname === LIVE_PATH) {
33
+ if (req.headers.get('origin') !== origin) return json({ error: 'Same-origin Origin required' }, 403);
34
+ return live.upgrade(req, srv, headers);
35
+ }
36
+ live.onRequestStart(url.pathname);
37
+ try {
38
+ if (url.pathname === '/api/parts' && req.method === 'GET') return json(partsViewJson(pkg, await readVerdict(pkg)));
39
+ if (url.pathname === '/api/parts/verdict' && req.method === 'POST') {
40
+ if (req.headers.get('origin') !== origin) return json({ error: 'Same-origin Origin required' }, 403);
41
+ saving = true;
42
+ try { return json({ verdict: await saveVerdict(pkg, await bodyJson(req)) }); } finally { saving = false; }
43
+ }
44
+ const image = /^\/api\/parts\/(image|page)\/(\d+)$/.exec(url.pathname);
45
+ if (image && (req.method === 'GET' || req.method === 'HEAD')) {
46
+ const path = servedImage(pkg, image[1] as 'image' | 'page', Number(image[2]));
47
+ if (!path) return json({ error: 'Not found' }, 404);
48
+ const file = Bun.file(path);
49
+ return new Response(req.method === 'HEAD' ? null : file, { headers: { ...headers, 'Content-Security-Policy': "default-src 'none'; sandbox", 'Content-Type': file.type || 'application/octet-stream' } });
50
+ }
51
+ if (url.pathname === '/parts.js') return new Response(req.method === 'HEAD' ? null : bundle, { headers: { ...headers, 'Content-Type': 'text/javascript' } });
52
+ if (url.pathname === '/' || url.pathname === '/parts.html') return new Response(req.method === 'HEAD' ? null : await readFile(appRoot + 'web/parts.html'), { headers: { ...headers, 'Content-Type': 'text/html; charset=utf-8' } });
53
+ if (url.pathname === '/parts.css') return new Response(req.method === 'HEAD' ? null : await readFile(appRoot + 'web/parts.css'), { headers: { ...headers, 'Content-Type': 'text/css' } });
54
+ return json({ error: 'Not found' }, 404);
55
+ } finally { live.onRequestEnd(url.pathname); }
56
+ } catch (e) {
57
+ const message = e instanceof Error ? e.message : 'Request failed';
58
+ return json({ error: message }, message.startsWith('PARTS_VIEW_SOURCE_CHANGED') ? 409 : 400);
59
+ }
60
+ };
61
+ const server = Bun.serve({ hostname: '127.0.0.1', port: options.port ?? 4317, websocket: live.websocket, async fetch(req, srv) { const res = await handle(req, srv.port, srv); return res as Response; } });
62
+ rawStop = server.stop.bind(server);
63
+ server.stop = ((closeActiveConnections?: boolean) => { live.stop(); return rawStop!(closeActiveConnections); }) as typeof server.stop;
64
+ return Object.assign(server, { live });
65
+ }