@rig-c/review 2.7.0 → 2.8.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/src/rebuild.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import {isDeepStrictEqual} from 'node:util';
2
- import {recordFor,type AnyJobView} from '../web/rebuild-client.ts';
2
+ import {MESH_DELTA_APPLIED_SOURCE,recordFor,type AnyJobView} from '../web/rebuild-client.ts';
3
3
  /**
4
4
  * Apply · Rebuild (issue #99): the user's chest-region designation goes to the installed producer as one mesh entry,
5
5
  * `rig-parts remesh` re-fits that one part of the package's gated rig into a scratch revision, `rigc build` compiles
@@ -16,8 +16,9 @@ import { copyFile, mkdir, readFile, readdir, realpath, rename, rm, writeFile, ls
16
16
  import { dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
17
17
  import { object, packagePath, safeFile, type ReviewPackage } from './manifest.ts';
18
18
  import { compileArgs, firstRefusal, modelingProducerTooOld, REMESH_DELTA_SINCE, remeshArgs, remeshDeltaArgs, resolvePose, resolveProducer, runTool, versionAtLeast, type CompileRequest, type InstalledTool, type ProcessResult } from './producer.ts';
19
- import { meshEditText } from './mesh-edit.ts';
20
- import { CONFIG_NAMED_FILES, CONFIG_SKELETON_NAMES, HANDOFF_DECLARATION, type Handoff, type HandoffRecord } from './handoff.ts';
19
+ import { attachmentHashText, MESH_EDIT_BASIS, MESH_EDIT_CODES, MESH_EDIT_SCHEMA, meshEditText } from './mesh-edit.ts';
20
+ import { readStoredSetupMesh } from './setup-mesh.ts';
21
+ import { CONFIG_NAMED_FILES, CONFIG_SKELETON_NAMES, configNamedReferences, DIRECTORY_INPUT_RECEIPT, HANDOFF_DECLARATION, plateReceiptSpec, receiptSpec, type ConfigReference, type Handoff, type HandoffRecord } from './handoff.ts';
21
22
  import { assertWholeRigBaseline, BaselineError, baselineKey, producerDiff, runBaseline, runInspectedCheck, runningInspectedCheck, type BaselineResult, type InspectedCheck } from './baseline.ts';
22
23
  import { applyConfigPatch, assertOpNames, assertPatchFresh, ConfigPatchError, parseConfigPatch, PATCH_FLAGS, patchSha256, patchText, remeshPart, type ConfigPatch, type JsonValue } from './config-patch.ts';
23
24
  import { barLine } from './physics-tuning.ts';
@@ -39,11 +40,12 @@ import { candidateRow, DENSITY_STRIP_SCHEMA, DensityStripError, stripLabels, str
39
40
  import { samplesClock } from './frame-clock.ts';
40
41
  import { cleanArgs, mapText, motionSummary, parseRetargetRequest, retargetArgs, retargetLines, retargetRecord, retargetRecordText, RetargetError, type MotionSummary, type RetargetLine, type RetargetRecord } from './retarget.ts';
41
42
  import { assertStateOutside as assertStateDirOutside } from './state-dir.ts';
43
+ import type { JoinedProject } from './joined-project.ts';
42
44
 
43
45
  export const REBUILD_SCHEMA = 'rig-review-rebuild/1';
44
46
  const MAX_REGIONS = CHEST_REGIONS_MAX, MAX_POINTS = 256, MAX_LINES = 4000, GRID = 256;
45
47
 
46
- export interface ProducerInputs { config: string; parts: string; rig: string; configText: string; configHash: string; handoff: HandoffRecord; requirements?: { source: string; sha256: string } }
48
+ export interface ProducerInputs { config: string; parts: string; rig: string; configText: string; configHash: string; handoff: HandoffRecord | null; requirements?: { source: string; sha256: string } }
47
49
  const sha256 = (bytes: string | Uint8Array) => createHash('sha256').update(bytes).digest('hex');
48
50
 
49
51
  /** Without any handoff, Apply refuses by this name and says which flag declares one. */
@@ -53,11 +55,11 @@ export const VIEW_ONLY_HANDOFF_STATUS = 'view only, no producer handoff';
53
55
  /** What remesh needs from the handoff, or the line naming what is missing. */
54
56
  export function handoffGap(handoff: Handoff): string | null {
55
57
  if (!handoff.parts) return `MODELING_INPUT_UNAVAILABLE: ${handoff.record.missing.join(', ')}`;
56
- const missing = handoff.record.missing.filter(m => m.startsWith('parts.json') || m.startsWith('rig ') || m.startsWith('requirements '));
58
+ const missing = handoff.record.missing.filter(m => m.startsWith('parts.json') || m.startsWith('rig ') || m.startsWith('requirements ') || m.startsWith('assemble.occluders['));
57
59
  return handoff.rig && !missing.length ? null : `MODELING_INPUT_UNAVAILABLE: ${missing.join(', ') || 'rig'}`;
58
60
  }
59
61
  /** The handoff's config, parts and inspected rig, the config read and checked against the bytes the session is bound to. */
