@rig-c/review 2.10.0 → 2.12.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/DESIGN.md CHANGED
@@ -6,13 +6,73 @@ The delivery unit is an existing output folder or an optional curated review pac
6
6
 
7
7
  The person uses one inspection workspace with **Setup** and **Animate** sections and a review dialog for feedback (the compare page keeps **View**, **Rig**, **Playback** and **Feedback** sections). Setup covers setup geometry, source art, pivot/joint placement, meshes, weights and draw order; Animate covers angle coverage, frame intervals, reference video/poses, contact/deformation, audio inspection and the inspection environment (wind, gravity and impulses through the published player's `environment`/`moved`; its state is feedback context, never a model or motion edit) and the physics tuning panel (#103: constraint values edited as config patch ops and applied through the producer, never written into the model by review), and the readings block (#108: the compiler's own `rigc render` readings of the drawn animation, run on the inspected build and on the latest scratch build, shown as timeline ticks and worst-frame lines), the Environment block's *Use for readings* (#112: the controls exported as a `rigc-environment/1` schedule that readings, Apply's check and *Check under this world* — the installed producer's `rig-parts check --environment` — read, so the bars and readings are taken under the wind the person watched; the schedule is feedback context and is never authored into the rig), and the requirements block (#113: the scene's declared requirements written as a `spine-parts-requirements/1` file and measured by the installed producer's `rig-parts check --requirements`, one worst-frame line each). Time/angle controls navigate inspection. Timeline edits are six typed keyed operations on a scratch copy of `motion.animations_from`, built by the installed producer; review never writes source motion. Implemented modeling instruments send bounded changes through the installed producer into scratch, including setup-space mesh deltas.
8
8
 
