rig-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/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 };
@@ -3,6 +3,12 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpat
3
3
  import { extname, join, resolve } from 'node:path';
4
4
  import { isDeepStrictEqual as equal } from 'node:util';
5
5
  import {coveringChange, sceneAt} from './interview-scene.ts';
6
+ import type {
7
+ JobInterviewDiagnostic,
8
+ JobInterviewDiagnostics,
9
+ JobInterviewJson,
10
+ JobInterviewRecord,
11
+ } from './job-contract.ts';
6
12
 
7
13
  type RecordData = Record<string, unknown>;
8
14
  export interface SetRef {path: string; sha256: string}
@@ -133,6 +139,19 @@ function approval(project: RecordData, stage: string, at: number) {
133
139
  text(s.by) && s.by.toLowerCase() !== 'agent' && date(s.at) <= at &&
134
140
  !reopened(project, stage, date(s.at) - 1, at)).reverse().sort((a, b) => date(b.at) - date(a.at))[0];
135
141
  }
142
+ /** Draft correction follows the existing effective parts approval, including covering reopens. */
143
+ export function partsDraftEditable(project: RecordData, now = Date.now()): boolean {
144
+ if (!['parts', 'parts-review'].includes(String(project.stage))) return false;
145
+ if ((project.reopens !== undefined && !Array.isArray(project.reopens)) ||
146
+ (project.amendments !== undefined && !Array.isArray(project.amendments))) return false;
147
+ const approvals = records(project.signoffs).filter(s => s.stage === 'parts-review' &&
148
+ (s.checkpoint === null || s.checkpoint === undefined));
149
+ const changes = [...records(project.reopens), ...records(project.amendments).map((entry): RecordData =>
150
+ ({...entry, stage: object(entry.target).stage}))].filter(entry =>
151
+ ['interview', 'plan-approved', 'parts', 'parts-review'].includes(String(entry.stage)));
152
+ if ([...approvals, ...changes].some(entry => !Number.isFinite(date(entry.at)) || date(entry.at) > now)) return false;
153
+ return !approval(project, 'parts-review', now);
154
+ }
136
155
  function draftFor(project: RecordData, signoff: RecordData | undefined, at: number) {
137
156
  return records(project.drafts).find(draft => draft.id === signoff?.draft_id && date(draft.at) <= at);
138
157
  }
@@ -221,7 +240,37 @@ function inspectContext(root: string, project: RecordData, raw: RecordData, set:
221
240
  return {images, hasParts: ctx.kind !== 'inputs'};
222
241
  }
223
242
 