60
- export async function producerInputs(handoff: Handoff | null, reason: string | null): Promise<ProducerInputs> {
62
+ export async function producerInputs(handoff: Handoff | null, reason: string | null, starts?: readonly string[]): Promise<ProducerInputs> {
61
63
  if (!handoff) throw new RebuildError('MODELING_HANDOFF_MISSING', modelingHandoffMissing(reason).slice('MODELING_HANDOFF_MISSING: '.length));
62
64
  const gap = handoffGap(handoff);
63
65
  if (gap) throw new RebuildError('MODELING_INPUT_UNAVAILABLE', gap.slice('MODELING_INPUT_UNAVAILABLE: '.length));
@@ -65,7 +67,10 @@ export async function producerInputs(handoff: Handoff | null, reason: string | n
65
67
  if (configHash !== handoff.record.config.sha256) throw new RebuildError('REBUILD_INPUTS_CHANGED', `${handoff.record.config.path} changed since the review was opened; restart review`);
66
68
  let config: unknown;
67
69
  try { config = JSON.parse(configText); } catch { /* the producer diagnoses invalid JSON */ }
68
- const value = namedFile(config, ['requirements']);
70
+ const searchStarts = [dirname(handoff.config), handoff.root, ...(starts ?? handoff.starts ?? [process.cwd()])];
71
+ const { partsRoot, references } = config !== undefined ? configNamedReferences(config, searchStarts) : { partsRoot: null, references: [] };
72
+ const reqRef = references.find(ref => ref.kind === 'requirements');
73
+ const value = reqRef?.value ?? namedFile(config, ['requirements']);
69
74
  let requirements: ProducerInputs['requirements'];
70
75
  if (typeof value === 'string' && value) {
71
76
  const lexical = resolve(dirname(handoff.config), value);
@@ -82,8 +87,213 @@ export async function producerInputs(handoff: Handoff | null, reason: string | n
82
87
  if (!binding) throw new RebuildError('REBUILD_REQUIREMENTS_UNAVAILABLE', 'config.requirements has no bound handoff hash');
83
88
  requirements = { source, sha256: binding.sha256 };
84
89
  }
90
+ for (const ref of references) {
91
+ if (!ref.at.startsWith('assemble.occluders[')) continue;
92
+ const lexical = resolve(dirname(handoff.config), ref.value);
93
+ const recordedRel = posix.join(posix.dirname(handoff.record.config.path), ref.value);
94
+ if (ref.kind === 'plate') {
95
+ const receiptPath = `${recordedRel}/${DIRECTORY_INPUT_RECEIPT}`;
96
+ const binding = handoff.record.files.find(file => file.path === receiptPath && file.directory === recordedRel);
97
+ if (!binding) throw new RebuildError('MODELING_INPUT_UNAVAILABLE', `${ref.at} ${receiptPath}`);
98
+ let bytes: Buffer;
99
+ try {
100
+ const dirSt = await lstat(lexical);
101
+ if (!dirSt.isDirectory() || await realpath(lexical) !== lexical) throw new Error('invalid dir');
102
+ const receiptLexical = join(lexical, DIRECTORY_INPUT_RECEIPT);
103
+ const fileSt = await lstat(receiptLexical);
104
+ if (!fileSt.isFile() || await realpath(receiptLexical) !== receiptLexical) throw new Error('invalid file');
105
+ bytes = await readFile(receiptLexical);
106
+ } catch {
107
+ throw new RebuildError('REBUILD_INPUTS_CHANGED', `${receiptPath} changed since the review was opened; restart review`);
108
+ }
109
+ const expectedSpec = plateReceiptSpec(partsRoot, `config ${ref.at}`);
110
+ if (sha256(bytes) !== binding.sha256 || binding.spec !== expectedSpec || receiptSpec(bytes) !== expectedSpec) {
111
+ throw new RebuildError('REBUILD_INPUTS_CHANGED', `${receiptPath} changed since the review was opened; restart review`);
112
+ }
113
+ continue;
114
+ }
115
+ const binding = handoff.record.files.find(file => file.path === recordedRel && file.directory === undefined);
116
+ if (!binding) throw new RebuildError('MODELING_INPUT_UNAVAILABLE', `${ref.at} ${recordedRel}`);
117
+ let bytes: Buffer;
118
+ try {
119
+ const fileSt = await lstat(lexical);
120
+ if (!fileSt.isFile() || await realpath(lexical) !== lexical) throw new Error('invalid file');
121
+ bytes = await readFile(lexical);
122
+ } catch {
123
+ throw new RebuildError('REBUILD_INPUTS_CHANGED', `${recordedRel} changed since the review was opened; restart review`);
124
+ }
125
+ if (sha256(bytes) !== binding.sha256) {
126
+ throw new RebuildError('REBUILD_INPUTS_CHANGED', `${recordedRel} changed since the review was opened; restart review`);
127
+ }
128
+ }
85
129
  return { config: handoff.config, parts: handoff.parts!, rig: handoff.rig!, configText, configHash, handoff: handoff.record, ...(requirements ? { requirements } : {}) };
86
130
  }
131
+
132
+ export interface DraftRebuildOption {
133
+ root: string;
134
+ draftId?: string;
135
+ source: NonNullable<JoinedProject['draft']>;
136
+ assertCurrent?: () => Promise<void>;
137
+ starts?: readonly string[];
138
+ }
139
+
140
+ export function draftRebuildOption(joined?: JoinedProject, starts?: readonly string[]): DraftRebuildOption | undefined {
141
+ if (!joined?.draft) return undefined;
142
+ return { root: joined.opened.root, draftId: joined.designation.draftId, source: joined.draft, assertCurrent: joined.assertCurrent, ...(starts ? { starts } : {}) };
143
+ }
144
+
145
+ async function checkDraftRef(root: string, entry: { path: string; sha256: string }): Promise<{ abs: string; bytes: Buffer }> {
146
+ if (!entry || typeof entry.path !== 'string' || !entry.path || isAbsolute(entry.path) || entry.path.split('/').some(seg => !seg || seg === '.' || seg === '..') || typeof entry.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(entry.sha256)) {
147
+ throw new RebuildError('INTERVIEW_SOURCE_MISMATCH', `${String(entry?.path ?? '')} is not a canonical project-relative SetRef`);
148
+ }
149
+ const lexical = resolve(root, entry.path);
150
+ let st: import('node:fs').Stats;
151
+ try {
152
+ st = await lstat(lexical);
153
+ } catch (e) {
154
+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') {
155
+ throw new RebuildError('REBUILD_INPUTS_CHANGED', `${entry.path} is missing since the review was opened; restart review`);
156
+ }
157
+ throw new RebuildError('INTERVIEW_SOURCE_MISMATCH', `${entry.path} is not readable`);
158
+ }
159
+ if (!st.isFile()) throw new RebuildError('INTERVIEW_SOURCE_MISMATCH', `${entry.path} is not a regular file`);
160
+ let real: string;
161
+ try {
162
+ real = await safeFile(root, entry.path);
163
+ } catch {
164
+ throw new RebuildError('INTERVIEW_SOURCE_MISMATCH', `${entry.path} escapes the project root`);
165
+ }
166
+ if (real !== lexical) throw new RebuildError('INTERVIEW_SOURCE_MISMATCH', `${entry.path} resolves through a symlink`);
167
+ const bytes = await readFile(real);
168
+ if (sha256(bytes) !== entry.sha256) {
169
+ throw new RebuildError('REBUILD_INPUTS_CHANGED', `${entry.path} changed since the review was opened; restart review`);
170
+ }
171
+ return { abs: real, bytes };
172
+ }
173
+
174
+ /**
175
+ * #562C: recorded Create Stage 1 draft adapter (`project.json` `drafts[]`). Validates in CP1 order (`config` ->
176
+ * `config_inputs` -> `parts.files` -> `files`) with project-root containment and separate `parts` vs `rig` directories.
177
+ */
178
+ export async function draftProducerInputs(draft: DraftRebuildOption, requireEditable = true, starts?: readonly string[]): Promise<ProducerInputs> {
179
+ if (requireEditable && !draft.source.editable) {
180
+ throw new RebuildError('PARTS_VERDICT_READ_ONLY', 'Stage 1 draft is inspection-only');
181
+ }
182
+ const record = draft.source.record;
183
+ if (draft.draftId !== undefined && draft.draftId !== record.id) {
184
+ throw new RebuildError('INTERVIEW_SOURCE_MISMATCH', `draft id ${draft.draftId} does not match ${record.id}`);
185
+ }
186
+ let root: string;
187
+ try {
188
+ root = await realpath(draft.root);
189
+ if (root !== resolve(draft.root)) throw new Error('redirected');
190
+ } catch {
191
+ throw new RebuildError('INTERVIEW_SOURCE_MISMATCH', 'project root is missing or redirected');
192
+ }
193
+ const cfg = await checkDraftRef(root, record.config);
194
+ const configText = cfg.bytes.toString('utf8'), configHash = record.config.sha256;
195
+ let configDoc: unknown;
196
+ try { configDoc = JSON.parse(configText); } catch { /* the producer diagnoses invalid JSON */ }
197
+ const configInputs = record.config_inputs ?? [];
198
+ let requirements: ProducerInputs['requirements'];
199
+ let partsRoot: string | null = null;
200
+ let references: ConfigReference[] = [];
201
+ const searchStarts = [dirname(cfg.abs), root, ...(starts ?? draft.starts ?? draft.source.starts ?? [process.cwd()])];
202
+ if (configDoc !== undefined) {
203
+ try {
204
+ ({ partsRoot, references } = configNamedReferences(configDoc, searchStarts));
205
+ } catch (e) {
206
+ throw new RebuildError('INTERVIEW_SOURCE_MISMATCH', e instanceof Error ? e.message : String(e));
207
+ }
208
+ }
209
+ for (const ref of references) {
210
+ const isReq = ref.kind === 'requirements';
211
+ if (isAbsolute(ref.value)) {
212
+ throw new RebuildError(isReq ? 'REBUILD_REQUIREMENTS_UNAVAILABLE' : 'INTERVIEW_SOURCE_MISMATCH', `config.${ref.at} must be relative to the config directory`);
213
+ }
214
+ const lexical = resolve(dirname(cfg.abs), ref.value);
215
+ const rel = relative(root, lexical).split(sep).join('/');
216
+ if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
217
+ throw new RebuildError(isReq ? 'REBUILD_REQUIREMENTS_UNAVAILABLE' : 'INTERVIEW_SOURCE_MISMATCH', `config.${ref.at} is missing or outside the bound project`);
218
+ }
219
+ if (ref.kind === 'plate') {
220
+ try {
221
+ const st = await lstat(lexical);
222
+ if (!st.isDirectory()) throw new Error('not a directory');
223
+ const realDir = await realpath(lexical);
224
+ if (realDir !== lexical) throw new Error('redirected');
225
+ } catch {
226
+ throw new RebuildError('INTERVIEW_SOURCE_MISMATCH', `config.${ref.at} is missing or outside the bound project`);
227
+ }
228
+ const receiptRel = `${rel}/${DIRECTORY_INPUT_RECEIPT}`;
229
+ const binding = configInputs.find(file => file.path === receiptRel && file.directory === rel);
230
+ if (!binding) {
231
+ throw new RebuildError('INTERVIEW_SOURCE_MISMATCH', `config.${ref.at} has no bound draft config_inputs hash`);
232
+ }
233
+ const checked = await checkDraftRef(root, binding);
234
+ let expectedSpec: string;
235
+ try {
236
+ expectedSpec = plateReceiptSpec(partsRoot, `config.${ref.at}`);
237
+ } catch (e) {
238
+ throw new RebuildError('INTERVIEW_SOURCE_MISMATCH', e instanceof Error ? e.message : String(e));
239
+ }
240
+ if (binding.spec !== expectedSpec || receiptSpec(checked.bytes) !== expectedSpec) {
241
+ throw new RebuildError('INTERVIEW_SOURCE_MISMATCH', `config.${ref.at} receipt spec does not match ${expectedSpec}`);
242
+ }
243
+ continue;
244
+ }
245
+ let source: string;
246
+ try {
247
+ const st = await lstat(lexical);
248
+ if (!st.isFile()) throw new Error('not a regular file');
249
+ source = await safeFile(root, rel);
250
+ if (source !== lexical) throw new Error('redirected');
251
+ } catch {
252
+ throw new RebuildError(isReq ? 'REBUILD_REQUIREMENTS_UNAVAILABLE' : 'INTERVIEW_SOURCE_MISMATCH', `config.${ref.at} is missing or outside the bound project`);
253
+ }
254
+ const binding = configInputs.find(file => file.path === rel && file.directory === undefined);
255
+ if (!binding) {
256
+ throw new RebuildError(isReq ? 'REBUILD_REQUIREMENTS_UNAVAILABLE' : 'INTERVIEW_SOURCE_MISMATCH', `config.${ref.at} has no bound draft config_inputs hash`);
257
+ }
258
+ if (isReq) requirements = { source, sha256: binding.sha256 };
259
+ }
260
+ for (const entry of configInputs) await checkDraftRef(root, entry);
261
+ for (const entry of record.parts.files) await checkDraftRef(root, entry);
262
+ for (const entry of record.files) await checkDraftRef(root, entry);
263
+ const rigDir = dirname(draft.source.rig);
264
+ try {
265
+ const realParts = await realpath(draft.source.parts);
266
+ const realRig = await realpath(rigDir);
267
+ if (realParts !== resolve(draft.source.parts) || realRig !== resolve(rigDir)) throw new Error('redirected');
268
+ const relParts = relative(root, realParts).split(sep).join('/');
269
+ const relRig = relative(root, realRig).split(sep).join('/');
270
+ if (!relParts || relParts.startsWith('..') || isAbsolute(relParts) || !relRig || relRig.startsWith('..') || isAbsolute(relRig)) {
271
+ throw new Error('outside root');
272
+ }
273
+ } catch {
274
+ throw new RebuildError('INTERVIEW_SOURCE_MISMATCH', 'draft parts or rig directory is missing or outside the project root');
275
+ }
276
+ if (draft.assertCurrent) {
277
+ try {
278
+ await draft.assertCurrent();
279
+ } catch (e) {
280
+ const msg = e instanceof Error ? e.message : String(e);
281
+ if (msg.startsWith('INTERVIEW_OPTIONS_STALE:')) {
282
+ throw new RebuildError('REBUILD_INPUTS_CHANGED', msg.slice('INTERVIEW_OPTIONS_STALE: '.length));
283
+ }
284
+ throw e;
285
+ }
286
+ }
287
+ return {
288
+ config: cfg.abs,
289
+ parts: draft.source.parts,
290
+ rig: rigDir,
291
+ configText,
292
+ configHash,
293
+ handoff: null,
294
+ ...(requirements ? { requirements } : {}),
295
+ };
296
+ }
87
297
  /**
88
298
  * #305: fast producer handoff readiness check for `open` (`handoffGap`, `producerInputs`, `resolveProducer`,
89
299
  * `contourParts`). With `viewOnly`, an absent handoff (`!p.handoff`) is permitted; a declared or partly discovered
@@ -95,7 +305,7 @@ export async function verifyHandoffReadiness(p: ReviewPackage, starts: readonly
95
305
  if (gap) return gap;
96
306
  let inputs: ProducerInputs;
97
307
  try {
98
- inputs = await producerInputs(p.handoff, p.handoffReason);
308
+ inputs = await producerInputs(p.handoff, p.handoffReason, starts);
99
309
  } catch (e) {
100
310
  return e instanceof Error ? e.message : String(e);
101
311
  }
@@ -510,12 +720,13 @@ const namedFile = (doc: unknown, keys: readonly string[]): unknown => keys.reduc
510
720
  * loader resolves against the config's directory made
511
721
  * absolute when it names a file there, so the scratch copy reads the same files as the handoff config.
512
722
  */
513
- export function scratchConfigText(configPath: string, doc: JsonValue): string {
723
+ export function scratchConfigText(configPath: string, doc: JsonValue, starts: readonly string[] = [process.cwd()]): string {
514
724
  const configDir = dirname(resolve(configPath)), out = structuredClone(doc) as Record<string, unknown>;
515
- for (const keys of CONFIG_NAMED_FILES) {
516
- const holder = namedFile(out, keys.slice(0, -1)) as Record<string, unknown> | undefined, key = keys.at(-1)!, value = holder?.[key];
517
- if (keys.length === 3 && (CONFIG_SKELETON_NAMES as readonly unknown[]).includes(value)) continue;
518
- if (typeof value === 'string' && value && !isAbsolute(value) && existsSync(resolve(configDir, value))) holder![key] = resolve(configDir, value);
725
+ const { references } = configNamedReferences(out, [configDir, ...starts]);
726
+ for (const ref of references) {
727
+ if (!isAbsolute(ref.value) && existsSync(resolve(configDir, ref.value))) {
728
+ ref.set(resolve(configDir, ref.value));
729
+ }
519
730
  }
520
731
  return JSON.stringify(out, null, 2) + '\n';
521
732
  }
@@ -542,8 +753,24 @@ function rebuildConfigIdentity(inputs: ProducerInputs): string {
542
753
  }
543
754
 
544
755
  /** A patch may not change which files the config names (they are the handoff's hashed files): `EDIT_PATCH_PATH_HELD`. */
545
- export function assertNamedFilesHeld(before: unknown, after: unknown): void {
546
- for (const keys of CONFIG_NAMED_FILES) if (JSON.stringify(namedFile(before, keys)) !== JSON.stringify(namedFile(after, keys))) throw new RebuildError('EDIT_PATCH_PATH_HELD', `${keys.join('.')} names a handoff file; a patch may not change it`);
756
+ export function assertNamedFilesHeld(before: unknown, after: unknown, starts: readonly string[] = [process.cwd()]): void {
757
+ for (const keys of CONFIG_NAMED_FILES) {
758
+ if (JSON.stringify(namedFile(before, keys)) !== JSON.stringify(namedFile(after, keys))) {
759
+ throw new RebuildError('EDIT_PATCH_PATH_HELD', `${keys.join('.')} names a handoff file; a patch may not change it`);
760
+ }
761
+ }
762
+ const beforeRefs = configNamedReferences(before, starts).references;
763
+ const afterRefs = configNamedReferences(after, starts).references;
764
+ const byAt = new Map(beforeRefs.map(ref => [ref.at, ref.value]));
765
+ for (const ref of afterRefs) {
766
+ if (byAt.get(ref.at) !== ref.value) {
767
+ throw new RebuildError('EDIT_PATCH_PATH_HELD', `${ref.at} names a handoff file; a patch may not change it`);
768
+ }
769
+ byAt.delete(ref.at);
770
+ }
771
+ for (const [at] of byAt) {
772
+ throw new RebuildError('EDIT_PATCH_PATH_HELD', `${at} names a handoff file; a patch may not change it`);
773
+ }
547
774
  }
548
775
  /** The value of a flag in the patch's args, or the producer's default. */
549
776
  const flagValue = (args: readonly string[], flag: string, fallback: string) => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1]! : fallback; };
@@ -556,6 +783,8 @@ export interface RebuildOptions {
556
783
  stripPrefix?: string;
557
784
  /** #305: viewer-only mode (`--view-only`); when there is no handoff, reports neutral view-only status instead of `MODELING_*`. */
558
785
  viewOnly?: boolean;
786
+ /** #562C: recorded Create Stage 1 draft (`project.json` `drafts[]`). */
787
+ draft?: DraftRebuildOption;
559
788
  }
560
789
  /** #173: a density strip's scratch — one folder per package, holding at most the one strip on screen. */
561
790
  export const stripRoot = (stateDir: string, sourceHash: string) => join(stateDir, 'density-strip', sourceHash);
@@ -770,16 +999,40 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
770
999
  let restoring: { id: string; files: Record<string, string> } | null = null;
771
1000
  const snapshot = <J extends RebuildJob | PatchJob | DeltaJob | RetargetJob | AnimationJob>(job: J): J => ({ ...job, lines: [...job.lines] });
772
1001
 
773
- /** The state directory may not sit inside the package or the handoff's root (the parent of an opened out/). */
1002
+ /** The state directory may not sit inside the package, the handoff's root, or a designated Create project root. */
774
1003
  function assertStateOutside(): void {
775
- assertStateDirOutside(options.stateDir, p, (message, code) => new RebuildError(code ?? 'REBUILD_STATE_INSIDE_PACKAGE', message));
1004
+ const make = (message: string, code?: 'STATE_DIRECTORY_INVALID') => new RebuildError(code ?? 'REBUILD_STATE_INSIDE_PACKAGE', message);
1005
+ assertStateDirOutside(options.stateDir, p, make);
1006
+ if (options.draft) {
1007
+ assertStateDirOutside(options.stateDir, { root: options.draft.root }, make);
1008
+ }
1009
+ }
1010
+ async function activeProducerInputs(requireEditable = true): Promise<ProducerInputs> {
1011
+ if (options.draft) {
1012
+ if (requireEditable && (options.viewOnly ?? p.viewOnly)) {
1013
+ throw new RebuildError('PARTS_VERDICT_READ_ONLY', 'Stage 1 draft is inspection-only');
1014
+ }
1015
+ const inputs = await draftProducerInputs(options.draft, requireEditable, options.starts);
1016
+ try {
1017
+ await options.unchanged();
1018
+ } catch (e) {
1019
+ const msg = e instanceof Error ? e.message : String(e);
1020
+ if (msg.startsWith('INTERVIEW_OPTIONS_STALE:')) {
1021
+ throw new RebuildError('REBUILD_INPUTS_CHANGED', msg.slice('INTERVIEW_OPTIONS_STALE: '.length));
1022
+ }
1023
+ throw e;
1024
+ }
1025
+ return inputs;
1026
+ }
1027
+ await options.unchanged();
1028
+ return producerInputs(p.handoff, p.handoffReason, options.starts);
776
1029
  }
777
1030
  /** Once per session: the first time the handoff and the producer both resolve, the baseline starts (or is reused). */
778
1031
  let baseline: BaselineResult | null = null, baselineRun: Promise<BaselineResult> | null = null;
779
1032
  /** #108 (HQ): the inspected build's check, started once the baseline reproduces; stored beside the baseline record. */
780
1033
  let inspectedCheck: InspectedCheck | null = null, inspectedCheckRun: Promise<InspectedCheck> | null = null;
781
1034
  function ensureBaseline(resolved: ReturnType<typeof resolveProducer>): BaselineResult | null {
782
- if (baselineRun || !p.handoff || !resolved.ok) return baseline;
1035
+ if (options.draft || baselineRun || !p.handoff || !resolved.ok) return baseline;
783
1036
  try { assertStateOutside(); } catch { return null; }
784
1037
  const handoff = p.handoff, key = baselineKey(p.sourceHash, handoff, resolved.producer, resolved.compiler), rig = handoff.rig ?? p.root;
785
1038
  const show = (rel: string) => relative(p.root, join(rig, rel)).split(sep).join('/');
@@ -804,10 +1057,78 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
804
1057
 
805
1058
  /** `GET /api/rebuild`: whether Apply can run here, the handoff and its baseline, and what the config holds (so the editor can start from it). */
806
1059
  async function describe() {
1060
+ if (options.draft) {
1061
+ const d = options.draft.source, rec = d.record;
1062
+ const viewOnly = Boolean(options.viewOnly ?? p.viewOnly);
1063
+ const editable = d.editable && !viewOnly;
1064
+ const inputs = await activeProducerInputs(false);
1065
+ const resolved = resolveProducer(options.starts);
1066
+ const parts = contourParts(inputs.configText).map(({ name, regions }) => ({ name, regions }));
1067
+ const contour = Object.fromEntries(contourParts(inputs.configText).map(({ name, entry }) => [name, entry]));
1068
+ const rigRel = relative(options.draft.root, dirname(d.rig)).split(sep).join('/');
1069
+ const reason = !editable
1070
+ ? 'PARTS_VERDICT_READ_ONLY: Stage 1 draft is inspection-only'
1071
+ : !resolved.ok
1072
+ ? resolved.error
1073
+ : parts.length
1074
+ ? null
1075
+ : 'REBUILD_INPUTS_UNAVAILABLE: the config states no contour mesh';
1076
+ return {
1077
+ schema: 'rig-review-rebuild-status/1',
1078
+ available: editable && resolved.ok && parts.length > 0,
1079
+ ...(viewOnly ? { viewOnly: true } : {}),
1080
+ handoff: null,
1081
+ draft: {
1082
+ id: rec.id,
1083
+ kind: rec.kind,
1084
+ at: rec.at,
1085
+ producer: { name: rec.producer.name, version: rec.producer.version },
1086
+ editable,
1087
+ config: rec.config,
1088
+ ...(rec.config_inputs ? { config_inputs: rec.config_inputs } : {}),
1089
+ parts: rec.parts,
1090
+ files: rec.files,
1091
+ },
1092
+ inputs: { config: rec.config.path, parts: rec.parts.path, rig: rigRel, configHash: inputs.configHash },
1093
+ baseline: null,
1094
+ inspectedCheck: null,
1095
+ parts,
1096
+ contour,
1097
+ meshes: configMeshes(inputs.configText),
1098
+ constraints: null,
1099
+ bones: configBonesList(inputs.configText),
1100
+ fields: null,
1101
+ cuts: null,
1102
+ idle: null,
1103
+ cloth: null,
1104
+ producer: resolved.ok ? tool(resolved.producer) : null,
1105
+ compiler: resolved.ok ? tool(resolved.compiler) : null,
1106
+ retarget: {
1107
+ available: false,
1108
+ reason: 'STAGE_DRAFT_OPERATION: only applied mesh corrections belong to this inspection',
1109
+ producer: null,
1110
+ compiler: null,
1111
+ rig: rigRel,
1112
+ sequences: [],
1113
+ bones: [],
1114
+ animations: [],
1115
+ },
1116
+ animations: {
1117
+ available: false,
1118
+ reason: 'STAGE_DRAFT_OPERATION: only applied mesh corrections belong to this inspection',
1119
+ path: null,
1120
+ sha256: null,
1121
+ text: null,
1122
+ easings: null,
1123
+ },
1124
+ reason,
1125
+ running,
1126
+ };
1127
+ }
807
1128
  await options.unchanged();
808
1129
  const handoff = p.handoff, gap = handoff ? handoffGap(handoff) : null;
809
1130
  const viewOnly = Boolean((options.viewOnly ?? p.viewOnly) && !handoff);
810
- const inputs = handoff && !gap ? await producerInputs(handoff, p.handoffReason) : null;
1131
+ const inputs = handoff && !gap ? await producerInputs(handoff, p.handoffReason, options.starts) : null;
811
1132
  const resolved = resolveProducer(options.starts);
812
1133
  const parts = inputs ? contourParts(inputs.configText).map(({ name, regions }) => ({ name, regions })) : [];
813
1134
  const contour = inputs ? Object.fromEntries(contourParts(inputs.configText).map(({ name, entry }) => [name, entry])) : {};
@@ -890,7 +1211,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
890
1211
  };
891
1212
  }
892
1213
  const showFrom = relative(await realpath(p.root), absFrom).split(sep).join('/') || '.';
893
- const handoffFile = inputs.handoff.files.find(f => f.path === showFrom);
1214
+ const handoffFile = inputs.handoff!.files.find(f => f.path === showFrom);
894
1215
  if (!handoffFile) {
895
1216
  return {
896
1217
  available: false,
@@ -939,19 +1260,43 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
939
1260
  }
940
1261
  /** Stage 1 can read only the revision explicitly drawn by the page, never a pending candidate. */
941
1262
  async function stageDraft(id: string) {
942
- await options.unchanged();
943
- const current = latest();
944
- if (!current || current.id !== id || busy()) throw new RebuildError('STAGE_DRAFT_STALE', 'the requested scratch build is not the settled applied revision');
1263
+ const assertSource = async () => {
1264
+ await options.unchanged();
1265
+ if (options.draft) {
1266
+ if (options.viewOnly ?? p.viewOnly) throw new RebuildError('STAGE_DRAFT_UNAVAILABLE', 'Stage 1 draft is inspection-only');
1267
+ await draftProducerInputs(options.draft, true, options.starts);
1268
+ }
1269
+ };
1270
+ const assertCurrentSelection = () => {
1271
+ const active = latest();
1272
+ if (!active || active.id !== id || busy()) throw new RebuildError('STAGE_DRAFT_STALE', 'the requested scratch build is not the settled applied revision');
1273
+ return active;
1274
+ };
1275
+ await assertSource();
1276
+ const current = assertCurrentSelection();
945
1277
  const job = jobs.get(id)!;
946
- if (!job.stageInputHash || await stageInputDigest(rebuildDir(options.stateDir,p.sourceHash,id),current.spec) !== job.stageInputHash) throw new RebuildError('STAGE_DRAFT_CHANGED', 'scratch revision bytes differ from Apply');
947
- const now = await hashBuild(current.build, id, assetPrefix);
948
- if (JSON.stringify(now.files) !== JSON.stringify(job.build!.files)) throw new RebuildError('STAGE_DRAFT_CHANGED', 'scratch build bytes differ from the applied record');
949
- if (!('check' in job) || !job.check || job.check.pass !== true || job.check.exitCode !== 0) throw new RebuildError('STAGE_DRAFT_UNCHECKED', 'this revision has no successful recorded producer check');
950
- if (!('kind' in job) || job.kind === 'delta' || (job.kind === 'patch' && job.op === 'remesh')) {
951
- const carried = await opCarried('remesh', current.spec, null, () => {});
952
- if (carried && 'refused' in carried) throw new RebuildError('STAGE_DRAFT_CHANGED', carried.refused);
953
- } else throw new RebuildError('STAGE_DRAFT_OPERATION', 'only applied mesh corrections belong to this inspection');
954
- return {id, spec: current.spec, model: join(current.build, 'skeleton.model.json'), evidence: snapshot(job)};
1278
+ let now: RebuildBuild;
1279
+ try {
1280
+ if (!job.stageInputHash || await stageInputDigest(rebuildDir(options.stateDir,p.sourceHash,id),current.spec) !== job.stageInputHash) throw new RebuildError('STAGE_DRAFT_CHANGED', 'scratch revision bytes differ from Apply');
1281
+ now = await hashBuild(current.build, id, assetPrefix);
1282
+ if (JSON.stringify(now.files) !== JSON.stringify(job.build!.files)) throw new RebuildError('STAGE_DRAFT_CHANGED', 'scratch build bytes differ from the applied record');
1283
+ if (!('check' in job) || !job.check || job.check.pass !== true || job.check.exitCode !== 0) throw new RebuildError('STAGE_DRAFT_UNCHECKED', 'this revision has no successful recorded producer check');
1284
+ if (!('kind' in job) || job.kind === 'delta' || (job.kind === 'patch' && job.op === 'remesh')) {
1285
+ const carried = await opCarried('remesh', current.spec, null, () => {});
1286
+ if (carried && 'refused' in carried) throw new RebuildError('STAGE_DRAFT_CHANGED', carried.refused);
1287
+ } else throw new RebuildError('STAGE_DRAFT_OPERATION', 'only applied mesh corrections belong to this inspection');
1288
+ } catch (error) {
1289
+ assertCurrentSelection();
1290
+ if (error instanceof RebuildError) throw error;
1291
+ throw new RebuildError('STAGE_DRAFT_CHANGED', 'scratch revision bytes differ from Apply');
1292
+ }
1293
+ await assertSource();
1294
+ const settled = assertCurrentSelection();
1295
+ const settledJob = jobs.get(id)!;
1296
+ if (settled.spec !== current.spec || settled.build !== current.build || settled.modelHash !== current.modelHash || settledJob !== job || JSON.stringify(now.files) !== JSON.stringify(settledJob.build?.files)) {
1297
+ throw new RebuildError('STAGE_DRAFT_STALE', 'the requested scratch build is not the settled applied revision');
1298
+ }
1299
+ return {id, spec: settled.spec, model: join(settled.build, 'skeleton.model.json'), evidence: snapshot(settledJob)};
955
1300
  }
956
1301
  /** Historical evidence is independent of the disposable Undo cache; current-stage reads still use stageDraft. */
957
1302
  const evidenceBinding={id:p.manifest.id,revision:p.manifest.revision,sourceHash:p.sourceHash,reviewedSource:p.reviewedSource};
@@ -1126,6 +1471,11 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1126
1471
  let now = 'unreadable';
1127
1472
  try { now = sha256(await readFile(handoff.config)); } catch { /* named below */ }
1128
1473
  if (now !== pred.configHash) throw new RebuildError(UNDO_PREDECESSOR_CHANGED, `${handoff.record.config.path} sha256 ${pred.configHash.slice(0, 12)}… → ${now === 'unreadable' ? now : `${now.slice(0, 12)}…`}; the evicted build was made from the config as it was`);
1474
+ } else if (options.draft) {
1475
+ const cfgRef = options.draft.source.record.config;
1476
+ let now = 'unreadable';
1477
+ try { now = sha256(await readFile(await safeFile(await realpath(options.draft.root), cfgRef.path))); } catch { /* named below */ }
1478
+ if (now !== pred.configHash) throw new RebuildError(UNDO_PREDECESSOR_CHANGED, `${cfgRef.path} sha256 ${pred.configHash.slice(0, 12)}… → ${now === 'unreadable' ? now : `${now.slice(0, 12)}…`}; the evicted build was made from the config as it was`);
1129
1479
  }
1130
1480
  const retargeting = 'kind' in pred.job && pred.job.kind === 'retarget';
1131
1481
  const resolved = retargeting ? resolvePose(options.starts) : resolveProducer(options.starts);
@@ -1220,7 +1570,12 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1220
1570
  }
1221
1571
  // The package and its producer inputs must still be the bytes the request was made against.
1222
1572
  // The handoff files are in the reviewed identity, so this also catches a config, parts or rig change.
1223
- try { await options.unchanged(); } catch { throw new RebuildError('REBUILD_INPUTS_CHANGED', 'the package or its producer handoff changed during the rebuild'); }
1573
+ try {
1574
+ await options.unchanged();
1575
+ if (options.draft) await draftProducerInputs(options.draft, true, options.starts);
1576
+ } catch {
1577
+ throw new RebuildError('REBUILD_INPUTS_CHANGED', 'the package or its producer handoff changed during the rebuild');
1578
+ }
1224
1579
  if(!('kind' in job)||job.kind==='delta'||(job.kind==='patch'&&job.op==='remesh')||await exists(join(dir,CONFIG_INPUTS))) {
1225
1580
  job.stageInputHash = await stageInputDigest(dir, join(dir, op.spec));
1226
1581
  }
@@ -1279,7 +1634,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1279
1634
  let counts: RemeshCounts | null = null;
1280
1635
  let built: ProcessResult | null = null;
1281
1636
  async function writePatchConfig(): Promise<void> {
1282
- const doc = JSON.parse(scratchConfigText(inputs.config, patched)) as Record<string, unknown>;
1637
+ const doc = JSON.parse(scratchConfigText(inputs.config, patched, options.starts)) as Record<string, unknown>;
1283
1638
  await stageRequirements(dir, inputs.requirements, doc);
1284
1639
  await writeFile(join(dir, 'config.json'), JSON.stringify(doc, null, 2) + '\n', { mode: 0o600 });
1285
1640
  }
@@ -1305,7 +1660,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1305
1660
  const c = job.cloth!, plan2 = cloth!;
1306
1661
  // cloth.json: the patched handoff config with every path it names made absolute (the scratch copy reads the
1307
1662
  // handoff's files), so the config propose writes beside it builds from the same files.
1308
- const input = JSON.parse(scratchConfigText(inputs.config, patched)) as Record<string, unknown>;
1663
+ const input = JSON.parse(scratchConfigText(inputs.config, patched, options.starts)) as Record<string, unknown>;
1309
1664
  absolutizeBuildFiles(input, value => (isAbsolute(value) ? value : resolve(dirname(inputs.config), value)));
1310
1665
  await stageRequirements(dir, inputs.requirements, input);
1311
1666
  await writeFile(join(dir, 'cloth.json'), JSON.stringify(input, null, 2) + '\n', { mode: 0o600 });
@@ -1338,7 +1693,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1338
1693
  if (job.op === 'cloth' && cloth) return runCloth(push);
1339
1694
  if (job.op === 'build' && plan) {
1340
1695
  // #115: assemble → rig → check from the painting and the runs, the patched config's assemble-read files absolute.
1341
- const doc = JSON.parse(scratchConfigText(inputs.config, patched)) as Record<string, unknown>;
1696
+ const doc = JSON.parse(scratchConfigText(inputs.config, patched, options.starts)) as Record<string, unknown>;
1342
1697
  absolutizeBuildFiles(doc, value => (isAbsolute(value) ? value : resolve(dirname(inputs.config), value)));
1343
1698
  await stageRequirements(dir, inputs.requirements, doc);
1344
1699
  await writeFile(join(dir, 'config.json'), JSON.stringify(doc, null, 2) + '\n', { mode: 0o600 });
@@ -1429,8 +1784,10 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1429
1784
  let patch: ConfigPatch;
1430
1785
  try { patch = parseConfigPatch(input); } catch (e) { if (e instanceof ConfigPatchError) throw new RebuildError(e.code, e.message.slice(e.code.length + 2)); throw e; }
1431
1786
  assertStateOutside();
1432
- await options.unchanged();
1433
- const inputs = await producerInputs(p.handoff, p.handoffReason);
1787
+ const inputs = await activeProducerInputs();
1788
+ if (options.draft && (patch.op.cmd !== 'remesh' || world !== null)) {
1789
+ throw new RebuildError('STAGE_DRAFT_OPERATION', 'only applied mesh corrections belong to this inspection');
1790
+ }
1434
1791
  let patched: JsonValue, part: string | null = null;
1435
1792
  const original = JSON.parse(inputs.configText) as JsonValue;
1436
1793
  try {
@@ -1439,7 +1796,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1439
1796
  patched = applyConfigPatch(original, patch.ops);
1440
1797
  if (patch.op.cmd === 'remesh') part = remeshPart(patch);
1441
1798
  } catch (e) { if (e instanceof ConfigPatchError) throw new RebuildError(e.code, e.message.slice(e.code.length + 2)); throw e; }
1442
- assertNamedFilesHeld(original, patched);
1799
+ assertNamedFilesHeld(original, patched, [dirname(inputs.config), ...options.starts]);
1443
1800
  // #111: a cloth recipe patch (every op under /cloth) runs propose --cloth --write-config, then builds what it wrote.
1444
1801
  // Decision 1: without the declared keypoints the draft moves the body bones, so it is refused before anything else.
1445
1802
  const clothKind = clothPatchKind(patch.ops);
@@ -1513,15 +1870,14 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1513
1870
  let shape: ReturnType<typeof stripShape>;
1514
1871
  try { shape = stripShape(patches); } catch (e) { if (e instanceof DensityStripError) throw new RebuildError(e.code, e.message.slice(e.code.length + 2)); throw e; }
1515
1872
  assertStateOutside();
1516
- await options.unchanged();
1517
- const inputs = await producerInputs(p.handoff, p.handoffReason);
1873
+ const inputs = await activeProducerInputs();
1518
1874
  const original = JSON.parse(inputs.configText) as JsonValue;
1519
1875
  const planned: { patch: ConfigPatch; patched: JsonValue }[] = [];
1520
1876
  for (const patch of patches) {
1521
1877
  let patched: JsonValue;
1522
1878
  try { assertPatchFresh(patch, inputs.configHash); assertOpNames(original, patch.ops); patched = applyConfigPatch(original, patch.ops); remeshPart(patch); }
1523
1879
  catch (e) { if (e instanceof ConfigPatchError) throw new RebuildError(e.code, e.message.slice(e.code.length + 2)); throw e; }
1524
- assertNamedFilesHeld(original, patched);
1880
+ assertNamedFilesHeld(original, patched, [dirname(inputs.config), ...options.starts]);
1525
1881
  planned.push({ patch, patched });
1526
1882
  }
1527
1883
  const resolved = resolveProducer(options.starts);
@@ -1640,6 +1996,35 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1640
1996
  c.applied = true;
1641
1997
  }
1642
1998
 
1999
+ /** Only identify a retained scratch attachment. The producer still judges deltas over the inspected rig. */
2000
+ async function deltaOnAppliedDraft(request: DeltaRequest): Promise<boolean> {
2001
+ const draft = options.draft?.source;
2002
+ const delta = request.delta;
2003
+ const source = delta.source as { hash?: unknown } | null | undefined;
2004
+ const hash = source?.hash;
2005
+ if (!draft || !stack.length || delta.schema !== MESH_EDIT_SCHEMA || delta.basis !== MESH_EDIT_BASIS ||
2006
+ delta.slot !== request.part || typeof delta.skin !== 'string' || typeof delta.attachment !== 'string' ||
2007
+ typeof hash !== 'string' || !/^[a-f0-9]{64}$/.test(hash)) return false;
2008
+ const key = { skin: delta.skin, attachment: delta.attachment };
2009
+ async function matches(path: string, expected: string | undefined): Promise<boolean> {
2010
+ if (!expected) return false;
2011
+ try {
2012
+ const bytes = await readFile(path);
2013
+ if (sha256(bytes) !== expected) return false;
2014
+ const result = readStoredSetupMesh(JSON.parse(bytes.toString('utf8')), request.part, key, MESH_EDIT_CODES);
2015
+ return result.ok && !result.mesh.linked && sha256(attachmentHashText(result.mesh.entry)) === hash;
2016
+ } catch { return false; }
2017
+ }
2018
+ // Reset can leave the server stack intact. An inspected-compatible delta always goes to the producer.
2019
+ if (await matches(draft.model, draft.files.get(draft.model))) return false;
2020
+ for (const entry of stack.slice(-MAX_KEPT_BUILDS).reverse()) {
2021
+ const dir = entry === stack.at(-1) ? rebuildDir(options.stateDir, p.sourceHash, entry.id)
2022
+ : join(keptRoot(options.stateDir, p.sourceHash), entry.id);
2023
+ if (await matches(join(dir, 'build', 'skeleton.model.json'), entry.modelHash)) return true;
2024
+ }
2025
+ return false;
2026
+ }
2027
+
1643
2028
  /** #135: the delta → `rig-parts remesh --delta mesh-edit.json --part <part>` → `<dir>/rig`; the tail adds the per-file diff. */
1644
2029
  function executeDelta(job: DeltaJob, dir: string, inputs: ProducerInputs, resolved: Resolved, text: string): Promise<void> {
1645
2030
  const producer = resolved.producer, part = job.request.part;
@@ -1676,8 +2061,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1676
2061
  async function startDelta(input: unknown): Promise<{ status: number; body: unknown }> {
1677
2062
  const request = parseDeltaRequest(input);
1678
2063
  assertStateOutside();
1679
- await options.unchanged();
1680
- const inputs = await producerInputs(p.handoff, p.handoffReason);
2064
+ const inputs = await activeProducerInputs();
1681
2065
  if (inputs.configHash !== request.configHash) throw new RebuildError('REBUILD_CONFIG_STALE', 'the producer config changed since the editor read it; reload');
1682
2066
  const resolved = resolveProducer(options.starts);
1683
2067
  if (!resolved.ok) return { status: 200, body: { status: 'refused', error: resolved.error, producerLine: resolved.error } };
@@ -1691,6 +2075,9 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1691
2075
  if (current?.status === 'running') return { status: 202, body: snapshot(current) };
1692
2076
  if (busy()) return { status: 200, body: { status: 'refused', error: busy(), producerLine: null } };
1693
2077
  return reserve(`REBUILD_BUSY: rebuild ${id} is still running`, async () => {
2078
+ if (await deltaOnAppliedDraft(request)) {
2079
+ return { status: 200, body: { status: 'refused', error: MESH_DELTA_APPLIED_SOURCE, producerLine: null } };
2080
+ }
1694
2081
  guardRestore(id);
1695
2082
  const dir = rebuildDir(options.stateDir, p.sourceHash, id);
1696
2083
  await adopt(id);
@@ -1788,9 +2175,13 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1788
2175
  * map's resolution against the rig, the flags' combinations and the pose are the producer's to judge, verbatim.
1789
2176
  */
1790
2177
  async function startRetarget(input: unknown, body: unknown = { retarget: input }): Promise<{ status: number; body: unknown }> {
2178
+ assertStateOutside();
2179
+ if (options.draft) {
2180
+ await activeProducerInputs();
2181
+ throw new RebuildError('STAGE_DRAFT_OPERATION', 'only applied mesh corrections belong to this inspection');
2182
+ }
1791
2183
  let request: ReturnType<typeof parseRetargetRequest>;
1792
2184
  try { request = parseRetargetRequest(input); } catch (e) { if (e instanceof RetargetError) throw new RebuildError(e.code, e.message.slice(e.code.length + 2)); throw e; }
1793
- assertStateOutside();
1794
2185
  await options.unchanged();
1795
2186
  const inputs = await producerInputs(p.handoff, p.handoffReason);
1796
2187
  if (inputs.configHash !== request.configHash) throw new RebuildError('REBUILD_CONFIG_STALE', 'the producer config changed since the editor read it; reload');
@@ -1803,7 +2194,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1803
2194
  const resolved = resolvePose(options.starts);
1804
2195
  if (!resolved.ok) return { status: 200, body: { status: 'refused', error: resolved.error, producerLine: resolved.error } };
1805
2196
  const rigJson = await readFile(join(inputs.rig, 'rig.json'));
1806
- const record = retargetRecord(request, { rig: { path: inputs.handoff.rig ?? '', sha256: sha256(rigJson) }, sequence: { path: reference.path, sha256: sha256(sequence) }, producer: { name: resolved.producer.package, version: resolved.producer.version } });
2197
+ const record = retargetRecord(request, { rig: { path: inputs.handoff?.rig ?? '', sha256: sha256(rigJson) }, sequence: { path: reference.path, sha256: sha256(sequence) }, producer: { name: resolved.producer.package, version: resolved.producer.version } });
1807
2198
  const id = retargetId({ sourceHash: p.sourceHash, configHash: rebuildConfigIdentity(inputs), record, producer: `${resolved.producer.package}@${resolved.producer.version}`, compiler: `${resolved.compiler.package}@${resolved.compiler.version}` });
1808
2199
  const current = jobs.get(id);
1809
2200
  if (current?.status === 'running') return { status: 202, body: snapshot(current) };
@@ -1855,8 +2246,12 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1855
2246
  * the handoff text) are refused before anything is written or run; producer refusals return by name with nothing landed.
1856
2247
  */
1857
2248
  async function startAnimation(input: unknown, world: ApplyWorld | null = null, rawEnvironment?: unknown): Promise<{ status: number; body: unknown }> {
1858
- const request = parseAnimationRequest(input);
1859
2249
  assertStateOutside();
2250
+ if (options.draft) {
2251
+ await activeProducerInputs();
2252
+ throw new RebuildError('STAGE_DRAFT_OPERATION', 'only applied mesh corrections belong to this inspection');
2253
+ }
2254
+ const request = parseAnimationRequest(input);
1860
2255
  await options.unchanged();
1861
2256
  const inputs = await producerInputs(p.handoff, p.handoffReason);
1862
2257
  if (inputs.configHash !== request.configHash) throw new RebuildError('REBUILD_CONFIG_STALE', 'the producer config changed since the editor read it; reload');
@@ -1869,7 +2264,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1869
2264
  try { absFrom = await realpath(resolve(dirname(inputs.config), relFrom)); }
1870
2265
  catch { throw new RebuildError('ANIMATION_SOURCE_MISSING', `config motion.animations_from (${relFrom}) does not exist`); }
1871
2266
  const showFrom = relative(await realpath(p.root), absFrom).split(sep).join('/') || '.';
1872
- const handoffFile = inputs.handoff.files.find(f => f.path === showFrom);
2267
+ const handoffFile = inputs.handoff!.files.find(f => f.path === showFrom);
1873
2268
  if (!handoffFile) throw new RebuildError('ANIMATION_SOURCE_MISSING', `config motion.animations_from (${showFrom}) is missing from the handoff`);
1874
2269
  const baseAnimText = await readFile(absFrom, 'utf8'), baseAnimHash = sha256(baseAnimText);
1875
2270
  if (baseAnimHash !== handoffFile.sha256) throw new RebuildError('REBUILD_INPUTS_CHANGED', `${showFrom} changed since the review was opened; restart review`);
@@ -1926,7 +2321,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1926
2321
  if (current?.status === 'running') return { status: 202, body: snapshot(current) };
1927
2322
  if (busy()) return { status: 200, body: { status: 'refused', error: busy(), producerLine: null } };
1928
2323
 
1929
- const scratchDoc = JSON.parse(scratchConfigText(inputs.config, configDoc as unknown as JsonValue)) as Record<string, unknown>;
2324
+ const scratchDoc = JSON.parse(scratchConfigText(inputs.config, configDoc as unknown as JsonValue, options.starts)) as Record<string, unknown>;
1930
2325
  (scratchDoc.motion as Record<string, unknown>).animations_from = 'animations.json';
1931
2326
  const scratchCfgText = JSON.stringify(scratchDoc, null, 2) + '\n';
1932
2327
  const recordedBody = {
@@ -2000,8 +2395,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
2000
2395
  }
2001
2396
  const request = parseRebuildRequest(input, options.bones);
2002
2397
  assertStateOutside();
2003
- await options.unchanged();
2004
- const inputs = await producerInputs(p.handoff, p.handoffReason);
2398
+ const inputs = await activeProducerInputs();
2005
2399
  if (inputs.configHash !== request.configHash) throw new RebuildError('REBUILD_CONFIG_STALE', 'the producer config changed since the editor read it; reload');
2006
2400
  const entry = request.bust ? bustEntryText(inputs.configText, request.part, request.bust) : meshEntryText(inputs.configText, request.part, request.regions);
2007
2401
  const resolved = resolveProducer(options.starts);