9
+ ## Core UI rules (owner, 2026-11-11)
10
+
11
+ These rules govern every Review view and all job kinds, including parts, interview,
12
+ plan, checkpoint, rig, direction, image review and signoff.
13
+
14
+ - **R0** Every Review UI addition or change requires the owner's ruling twice.
15
+ The owner rules on the layout before implementation and on the working screen
16
+ before merge. Show both through the Review tool or a local page. Chat images
17
+ cannot serve this review. HQ acceptance alone is insufficient. This covers
18
+ screens, gates, input fields, toolbars, panels and owner checkpoints, including
19
+ Create-side changes that make Review render new owner content, gates or
20
+ checkpoints. Nonvisual bug fixes are exempt.
21
+ - **R1** Every review view separates its main toolbar and secondary toolbar into
22
+ distinct areas. Group primary inspection actions in the main area and auxiliary
23
+ controls in the secondary area.
24
+ - **R2** Comments are the only feedback-input feature. A submission can contain
25
+ any number of comments. Each comment can be general or pinned to an image
26
+ point, region, part, frame or checkpoint. Keep pointed image comments through
27
+ `stage-comments.ts` and `parts-comment-crops.ts` with their source-bound evidence.
28
+ Remove separate memo, note, per-part note, summary and `words` input surfaces.
29
+ Structured-answer mappings that conflict with this rule require an HQ ruling.
30
+ - **R3** Inspection uses the main view's Difference switch to cover all regions.
31
+ Remove separate sidebar key-region checkpoint and evidence panels. Retain the
32
+ supported checkpoint act flow through its existing contract.
33
+ - **R4** All view areas share zoom, Fit, 1:1 and resize behavior through the existing
34
+ viewport modules. Extend the shared modules for a missing capability.
35
+
36
+ Act-field and downstream-consumer changes follow the existing HQ approval boundary
37
+ for public contracts. Preserve historical record parsing, source binding and
38
+ replay, with the original recorded text intact. Keep the frozen payload definitions
39
+ in their contract references until an approved change maps the comments feature to
40
+ those fields. [Live job contract](REVIEW_PACKAGE.md#live-job-contract),
41
+ [Public API stability](STABILITY.md).
42
+
43
+ The owner's wording is retained verbatim.
44
+
45
+ ```text
46
+ 위 지적 사항은 리뷰 UI 핵심 지침이야 모든 작업에 일관성 확보될 수 있게 기획을 업데이트 하거나 지침을 갈아 앞거나 해줘
47
+ 파츠 리뷰 툴바 * 툴바 메인 툴바 보조 툴바 영역 구분
48
+ 사용자 피드백 * 메모 기능은 모두 삭제, 모든 사용자 입력은 코멘트 하나로 통일
49
+ ```
50
+
51
+ The owner's UI ruling requirement is retained verbatim.
52
+
53
+ ```text
54
+ HQ는 리뷰 UI 추가/변경은 오빠 판정 무조건 받아
55
+ ```
56
+
57
+ The owner's comments clarification is retained verbatim.
58
+
59
+ ```text
60
+ 코멘트가 왜 하나야? 미친거야?
61
+ ```
62
+
63
+ The earlier shared-view requirement is also retained verbatim.
64
+
65
+ ```text
66
+ 뷰영역 공용 UX(리사이즈 등)
67
+ ```
68
+
9
69
  ## Implemented foundation
10
70
 
11
71
  The CLI opens `review.json` or an existing output directory. The directory adapter builds a manifest in memory from `skeleton.*`, `motion.json`, `report.json`, source video, contact strips and canonical pose-sequence evidence. It never changes delivered output. A compiled model uses the published play runtime. Raw Spine output is evidence with playback explicitly unavailable. Source-only data never becomes a fabricated playback success.
12
72
 
13
73
  Inspection supports local references, checkpoint context, runtime playback when a real compatible model exists, available angle/audio facilities and explicit review state. The canonical `rig-pose-sequence/1` format documented by `@rig-c/pose` preserves frame times, person IDs, joint states/coordinates/confidence and optional camera metadata. The demo pose is an authored synthetic transport example, not extracted from footage.
14
74
 
15
- Manual feedback has an inclusive integer frame interval; a clockless single stage comment explicitly records seconds with frame/interval unavailable (see REVIEW_PACKAGE). Feedback has a target `{kind: bone|slot|rig, name}`, category `defect|quality`, and one-line summary. Optional context records the checkpoint, time, reference/person and camera/axis state. The person can export data and issue-ready Markdown; this app neither posts issues automatically nor writes proposed motion keys. Notes must be useful to the producing agent without interpreting a free-form key-edit JSON blob.
75
+ Each review submission collects feedback through the comments feature under R2 and can contain any number of general or pointed comments. Source-bound inspection context records an inclusive integer frame interval, or explicit seconds when a frame/interval is unavailable, the target `{kind: bone|slot|rig, name}`, category `defect|quality`, checkpoint, time, reference/person and camera/axis state. The person can export data and issue-ready Markdown; this app neither posts issues automatically nor writes proposed motion keys. Comments must be useful to the producing agent without interpreting a free-form key-edit JSON blob. Existing serialized feedback and comment fields follow the compatibility boundary above.
16
76
 
17
77
  Identity, revision and content hash bind every decision. A submission also records separate exact rig/motion hashes and paths, packageRevision, viewerVersion and installed runtimeVersion; absent source stays null. The producing agent can retrieve the saved JSON with the read-only feedback CLI after the UI closes. Opening never means reviewed. The person explicitly approves, requests changes or returns to pending, independently of checkpoint outcomes. Changed inputs do not inherit prior approval. Feedback writes remain outside source, are bounded and atomic, and require the app's exact Origin.
18
78
 
@@ -22,11 +82,11 @@ Animate's Retarget block edits what a pose retarget is made from — the `rig-po
22
82
 
23
83
  ## Modeling touch-up direction
24
84
 
25
- The chest-region editor and Edit Mesh exist for detail that cannot be said in words. Issue #99 states the loop: **point → rebuild → watch → repeat → submit**. Review builds no mesh itself; **Apply · Rebuild runs the installed producer as a child process** on the user's own designation, into a scratch build beside the inspected one, and the viewer reloads that build in place. A feedback row captures the applied state being watched when that row is created (`context.applied`); submitting the review sends those existing rows. Apply followed directly by Submit does not automatically add the latest applied state to feedback. A unified described/made handoff remains separate work (#369 / create#91), not an automatic transfer promised by this workspace. Edit Mesh sends a typed setup-space delta through `rig-parts remesh --delta` and the shared compile/check runner, loading the scratch revision in place; producer refusals remain named.
85
+ The chest-region editor and Edit Mesh exist for detail that cannot be said in words. Issue #99 states the loop: **point → rebuild → watch → repeat → submit**. Review builds no mesh itself; **Apply · Rebuild runs the installed producer as a child process** on the user's own designation, into a scratch build beside the inspected one, and the viewer reloads that build in place. Captured applied evidence (`context.applied`) remains bound to the state that was being watched when it was collected. Submission preserves that captured state. Apply followed directly by Submit does not automatically add the latest applied state to feedback. A unified described/made handoff remains separate work (#369 / create#91), not an automatic transfer promised by this workspace. Edit Mesh sends a typed setup-space delta through `rig-parts remesh --delta` and the shared compile/check runner, loading the scratch revision in place; producer refusals remain named.
26
86
 
27
87
  Every Apply needs a binding to what the inspected rig was built from (issue #101): the **producer handoff**, declared (`open --config`, or the review.json `producer` block) or found at fixed places (`config.json`, `rig/config.json`, and last `../config.json` beside an opened `out/`, which the bar names as outside the folder). Its files are hashed into the reviewed identity beside the package, and once per session a **baseline** rebuilds the whole rig from them and says whether it reproduces the inspected one. An op that rebuilds the whole rig runs only on a reproduced baseline (`EDIT_BASELINE_MISMATCH` names the first differing path); `remesh` checks its own part (`REMESH_BASELINE_MISMATCH`). A patch that touches only what `rig-parts retune` splices — constraints, the idle's tracks and duration, the blink's numbers — runs retune instead (parts 1.44.0+, #136), which holds every other byte of the inspected rig itself, so a build whose repair is a mesh the config does not reproduce can still take a physics or idle edit — but not one whose repair redrew an image, which retune holds too, nor one whose rig.json is not the writer's text (#148; the baseline line says which); bones, stops, regions, turn and the blink's groups and still keep the whole-rig path and its guard.
28
88
 
29
- Edits reach the producer as data (issue #102): config-based edit cards state their edit as one **config patch** (`rig-review-config-patch/1`: the config hash it was made against, JSON Pointer ops, the producer and the op), and one generic runner applies it to a scratch copy of the handoff config, runs the op (`rig` for the whole rig, `remesh` for one part's entry), compiles and runs `check` on the result. Mesh deltas, retarget requests and keyed motion operations retain their own typed artifacts and runner paths; they are not flattened into config patches. A stale config patch is refused (`EDIT_PATCH_STALE`) rather than rebased. The page's client exposes `applyPatch(patch)` with #99's stream, in-place reload and Reset; the physics tuning panel (#103) is the first editing UI that produces them. For a feedback row created while that patch build is drawn, `context.applied` captures the patch, its hash, the producer's line, check's summary and the rig.json diff. Submit preserves that row's captured state rather than replacing it with the latest Apply.
89
+ Edits reach the producer as data (issue #102): config-based edit cards state their edit as one **config patch** (`rig-review-config-patch/1`: the config hash it was made against, JSON Pointer ops, the producer and the op), and one generic runner applies it to a scratch copy of the handoff config, runs the op (`rig` for the whole rig, `remesh` for one part's entry), compiles and runs `check` on the result. Mesh deltas, retarget requests and keyed motion operations retain their own typed artifacts and runner paths; they are not flattened into config patches. A stale config patch is refused (`EDIT_PATCH_STALE`) rather than rebased. The page's client exposes `applyPatch(patch)` with #99's stream, in-place reload and Reset; the physics tuning panel (#103) is the first editing UI that produces them. For evidence captured while that patch build is drawn, `context.applied` retains the patch, its hash, the producer's line, check's summary and the rig.json diff. Submit preserves the captured state rather than replacing it with the latest Apply.
30
90
 
31
91
  Physics tuning (#103) edits only what the handoff config declares: a constraint row is resolved by `name` (and kind) against the config, never by index alone, and every op records both the index (its pointer) and the name, which the server checks (`EDIT_PATCH_NAME_MISMATCH`). Rows the rig stage adds (the `turn` twins) have no config field and are shown not editable with the reason. An Apply reloads under the world it was pressed in so before and after are seen under one wind, gust and jolt state; review judges no value (a mass of 0 is rigc's `A23` to refuse). A build whose check FAILed may be loaded and looked at, but a review written on it is not submitted (`EDIT_SUBMIT_UNCHECKED`). Published Play 1.14.0 supplies the six-field live preview (#206): strength, damping, inertia, wind, gravity and mix use its public set/read/clear methods; mass and component toggles still require Apply. Slider input updates the pending override; the label distinguishes it from the last evaluated effective values. The next evaluation uses the patch; a paused page explicitly re-poses the held time without seeking. Clear removes overrides while preserving pending ops and integrated history, and authored values resume at the next evaluation; it does not undo the old trajectory. Apply and model replacement clear the preview. It is labelled "preview — Apply decides" and is never recorded as applied state. Play replays the current standing patch, not historical edits: backward seek recomputes with today's patch, and a newly opened track's first authored pose precedes its pending patch. The readout's BEFORE for the inspected build is that build's own check: once the baseline reproduces, `rig-parts check` runs on the baseline output (byte-identical to the inspected rig) in the background, and its summary is stored beside the baseline record.
32
92
 
@@ -44,7 +104,7 @@ Any future modeling edit needs provenance, undo/redo, explicit units and an expo
44
104
 
45
105
  ## Acceptance progression
46
106
 
47
- 1. Delivery and feedback: one command opens unchanged output; declared assets load; explicit frame/target/category feedback saves and exports; changed source invalidates approval.
107
+ 1. Delivery and feedback: one command opens unchanged output; declared assets load; comments with source-bound inspection context save and export; changed source invalidates approval.
48
108
  2. Runtime inspection: a real gated artifact plays and seeks through the public runtime, survives reference and Inspector section changes and names missing dependencies. Source-only fixtures cannot close this item.
49
109
  3. Modeling touch-up: a bounded real geometry edit round-trips into authoritative source, reruns its gate and presents measured before/after evidence with undo/conflict controls.
50
110
 
@@ -56,9 +116,9 @@ Any future modeling edit needs provenance, undo/redo, explicit units and an expo
56
116
 
57
117
  The single review page is one inspection workspace: a left column, the stage, the Inspector under the stage and one status footer. There is no right panel.
58
118
 
59
- - **Left column.** A fixed header row (Parts title and slot search on one line; the search's name, *Find slot*, is its `aria-label`) and one scrolling body. Nothing sits above the header and it never scrolls. The body holds, in order, the checkpoints/reference strip (current checkpoint title, checkpoints and the reference select, folded into a compact strip that opens when the package supplies checkpoints or references), the part list and browser Settings; it is the column's only scroll container. Settings opens and closes from its own header (`#settings-toggle`, `aria-expanded`, controlling `#settings-body`); it starts collapsed and the state is a browser preference.
119
+ - **Left column.** A fixed header row (Parts title and slot search on one line; the search's name, *Find slot*, is its `aria-label`) and one scrolling body. Nothing sits above the header and it never scrolls. The body holds the reference select, the part list and browser Settings; it is the column's only scroll container. Region coverage and Difference inspection stay in the main view under R3. Settings opens and closes from its own header (`#settings-toggle`, `aria-expanded`, controlling `#settings-body`); it starts collapsed and the state is a browser preference.
60
120
  - **Header.** The **Setup** / **Animate** mode switch sits next to the package title and is the Inspector's only section control: its buttons carry `data-inspector` and `aria-pressed`, and every section change (click, `showInspector` from a part selection or a tool, a restored bookmark) goes through them. On the right, **Write review** (primary) opens the review dialog. The top bar has no feedback export buttons; `rig-review feedback --format json|issue` is the export path.
61
- - **View bar.** The persistent image / mesh edges / bone points layer toggles (keys `I`, `M`, `B`), camera sync and zoom, then the **View** menu (a `<details>` holding Side by side, Reference and Rig, labelled with the effective choice) at the right end, wrapping when the stage is narrow so every control stays in reach. The toggles stay native checkboxes, so their checked state is the pressed state, the draft input and the `layers` control value. A disabled toggle names the footer's layer reason as its tooltip. Turning images off leaves the mesh/bone overlay alone. Appearance lives only in Settings (its Theme select shows the inspection's current appearance and drives it), the per-inspection Repeat idle toggle lives in the Animate transport row, and there is no Copy view link button: the persisted `#review=` fragment stays in the address bar and the numeric region stays behind **View region**.
121
+ - **View bars.** Distinct main and secondary toolbar areas follow R1. Group the persistent image / mesh edges / bone points layer toggles (keys `I`, `M`, `B`), camera sync, zoom and the **View** menu in the owner-ruled layout under R0. The **View** menu remains a `<details>` holding Side by side, Reference and Rig, labelled with the effective choice. Each area wraps when the stage is narrow so every control stays in reach. The toggles stay native checkboxes, so their checked state is the pressed state, the draft input and the `layers` control value. A disabled toggle names the footer's layer reason as its tooltip. Turning images off leaves the mesh/bone overlay alone. Appearance lives only in Settings (its Theme select shows the inspection's current appearance and drives it), the per-inspection Repeat idle toggle lives in the Animate transport row, and there is no Copy view link button: the persisted `#review=` fragment stays in the address bar and the numeric region stays behind **View region**.
62
122
  - **Panel headers and scrolling.** The left column's header is a fixed row outside its scrolling body. The Inspector heading, the Settings title and each drawer's header (title and close) carry `.sticky-header` and are their panel's first child, so the body scrolls beneath them. Every scrolling region shares one thin scrollbar rule on `*` whose colours are the `--rv-scrollbar-*` tokens. Resize separators are drawn 4px with a 16px transparent hit area (22px on coarse pointers) and use `--rv-separator` / `--rv-separator-hover`, never a scrollbar colour.
63
123
  - **Chest-region editor.** In Setup only, the view bar's **Chest regions** toggle (`#chest-edit`, `aria-pressed`) opens `#chest-editor-bar` under the view bar: R / L groups (X, Y, R, Band), Mirror R → L, Download JSON, **Apply · Rebuild** and **Reset**. Apply sends the rows to the installed producer (`rig-parts remesh` on that part, then `rigc build`) through `POST /api/rebuild` (`src/rebuild.ts`, `src/producer.ts`) and loads the compiled scratch build in place; the producer's lines stream into `#chest-editor-status` and `#chest-editor-log`, a refusal shows its first named line verbatim, and Reset returns to the inspected build (README, *Chest regions*). The circles, their centre / core / band handles and labels are drawn on `#rig-overlay` through the crop → world mapping; handle drags (move, r, band) are clamped live with the example rebuild script's non-overlap rule (`CHEST_REGIONS_CLAMPED`) and never move the camera, while other drags and Space-drags pan. The values are the Setup **Chest regions · detail** block's fields, so its draft, export and binding apply unchanged; the block keeps names, bones, semi-axes, clip and the contour. Review builds no mesh: the rebuild is the producer's, into scratch under the state directory, never into the package. A **Circles** / **Landmarks** switch (`#bust-mode`, a hidden input the draft keeps) selects what Apply sends: Landmarks (#105) places the right apex, left apex and cleavage with draggable markers (`#lm-*`), alpha and clearance sliders and optional bone names, draws the producer's derived `bust_r` / `bust_l` live (`src/chest-landmarks.ts`, a transcription of parts' `deriveBustRegions`) and sends `{part, bust, configHash}`; review pre-checks only `CONFIG_BUST_CLEARANCE` and leaves bones and names to the producer.
64
124
  - **Mesh panel.** In Setup, after Chest regions · detail: `#mesh-panel` for the selected mesh part — mode-specific sliders with number fields (`#mesh-params`), regions (`#mesh-regions`; **Add circle**, **Draw polygon** and **Drag on stage** with `aria-pressed`), segments (`#mesh-segments`, bones from the loaded model, ribs stations per chain), the pending diff (`#mesh-diff`), the pre-check (`#mesh-precheck`), **Apply** / **Reset** / **Folds reading**, the status (`#mesh-status`), the counts (`#mesh-counts`) and the `TEXTURE_STRETCH` readout (`#mesh-readout`). Region colours are theme tokens (`--rv-mesh-region`, `--rv-mesh-region-fill`, `--rv-mesh-handle`).
@@ -68,7 +128,7 @@ The single review page is one inspection workspace: a left column, the stage, th
68
128
  - **Cloth.** In Setup, after Cuts: `#cloth-panel` (#111). One form per cloth tag the installed reader accepts (`bottomwear`, `back hair`, `front hair` — its own `CLOTH_TARGETS`), holding the recipe's fields as the config states them; each change is a patch op at `/cloth/<tag>/…` (`src/cloth-recipe.ts`, `web/cloth-panel.ts`). **Show links** draws, in rig px of the setup pose, every chain the tag's parts are meshed on from the config's `points` and `tip`, and after an Apply the chains of the config the producer wrote (one label per set). Apply runs `rig-parts propose --cloth --write-config` on the declared parts, painting and keypoints, then builds the written config (`build` when the config declares `limbs`, else `rig --config`) and reloads it under the stage's Environment. Review never merges the producer's draft: it reads only the written config, lists where it differs from its input and refuses one that differs outside the drafted sections. Hand-editing the drafted constraints is the physics block's, after the draft.
69
129
  - **Mesh edit.** In Setup only, the view bar's **Edit mesh** toggle (`#mesh-edit`, `aria-pressed`) opens `#mesh-editor-bar`: sub-modes Modify / Create / Delete / Edges (keys `V` / `C` / `X` / `E`, one pressed), Undo, Redo, Reset, Download JSON and **Apply · Rebuild** (#135: `rig-parts remesh --delta` through the shared runner, the revision loaded in place, the producer's refusal verbatim; while a delta revision is on the stage Reset returns to the inspected build). A package without the compiled model document refuses `MESH_EDIT_MODEL_UNAVAILABLE` and does not open; whole rig refuses `MESH_EDIT_SELECT_SLOT`; a non-mesh or linked-mesh slot `MESH_EDIT_NO_MESH <slot>`. It edits in setup space (#100): the attachment's stored provenance in the model document (`src/setup-mesh.ts`) and geometry from Play's public `readSetupMesh` (`web/setup-pose.ts`, shared with Weights) and drawn over the paused stage with the stage camera. It records a typed delta (`src/mesh-edit.ts`, `basis: "setup"`, the shape `rig-parts remesh --delta` reads) and previews it over the original triangulation on the overlay; Delete removes only constraint edges the delta added (the triangulation is the producer's); it is not a mesher and never retriangulates, writes the package or runs a producer. The chest editor and mesh edit are exclusive: turning one on turns the other off.
70
130
  - **Inspector.** Two sections and no section tab row: **Setup** is the mesh-review composition (selected part, part presets, the modeling-review proposals for mesh density, contour curvature and chest position) and holds no control that seeks or plays; **Animate** has the transport with the Repeat idle toggle, frame navigation, the motion-review proposals and angle inspection with its axis panel, sound cues and report events. Their element ids and saved section names (`rig`, `playback`) are unchanged. Each section opens with a sticky block row (`.block-row`, `web/inspector-blocks.ts`), a WAI-ARIA tablist: Setup — Part · Modeling · Chest · Mesh · Weights · Bones · Fields · Cuts · Cloth; Animate — Transport (the motion tools and the angle panel) · Sound · Environment · Physics · Idle tracks · Readings · Requirements · Retarget · Report, in document order. Animate's timeline is its own panel beside the blocks, not a tab. Each `role=tab` button controls the `role=tabpanel` block it names: selecting it shows that block alone and hides the others (`hidden`; a block a tab carries, such as the angle panel, by `data-block-hidden`, so its own `hidden` stays its own), and nothing scrolls between blocks. Arrow keys, Home and End move between tabs and select as they go. Hiding writes nothing inside a block, so drafts, pending edits and stage overlays such as the chest editor's are kept while their tab is hidden, and each block keeps its own scroll offset for the session. The row is one line that scrolls sideways when narrow. The active tab per section is the only thing the row adds to the inspection draft (`ui.inspectorBlocks`); the section's scroll offset stays with the Inspector scroll memory, and the control protocol and saved-view link are unchanged. A saved `view` or `feedback` section from older links and drafts restores without selecting a section or opening the dialog.
71
- - **Review dialog.** A native modal `<dialog id="review-dialog">` holds the former Feedback section unchanged (review status, reviewed source with the read-only source-file list, selected checkpoint, structured feedback, frame-strip export; every element id kept) and the **Submit review** button (`#save`). **Write review**, a part's or a proposal tool's Add feedback opens it with `showModal()` and pauses playback; Escape or Close dismisses it and focus returns to **Write review**. Its inputs stay in the document while it is closed, so the draft mechanism (autosave, recovery, conflict handling) is unchanged and closing loses nothing. The modal makes the rest of the page inert, so the dialog repeats the footer's message and draft state in its own status line; the footer keeps reporting both.
131
+ - **Review dialog.** A native modal `<dialog id="review-dialog">` holds the review status, reviewed source with the read-only source-file list, the comments feature under R2, frame-strip export and the **Submit review** button (`#save`). **Write review** opens it with `showModal()` and pauses playback; Escape or Close dismisses it and focus returns to **Write review**. Comment drafts stay in the document while the dialog is closed, with source-bound autosave, recovery and conflict handling. The modal makes the rest of the page inert, so the dialog repeats the footer's message and draft state in its own status line; the footer keeps reporting both.
72
132
  - **Footer.** Message (truncated, full text as tooltip) on the left; player, effective layout, renderer, layers, idle, remote control and draft state in the middle; the numeric view region (behind **View region**) and the source hash on the right. The View region body is a `position:fixed` popover above the 40px footer, right-aligned, its width and height clamped to the viewport and its content scrolling inside, so the footer's clipping never hides it and opening it never scrolls the page.
73
133
 
74
134
  The compare page keeps its own markup and stylesheet: sources left, Parts explorer right, its four Inspector sections, its export buttons and its separator colour. It shares the workspace coordinator, so its separators are drawn at the same 4px.
@@ -1360,3 +1360,184 @@ with the earlier closed key set refuse evidence-bearing sources. New consumers
1360
1360
  require the signed extended contract. Owner-screen integration,
1361
1361
  EN/KO visual verification and later release serving have their own acceptance
1362
1362
  steps.
1363
+
1364
+ ### Sealed plan step text
1365
+
1366
+ Both publication-pinned `api/review` responses append delivery-only `planText`
1367
+ when the accepted source has a plan. The daemon authenticates `project.json`
1368
+ from that publication's retained snapshot against its record seal and existing
1369
+ `projectHash`, then projects `does`, `produces`, `bar` and `rests_on`.
1370
+
1371
+ The projected envelope has ordered keys `schema`, `record`, `status`, `steps`.
1372
+ `schema` is `rig-review/job-plan-text@1`, `record` is `{path:"project.json",sha256}`,
1373
+ and `status` is `projected`. Rows follow the accepted plan's exact id/hash order.
1374
+ Each row has `id`, `hash`, optional `does`, `produces`, `bar`, `rests_on`, then
1375
+ `issues`. Each field supplies exactly one value or an ordered
1376
+ `{field,reason:"absent"|"invalid"|"limit"}` issue. Scalar values are strings and
1377
+ `rests_on` is an ordered string array. Empty strings/arrays, whitespace, line
1378
+ endings, Unicode form, duplicate references and array order are preserved.
1379
+ Producer extras stay outside this display projection.
1380
+
1381
+ D1 matches only accepted ids, preserving source order and existing checkpoint
1382
+ aliases (`planStepId ?? checkpointId`). D2 retains its existing whole-plan
1383
+ count/ordered-id admission checks. Hashes are the producer's opaque accepted
1384
+ identities. The existing reader retains responsibility for their semantic value.
1385
+
1386
+ The unavailable envelope has `schema`, `record` (or null),
1387
+ `status:"unavailable"`, `reason`. Named reasons are
1388
+ `PLAN_TEXT_RECORD_UNAVAILABLE`, `PLAN_TEXT_RECORD_UNSUPPORTED`,
1389
+ `PLAN_TEXT_STEPS_ABSENT`, `PLAN_TEXT_STEPS_INVALID`,
1390
+ `PLAN_TEXT_MAPPING_UNAVAILABLE` and `PLAN_TEXT_LIMIT`. The UI shows the named
1391
+ absence and existing ids/hashes. Partial valid fields remain visible beside
1392
+ their missing/invalid field labels. Existing act authority and historical
1393
+ metadata omission retain their fallback behavior.
1394
+
1395
+ The server retains its 8 MiB project read bound. Display limits are 4,096 plan
1396
+ steps, 4,096 `rests_on` entries and 512 KiB UTF-8 for `planText`. Whole owner
1397
+ metadata retains its 2 MiB bound. A small unavailable envelope replaces an
1398
+ oversized projection. If that envelope also exceeds the response budget, the
1399
+ server returns `JOB_BODY_LIMIT` with `PLAN_TEXT_LIMIT`. Values remain complete
1400
+ within the admitted display budget.
1401
+
1402
+ The browser checks the closed grammar, metadata/source association, record SHA
1403
+ and ordered id/hash mapping. Field values have the normal daemon's authority.
1404
+ Type-valid post-server text mutation can pass those checks. The server's sealed
1405
+ record authentication and the browser's source/grammar checks are their
1406
+ respective validation boundaries. Checkpoint evidence retains its established
1407
+ raw-member authentication.
1408
+
1409
+ This metadata is produced at response time. Source/act schemas, producer reader
1410
+ DTOs, stable `job-host` exports, durable state and canonical hash preimages retain
1411
+ their existing definitions. Checkpoint and signoff values continue through their
1412
+ existing forms, outcome select and submission lifecycle.
1413
+
1414
+ Under HQ ruling 7896ec71, the official D2 consumer gate is the supported
1415
+ record-checkpoint flow following Create #395 integration. Create owns the actual
1416
+ producer receipt. Review's plan-signoff rendering has synthetic UI coverage.
1417
+ Normal CLI plan-signoff bootstrap and `plan-approved` act@4 ingestion are a
1418
+ separate Create follow-up. (Naru, 2026-11-11)
1419
+
1420
+ ## Comments decoder contract
1421
+
1422
+ The comments feature accepts multiple ordered entries, each general or pinned to
1423
+ an existing inspection target. Surveys remain separate answer inputs: interview
1424
+ selections, inline Other text and per-question notes keep their existing formats,
1425
+ strings and readers. There is no interview-picks arm or question/ask anchor in
1426
+ this extension. Technical configuration and search controls are outside it.
1427
+
1428
+ This change prepares read-only decoders and consumer projections. Current UI
1429
+ finalizers, standalone save paths and legacy act unions keep their existing
1430
+ versions. Fresh comments writers stay off until Create #422 is merged to main,
1431
+ its actual runner receipt records source SHA, installation, imports from the
1432
+ Review facade, normal @6 ingest/replay and command exits, and HQ reads that
1433
+ receipt. Create consumes private source; registry publication and Create
1434
+ version/workflow changes are not part of this gate. Owner review of the working
1435
+ screen remains required before UI merge.
1436
+
1437
+ The existing `@rig-c/review/job-host` facade exports:
1438
+
1439
+ | Function | Input → output |
1440
+ | --- | --- |
1441
+ | `parseCommentsAct` | `unknown` → `JobCommentsAct` |
1442
+ | `projectComments` | `readonly JobComment[]` → `string` |
1443
+ | `parseCommentsSession` | `unknown` → `ReviewCommentsSession` |
1444
+ | `parseCommentsCompareSession` | `unknown` → `CompareCommentsSession` |
1445
+ | `parseCommentsPartsVerdict` | `unknown` → `PartsCommentsVerdict` |
1446
+ | `projectSelectedCommentsFeedback` | `ReviewCommentsSession, itemId: string` → `{anchor: JobCommentFeedbackAnchor; summary: string}` |
1447
+
1448
+ Use a decoder before projecting untrusted input. These functions perform no
1449
+ filesystem writes. Decode success validates declared identities and syntax; it
1450
+ does not grant producer/source-kind admission or prove retained asset freshness,
1451
+ source-native pixels, clock availability or owner authority. Those checks stay
1452
+ with the existing retained-source, package feedback and crop pipeline. The
1453
+ native-image region preparation adapter is still required before image-region
1454
+ writers activate.
1455
+
1456
+ `JOB_COMMENTS_ACT_SCHEMA` is `rig-review/act@6`. Its exact envelope keys are
1457
+ `schema, actId, jobId, askId, publicationId, kind, authority, at, source, value`.
1458
+ The existing top-level `still` is required only for a model `rig-review` verdict
1459
+ and forbidden otherwise. It retains fixed camera, content-addressed PNG path,
1460
+ SHA-256 and setup-or-numeric-animation-time validation. The raw export and CLI
1461
+ reuse their existing PNG byte checks and preserve original act stdout bytes.
1462
+ The authority remains daemon-owned human `review-ui` authority. Model/image
1463
+ bindings and record plan sources retain their existing definitions; record
1464
+ option-set sources are excluded. Source capabilities remain consumer-owned.
1465
+
1466
+ | Kind | Exact value keys |
1467
+ | --- | --- |
1468
+ | `checkpoint` | `checkpointId, planStepId, outcome, comments` (`pass` or `fail`) |
1469
+ | `parts-verdict` | `verdict, comments` (`approved` or `changes-requested`) |
1470
+ | `review-verdict` | `stage, verdict, comments` (existing rig/direction/image stages and verdicts) |
1471
+ | `signoff` | `stage, decision, comments` (`approved`) |
1472
+ | `reopen` | `stage, comments` (existing declared record plan subject) |
1473
+
1474
+ The declared plan/source/selector and ask eligibility checks remain applicable.
1475
+ The browser never supplies authoritative checkpoint-to-plan mapping. A Parts
1476
+ verdict is approved exactly when it has no pointed Parts issue anchors; general
1477
+ comments do not create issues. Verdict and signoff remain distinct immutable
1478
+ acts even when one user action will submit the same comments to both.
1479
+
1480
+ A `comments` array has at most 1,000 entries. Each entry has exactly `text` and
1481
+ optional `anchor`. Fresh text is a nonblank string of at most 10,000 UTF-16 units;
1482
+ trimming is a validation predicate and never changes the stored text. Reusing a
1483
+ Feedback or Parts codec preserves its stricter existing text limit. Existing
1484
+ evidence IDs stay unique. Intentional duplicate text and stored order remain.
1485
+ Unknown fields and mixed anchor arms refuse.
1486
+
1487
+ Anchors use existing source-bound fields without a new kind discriminator:
1488
+
1489
+ - Feedback without `summary`: `id, frameStart, frameEnd, target, category`, with
1490
+ optional `context` and compare-only `side`. StageComment remains inside
1491
+ `context.comment`; existing codecs and inline PNG validation are reused.
1492
+ - PartsIssue without `summary`: `schema, id, parts, sourceHash, rigRegion,
1493
+ imageRegion, view, crop, nativeCrop`. Finalized item anchors require prepared
1494
+ native crop metadata. Assembled anchors retain null native crop.
1495
+ - Named image: `name`, optionally the complete existing-field composition
1496
+ `imageRegion, crop, nativeCrop`. Names resolve in the sealed image set. Regions
1497
+ use nonnegative native-pixel integer origins, positive extents and at most
1498
+ 16,777,216 pixels. Actual image bounds and crop-to-original equality remain
1499
+ native preparation checks.
1500
+ - Checkpoint: `checkpointId, planStepId`, resolved through the existing source
1501
+ plan and any declared evidence mapping.
1502
+
1503
+ `projectComments` traverses stored order. Each scalar block is
1504
+ `[label]\n` followed by exact `text`, with `\n\n` between blocks; the empty array
1505
+ projects to the empty string. The complete scalar is bounded to 10,000 UTF-16
1506
+ units. Lists retain individual entries. A general label is `general`; other
1507
+ labels are `JSON.stringify` of these logical target tuples:
1508
+
1509
+ | Anchor | Label tuple |
1510
+ | --- | --- |
1511
+ | Checkpoint | `["checkpoint", checkpointId]` |
1512
+ | Parts | `[schema, parts.map(part => part.name), view.mode]` |
1513
+ | Image | `[name]` |
1514
+ | StageComment-backed Feedback | `[mark.schema, mark.mode, mark.viewport, target.kind, target.name, frameStart, frameEnd]` |
1515
+ | Other Feedback | `[target.kind, target.name, frameStart, frameEnd, side ?? null]` |
1516
+
1517
+ Capture IDs, hashes and crop bytes stay in the raw anchor and do not enter the
1518
+ logical label. This keeps wording stable when a later Apply recaptures the same
1519
+ target. Consumer projection never serializes a synthetic historical act/session.
1520
+
1521
+ The standalone schema constants are `REVIEW_COMMENTS_SESSION_SCHEMA` =
1522
+ `rig-review-session/2`, `REVIEW_COMMENTS_COMPARE_SESSION_SCHEMA` =
1523
+ `rig-review-compare-session/2`, and `PARTS_COMMENTS_VERDICT_SCHEMA` =
1524
+ `rig-review-parts-verdict/5`. Session/2 replaces `feedback` with `comments` and
1525
+ checkpoint note entries with outcome-only entries. Compare/2 replaces `feedback`
1526
+ with `comments`, requires an explicit side on Feedback anchors and checks its
1527
+ existing binding hash. Parts/5 replaces `issues` with `comments`, deriving the
1528
+ issue relation from Parts anchors. Other existing envelope/provenance fields
1529
+ remain. `projectSelectedCommentsFeedback` selects exactly one Feedback
1530
+ `anchor.id` and returns that anchor plus the scalar projection of its entry for
1531
+ existing correction-writer arguments. The original new-session stdout remains
1532
+ the immutable evidence.
1533
+
1534
+ Historical @2–@5 acts, session/1, compare-session/1, Parts/4 and survey records
1535
+ stay on their original readers, raw bytes, hashes, stills and replay paths.
1536
+ Display adaptation of old user feedback creates one general comment per existing
1537
+ summary/note/words field, including empty strings; it never rewrites history or
1538
+ reclassifies survey answers. Legacy correction summaries remain literal. Create's
1539
+ old Parts names projection gives a present `issues[]` precedence even for /1-/2;
1540
+ only absent `issues[]` uses `part.note`. Literal-byte controls and all eighteen
1541
+ cross-repository oracle outcomes belong in the PR evidence. Parser-only native
1542
+ coverage does not substitute for Create's actual ingest/replay receipt or owner
1543
+ working-screen review.
package/docs/STABILITY.md CHANGED
@@ -563,6 +563,11 @@ model binding nor a valid image-set binding uses `JOB_ASK_INVALID`.
563
563
 
564
564
  The backend rig-still extension retains the original twelve runtime exports and `JOB_ACT_SCHEMA` at act@2. `JobAct` additionally includes `JobRigReviewAct` at act@3 with top-level `JobRigStill` and `JobPartsVerdictAct` at act@5 (`PartsVerdictValue` with pointed `issues` and `words`, while preserving `JobLegacyPartsVerdictValue` at act@2 for historical acts). The facade adds type-only `JobLegacyAct`, `JobRigReviewAct`, `JobPartsVerdictAct`, `JobLegacyPartsVerdictValue`, `PartsVerdictValue`, `JobPanelComposition`, `PanelComponent`, `JobRigStill` and `JobRigCapture` exports, [Review #563](https://github.com/rig-c/review/issues/563) adds five type-only exports (`JobHostListenerIncarnation`, `JobHostReuseBinding`, `JobHostReuseExpectation`, `JobHostAttachField` and `JobHostAttachFailure`), and [Review #555](https://github.com/rig-c/review/issues/555) adds four type-only interview diagnostic exports (`JobInterviewJson`, `JobInterviewRecord`, `JobInterviewDiagnostic` and `JobInterviewDiagnostics`). [Review #588](https://github.com/rig-c/review/issues/588) activates record mode when `readRecordPublished` and `recordReaderId` are supplied to a host or session (`publicationMode: 'record-and-package'`), serving `rig-review/job-api@3` (`JOB_API_V3_SCHEMA`), `rig-review/act@4` (`JOB_RECORD_ACT_SCHEMA`) and normal owner URL model-free record inspection while keeping default package-only hosts and exact `package-only` `job-ui/<jobId>.json` descriptor bytes at @2 and enforcing `publicationMode` / `recordReaderId` reuse compatibility across ordinary reuse and strict `reuseOnly` attachment. It exports six additional record-mode runtime symbols (`JOB_API_V3_SCHEMA`, `JOB_RECORD_ACT_SCHEMA`, `JOB_RECORD_READER_ID`, `parseRecordAct`, `prepareJobRecordAct` and `prepareJobRecordSource`, for eighteen runtime exports total) and the V3/record type surface listed below. The rig and parts-verdict act revision constants, transport limits and the internal `POST /jobs/<jobId>/host` helper remain internal to their modules. Consumer checks distinguish these act revisions as described in [Rig verdict still backend](REVIEW_PACKAGE.md#rig-verdict-still-backend) and [Model-free record mode and source seam](REVIEW_PACKAGE.md#model-free-record-mode-and-source-seam).
565
565
 
566
+ The comments decoder extension adds six functions and four schema constants,
567
+ for twenty-eight runtime exports total. It is a read-only contract preparation;
568
+ the existing UI finalizers and legacy type unions retain their current versions.
569
+ See [Comments decoder contract](REVIEW_PACKAGE.md#comments-decoder-contract).
570
+
566
571
  The exact runtime exports are listed below. Constants preserve their literal
567
572
  values from the frozen semantic contract.
568
573
 
@@ -572,6 +577,16 @@ values from the frozen semantic contract.
572
577
  - `parseRecordAct`
573
578
  - `prepareJobRecordAct`
574
579
  - `prepareJobRecordSource`
580
+ - `parseCommentsAct`
581
+ - `projectComments`
582
+ - `parseCommentsSession`
583
+ - `parseCommentsCompareSession`
584
+ - `parseCommentsPartsVerdict`
585
+ - `projectSelectedCommentsFeedback`
586
+ - `JOB_COMMENTS_ACT_SCHEMA`
587
+ - `REVIEW_COMMENTS_SESSION_SCHEMA`
588
+ - `REVIEW_COMMENTS_COMPARE_SESSION_SCHEMA`
589
+ - `PARTS_COMMENTS_VERDICT_SCHEMA`
575
590
  - `JOB_CAPABILITIES`
576
591
  - `JOB_API_SCHEMA`
577
592
  - `JOB_API_V3_SCHEMA`
@@ -734,6 +749,16 @@ without aliases or copied wire shapes.
734
749
  - `JobRetainedSource`
735
750
  - `JobRetainedSourceV3`
736
751
  - `JobRootIdentity`
752
+ - `JobComment`
753
+ - `JobCommentAnchor`
754
+ - `JobCommentFeedbackAnchor`
755
+ - `JobCommentPartsAnchor`
756
+ - `JobCommentImageAnchor`
757
+ - `JobCommentsAct`
758
+ - `JobCommentsActValues`
759
+ - `ReviewCommentsSession`
760
+ - `CompareCommentsSession`
761
+ - `PartsCommentsVerdict`
737
762
 
738
763
  ## Parts enumeration boundary
739
764
 
@@ -746,11 +771,11 @@ Rows are capped at 4096, roles at 128 UTF-16 code units and literal paths at 409
746
771
  ## Installed acceptance
747
772
 
748
773
  `bun run smoke` packs the package and installs that tarball into an empty project.
749
- A consumer imports the eighteen runtime exports and every listed type, including
774
+ A consumer checks the twenty-eight runtime exports and every listed type, including
750
775
  `JobHostListenerIncarnation`, `JobHostReuseBinding`, `JobHostReuseExpectation`,
751
776
  `JobHostAttachField`, `JobHostAttachFailure`, `JobInterviewJson`,
752
777
  `JobInterviewRecord`, `JobInterviewDiagnostic`, `JobInterviewDiagnostics` and
753
- the record-mode `JobRecordAct` / `JobActV3` / `JobPlanSource` /
778
+ the comments decoder types and the record-mode `JobRecordAct` / `JobActV3` / `JobPlanSource` /
754
779
  `JobFetchActRequestV3` / `JobRecordHostHooks` surface, through `@rig-c/review/job-host`.
755
780
  TypeScript checks the installed consumer and the runtime checks the full owner
756
781
  resources, retained publication, semantic ports, declared hooks, enumerator
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/review",
3
- "version": "2.10.0",
3
+ "version": "2.12.0",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -9,9 +9,14 @@ import {parseStageComment,hasStageComment} from './stage-comment.ts';
9
9
  import type {Feedback} from './session.ts';
10
10
  export interface PngCrop {path:string;sha256:string;png:string;width:number;height:number}
11
11
  export function validateCommentCrop(value:unknown):Buffer {return validatePngCrop(parseStageComment(value).crop);}
12
+ /** Shared metadata boundary for sealed records with no inline PNG bytes. Callers own closed keys. */
13
+ export function validatePngCropMetadata(crop:Omit<PngCrop,'png'>):void {
14
+ if(!crop||!Number.isSafeInteger(crop.width)||!Number.isSafeInteger(crop.height)||crop.width<1||crop.height<1||crop.width>16384||crop.height>16384||crop.width*crop.height>16777216||!/^[a-f0-9]{64}$/.test(crop.sha256)||crop.path!==`comment-crops/${crop.sha256}.png`)throw new Error('COMMENT_CROP_INVALID: bounded content-addressed PNG required');
15
+ }
12
16
  /** Shared bounded PNG validator; callers own their closed comment codecs. */
13
17
  export function validatePngCrop(crop:PngCrop):Buffer {
14
- if(!crop||!Number.isSafeInteger(crop.width)||!Number.isSafeInteger(crop.height)||crop.width<1||crop.height<1||crop.width>16384||crop.height>16384||crop.width*crop.height>16777216||typeof crop.png!=='string'||crop.png.length>90*1024*1024||!/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(crop.png)||!/^[a-f0-9]{64}$/.test(crop.sha256)||crop.path!==`comment-crops/${crop.sha256}.png`)throw new Error('COMMENT_CROP_INVALID: bounded content-addressed PNG required');
18
+ validatePngCropMetadata(crop);
19
+ if(typeof crop.png!=='string'||crop.png.length>90*1024*1024||!/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(crop.png))throw new Error('COMMENT_CROP_INVALID: bounded content-addressed PNG required');
15
20
  const bytes=Buffer.from(crop.png.slice('data:image/png;base64,'.length),'base64');
16
21
  if(createHash('sha256').update(bytes).digest('hex')!==crop.sha256)throw new Error('COMMENT_CROP_INVALID: PNG signature, dimensions or SHA-256 differ');
17
22
  return validatePngBytes(bytes,crop.width,crop.height);
@@ -1,4 +1,6 @@
1
- import {hasStageComment} from './stage-comment.ts';
1
+ import {hasStageComment, parseStageComment} from './stage-comment.ts';
2
+ import {commentsObject, jobSha, parseComments} from './job-api.ts';
3
+ import {REVIEW_COMMENTS_COMPARE_SESSION_SCHEMA, type CompareCommentsSession} from './job-contract.ts';
2
4
  import {parseBookmark} from '../web/inspection-persistence.ts';
3
5
  import {saveCommentCrops,assertSubmittedComments} from './comment-crops.ts';
4
6
  import {sharedTurnDials} from './turn-pad.ts';
@@ -7,12 +9,48 @@ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
7
9
  import { join } from 'node:path';
8
10
  import { homedir } from 'node:os';
9
11
  import { isDeepStrictEqual } from 'node:util';
10
- import { choice, object } from './manifest.ts';
11
- import { parseFeedback, readPackageFeedback, validatePackageFeedback, type FeedbackWarning, type Feedback } from './session.ts';
12
+ import { choice, object, string } from './manifest.ts';
13
+ import { parseFeedback, readPackageFeedback, validatePackageFeedback, parseCommentsReviewedSource, parseCommentsWarnings, type FeedbackWarning, type Feedback } from './session.ts';
12
14
  import { assertCompareUnchanged, type CompareBinding, type ComparePackage } from './compare.ts';
13
15
 
14
16
  export interface CompareFeedback extends Feedback {side:'a'|'b'}
15
17
  export interface CompareSession {schema:'rig-review-compare-session/1';id:string;revision:'compare/1';sourceHash:string;binding:CompareBinding;status:'pending'|'approved'|'changes-requested';feedback:CompareFeedback[];feedbackWarnings:FeedbackWarning[];updatedAt:string|null}
18
+
19
+ /** Read-only compare/2 decoder; each feedback anchor keeps its explicit side. */
20
+ export function parseCommentsCompareSession(value: unknown): CompareCommentsSession {
21
+ const raw = commentsObject(value, ['schema', 'id', 'revision', 'sourceHash', 'binding', 'status', 'comments', 'feedbackWarnings', 'updatedAt']);
22
+ if (raw.schema !== REVIEW_COMMENTS_COMPARE_SESSION_SCHEMA || raw.revision !== 'compare/1') throw new Error('JOB_ACT_INVALID');
23
+ string(raw.id, 'compare.id'); jobSha(raw.sourceHash);
24
+ choice(raw.status, ['pending', 'approved', 'changes-requested'], 'compare.status');
25
+ const binding = commentsObject(raw.binding, ['a', 'b', 'reference', 'animation']);
26
+ for (const side of ['a', 'b']) {
27
+ const row = commentsObject(binding[side], ['sourceHash', 'reviewedSource']);
28
+ jobSha(row.sourceHash); parseCommentsReviewedSource(row.reviewedSource);
29
+ }
30
+ const reference = commentsObject(binding.reference, ['name', 'sha256']);
31
+ string(reference.name, 'compare.reference.name'); jobSha(reference.sha256); string(binding.animation, 'compare.animation');
32
+ if (createHash('sha256').update(JSON.stringify(binding)).digest('hex') !== raw.sourceHash) throw new Error('JOB_ACT_INVALID');
33
+ const comments = parseComments(raw.comments);
34
+ for (const comment of comments) {
35
+ const anchor = comment.anchor;
36
+ if (!anchor) continue;
37
+ if (!('frameStart' in anchor) || !('side' in anchor)) throw new Error('JOB_ACT_INVALID');
38
+ const context = anchor.context as Record<string, unknown> | undefined;
39
+ if (hasStageComment(context?.comment)) {
40
+ const mark = parseStageComment(context!.comment);
41
+ const a = binding.a as CompareBinding['a'], b = binding.b as CompareBinding['b'];
42
+ parseBookmark(mark.bookmark, {mode: 'compare', sourceHash: raw.sourceHash as string,
43
+ rigs: [a.reviewedSource.rig?.sha256 ?? null, b.reviewedSource.rig?.sha256 ?? null]});
44
+ if (mark.sourceHash !== raw.sourceHash || mark.referenceHash !== reference.sha256 ||
45
+ mark.viewport !== 'reference' && mark.viewport !== anchor.side ||
46
+ mark.modelHash !== (mark.viewport === 'reference' ? null : (anchor.side === 'a' ? a : b).reviewedSource.rig?.sha256 ?? null)) throw new Error('JOB_ACT_INVALID');
47
+ }
48
+ }
49
+ parseCommentsWarnings(raw.feedbackWarnings);
50
+ if (raw.updatedAt !== null &&
51
+ (typeof raw.updatedAt !== 'string' || !Number.isFinite(Date.parse(raw.updatedAt)))) throw new Error('JOB_ACT_INVALID');
52
+ return {...structuredClone(raw), comments} as unknown as CompareCommentsSession;
53
+ }
16
54
  export function freshCompareSession(p:ComparePackage):CompareSession {const d=p.response;return {schema:'rig-review-compare-session/1',id:d.id,revision:d.revision,sourceHash:d.sourceHash,binding:d.binding,status:'pending',feedback:[],feedbackWarnings:[],updatedAt:null};}
17
55
  export function parseCompareSession(input:unknown,p:ComparePackage,strict=true):CompareSession {
18
56
  const value=object(input,'compare session'),fresh=freshCompareSession(p);
@@ -9,6 +9,25 @@ import { environmentSummary, parseEnvironmentContext } from './environment.ts';
9
9
  import { appliedSummary } from './applied-context.ts';
10
10
  import { requirementsSummaryLine } from './requirements.ts';
11
11
  import { scheduleContextLine } from './environment-schedule.ts';
12
+ import {parseCommentsSession} from './session.ts';
13
+ import {projectComments} from './stage-comment.ts';
14
+ import type {ReviewCommentsSession, JobCommentFeedbackAnchor} from './job-contract.ts';
15
+
16
+ /** A display view over explicitly selected legacy feedback fields, including empty strings. */
17
+ export function legacyFeedbackComments(fields: readonly string[]): {text: string}[] {
18
+ if (!Array.isArray(fields) || fields.some(value => typeof value !== 'string')) throw new Error('JOB_ACT_INVALID');
19
+ return fields.map(text => ({text}));
20
+ }
21
+
22
+ /** Pure adapter arguments. The source session/2 bytes stay in the consumer's receipt. */
23
+ export function projectSelectedCommentsFeedback(session: ReviewCommentsSession, itemId: string): {
24
+ anchor: JobCommentFeedbackAnchor; summary: string;
25
+ } {
26
+ const parsed = parseCommentsSession(session);
27
+ const matches = parsed.comments.filter(comment => comment.anchor && 'frameStart' in comment.anchor && comment.anchor.id === itemId);
28
+ if (matches.length !== 1) throw new Error('JOB_ACT_INVALID');
29
+ return {anchor: matches[0]!.anchor as JobCommentFeedbackAnchor, summary: projectComments(matches)};
30
+ }
12
31
  type Category = Feedback['category'];
13
32
  type Side = 'single' | 'a' | 'b';
14
33
  type ParsedFeedbackSession = FeedbackHistory<ReviewSession | CompareSession>;