rig-review 2.7.0 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/PANELS.md CHANGED
@@ -371,7 +371,7 @@ Hit-testing is in screen pixels through the current camera: a vertex within 6 px
371
371
 
372
372
  Everything is a typed delta over the loaded mesh, in setup-pose crop pixels of the rig canvas (x right, y down, the chest regions' crop mapping): `{schema:"rig-review-mesh-edit/1", slot, skin, attachment, source:{vertexCount, triangleCount, hullLength, hash}, units, basis:"setup", preview, ops}` with ordered ops `move {v, from, to}`, `add {at, onEdge?}`, `remove {v}`, `edge {a, b}` and `unedge {a, b}`. Source vertex ids are the attachment's indices; an added vertex takes the next id; a removed id is never reused. `hullLength` is the model's `hull` (the first `hull` vertices, in order, are the hull) and `hash` is the SHA-256 of `JSON.stringify` of the attachment's entry in the hash-verified model document. Source positions are not rounded (a `move`'s `from` is the vertex's exact setup position; `to` and `add.at` are rounded to 0.01 px). This is the input `rig-parts remesh --delta` reads as it is (see [docs/REVIEW_PACKAGE.md](REVIEW_PACKAGE.md#mesh-edit-export)); the former last-drawn-pose basis is gone. The overlay previews moved, added and removed vertices and the constraint edges over the original triangulation; nothing is retriangulated in the browser (the status line says *preview only — the producer retriangulates*).
373
373
 
374
- **Download JSON** saves `mesh-edit.json` and `mesh-edit.binding.json` (package source hash, rig and motion SHA-256, the attachment and its hash, export time, viewer and runtime versions and the mapping). **Apply · Rebuild** (#135) sends the delta to the installed producer as `POST /api/rebuild {part, delta, configHash}`: the server writes it as `mesh-edit.json` (the download's bytes) into the scratch directory and runs `rig-parts remesh --rig <handoff rig> --config <handoff config> --parts <handoff parts> --part <part> --delta mesh-edit.json --out rig`, then the shared tail (per-file diff, compile with remesh.json's pack flags, hash). The producer must read `--delta` (`@rig-c/parts` 1.43.0 or later, read from its own `package.json`), else `MODELING_PRODUCER_TOO_OLD <found> 1.43.0`. The delta's schema, basis, source counts and `source.hash` and every op are the producer's judgment: its `REMESH_DELTA_*` / `REMESH_*` line comes back verbatim and the stage keeps its model. A built revision loads in place and the editor re-reads that revision's setup mesh; `context.applied` becomes `rig-review-applied/3` (the delta by content, `deltaSha256` of its bytes, the producer's line, `op: "remesh"`, the per-file diff and the part's counts). While the revision is on the stage, Reset returns to the inspected build and the draft's delta is restored over it. A delta drawn over the revision's mesh is refused by the producer (`REMESH_DELTA_SOURCE`): its input is always the handoff rig. The delta rides in the inspection's local draft bound to the attachment hash (at most 300 ops per attachment); it never enters the review session and nothing is written into the package.
374
+ **Download JSON** saves `mesh-edit.json` and `mesh-edit.binding.json` (package source hash, rig and motion SHA-256, the attachment and its hash, export time, viewer and runtime versions and the mapping). **Apply · Rebuild** (#135) sends the delta to the installed producer as `POST /api/rebuild {part, delta, configHash}`: the server writes it as `mesh-edit.json` (the download's bytes) into the scratch directory and runs `rig-parts remesh --rig <handoff rig> --config <handoff config> --parts <handoff parts> --part <part> --delta mesh-edit.json --out rig`, then the shared tail (per-file diff, compile with remesh.json's pack flags, hash). The producer must read `--delta` (`@rig-c/parts` 1.43.0 or later, read from its own `package.json`), else `MODELING_PRODUCER_TOO_OLD <found> 1.43.0`. The delta's schema, basis, source counts and `source.hash` and every op are the producer's judgment: its `REMESH_DELTA_*` / `REMESH_*` line comes back verbatim and the stage keeps its model. A built revision loads in place and the editor re-reads that revision's setup mesh; `context.applied` becomes `rig-review-applied/3` (the delta by content, `deltaSha256` of its bytes, the producer's line, `op: "remesh"`, the per-file diff and the part's counts). While the revision is on the stage, Reset returns to the inspected build and the draft's delta is restored over it. In a joined draft, Apply on a displayed scratch revision refuses with `MESH_DELTA_APPLIED_SOURCE`. Export the delta and rebuild the prior revision, including any Mesh Parameters patch, first. Reset returns to the inspected draft and allows a fresh delta. Review refuses a legacy request with the same code when its attachment matches retained scratch geometry and differs from the inspected attachment. Other deltas still go to the producer for validation. The delta rides in the inspection's local draft bound to the attachment hash (at most 300 ops per attachment); it never enters the review session and nothing is written into the package.
375
375
 
376
376
  For inspection automation, `window.rigReviewEditor.meshEdit()` returns the open editor's source (setup-pose crop px per vertex, unrounded), its ops and each drawn vertex as page client pixels, or `null` when the editor is closed; it reads only.
377
377
 
@@ -444,6 +444,8 @@ Correction-record export is unfinished, blocked on review#369/create#91. Existin
444
444
  comments and feedback preserve reviewer wording, but are not a substitute for
445
445
  that shared export or for create-owned structure decisions.
446
446
 
447
+ When `--project` and `--project-draft` select a recorded Create draft that declares its `config`, `parts`, `rig` and `check` directories, Stage 1 also enables the mesh correction instruments before a rig version exists while the draft is editable (`parts` or `parts-review` stage without an effective `parts-review` sign-off, and not `--view-only`). The status bar reports the recorded draft producer version as provenance alongside the installed producer and compiler versions; Apply runs the installed producer and compiler resolved by `resolveProducer` and its operation-capability floors (`REMESH_SINCE` and `REMESH_DELTA_SINCE`, plus `EDIT_PRODUCER_MISMATCH` if a patch's `producer` differs from the installed producer), without an equality version gate against the recorded draft producer. Opening an instrument switches to the Setup inspector for that mesh correction, while direct Stage 3 navigation stays refused with `RIG_VERSION_UNAVAILABLE`. When the project stage is outside `parts`/`parts-review`, an effective `parts-review` sign-off is already recorded, or `--view-only` is set, Stage 1 remains inspection-only (`draft.inspectionOnly: true`) and hides the correction instruments; omitting `--parts-verdict-dir` or viewing an applied scratch build keeps the Stage 1 parts verdict save/export controls read-only (`PARTS_VERDICT_READ_ONLY`) while leaving the correction instruments available on an editable draft.
448
+
447
449
  ### Declared-grid Difference
448
450
 
449
451
  **Difference** in an individual part view reads the optional producer declaration
@@ -159,7 +159,7 @@ An Apply rebuilds through the installed producer from the files the inspected ri
159
159
 
160
160
  Without `--parts` the parts directory is `out/` beside the config (for step 4, the opened `out/` itself; for step 5, the build root). A declared or discovered path that is missing, outside its root (the package root; for step 4 the folder holding `out/`; for step 5 the config's folder), or a symlink that leaves it is refused by name: `HANDOFF_PATH_OUTSIDE_ROOT`, `HANDOFF_SYMLINK_ESCAPE`, `HANDOFF_INPUT_MISSING`, `HANDOFF_INPUT_INVALID`, `HANDOFF_PATH_INVALID` (`open` prefixes `OPEN_HANDOFF_INVALID <flag or path>`). `rig-review open` verifies at start (before spawning or reusing a worker) that every inspected package has a compiled `model` that `@rig-c/play` loads and decodes, and in single mode by default also requires a complete producer handoff (`handoffGap`, `producerInputs`, `resolveProducer`, `contourParts`), exiting non-zero with `OPEN_MODEL_UNAVAILABLE: <reason>` when the model or handoff is missing or broken. Passing `--view-only` explicitly permits opening a compiled model that has no producer handoff at all (`handoff === null`), in which case `/api/rebuild` reports the neutral status `"view only, no producer handoff"` (with `viewOnly: true`) and no panel renders a `MODELING_*` error string; a declared or partially-present handoff with a gap still refuses `OPEN_MODEL_UNAVAILABLE: <reason>` even with `--view-only`. When `startServer` runs directly without `--view-only` and no handoff is found, `/api/rebuild` reports `MODELING_INPUT_UNAVAILABLE: config.json — looked at config.json, rig/config.json, ../config.json (beside an opened out/); declare it with rig-review open <dir> --config <path> [--parts <dir>] or the review.json "producer" block`, and Apply refuses `MODELING_HANDOFF_MISSING`.
161
161
 
162
- **Hashed files.** The config; the files the config names that the producer resolves against the config's directory (`motion.animations_from`, `generation.control.skeleton`; each must stay inside the root, a missing one is listed in `missing`); `parts.json` and every regular file directly in `parts/`; every regular file directly in the inspected `rig/` (`rig.json`, `motion.json`, `mesh_report.json`, `sets.json`, …) and `rig/images/`; with `--source`/`--full`/`--head`, that PNG and the regular files directly in those directories; for a discovered handoff, the `painting.png` beside its config when there is one; with `--keypoints` (#111; the review.json block's `keypoints`), that file — the same path rules as `--source` (literal, inside the root, no symlink escape).
162
+ **Hashed files.** The config; the references the installed `@rig-c/parts` `configFileReferences` export declares against the config's directory (`requirements`, `motion.animations_from`, `generation.control.skeleton`, `assemble.occluders[i].image` as regular files, and `assemble.occluders[i].plate` as a directory input bound by `<directory>/receipt.json`'s raw SHA-256 with `{path:"<directory>/receipt.json", sha256, directory:"<directory>", spec}` matching `@rig-c/parts` `PLATE_RECEIPT_SPEC` and `create#326` `93b361f8bfec0ec7e20318d9c8e643eef5d7a674`, never by hashing plate sibling files; each must stay inside the root, a missing one is listed in `missing`, and an unknown reference or an older installed loader that omits a declared occluder input is refused by name with `HANDOFF_INPUT_INVALID`); `parts.json` and every regular file directly in `parts/`; every regular file directly in the inspected `rig/` (`rig.json`, `motion.json`, `mesh_report.json`, `sets.json`, …) and `rig/images/`; with `--source`/`--full`/`--head`, that PNG and the regular files directly in those directories; for a discovered handoff, the `painting.png` beside its config when there is one; with `--keypoints` (#111; the review.json block's `keypoints`), that file — the same path rules as `--source` (literal, inside the root, no symlink escape).
163
163
 
164
164
  **Record and identity.** `reviewedSource.handoff` (absent when there is no handoff, so earlier identities are unchanged):
165
165
 
@@ -186,13 +186,13 @@ Every edit card states its edit as one config patch; review applies it to a scra
186
186
  ```
187
187
 
188
188
  - **Document.** Exactly these five keys. `ops` holds 1–256 operations, each `replace` or `add` (`{op, path, value}`, value any JSON) or `remove` (`{op, path}`), each with an optional `name` (#103): the `name` the list entry `/<list>/<index>` holds in the config the patch was made against (a physics edit records `{"op":"replace","path":"/constraints/1/damping","value":0.3,"name":"fringe_r1_physics"}`), applied in order with RFC 6902 semantics; `path` is an RFC 6901 JSON Pointer into the config (`~1` is `/`, `~0` is `~`; an array index is a decimal without leading zeros, and `add` may use `-` to append). `""` (the whole config) is refused. `producer` is the producer the patch was made for. `op.cmd` is `rig` (rebuild the whole rig from the patched config) or `remesh` (re-fit one part from its patched `meshes.<part>` entry; `args` must hold `--part <name>`). `op.args` may also hold `--idle-keys ctl|direct`, `--page-edges pot|free` and `--pack-shape rect|polygon`, each once; nothing else, never a path.
189
- - **Refusals before anything runs.** Malformed (HTTP 400): `EDIT_PATCH_INVALID`, `EDIT_PATCH_OP_UNKNOWN`, `EDIT_PATCH_POINTER_INVALID`, `EDIT_PATCH_CMD_UNKNOWN`, `EDIT_PATCH_ARG_UNKNOWN`. Outcomes (HTTP 200, `{status:"refused", error, producerLine:null}`): `EDIT_PATCH_STALE` when `config_sha256` is not the handoff config's hash; `EDIT_PATCH_PATH_MISSING` when a pointer does not resolve in that config; `EDIT_PATCH_NAME_MISMATCH` when an op's `name` is not the name its index holds there; `EDIT_PATCH_PATH_HELD` when the patch changes a file name the config resolves against its directory (`motion.animations_from`, `generation.control.skeleton` — handoff files); `EDIT_PATCH_OUT_OF_SCOPE` when a `remesh` patch edits outside `/meshes/<part>`; `EDIT_PRODUCER_MISMATCH` when the installed producer is not the patch's; for a `rig` patch the runner runs as the whole-rig `rig` (*Routing*, below), `EDIT_BASELINE_MISMATCH: <first differing path>` unless the session's baseline reproduced the inspected rig (*Producer handoff*, Baseline); and the producer-resolution refusals of an Apply.
189
+ - **Refusals before anything runs.** Malformed (HTTP 400): `EDIT_PATCH_INVALID`, `EDIT_PATCH_OP_UNKNOWN`, `EDIT_PATCH_POINTER_INVALID`, `EDIT_PATCH_CMD_UNKNOWN`, `EDIT_PATCH_ARG_UNKNOWN`. Outcomes (HTTP 200, `{status:"refused", error, producerLine:null}`): `EDIT_PATCH_STALE` when `config_sha256` is not the handoff config's hash; `EDIT_PATCH_PATH_MISSING` when a pointer does not resolve in that config; `EDIT_PATCH_NAME_MISMATCH` when an op's `name` is not the name its index holds there; `EDIT_PATCH_PATH_HELD` when the patch changes a reference the config resolves against its directory (`requirements`, `motion.animations_from`, `generation.control.skeleton`, `assemble.occluders[i].image`, `assemble.occluders[i].plate` — handoff inputs); `EDIT_PATCH_OUT_OF_SCOPE` when a `remesh` patch edits outside `/meshes/<part>`; `EDIT_PRODUCER_MISMATCH` when the installed producer is not the patch's; for a `rig` patch the runner runs as the whole-rig `rig` (*Routing*, below), `EDIT_BASELINE_MISMATCH: <first differing path>` unless the session's baseline reproduced the inspected rig (*Producer handoff*, Baseline); and the producer-resolution refusals of an Apply.
190
190
  - **Routing (#136).** A `rig` patch runs `rig-parts retune` instead of the whole-rig `rig` when the installed producer is `@rig-c/parts` 1.44.0 or later (`RETUNE_SINCE`, the CHANGELOG's first release with retune) and **every** op's pointer lies at or under one of `/constraints`, `/motion/duration`, `/motion/tracks`, `/motion/blink/t`, `/motion/blink/squash`, `/motion/blink/brow_drop` (`src/retune-route.ts`). The scope is retune's own help: it splices the config's constraints (rig.json `constraints` and `invariants.detached`) and idle (motion.json `animations.idle`) onto the gated inspected rig and holds stops, bones, slots, skeleton, images, every other invariant and every other byte of motion.json (`RETUNE_REQUEST_HELD`). So `/stops`, `/bones`, `/regions`, `/turn`, `/meshes`, `/motion/animations_from`, the blink's `eyes` and `brows` (its motion.json groups) and `still` (a `<part>_still` slot), and a patch mixing any of them with retune's pointers, keep the whole-rig `rig` behind the baseline guard; so does every patch on an older producer. Retune needs no baseline, but it does not carry every repair (#148, `@rig-c/parts` 1.49.1 AUTHORING §retune and `src/retune.ts`): it carries every attachment and every `mesh_report.json` row over as bytes, so a **mesh** repair the config does not reproduce stays; it holds every image file (with stops, bones, slots, skeleton, every invariant but `detached` and motion.json outside the idle) to the config's rebuild, so on a build whose repair redrew an image every retune refuses `RETUNE_REQUEST_HELD: images/<part>.png — the config changes it`; and it splices `rig.json` and `motion.json` as text, so an input that is not the writer's text refuses `RETUNE_INPUT_WRITTEN`. Measured on parts-examples `family/roa` (a hand shoulder repair that redrew `topwear.png`, parts 1.49.1): as committed, retune refuses `RETUNE_INPUT_WRITTEN` (its `rig.json` is not the writer's text); re-serialised in the writer's format, it refuses `RETUNE_REQUEST_HELD: images/topwear.png`. The baseline line says which applies (*Baseline reach*, below). What it judges per value (a track that newly keys a mesh-bound bone, which gains a `<bone>_ctl` under `--idle-keys ctl`) comes back as its own `RETUNE_REQUEST_HELD` line verbatim, as do `RETUNE_CONFIG_REFUSED` and its other refusals.
191
191
  - **Baseline reach (#148).** When the baseline does not reproduce, `baseline.reach` (`src/baseline-reach.ts`) reads both rig directories and states what each producer op will still take, from the producer's own holds: `{schema:"rig-review-baseline-reach/1", notWriterText[], images[], retuneHeld, remeshRefused[], meshParts[], bonesDiffer, ops:{retune, delta, version}, text}`. `notWriterText`: the inspected `rig.json`, `motion.json` and `mesh_report.json` that are not `JSON.stringify(value, null, 1)` and a closing newline (the writer, parts `rigJsonText`) — remesh and its mesh edit refuse `rig.json` / `mesh_report.json` (`REMESH_INPUT_WRITTEN`), retune `rig.json` / `motion.json` (`RETUNE_INPUT_WRITTEN`). `images`: the images the config draws differently. `retuneHeld`: retune's first held difference in its own order (stops, bones, slots, skeleton, images, invariants but `detached`, each image, motion.json outside `animations.idle`), or null when a physics or idle edit Applies. `remeshRefused`: the meshed parts (`skins.default.<part>.<part>` of type `mesh`) whose attachment, image or report row (or an `auto` row's motion) the config does not reproduce — remesh from a config entry refuses them `REMESH_BASELINE_MISMATCH` and re-fits the rest; `bonesDiffer` refuses every part. A mesh edit (`remesh --delta`) builds no config entry, so the baseline does not hold it. `ops` is the installed producer's: below 1.44.0 a physics or idle edit is whole-rig. `text` is appended to the baseline line (`baseline: not reproduced — <first differing path> · <text>`) and to `EDIT_BASELINE_MISMATCH: <path> — <text>`. It is review's reading of the producer's rules; the producer's line on Apply stays the judgment. For family/roa as committed: `out/rig/rig.json, out/rig/mesh_report.json are not the text rig writes for their values (reformatted, or written by another tool), and an op that splices a revision as text refuses such a file — use the files as rig wrote them, or re-serialise them in a copy of the package exactly as rig writes them (JSON with one space of indent and a closing newline) and open the copy; whole-rig edits refuse (EDIT_BASELINE_MISMATCH); physics and idle edits (retune) refuse out/rig/rig.json (RETUNE_INPUT_WRITTEN), and past that the config draws out/rig/images/topwear.png differently and retune holds every image (RETUNE_REQUEST_HELD); remesh and a mesh edit refuse out/rig/rig.json, out/rig/mesh_report.json (REMESH_INPUT_WRITTEN); past that, remesh: bottomwear, topwear, hair_back, hair_front are refused (REMESH_BASELINE_MISMATCH: …); handwear_r, neck, earring can be re-fit`.
192
192
  - **Producer refusal hint (#148).** When the producer refuses with a line review can explain — `REMESH_INPUT_WRITTEN` / `RETUNE_INPUT_WRITTEN` (a file that is not the writer's text) or `RETUNE_REQUEST_HELD: images/<name>` (an image the config draws differently) — the job keeps `producerLine` as printed and adds `hint` (absent otherwise), also pushed to `lines` as `review: <hint>`; the status line reads `<producer line> · review: <hint>`. For `RETUNE_INPUT_WRITTEN` on `rig.json`: `rig.json in the inspected rig is not the text rig writes for its value (reformatted, or written by another tool); retune splices a revision as text, so it refuses the file — use the files as rig wrote them, or re-serialise them in a copy of the package exactly as rig writes them (JSON with one space of indent and a closing newline) and open the copy`.
193
193
  - **Build (#115).** A `rig` patch with any op at or under `/assemble` or `/limbs` — or under `/bones` on a config that declares `limbs`, whose joints are their bones' origins — runs `rig-parts build` (op `build`): those sections are read by the producer's assemble stage, which `rig --config --parts` never runs (rig-parts AUTHORING §3, the `assemble.cuts`, `assemble.patches` and `limbs` rows). It needs the handoff's painting and full run (`--source <png> --full <dir> [--head <dir>]`, or the review.json block); without them it refuses before anything runs: `MODELING_INPUT_UNAVAILABLE: source painting and See-through runs — rig-parts build reassembles the parts from the painting (--source) and the runs (--full, --head) before the rig, and the handoff declares none; declare them with …`. It is a whole-rig op behind the reproduced baseline (`EDIT_BASELINE_MISMATCH`). The files assemble reads by the config's own naming (each cut's `under`, each limb segment's `cap`, each alternate's `source`, `full`, `head` and `skeleton`) are resolved against the handoff config's directory, must stay inside the package root (`BUILD_INPUT_OUTSIDE_ROOT`, `BUILD_INPUT_MISSING`) and are hashed into the build id — a named directory outside the declared runs by its contents (every regular file under it, at most 8 levels deep and 4096 files, each held inside the package root, in path order; over the bound refuses `BUILD_INPUT_TOO_LARGE`), a declared run through the handoff record (#185); a patch may not name a new one (`EDIT_PATCH_PATH_HELD` — it may keep, move or drop one the config names). `config.json` is the patched config with those paths and the two above made absolute, then `rig-parts build --config config.json --source <handoff source> --full <handoff full> [--head <handoff head>] --out out --seam-pairs [args]`; the rig spec is `out/rig`, and the shared tail diffs and compiles it (no second check: build's own check ran on the parts it assembled). A stage that refuses leaves no scratch, and its FAIL lines come back verbatim (the stage prefix `[assemble]`, `[rig]`, `[check]` stripped); a build that stopped at check with bars not met is kept, check's FAIL lines beside it. The job adds `assembled: {inputs:{source, full, head, named:[{field, path, sha256|null}]}, refusals[], checkFails[], lines[] (the cut:, limb cut:, limb cap: and uncovered-hole lines), seam[], seamPairs[] (the base set's `seam pair` lines), recomposite:{line, before, after, errorMap:{url, sha256}|null}, parts:{changed[], unchanged, partsJson:{count, paths}}|null}` (`before` is the handoff's `parts.json` recomposite block, `after` the scratch one; `errorMap` serves `out/recomposite_error_rig.png` read-only at `/rebuild/<id>/recomposite/recomposite_error_rig.png`), and `wallMs.op` is the build's own wall clock (assemble → rig → check).
194
194
  - **Cloth (#111).** A `rig` patch whose ops all lie under `/cloth` (the Setup · Cloth block: one recipe per tag the installed reader accepts — read from its own `CLOTH_TARGETS` — with the reader's fields) runs op `cloth`; a patch mixing `/cloth` ops with others is refused before anything runs (`CLOTH_PATCH_MIXED`). Refused before anything runs: `CLOTH_KEYPOINTS_UNDECLARED` when the handoff declares no `--keypoints` (without them the draft moves the body bones the config states — Decision 1), `MODELING_PRODUCER_TOO_OLD <found> 1.49.1` (the first `@rig-c/parts` whose `--write-config` splices `bones`, `constraints` and `motion.tracks` entry by entry, parts#552), `MODELING_INPUT_UNAVAILABLE: source painting …` without `--source`, and, as a whole-rig op, `EDIT_BASELINE_MISMATCH`. `cloth.json` is the patched config written as `rig` writes its scratch config, with the assemble-read paths made absolute as for `build`; then `rig-parts propose --parts <handoff parts> --source <handoff source> --keypoints <handoff keypoints> --out propose --cloth cloth.json --write-config config.json` (no `--wrist-snap` or `--grid-rule`: the handoff states neither). Its refusals come back verbatim, every FAIL line in `cloth.refusals` — the reader's `CONFIG_CLOTH_*`, `PROPOSE_CLOTH_DRAFTED` (a recipe that drafts nothing), `PROPOSE_CLOTH_PART`, and the write's `PROPOSE_WRITE_CONFIG_FRESH`, `PROPOSE_WRITE_CONFIG_CONFLICT` (an entry the recipe re-drafts or removes that equals neither the draft with the recipe nor the draft without it, rig-parts AUTHORING *The config written*) and `PROPOSE_WRITE_CONFIG_SPLICE`. Review reads only the written `config.json`, never the producer's draft file: it lists every JSON Pointer at which the written config differs from `cloth.json` and refuses to build one that differs outside the sections propose splices (`bones`, `constraints`, `meshes`, `regions`, `limbs`, `motion/tracks`, `turn`, `proposed_rig_scale`): `CLOTH_WRITTEN_OUTSIDE_DRAFTED`. The written config is then built (Decision 2) as `rig-parts build --config config.json …` exactly as a `build` patch when the config declares `limbs` (the job adds `assembled`), else `rig-parts rig --config config.json --parts <handoff parts> --out rig`, and goes through the shared tail. The id adds `cloth`, the keypoint file's hash and (for the build route) the build inputs' hash. The job adds `cloth: {route:"build"|"rig", inputs:{source, keypoints:{path, sha256}}, refusals[], line (propose's `wrote config.json: …` line), written:{count, paths[≤200], outside[≤200], sections[]}|null, links[] (per tag: its parts and the written config's chains, the link preview), wallMs:{propose, build}}`. `GET /api/rebuild` adds `cloth: {targets, targetsRead, recipes, tags[] (per tag: its parts by See-through tag or by the recipe's `part`/`parts`, and the chains their `meshes.<part>.segments` name with `points` and `tip`), keypoints, route, reason}`.
195
- - **Run.** Scratch is `<state>/rebuild/<package source hash>/<id>/`, `id = sha256([rig-review-rebuild/1, "patch", source hash, config SHA-256, the patch's canonical bytes, producer@version, compiler@version])` — no clock; the same patch again reuses its build. `rig`: `config.json` there is the patched config written as the producer's own scratch configs are (2-space JSON, `motion.animations_from` and `generation.control.skeleton` made absolute when they name a file beside the handoff config), then `rig-parts rig --config config.json --parts <handoff parts> --out rig [args]`, or for a retune-routed patch `rig-parts retune --rig <handoff rig> --config config.json --parts <handoff parts> --out rig [args]` (the same config; retune reads the inspected rig and writes only `rig/`, with `retune.json`). `remesh`: `mesh.json` is the patched `meshes.<part>` entry and `rig-parts remesh --rig <handoff rig> --config <handoff config> --parts <handoff parts> --part <part> --mesh mesh.json --out rig [args]` (remesh reads the config as written). Then `rigc build --rig rig/rig.json --motion rig/motion.json --out build --profile rig-play --pack --page-edges … --pack-shape …` (the args' values, else `free` / `polygon`; for remesh, its `remesh.json` request; for retune, its `retune.json` request) and `rig-parts check --rig rig --out check --parts <handoff parts>` with the same pack flags. A producer or compiler refusal is the first named line verbatim and leaves no scratch; a check `FAIL` is check's judgment, kept beside the build.
195
+ - **Run.** Scratch is `<state>/rebuild/<package source hash>/<id>/`, `id = sha256([rig-review-rebuild/1, "patch", source hash, config SHA-256, the patch's canonical bytes, producer@version, compiler@version])` — no clock; the same patch again reuses its build. `rig`: `config.json` there is the patched config written as the producer's own scratch configs are (2-space JSON, every `configFileReferences` path made absolute when it names an existing entry beside the handoff config), then `rig-parts rig --config config.json --parts <handoff parts> --out rig [args]`, or for a retune-routed patch `rig-parts retune --rig <handoff rig> --config config.json --parts <handoff parts> --out rig [args]` (the same config; retune reads the inspected rig and writes only `rig/`, with `retune.json`). `remesh`: `mesh.json` is the patched `meshes.<part>` entry and `rig-parts remesh --rig <handoff rig> --config <handoff config> --parts <handoff parts> --part <part> --mesh mesh.json --out rig [args]` (remesh reads the config as written). Then `rigc build --rig rig/rig.json --motion rig/motion.json --out build --profile rig-play --pack --page-edges … --pack-shape …` (the args' values, else `free` / `polygon`; for remesh, its `remesh.json` request; for retune, its `retune.json` request) and `rig-parts check --rig rig --out check --parts <handoff parts>` with the same pack flags. A producer or compiler refusal is the first named line verbatim and leaves no scratch; a check `FAIL` is check's judgment, kept beside the build.
196
196
  - **A retune's check (#139).** A retune-routed Apply does not run `rig-parts check` a second time: retune already gated and checked the revision it wrote (`checkStage` over that revision, the same `--parts` and pack flags review passes), and from `@rig-c/parts` 1.49.0 (`RETUNE_CHECK_SINCE`, parts#541) `retune.json`'s `check.revision` carries `line` — check's own last line, byte for byte — and `status` — every block's status as that tree's `check.json` records it, in the file's order. Review first binds it to the files: every `revision` hash row's file under `rig/` must hash to its row, none missing, and `rig/` holds no file but those rows and `retune.json`; otherwise the Apply is refused `RETUNE_CHECK_STALE: <file> sha256 <in retune.json> … <on disk>; retune's check is not this revision's, so no build is recorded` (`absent` on the side without the file) and leaves no scratch. Bound, the side becomes the same check summary a separate check gives (below): `pass` ← `pass`; `exitCode` ← 0 when it passes, else 1 (check's own exit); `line` ← `line`; `bars` ← every upper-case `status` entry (`gate`, `loop` and `seam` are read off figures and are not check.json bars); `gate` ← `status.gate` is `PASS`; plus `source:"retune"`. The job's `wallMs.check` is `null` and its lines say `review: check not run again — retune.json carries retune's check of this revision, bound to it by N revision hash row(s): <line>`. Check still runs on the revision, as before, when `retune.json` carries no `line` / `status` (an older producer; the line says so — not a refusal) or when the Apply checks under an exported world (#112; retune's check read the default one). Whole-rig `rig`, `build` and cloth keep running check.
197
197
  - **A remesh's check (#174).** A `remesh` patch Apply (#106) reads `rig-parts remesh`'s own check of its revision the same way, with one binding shared with retune: `remesh.json`'s `check.revision` (`line` and `status` since `@rig-c/parts` 1.49.0, `REMESH_CHECK_SINCE`; the same parts#541 change) is bound by its `revision` hash rows to the files under `rig/` (none missing, none but those rows and `remesh.json`), else the Apply is refused `REMESH_CHECK_STALE: <file> sha256 <in remesh.json> … <on disk>; remesh's check is not this revision's, so no build is recorded` and leaves no scratch. remesh checked the revision with its request's `page_edges` / `pack_shape` — the flags review's own check reads from `remesh.json` — and the handoff `--parts`; a patch passes no `--requirements`. Bound, the summary is the same mapping as retune's with `source:"remesh"`; `wallMs.check` is `null` and the line says `review: check not run again — remesh.json carries remesh's check of this revision, bound to it by N revision hash row(s): <line>`. An older `remesh.json` or an Apply under an exported world runs check, and the line says why. The designation remesh (#99) and Edit Mesh's `remesh --delta` (#135) run no review check at all (remesh's own gate holds check there), so they are unchanged.
198
198
  - **Request and job.** `POST /api/rebuild` takes exactly `{patch}` (or #99's `{part, regions, configHash}`, or #105's `{part, bust, configHash}` — see *Chest landmarks* below, or #135's `{part, delta, configHash}` — see *Mesh edit export*), same-origin, 64 KiB. The job (`GET /api/rebuild/<id>`): `{schema:"rig-review-rebuild/1", kind:"patch", id, status:"running"|"built"|"refused"|"failed", reused, request:{patch, patchSha256, configHash}, producer, compiler, lines[], producerLine, exitCode, wallMs:{op, compile, check}, check, diff:{count, paths[≤200]}, build:{model, modelUrl, modelHash, files}|null}`. `diff` lists every JSON Pointer at which the scratch `rig.json` differs from the inspected one (a changed leaf or type, a key or index only one side has). `check` is `{schema:"rig-review-check-summary/1", pass (check.json's PASS, or null without one), exitCode, line (check's last `check: …` line, or its first named refusal), bars:{NAME: status}, gate}`, plus `source:"retune"` or `source:"remesh"` when the summary is that op's carried check (#139, #174; absent: check's own output, `check.json` and its stdout).
@@ -975,6 +975,8 @@ Packages without authored direction continue to use their explicit legacy
975
975
  selector. Direction patch Apply is unavailable. Existing supported rig and
976
976
  draft Apply records keep their producer and result evidence.
977
977
 
978
+ When `--project` and `--project-draft` select a recorded draft whose project entry declares `config`, `parts`, `rig` and `check` directories, `/api/rebuild` exposes `draft` metadata with the recorded draft id, producer provenance (`draft.producer`) and input paths alongside the resolved installed `producer` and `compiler` without synthesizing a package `reviewedSource.handoff`. Rebuild status resolves the installed producer and compiler via `resolveProducer` and its operation-capability floors (`REMESH_SINCE` for `remesh --mesh`, `REMESH_DELTA_SINCE` for `remesh --delta`, and `EDIT_PRODUCER_MISMATCH` when a config patch's `producer` differs from the installed producer), without an equality version gate against `draft.producer`. While the draft is editable (`project.stage` in `parts` or `parts-review` without an effective `parts-review` sign-off, and not `--view-only`), `/api/rebuild` accepts region rebuilds, `remesh` config patches and mesh deltas in scratch, and refuses whole-rig, retarget and animation operations with `STAGE_DRAFT_OPERATION`. When the draft is not editable or `--view-only` is set, `/api/rebuild` and `/api/stage-parts` report the draft as inspection-only (`PARTS_VERDICT_READ_ONLY: Stage 1 draft is inspection-only` and `draft.inspectionOnly: true`) and refuse rebuild mutations and scratch Stage 1 build reads (`STAGE_DRAFT_UNAVAILABLE`). Separately, saving or exporting the Stage 1 parts verdict requires an editable draft, `--parts-verdict-dir`, no `--view-only`, and the `inspected` build (`PARTS_VERDICT_READ_ONLY` otherwise).
979
+
978
980
  A supported made item must match the server-owned settled Apply seal and
979
981
  retained scratch model and pages when the item is added or changed and on
980
982
  selected export. Older unchanged items remain saved as historical evidence
package/docs/WORKFLOWS.md CHANGED
@@ -739,6 +739,8 @@ offers the registered pending sets and displays historical answers read-only.
739
739
  **3 Rig + animation** and **4 Direction** report that the recorded rig review
740
740
  package is unavailable. Reopen with a rig version once Create records one.
741
741
 
742
+ When the recorded draft entry includes `config`, `parts`, `rig` and `check` directories and the draft is editable (`parts` or `parts-review` stage without an effective `parts-review` sign-off, and not `--view-only`), **1 Parts + mesh** also offers the Chest regions, Mesh parameters and Edit Mesh instruments for mesh-bearing parts regardless of whether `--parts-verdict-dir` is supplied. Selecting an instrument opens the Setup inspector for that part while direct selection of **3 Rig + animation** remains refused with `RIG_VERSION_UNAVAILABLE`. Apply runs the installed producer and compiler in scratch under the existing discovery and operation-capability floors while keeping the recorded draft producer as provenance, and returning to **1 Parts + mesh** or running Undo or Reset updates the displayed mesh and report readings from the active build (verdict saving remains read-only on scratch builds and when `--parts-verdict-dir` is omitted).
743
+
742
744
  From a create project with retained choice sets, create a dedicated output
743
745
  directory and open the foreground Stage 2 view:
744
746
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-review",
3
- "version": "2.7.0",
3
+ "version": "2.7.1",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -25,7 +25,7 @@
25
25
  "pngjs": "7.0.0"
26
26
  },
27
27
  "devDependencies": {
28
- "@rig-c/parts": "2.25.1",
28
+ "@rig-c/parts": "2.35.0",
29
29
  "@types/bun": "^1.3.0",
30
30
  "typescript": "^5.9.3"
31
31
  },
package/src/handoff.ts CHANGED
@@ -23,8 +23,11 @@
23
23
  * folder no symlink at all — and when present it is the record's `source` like a declared one.
24
24
  */
25
25
  import { createHash } from 'node:crypto';
26
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
26
27
  import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';
28
+ import { createRequire } from 'node:module';
27
29
  import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
30
+ import { findPackage, MODELING_PRODUCER_NOT_INSTALLED, PRODUCER_PACKAGE } from './producer.ts';
28
31
 
29
32
  export const HANDOFF_SCHEMA = 'rig-review-handoff/1';
30
33
  /** The fixed discovery order, as the refusal names it. */
@@ -37,6 +40,12 @@ export const BUILD_MODELING_INPUT_UNAVAILABLE = `MODELING_INPUT_UNAVAILABLE: con
37
40
  /** Files the producer reads by the config's own naming, resolved against the config's directory (rig-parts `relativeConfigPaths`). */
38
41
  export const CONFIG_NAMED_FILES = [['requirements'], ['motion', 'animations_from'], ['generation', 'control', 'skeleton']] as const;
39
42
  export const CONFIG_SKELETON_NAMES = ['stand_sides', 'stand_clasp'] as const;
43
+ /**
44
+ * #591 (create#326, 93b361f8bfec0ec7e20318d9c8e643eef5d7a674): the file a directory reference binds.
45
+ * A See-through occluder plate directory (`comfy plate --mode occluder`) is bound by its producer's receipt;
46
+ * review never hashes or generates plate sibling files.
47
+ */
48
+ export const DIRECTORY_INPUT_RECEIPT = 'receipt.json';
40
49
  /** What `rig-parts rig` writes into its --out and remesh reads from --rig: the rig spec, its motion, the mesh report and the part images. */
41
50
  export const RIG_FILES = ['rig.json', 'motion.json', 'mesh_report.json'] as const;
42
51
  const MAX_LISTED = 4096;
@@ -46,7 +55,9 @@ export const DISCOVERED_PAINTING = 'painting.png';
46
55
  export interface HandoffDeclaration { config: string; parts?: string; source?: string; full?: string; head?: string; keypoints?: string }
47
56
  export type HandoffFlags = HandoffDeclaration;
48
57
  export const HANDOFF_FLAGS = ['config', 'parts', 'source', 'full', 'head', 'keypoints'] as const;
49
- export interface HandoffFile { path: string; sha256: string }
58
+ export interface HandoffFile { path: string; sha256: string; directory?: string; spec?: string }
59
+ export type ConfigReferenceKind = 'requirements' | 'file' | 'plate';
60
+ export interface ConfigReference { at: string; value: string; set: (value: string) => void; kind: ConfigReferenceKind }
50
61
  /** The identity record: paths relative to the package root (`../` only for the discovered parent config), every hashed file. */
51
62
  export interface HandoffRecord {
52
63
  schema: typeof HANDOFF_SCHEMA;
@@ -64,11 +75,148 @@ export interface HandoffRecord {
64
75
  /** `source` (#109): the declared source painting's absolute path, which `propose --from-config` reads; null when none was declared. */
65
76
  /** `full` / `head` (#115): the declared See-through runs' absolute paths, which `rig-parts build` reads; null when none was declared. */
66
77
  /** `keypoints` (#111): the declared keypoint file's absolute path, which a cloth recipe Apply's `propose --keypoints` reads; null when none was declared. */
67
- export interface Handoff { record: HandoffRecord; config: string; parts: string | null; rig: string | null; root: string; flags?: HandoffFlags; source?: string | null; full?: string | null; head?: string | null; keypoints?: string | null }
78
+ export interface Handoff { record: HandoffRecord; config: string; parts: string | null; rig: string | null; root: string; flags?: HandoffFlags; source?: string | null; full?: string | null; head?: string | null; keypoints?: string | null; starts?: readonly string[] }
79
+ export interface ResolveHandoffOptions { starts?: readonly string[] }
68
80
 
69
81
  export class HandoffError extends Error {
70
82
  constructor(readonly code: string, readonly field: string, readonly detail: string) { super(`${code} ${field}: ${detail}`); }
71
83
  }
84
+ const load = createRequire(import.meta.url);
85
+ const isPlainObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
86
+
87
+ function expandStarts(starts: readonly string[]): string[] {
88
+ const roots: string[] = [];
89
+ for (const start of starts) {
90
+ if (!start) continue;
91
+ const resolved = resolve(start);
92
+ if (!roots.includes(resolved)) roots.push(resolved);
93
+ try {
94
+ const real = realpathSync(resolved);
95
+ if (!roots.includes(real)) roots.push(real);
96
+ } catch { /* non-existent start path */ }
97
+ }
98
+ return roots;
99
+ }
100
+
101
+ /** Resolve the nearest installed `@rig-c/parts` package directory using `findPackage` from `src/producer.ts`. */
102
+ export function findInstalledParts(starts: readonly string[] = [process.cwd()]): string | null {
103
+ const manifest = findPackage(PRODUCER_PACKAGE, expandStarts(starts));
104
+ if (!manifest) return null;
105
+ try { return realpathSync(dirname(manifest)); } catch { return dirname(manifest); }
106
+ }
107
+
108
+ /** Resolve the nearest installed `@rig-c/parts` package directory, or refuse by name when absent. */
109
+ export function locateInstalledParts(starts: readonly string[] = [process.cwd()]): string {
110
+ const found = findInstalledParts(starts);
111
+ if (!found) throw new HandoffError('HANDOFF_INPUT_INVALID', 'config', MODELING_PRODUCER_NOT_INSTALLED);
112
+ return found;
113
+ }
114
+
115
+ export function classifyConfigReference(at: string): ConfigReferenceKind | null {
116
+ if (at === 'requirements') return 'requirements';
117
+ if (at === 'motion.animations_from' || at === 'generation.control.skeleton' || /^assemble\.occluders\[\d+\]\.image$/.test(at)) return 'file';
118
+ if (/^assemble\.occluders\[\d+\]\.plate$/.test(at)) return 'plate';
119
+ return null;
120
+ }
121
+
122
+ function undeclaredOccluderReference(raw: unknown, declaredAt: ReadonlySet<string>): string | null {
123
+ const assemble = isPlainObject(raw) ? raw.assemble : undefined;
124
+ const occluders = isPlainObject(assemble) && Array.isArray(assemble.occluders) ? assemble.occluders : [];
125
+ for (let i = 0; i < occluders.length; i++) {
126
+ const entry = occluders[i];
127
+ if (!isPlainObject(entry)) continue;
128
+ if (typeof entry.image === 'string' && entry.image !== '' && !declaredAt.has(`assemble.occluders[${i}].image`)) {
129
+ return `assemble.occluders[${i}].image`;
130
+ }
131
+ if (typeof entry.plate === 'string' && entry.plate !== '' && !declaredAt.has(`assemble.occluders[${i}].plate`)) {
132
+ return `assemble.occluders[${i}].plate`;
133
+ }
134
+ }
135
+ return null;
136
+ }
137
+
138
+ function fallbackNamedReferences(raw: Record<string, unknown>): ConfigReference[] {
139
+ const out: ConfigReference[] = [];
140
+ if (typeof raw.requirements === 'string' && raw.requirements !== '') {
141
+ out.push({ at: 'requirements', value: raw.requirements, set: value => { raw.requirements = value; }, kind: 'requirements' });
142
+ }
143
+ const motion = isPlainObject(raw.motion) ? raw.motion : null;
144
+ if (motion && typeof motion.animations_from === 'string' && motion.animations_from !== '') {
145
+ out.push({ at: 'motion.animations_from', value: motion.animations_from, set: value => { motion.animations_from = value; }, kind: 'file' });
146
+ }
147
+ const generation = isPlainObject(raw.generation) ? raw.generation : null;
148
+ const control = generation && isPlainObject(generation.control) ? generation.control : null;
149
+ if (control && typeof control.skeleton === 'string' && control.skeleton !== '' && !(CONFIG_SKELETON_NAMES as readonly string[]).includes(control.skeleton)) {
150
+ out.push({ at: 'generation.control.skeleton', value: control.skeleton, set: value => { control.skeleton = value; }, kind: 'file' });
151
+ }
152
+ return out;
153
+ }
154
+
155
+ /**
156
+ * #591: enumerate config-named references from the installed `@rig-c/parts` `configFileReferences` export (stable since v2.23.0).
157
+ * Refuses by name when a parts reference is unknown to the handoff or when an older/absent loader omits a declared occluder input,
158
+ * while preserving read-only inspection for non-occluder configs when optional `@rig-c/parts` is not installed.
159
+ */
160
+ export function configNamedReferences(
161
+ raw: unknown,
162
+ starts: readonly string[] = [process.cwd()],
163
+ ): { partsRoot: string | null; references: ConfigReference[] } {
164
+ const partsRoot = findInstalledParts(starts);
165
+ if (!isPlainObject(raw)) return { partsRoot, references: [] };
166
+ const configModulePath = partsRoot ? join(partsRoot, 'src', 'config.ts') : null;
167
+ if (!partsRoot || !configModulePath || !existsSync(configModulePath)) {
168
+ const missingOccluder = undeclaredOccluderReference(raw, new Set());
169
+ if (missingOccluder) {
170
+ if (!partsRoot) {
171
+ throw new HandoffError('HANDOFF_INPUT_INVALID', `config ${missingOccluder}`, MODELING_PRODUCER_NOT_INSTALLED);
172
+ }
173
+ const pkg = JSON.parse(readFileSync(join(partsRoot, 'package.json'), 'utf8')) as { version?: string };
174
+ throw new HandoffError('HANDOFF_INPUT_INVALID', `config ${missingOccluder}`, `@rig-c/parts ${pkg.version ?? 'unknown'} has no configFileReferences export; install a version providing occluder file declarations`);
175
+ }
176
+ return { partsRoot, references: fallbackNamedReferences(raw) };
177
+ }
178
+ const mod = load(configModulePath) as { configFileReferences?: (config: unknown) => { at: string; value: string; set: (value: string) => void }[] };
179
+ if (typeof mod.configFileReferences !== 'function') {
180
+ const missingOccluder = undeclaredOccluderReference(raw, new Set());
181
+ const pkg = JSON.parse(readFileSync(join(partsRoot, 'package.json'), 'utf8')) as { version?: string };
182
+ if (missingOccluder) {
183
+ throw new HandoffError('HANDOFF_INPUT_INVALID', `config ${missingOccluder}`, `@rig-c/parts ${pkg.version ?? 'unknown'} has no configFileReferences export; install a version providing occluder file declarations`);
184
+ }
185
+ return { partsRoot, references: fallbackNamedReferences(raw) };
186
+ }
187
+ const rawRefs = mod.configFileReferences(raw);
188
+ const missingOccluder = undeclaredOccluderReference(raw, new Set(rawRefs.map(r => r.at)));
189
+ if (missingOccluder) {
190
+ const pkg = JSON.parse(readFileSync(join(partsRoot, 'package.json'), 'utf8')) as { version?: string };
191
+ throw new HandoffError('HANDOFF_INPUT_INVALID', `config ${missingOccluder}`, `@rig-c/parts ${pkg.version ?? 'unknown'} configFileReferences does not declare ${missingOccluder}; install a version providing occluder file declarations`);
192
+ }
193
+ const references: ConfigReference[] = [];
194
+ for (const ref of rawRefs) {
195
+ const kind = classifyConfigReference(ref.at);
196
+ if (!kind) throw new HandoffError('HANDOFF_INPUT_INVALID', `config ${ref.at}`, `unsupported config file reference ${ref.at}`);
197
+ references.push({ ...ref, kind });
198
+ }
199
+ return { partsRoot, references };
200
+ }
201
+
202
+ /** Read `PLATE_RECEIPT_SPEC` from the installed `@rig-c/parts/src/plate.ts` without copying the constant into review. */
203
+ export function plateReceiptSpec(partsRoot: string | null, field = 'config'): string {
204
+ if (!partsRoot) throw new HandoffError('HANDOFF_INPUT_INVALID', field, MODELING_PRODUCER_NOT_INSTALLED);
205
+ let spec: unknown;
206
+ try { spec = (load(join(partsRoot, 'src', 'plate.ts')) as { PLATE_RECEIPT_SPEC?: unknown }).PLATE_RECEIPT_SPEC; } catch { spec = undefined; }
207
+ if (typeof spec !== 'string' || !spec) {
208
+ const pkg = JSON.parse(readFileSync(join(partsRoot, 'package.json'), 'utf8')) as { version?: string };
209
+ throw new HandoffError('HANDOFF_INPUT_INVALID', field, `@rig-c/parts ${pkg.version ?? 'unknown'} has no PLATE_RECEIPT_SPEC export in src/plate.ts; install a version declaring the plate receipt spec before binding a directory input`);
210
+ }
211
+ return spec;
212
+ }
213
+
214
+ /** The `spec` a receipt's bytes declare, or null when they are not a JSON object with a string spec. */
215
+ export function receiptSpec(bytes: Uint8Array): string | null {
216
+ let parsed: unknown;
217
+ try { parsed = JSON.parse(Buffer.from(bytes).toString('utf8')); } catch { return null; }
218
+ return isPlainObject(parsed) && typeof parsed.spec === 'string' ? parsed.spec : null;
219
+ }
72
220
  const sha256 = (bytes: Uint8Array | string) => createHash('sha256').update(bytes).digest('hex');
73
221
  const inside = (base: string, path: string, allowSelf = false) => { const rel = relative(base, path); return rel === '' ? allowSelf : rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel); };
74
222
  const code = (e: unknown) => (e as NodeJS.ErrnoException).code ?? '';
@@ -179,28 +327,46 @@ async function listed(base: string, dir: string, field: string): Promise<string[
179
327
  }
180
328
 
181
329
  /** Hash every handoff file and build the record. `root` is the package root (display paths are relative to it). */
182
- async function record(root: string, base: string, how: HandoffRecord['how'], via: HandoffRecord['via'], config: string, partsPath: string | null, extra: { source?: string; full?: string; head?: string; keypoints?: string }, partsDeclared: boolean): Promise<Handoff> {
330
+ async function record(root: string, base: string, how: HandoffRecord['how'], via: HandoffRecord['via'], config: string, partsPath: string | null, extra: { source?: string; full?: string; head?: string; keypoints?: string }, partsDeclared: boolean, options: ResolveHandoffOptions = {}): Promise<Handoff> {
183
331
  const show = (path: string) => relative(root, path).split(sep).join('/') || '.';
184
- const files = new Map<string, string>(), missing: string[] = [];
185
- const add = async (path: string) => { files.set(show(path), await hashFile(path)); };
332
+ const files = new Map<string, HandoffFile>(), missing: string[] = [];
333
+ const add = async (path: string) => { const p = show(path); files.set(p, { path: p, sha256: await hashFile(path) }); };
186
334
  await add(config);
187
335
  // Files the config names that the producer reads, resolved against the config's own directory.
188
336
  let parsed: unknown = null;
189
337
  try { parsed = JSON.parse(await readFile(config, 'utf8')); } catch { /* the producer refuses an unreadable config by name */ }
190
- for (const keys of CONFIG_NAMED_FILES) {
191
- let value: unknown = parsed;
192
- for (const k of keys) value = value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>)[k] : undefined;
193
- if (typeof value !== 'string' || !value) continue;
194
- if (keys.length === 3 && (CONFIG_SKELETON_NAMES as readonly string[]).includes(value)) continue;
195
- const field = `config ${keys.join('.')}`, lexical = resolve(dirname(config), value);
196
- if (!inside(base, lexical)) throw new HandoffError('HANDOFF_PATH_OUTSIDE_ROOT', field, `${value} resolves outside ${base}`);
197
- if (keys[0] === 'requirements' && (isAbsolute(value) || /[:\\%?#\x00-\x1f]/.test(value) ||
198
- value.split('/').some(part => !part || part === '.' || part === '..'))) {
338
+ const searchStarts = [dirname(config), base, root, ...(options.starts ?? [process.cwd()])];
339
+ const { partsRoot, references } = configNamedReferences(parsed, searchStarts);
340
+ for (const ref of references) {
341
+ const field = `config ${ref.at}`, lexical = resolve(dirname(config), ref.value);
342
+ if (!inside(base, lexical)) throw new HandoffError('HANDOFF_PATH_OUTSIDE_ROOT', field, `${ref.value} resolves outside ${base}`);
343
+ if (ref.kind === 'requirements' && (isAbsolute(ref.value) || /[:\\%?#\x00-\x1f]/.test(ref.value) ||
344
+ ref.value.split('/').some(part => !part || part === '.' || part === '..'))) {
199
345
  throw new HandoffError('HANDOFF_PATH_INVALID', field, 'expected a literal portable config-relative path');
200
346
  }
201
- if (!(await exists(lexical))) { missing.push(`${keys.join('.')} ${show(lexical)}`); continue; }
347
+ if (ref.kind === 'plate') {
348
+ if (!(await exists(lexical))) { missing.push(`${ref.at} ${show(lexical)}/${DIRECTORY_INPUT_RECEIPT}`); continue; }
349
+ const dir = await contained(base, lexical, field, 'dir', true);
350
+ const dirRel = show(dir), receiptLexical = join(dir, DIRECTORY_INPUT_RECEIPT), boundRel = `${dirRel}/${DIRECTORY_INPUT_RECEIPT}`;
351
+ if (!(await exists(receiptLexical))) {
352
+ throw new HandoffError('HANDOFF_INPUT_INVALID', field, `${dirRel} holds no regular-file ${DIRECTORY_INPUT_RECEIPT}; a directory input binds its producer's receipt, such as a comfy plate --mode occluder output`);
353
+ }
354
+ const receiptReal = await contained(base, receiptLexical, `${field}/${DIRECTORY_INPUT_RECEIPT}`, 'file', true);
355
+ if (receiptReal !== receiptLexical || !(await lstat(receiptLexical)).isFile()) {
356
+ throw new HandoffError('HANDOFF_INPUT_INVALID', field, `${boundRel} is not a regular file`);
357
+ }
358
+ const bytes = await readFile(receiptReal);
359
+ const spec = plateReceiptSpec(partsRoot, field);
360
+ const declared = receiptSpec(bytes);
361
+ if (declared !== spec) {
362
+ throw new HandoffError('HANDOFF_INPUT_INVALID', field, `${boundRel} declares spec ${JSON.stringify(declared)}; a directory input binds a ${spec} receipt, such as a comfy plate --mode occluder output`);
363
+ }
364
+ files.set(boundRel, { path: boundRel, sha256: sha256(bytes), directory: dirRel, spec });
365
+ continue;
366
+ }
367
+ if (!(await exists(lexical))) { missing.push(`${ref.at} ${show(lexical)}`); continue; }
202
368
  const file = await contained(base, lexical, field, 'file', true);
203
- if (keys[0] === 'requirements' && file !== lexical) {
369
+ if (ref.kind === 'requirements' && file !== lexical) {
204
370
  throw new HandoffError('HANDOFF_PATH_INVALID', field, 'expected a regular file without a symlink alias');
205
371
  }
206
372
  await add(file);
@@ -221,14 +387,15 @@ async function record(root: string, base: string, how: HandoffRecord['how'], via
221
387
  } else missing.push(`rig ${show(rigDir)}`);
222
388
  } else missing.push(`parts ${partsPath ? show(partsPath) : '(none)'}`);
223
389
  let source: HandoffFile | null = null;
224
- if (extra.source) { await add(extra.source); source = { path: show(extra.source), sha256: files.get(show(extra.source))! }; }
390
+ if (extra.source) { await add(extra.source); source = { path: show(extra.source), sha256: files.get(show(extra.source))!.sha256 }; }
225
391
  for (const dir of [extra.full, extra.head]) if (dir) for (const file of await listed(base, dir, show(dir))) await add(file);
226
392
  // #111: hashed only when declared — an undeclared handoff's record (and so its identity) holds no keypoints key at all.
227
393
  if (extra.keypoints) await add(extra.keypoints);
228
- const sorted = [...files].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([path, hash]) => ({ path, sha256: hash }));
394
+ const sorted = [...files.values()].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
229
395
  return {
230
- record: { schema: HANDOFF_SCHEMA, how, via, outside: !inside(root, config), config: { path: show(config), sha256: files.get(show(config))! }, parts: parts ? show(parts) : null, rig: rig ? show(rig) : null, source, full: extra.full ? show(extra.full) : null, head: extra.head ? show(extra.head) : null, ...(extra.keypoints ? { keypoints: { path: show(extra.keypoints), sha256: files.get(show(extra.keypoints))! } } : {}), files: sorted, missing },
396
+ record: { schema: HANDOFF_SCHEMA, how, via, outside: !inside(root, config), config: { path: show(config), sha256: files.get(show(config))!.sha256 }, parts: parts ? show(parts) : null, rig: rig ? show(rig) : null, source, full: extra.full ? show(extra.full) : null, head: extra.head ? show(extra.head) : null, ...(extra.keypoints ? { keypoints: { path: show(extra.keypoints), sha256: files.get(show(extra.keypoints))!.sha256 } } : {}), files: sorted, missing },
231
397
  config, parts, rig, root: base, source: extra.source ?? null, full: extra.full ?? null, head: extra.head ?? null, keypoints: extra.keypoints ?? null,
398
+ starts: searchStarts,
232
399
  };
233
400
  }
234
401
 
@@ -237,7 +404,7 @@ async function record(root: string, base: string, how: HandoffRecord['how'], via
237
404
  * fixed discovery order. `root` is the canonical package root (the opened folder). A declared path that is missing,
238
405
  * outside its root or a symlink escape is refused by name; nothing found is `{handoff: null}` with the refusal line.
239
406
  */
240
- export async function resolveHandoff(root: string, declared: HandoffDeclaration | undefined, flags: HandoffFlags | undefined): Promise<{ handoff: Handoff | null; reason: string | null }> {
407
+ export async function resolveHandoff(root: string, declared: HandoffDeclaration | undefined, flags: HandoffFlags | undefined, options: ResolveHandoffOptions = {}): Promise<{ handoff: Handoff | null; reason: string | null }> {
241
408
  if (flags) {
242
409
  const problem = checkHandoffFlags(flags);
243
410
  if (problem) throw new HandoffError('HANDOFF_FLAGS_INVALID', problem.split(':')[0]!, problem);
@@ -251,7 +418,7 @@ export async function resolveHandoff(root: string, declared: HandoffDeclaration
251
418
  const full = flags.full !== undefined ? await flagPath(base, flags.full, '--full', 'dir') : undefined;
252
419
  const head = flags.head !== undefined ? await flagPath(base, flags.head, '--head', 'dir') : undefined;
253
420
  const keypoints = flags.keypoints !== undefined ? await flagPath(base, flags.keypoints, '--keypoints', 'file') : undefined;
254
- const handoff = await record(root, base, 'declared', 'open --config', config, parts, { source, full, head, keypoints }, flags.parts !== undefined);
421
+ const handoff = await record(root, base, 'declared', 'open --config', config, parts, { source, full, head, keypoints }, flags.parts !== undefined, options);
255
422
  // Canonical absolute flags: the background worker and later reloads read exactly these.
256
423
  handoff.flags = { config, ...(flags.parts !== undefined ? { parts } : {}), ...(source ? { source } : {}), ...(full ? { full } : {}), ...(head ? { head } : {}), ...(keypoints ? { keypoints } : {}) };
257
424
  return { handoff, reason: null };
@@ -264,14 +431,14 @@ export async function resolveHandoff(root: string, declared: HandoffDeclaration
264
431
  const head = declared.head !== undefined ? await blockPath(root, declared.head, 'producer.head', 'dir') : undefined;
265
432
  const keypoints = declared.keypoints !== undefined ? await blockPath(root, declared.keypoints, 'producer.keypoints', 'file') : undefined;
266
433
  if ((source === undefined) !== (full === undefined) || (head !== undefined && full === undefined)) throw new HandoffError('HANDOFF_FLAGS_INVALID', 'producer', 'source and full are given together, head only with them');
267
- return { handoff: await record(root, root, 'declared', 'review.json producer', config, parts, { source, full, head, keypoints }, declared.parts !== undefined), reason: null };
434
+ return { handoff: await record(root, root, 'declared', 'review.json producer', config, parts, { source, full, head, keypoints }, declared.parts !== undefined, options), reason: null };
268
435
  }
269
436
  for (const name of ['config.json', 'rig/config.json']) {
270
437
  const path = join(root, name);
271
438
  if (!(await exists(path))) continue;
272
439
  const config = await contained(root, path, name, 'file', true);
273
440
  const source = await discoveredPainting(root, path, name, false);
274
- return { handoff: await record(root, root, 'discovered', 'discovery', config, join(dirname(path), 'out'), { source }, false), reason: null };
441
+ return { handoff: await record(root, root, 'discovered', 'discovery', config, join(dirname(path), 'out'), { source }, false, options), reason: null };
275
442
  }
276
443
  // #149: the check package of a rig-parts build root — the build's own config, in the build root, else beside it.
277
444
  const build = await buildPlaces(root);
@@ -281,7 +448,7 @@ export async function resolveHandoff(root: string, declared: HandoffDeclaration
281
448
  const config = await contained(place.base, place.config, place.field, 'file', true);
282
449
  if (config !== place.config) throw new HandoffError('HANDOFF_SYMLINK_ESCAPE', place.field, `${place.config} is a symlink; only the build's own config file is discovered`);
283
450
  const source = await discoveredPainting(place.base, config, place.field, true);
284
- return { handoff: await record(root, place.base, 'discovered', 'discovery', config, build.build, { source }, false), reason: null };
451
+ return { handoff: await record(root, place.base, 'discovered', 'discovery', config, build.build, { source }, false, options), reason: null };
285
452
  }
286
453
  return { handoff: null, reason: BUILD_MODELING_INPUT_UNAVAILABLE };
287
454
  }
@@ -292,7 +459,7 @@ export async function resolveHandoff(root: string, declared: HandoffDeclaration
292
459
  const config = await contained(parent, path, '../config.json', 'file', true);
293
460
  if (config !== path) throw new HandoffError('HANDOFF_SYMLINK_ESCAPE', '../config.json', `${path} is a symlink; only the file beside out/ is discovered`);
294
461
  const source = await discoveredPainting(parent, config, '../config.json', true);
295
- return { handoff: await record(root, parent, 'discovered', 'discovery', config, root, { source }, false), reason: null };
462
+ return { handoff: await record(root, parent, 'discovered', 'discovery', config, root, { source }, false, options), reason: null };
296
463
  }
297
464
  }
298
465
  return { handoff: null, reason: MODELING_INPUT_UNAVAILABLE };
@@ -133,6 +133,19 @@ function approval(project: RecordData, stage: string, at: number) {
133
133
  text(s.by) && s.by.toLowerCase() !== 'agent' && date(s.at) <= at &&
134
134
  !reopened(project, stage, date(s.at) - 1, at)).reverse().sort((a, b) => date(b.at) - date(a.at))[0];
135
135
  }
136
+ /** Draft correction follows the existing effective parts approval, including covering reopens. */
137
+ export function partsDraftEditable(project: RecordData, now = Date.now()): boolean {
138
+ if (!['parts', 'parts-review'].includes(String(project.stage))) return false;
139
+ if ((project.reopens !== undefined && !Array.isArray(project.reopens)) ||
140
+ (project.amendments !== undefined && !Array.isArray(project.amendments))) return false;
141
+ const approvals = records(project.signoffs).filter(s => s.stage === 'parts-review' &&
142
+ (s.checkpoint === null || s.checkpoint === undefined));
143
+ const changes = [...records(project.reopens), ...records(project.amendments).map((entry): RecordData =>
144
+ ({...entry, stage: object(entry.target).stage}))].filter(entry =>
145
+ ['interview', 'plan-approved', 'parts', 'parts-review'].includes(String(entry.stage)));
146
+ if ([...approvals, ...changes].some(entry => !Number.isFinite(date(entry.at)) || date(entry.at) > now)) return false;
147
+ return !approval(project, 'parts-review', now);
148
+ }
136
149
  function draftFor(project: RecordData, signoff: RecordData | undefined, at: number) {
137
150
  return records(project.drafts).find(draft => draft.id === signoff?.draft_id && date(draft.at) <= at);
138
151
  }