243
+ function cloneJson(value: unknown): JobInterviewJson {
244
+ if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;
245
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null;
246
+ if (Array.isArray(value)) return value.map(cloneJson);
247
+ if (typeof value === 'object') {
248
+ return Object.fromEntries(
249
+ Object.entries(value as RecordData)
250
+ .filter(([, entry]) => entry !== undefined)
251
+ .map(([key, entry]) => [key, cloneJson(entry)]),
252
+ );
253
+ }
254
+ return null;
255
+ }
256
+
257
+ function cloneJsonObject(value: RecordData): { readonly [key: string]: JobInterviewJson } {
258
+ return cloneJson(value) as { readonly [key: string]: JobInterviewJson };
259
+ }
260
+
261
+ function observeRetainedSet(root: string, ref: SetRef): SetRef | null {
262
+ try {
263
+ if (['derived', 'outputs', 'scratch', 'node_modules', '.git'].includes(ref.path.split('/')[0]!)) return null;
264
+ const bytes = readRegular(checkedPath(root, ref.path), 64 * 1024 * 1024);
265
+ return { path: ref.path, sha256: digest(bytes) };
266
+ } catch {
267
+ return null;
268
+ }
269
+ }
270
+
224
271
  export function readProject(root: string, now = Date.now()) {
272
+ if (!Number.isFinite(now)) return invalid('Evaluation instant must be finite');
273
+ const evaluatedAt = new Date(now).toISOString();
225
274
  try {
226
275
  root = realpathSync(resolve(root));
227
276
  if (!lstatSync(root).isDirectory()) return invalid('Project root must be a directory');
@@ -233,10 +282,13 @@ export function readProject(root: string, now = Date.now()) {
233
282
  project = jsonObject(bytes);
234
283
  } catch {return invalid('project.json must be a readable regular JSON file');}
235
284
  if (project.schema !== 'rig-create/project@0') return invalid('Unsupported create project');
285
+ const hash = digest(bytes);
236
286
  const interview = object(project.interview);
237
287
  const questions: InterviewQuestion[] = [];
238
288
  const historical: HistoricalInterview[] = [];
239
289
  const diagnostics: InterviewDiagnostic[] = [];
290
+ const interviewRecords: JobInterviewRecord[] = [];
291
+ const interviewDiagnostics: JobInterviewDiagnostic[] = [];
240
292
  let sceneAnswers = 0;
241
293
  const seen = new Map<string, string>();
242
294
  for (const [items, answerKey, allowed, collection] of [
@@ -277,11 +329,66 @@ export function readProject(root: string, now = Date.now()) {
277
329
  } catch (error) {
278
330
  if (editable) throw error;
279
331
  const answer = entry.answer!;
332
+ const observedSet = observeRetainedSet(root, ref);
333
+ const answerAt = typeof answer.at === 'string' ? answer.at : null;
280
334
  historical.push({question: String(item.id), verbatim: typeof answer.verbatim === 'string' ? answer.verbatim : '',
281
- by: typeof answer.by === 'string' ? answer.by : undefined, at: typeof answer.at === 'string' ? answer.at : undefined,
335
+ by: typeof answer.by === 'string' ? answer.by : undefined, at: answerAt ?? undefined,
282
336
  ref, record: entry.record, answer});
283
337
  diagnostics.push({code: 'INTERVIEW_OPTIONS_STALE', question: String(item.id), record: entry.record, ref,
284
- ...(typeof answer.at === 'string' ? {at: answer.at} : {})});
338
+ ...(answerAt !== null ? {at: answerAt} : {})});
339
+ interviewRecords.push({
340
+ questionId: String(item.id),
341
+ record: entry.record,
342
+ setId: null,
343
+ ref,
344
+ observedSet,
345
+ timeKind: 'answer',
346
+ at: answerAt,
347
+ original: cloneJsonObject(answer),
348
+ });
349
+ interviewDiagnostics.push({
350
+ record: entry.record,
351
+ at: answerAt,
352
+ code: 'INTERVIEW_OPTIONS_STALE',
353
+ severity: 'error',
354
+ });
355
+ const rawDecision = answer.agent_decision;
356
+ if (rawDecision !== null && typeof rawDecision === 'object' && !Array.isArray(rawDecision)) {
357
+ const decision = rawDecision as RecordData;
358
+ const decisionRecord = entry.record + '.agent_decision';
359
+ if (['at', 'value', 'fragments'].some(key => Object.hasOwn(decision, key))) {
360
+ const decisionAt = typeof decision.at === 'string' ? decision.at : null;
361
+ interviewRecords.push({
362
+ questionId: String(item.id),
363
+ record: decisionRecord,
364
+ setId: null,
365
+ ref,
366
+ observedSet,
367
+ timeKind: 'decision',
368
+ at: decisionAt,
369
+ original: cloneJsonObject(decision),
370
+ });
371
+ diagnostics.push({code: 'INTERVIEW_OPTIONS_STALE', question: String(item.id), record: decisionRecord, ref,
372
+ ...(decisionAt !== null ? {at: decisionAt} : {})});
373
+ interviewDiagnostics.push({
374
+ record: decisionRecord,
375
+ at: decisionAt,
376
+ code: 'INTERVIEW_OPTIONS_STALE',
377
+ severity: 'error',
378
+ });
379
+ } else {
380
+ interviewRecords.push({
381
+ questionId: String(item.id),
382
+ record: decisionRecord,
383
+ setId: null,
384
+ ref,
385
+ observedSet,
386
+ timeKind: 'decision',
387
+ at: null,
388
+ original: cloneJsonObject(decision),
389
+ });
390
+ }
391
+ }
285
392
  continue;
286
393
  }
287
394
  if (editable && (set.stage === 'interview' || set.stage === 'rigging-interview') &&
@@ -291,27 +398,96 @@ export function readProject(root: string, now = Date.now()) {
291
398
  if (editable && approval(project, set.stage === 'interview' ? 'plan-approved' : set.stage, now)) return invalid('Question approval is still live');
292
399
  const sceneKind = object(raw.context).kind === 'scene';
293
400
  if (!editable && sceneKind) sceneAnswers++;
294
- const evaluate = (at: number, record: string) => {
401
+ const observedSet: SetRef = { path: ref.path, sha256: ref.sha256 };
402
+ const evaluate = (at: number, record: string, recordAt: string | null) => {
295
403
  try {
296
404
  const {legacy, ...context} = inspectContext(root, project, raw, set, at, editable);
297
- if (legacy) diagnostics.push({code: 'INTERVIEW_OPTIONS_SCENE_LEGACY', question: set.question, record, ref, at: new Date(at).toISOString()});
405
+ if (legacy) {
406
+ diagnostics.push({code: 'INTERVIEW_OPTIONS_SCENE_LEGACY', question: set.question, record, ref,
407
+ ...(recordAt !== null ? {at: recordAt} : {})});
408
+ interviewDiagnostics.push({
409
+ record,
410
+ at: recordAt,
411
+ code: 'INTERVIEW_OPTIONS_SCENE_LEGACY',
412
+ severity: 'warning',
413
+ });
414
+ }
298
415
  return context;
299
416
  } catch (error) {
300
417
  if (editable || !(error instanceof Error) || !error.message.startsWith('INTERVIEW_OPTIONS_STALE:')) throw error;
301
418
  diagnostics.push({code: 'INTERVIEW_OPTIONS_STALE', question: set.question, record, ref,
302
- ...(Number.isFinite(at) ? {at: new Date(at).toISOString()} : {})});
419
+ ...(recordAt !== null ? {at: recordAt} : {})});
420
+ interviewDiagnostics.push({
421
+ record,
422
+ at: recordAt,
423
+ code: 'INTERVIEW_OPTIONS_STALE',
424
+ severity: 'error',
425
+ });
303
426
  return {images: [], hasParts: false};
304
427
  }
305
428
  };
306
- const context = evaluate(editable ? now : date(entry.answer?.at), entry.record);
307
- const decision = object(entry.answer?.agent_decision);
308
- if (!editable && ['at', 'value', 'fragments'].some(key => Object.hasOwn(decision, key))) {
309
- evaluate(date(decision.at), entry.record + '.agent_decision');
429
+ const recordAt = editable ? evaluatedAt : typeof entry.answer?.at === 'string' ? entry.answer.at : null;
430
+ interviewRecords.push({
431
+ questionId: String(item.id),
432
+ record: entry.record,
433
+ setId: set.id,
434
+ ref,
435
+ observedSet,
436
+ timeKind: editable ? 'inspection' : 'answer',
437
+ at: recordAt,
438
+ original: editable ? null : cloneJsonObject(entry.answer!),
439
+ });
440
+ const context = evaluate(editable ? now : date(entry.answer?.at), entry.record, recordAt);
441
+ const rawDecision = entry.answer?.agent_decision;
442
+ if (!editable && rawDecision !== null && typeof rawDecision === 'object' && !Array.isArray(rawDecision)) {
443
+ const decision = rawDecision as RecordData;
444
+ const decisionRecord = entry.record + '.agent_decision';
445
+ if (['at', 'value', 'fragments'].some(key => Object.hasOwn(decision, key))) {
446
+ const decisionAt = typeof decision.at === 'string' ? decision.at : null;
447
+ interviewRecords.push({
448
+ questionId: String(item.id),
449
+ record: decisionRecord,
450
+ setId: set.id,
451
+ ref,
452
+ observedSet,
453
+ timeKind: 'decision',
454
+ at: decisionAt,
455
+ original: cloneJsonObject(decision),
456
+ });
457
+ evaluate(date(decision.at), decisionRecord, decisionAt);
458
+ } else {
459
+ interviewRecords.push({
460
+ questionId: String(item.id),
461
+ record: decisionRecord,
462
+ setId: set.id,
463
+ ref,
464
+ observedSet,
465
+ timeKind: 'decision',
466
+ at: null,
467
+ original: cloneJsonObject(decision),
468
+ });
469
+ }
310
470
  }
311
471
  questions.push({ref, set, editable, answer: entry.answer, ...context});
312
472
  seen.set(ref.sha256, ref.path);
313
473
  }
314
474
  }
315
475
  }
316
- return {root, hash: digest(bytes), project, questions, historical, diagnostics, sceneAnswers};
476
+ const interviewDiagnosticsEnvelope: JobInterviewDiagnostics = {
477
+ schema: 'rig-review/job-interview@1',
478
+ project: { path: 'project.json', sha256: hash },
479
+ evaluatedAt,
480
+ records: interviewRecords,
481
+ diagnostics: interviewDiagnostics,
482
+ };
483
+ return {
484
+ root,
485
+ hash,
486
+ project,
487
+ questions,
488
+ historical,
489
+ diagnostics,
490
+ sceneAnswers,
491
+ interview: interviewDiagnosticsEnvelope,
492
+ };
317
493
  }