@rig-c/parts 2.45.0 → 2.47.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/inputs.ts CHANGED
@@ -73,7 +73,7 @@ export function padToSquare(w: number, h: number, side: number): SquarePad {
73
73
  return { side, left: Math.floor((side - w) / 2), top: Math.floor((side - h) / 2) };
74
74
  }
75
75
 
76
- export function makeInputs(painting: Raster, cfg: Pick<CharacterConfig, 'seethrough'>, label: string): SeeThroughInputs {
76
+ export function makeInputs(painting: Raster, cfg: { seethrough?: Partial<Pick<NonNullable<CharacterConfig['seethrough']>, 'head_box' | 'resolution'>> }, label: string): SeeThroughInputs {
77
77
  const problems: Problem[] = [];
78
78
  const { width: w, height: h } = painting;
79
79
  let translucent = 0;
package/src/parts.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { assemblyFieldDigest, isSplitTakeMetadataField } from './assembly-reading.ts';
1
2
  import { orderedEditedPartReceipt, type EditedPartReceipt } from './editedparts.ts';
2
3
  import { parseReceiptProducer, receiptText } from './receiptproducer.ts';
3
4
  import { takenSourceProblems, type TakenLayerSource } from './takesource.ts';
@@ -166,6 +167,8 @@ export interface LimbRecord {
166
167
  export interface HybridBandRecord {
167
168
  upper: string;
168
169
  width: number;
170
+ /** The centered source-run width before applying an override, including a nonpositive reading the default would refuse. */
171
+ measured_width?: number;
169
172
  radius: number;
170
173
  at: [number, number];
171
174
  axis: [number, number];
@@ -290,7 +293,7 @@ const CUT_KEYS = ['cut_offset', 'cut_at', 'cut_crossed', 'joint_crossed', 'band_
290
293
  function orderedLimb(l: LimbRecord): Record<string, unknown> {
291
294
  const cap = l.cap === undefined ? undefined : Object.fromEntries(CAP_KEYS.filter((k) => (l.cap as CapRecord)[k] !== undefined).map((k) => [k, (l.cap as CapRecord)[k]]));
292
295
  const band = (value: HybridBandRecord & { part?: string }): Record<string, unknown> => Object.fromEntries(
293
- (['part', 'upper', 'width', 'radius', 'at', 'axis'] as const).filter((k) => value[k] !== undefined).map((k) => [k, value[k]]));
296
+ (['part', 'upper', 'width', 'measured_width', 'radius', 'at', 'axis'] as const).filter((k) => value[k] !== undefined).map((k) => [k, value[k]]));
294
297
  const values = { ...l, cap, ...(l.hybrid === undefined ? {} : { hybrid: band(l.hybrid) }), ...(l.band === undefined ? {} : { band: band(l.band) }) };
295
298
  return Object.fromEntries(LIMB_KEYS.filter((k) => values[k] !== undefined).map((k) => [k, values[k]]));
296
299
  }
@@ -420,7 +423,13 @@ export interface OccluderGuardRecord {
420
423
  guarded_px_after: number;
421
424
  }
422
425
 
426
+ export interface AssemblyConfigRecord {
427
+ sha256: string;
428
+ fields: Array<{ name: string; sha256: string }>;
429
+ }
430
+
423
431
  export interface PartsFile {
432
+ assembly_config?: AssemblyConfigRecord;
424
433
  /** Optional on legacy packages; binds the opaque RGB raster assemble actually read. */
425
434
  painting_in_rig?: PaintingInRig;
426
435
  /** Structural moves, independent of per-pixel value equality. */
@@ -479,8 +488,8 @@ export interface SceneRecord {
479
488
  figure_mask: string;
480
489
  }
481
490
 
482
- const TOP_KEYS = ['painting_in_rig', 'rig_size', 'scale_rig_per_source', 'parts', 'ghost_px', 'recomposite', 'scene', 'occluder_plates', 'occluder_grow', 'occluder_guard', 'single_run_pad', 'alternates', 'motion_seams', 'cut_ownership'] as const;
483
- const REQUIRED_TOP_KEYS = TOP_KEYS.filter((k) => k !== 'painting_in_rig' && k !== 'recomposite' && k !== 'scene' && k !== 'single_run_pad' && k !== 'occluder_plates' && k !== 'occluder_grow' && k !== 'occluder_guard' && k !== 'alternates' && k !== 'motion_seams' && k !== 'cut_ownership');
491
+ const TOP_KEYS = ['assembly_config', 'painting_in_rig', 'rig_size', 'scale_rig_per_source', 'parts', 'ghost_px', 'recomposite', 'scene', 'occluder_plates', 'occluder_grow', 'occluder_guard', 'single_run_pad', 'alternates', 'motion_seams', 'cut_ownership'] as const;
492
+ const REQUIRED_TOP_KEYS = TOP_KEYS.filter((k) => k !== 'assembly_config' && k !== 'painting_in_rig' && k !== 'recomposite' && k !== 'scene' && k !== 'single_run_pad' && k !== 'occluder_plates' && k !== 'occluder_grow' && k !== 'occluder_guard' && k !== 'alternates' && k !== 'motion_seams' && k !== 'cut_ownership');
484
493
  export const OCCLUDER_PLATE_KEYS = ['receipt', 'receipt_sha256', 'occluder_sha256', 'painting_sha256', 'output_sha256', 'mask_sha256'] as const;
485
494
  export const OCCLUDER_GROW_KEYS = ['occluder', 'image', 'grow', 'covered_px_before', 'covered_px_after'] as const;
486
495
  export const OCCLUDER_GUARD_KEYS = ['occluder', 'image', 'guard', 'guarded_px_before', 'guarded_px_after'] as const;
@@ -654,6 +663,7 @@ export function serializeParts(file: PartsFile): string {
654
663
  path: file.painting_in_rig.path, sha256: file.painting_in_rig.sha256, resample: file.painting_in_rig.resample,
655
664
  } }),
656
665
  parts: serializePartList(file.parts),
666
+ ...(file.assembly_config === undefined ? {} : { assembly_config: { sha256: file.assembly_config.sha256, fields: file.assembly_config.fields.map(({ name, sha256 }) => ({ name, sha256 })) } }),
657
667
  ...(file.cut_ownership === undefined ? {} : { cut_ownership: orderedOwnership(file.cut_ownership) }),
658
668
  ...(file.motion_seams === undefined ? {} : { motion_seams: file.motion_seams.map(({ part, neighbour }) => ({ part, neighbour })) }),
659
669
  ghost_px: Object.fromEntries(Object.keys(file.ghost_px).sort().map((k) => [k, file.ghost_px[k]])),
@@ -741,7 +751,8 @@ export function partsFileReferences(dir: string): PartsFileReference[] {
741
751
  return [...unique.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.role < b.role ? -1 : a.role > b.role ? 1 : 0);
742
752
  }
743
753
 
744
- function readPartsManifest(path: string): PartsFile {
754
+ /** Read the manifest before checking any sidecar files beside it. */
755
+ export function readPartsManifest(path: string): PartsFile {
745
756
  if (!existsSync(path)) refuseIfAny([{ code: 'PARTS_FILE_PRESENT', object: path, detail: 'no such file; --parts names the directory holding parts.json and parts/ (work/rig from assemble --out work, or out from build --out out)' }]);
746
757
  let raw: unknown;
747
758
  try {
@@ -869,6 +880,19 @@ function checkParts(raw: unknown, path: string): PartsFile {
869
880
  const o = raw as Record<string, unknown>;
870
881
  for (const k of Object.keys(o)) if (!(TOP_KEYS as readonly string[]).includes(k)) fail('PARTS_KEY_KNOWN', `${path} key "${k}"`, `is not a parts.json field; known: ${TOP_KEYS.join(', ')}`);
871
882
  for (const k of REQUIRED_TOP_KEYS) if (!(k in o)) fail('PARTS_FIELD_PRESENT', `${path} field "${k}"`, 'is absent and required');
883
+ if ('assembly_config' in o) {
884
+ const value = o.assembly_config as Partial<AssemblyConfigRecord> | null;
885
+ const digest = (input: unknown): input is string => typeof input === 'string' && /^[a-f0-9]{64}$/.test(input);
886
+ if (value === null || typeof value !== 'object' || Object.keys(value).some(key => key !== 'sha256' && key !== 'fields') ||
887
+ !digest(value.sha256) || !Array.isArray(value.fields) || value.fields.length === 0 ||
888
+ !value.fields.every((row, i) => row !== null && typeof row === 'object' && Object.keys(row).length === 2 &&
889
+ typeof row.name === 'string' && (/^[a-z_]+(?:\.[a-z_]+)*$/.test(row.name) || isSplitTakeMetadataField(row.name)) &&
890
+ digest(row.sha256) && (i === 0 || value.fields![i - 1].name < row.name)) ||
891
+ assemblyFieldDigest(value.fields) !== value.sha256) {
892
+ fail('PARTS_FIELD_TYPE', `${path} field "assembly_config"`, 'requires sorted distinct field names with lowercase SHA-256 digests and their matching aggregate digest');
893
+ }
894
+ }
895
+
872
896
  if ('painting_in_rig' in o) {
873
897
  const p = o.painting_in_rig;
874
898
  if (typeof p !== 'object' || p === null || Array.isArray(p) ||
@@ -1212,7 +1236,11 @@ function checkLimbRecords(recordsRaw: unknown[], prefix: string, fail: (code: st
1212
1236
  else {
1213
1237
  const b = h as Record<string, unknown>;
1214
1238
  const pair = (v: unknown): v is number[] => Array.isArray(v) && v.length === 2 && v.every((n) => typeof n === 'number' && Number.isFinite(n));
1215
- if (Object.keys(b).sort().join(',') !== (field === 'hybrid' ? 'at,axis,part,radius,upper,width' : 'at,axis,radius,upper,width') || (field === 'hybrid' && (typeof b.part !== 'string' || b.part === '')) || !(typeof b.radius === 'number' && Number.isFinite(b.radius) && b.radius > 0) || typeof b.upper !== 'string' || b.upper === '' || b.upper === q.bone || !(typeof b.width === 'number' && Number.isFinite(b.width) && b.width > 0) || !pair(b.at) || !pair(b.axis) || Math.abs(edgeLength(b.axis[0], b.axis[1]) - 1) > 1e-6 || (field === 'band' && 'range' in q)) fail('PARTS_FIELD_TYPE', `${object} ${field}`, `is ${show(h)}; distinct upper carrier, positive width, finite at, unit axis and no duplicate range are required`);
1239
+ const keys = Object.keys(b).filter((k) => k !== 'measured_width').sort().join(',');
1240
+ if (keys !== (field === 'hybrid' ? 'at,axis,part,radius,upper,width' : 'at,axis,radius,upper,width') || (field === 'hybrid' && (typeof b.part !== 'string' || b.part === '')) || !(typeof b.radius === 'number' && Number.isFinite(b.radius) && b.radius > 0) || typeof b.upper !== 'string' || b.upper === '' || b.upper === q.bone || !(typeof b.width === 'number' && Number.isFinite(b.width) && b.width > 0) || !pair(b.at) || !pair(b.axis) || Math.abs(edgeLength(b.axis[0], b.axis[1]) - 1) > 1e-6 || (field === 'band' && 'range' in q)) fail('PARTS_FIELD_TYPE', `${object} ${field}`, `is ${show(h)}; distinct upper carrier, positive width, finite at, unit axis and no duplicate range are required`);
1241
+ if (Object.hasOwn(b, 'measured_width') && !(typeof b.measured_width === 'number' && Number.isFinite(b.measured_width))) {
1242
+ fail('PARTS_FIELD_TYPE', `${object} ${field}.measured_width`, `is ${show(b.measured_width)}; a finite centered source-run width is required`);
1243
+ }
1216
1244
  }
1217
1245
  }
1218
1246
  if (caps && 'cap' in q) checkCap(q.cap, `${object} "cap"`, fail);
@@ -1239,7 +1267,7 @@ function checkLimbRecords(recordsRaw: unknown[], prefix: string, fail: (code: st
1239
1267
  const record = (v: unknown): Record<string, unknown> | undefined => typeof v === 'object' && v !== null && !Array.isArray(v) ? v as Record<string, unknown> : undefined;
1240
1268
  const bl = record(target?.limb);
1241
1269
  const b = record(bl?.band);
1242
- const same = b !== undefined && ['upper', 'width', 'radius', 'at', 'axis'].every((k) => JSON.stringify(b[k]) === JSON.stringify(joint[k]));
1270
+ const same = b !== undefined && b.measured_width === joint.measured_width && ['upper', 'width', 'radius', 'at', 'axis'].every((k) => JSON.stringify(b[k]) === JSON.stringify(joint[k]));
1243
1271
  if (bl === undefined || bl.name !== l.name || bl.segment !== l.segment || bl.bone !== l.bone || bl.of !== l.of || bl.joint !== l.joint || !same) fail('PARTS_HYBRID_PAIR', `${prefix}part "${String(r.name)}" hybrid "${String(joint.part)}"`, 'requires its matching band on the same source, joint, carriers and measured geometry');
1244
1272
  }
1245
1273
  }
package/src/partsource.ts CHANGED
@@ -54,7 +54,10 @@ export function tracePartsDeclared(cfg: Pick<AssembleConfig, 'assemble'>): boole
54
54
  * Order is the config's: cuts, each alternate set's cuts, patches, painting
55
55
  * extensions, the arm split, limb splits in key order.
56
56
  */
57
- export function untracedPartSources(cfg: Pick<AssembleConfig, 'assemble' | 'seethrough' | 'limbs'>): Problem[] {
57
+ export function untracedPartSources(cfg: Pick<AssembleConfig, 'assemble'> & {
58
+ seethrough: Pick<AssembleConfig['seethrough'], 'arm_split'>;
59
+ limbs?: Record<string, Pick<NonNullable<AssembleConfig['limbs']>[string], 'segments' | 'split'>>;
60
+ }): Problem[] {
58
61
  if (!tracePartsDeclared(cfg)) return [];
59
62
  const out: Problem[] = [];
60
63
  const refuse = (object: string, found: string): void => {
package/src/propose.ts CHANGED
@@ -684,10 +684,10 @@ export class PartSet {
684
684
  private readonly masks = new Map<string, Mask>();
685
685
  private preLimbs: PartSet | null = null;
686
686
 
687
- constructor(file: PartsFile, images: ReadonlyMap<string, Raster>) {
688
- [this.W, this.H] = file.rig_size;
689
- this.rigScale = file.scale_rig_per_source;
690
- this.recs = file.parts;
687
+ constructor(readonly manifest: PartsFile, images: ReadonlyMap<string, Raster>) {
688
+ [this.W, this.H] = manifest.rig_size;
689
+ this.rigScale = manifest.scale_rig_per_source;
690
+ this.recs = manifest.parts;
691
691
  this.images = images;
692
692
  }
693
693
 
package/src/takelayers.ts CHANGED
@@ -161,7 +161,10 @@ function supportOverlap(a: Layer, b: Layer): number {
161
161
  return px;
162
162
  }
163
163
  /** Apply every declaration together, so replacing all tied layers from one run can retain its known order. */
164
- export function applyTakenLayers(runs: { full: LayerSet; head: LayerSet; single: boolean }, painting: Raster, cfg: Pick<EarlyConfig, 'seethrough' | 'depth'> & { assemble: { take?: TakeDeclaration[]; plan?: PlanEntry[]; occluders?: OccluderDeclaration[] } }, configPath: string): { full: LayerSet; head: LayerSet; single: boolean; notes: string[] } {
164
+ export function applyTakenLayers<T extends Pick<EarlyConfig, 'depth'> & {
165
+ seethrough: Pick<EarlyConfig['seethrough'], 'resolution' | 'head_box'>;
166
+ assemble: { take?: TakeDeclaration[]; plan?: PlanEntry[]; occluders?: OccluderDeclaration[] };
167
+ }>(runs: { full: LayerSet; head: LayerSet; single: boolean }, painting: Raster, cfg: T, configPath: string): { full: LayerSet; head: LayerSet; single: boolean; notes: string[] } {
165
168
  const wholeDeclarations = (cfg.assemble.take ?? []).filter((item): item is TakeLayers => 'tags' in item);
166
169
  const declarations = (cfg.assemble.take ?? []).filter((item): item is TakeLayers | TakeOccluderSplit => 'tags' in item || 'occluder' in item);
167
170
  const occluders = cfg.assemble.occluders ?? [];
package/src/takeregion.ts CHANGED
@@ -118,7 +118,10 @@ export function deriveTakenRegion(base: Layer, donor: Layer, painting: Raster, s
118
118
  }
119
119
 
120
120
  /** Called beside whole-layer take, before assembly or any output emission. */
121
- export function applyTakenRegions(runs: Runs, painting: Raster, cfg: AssembleConfig, configPath: string, setup: SetupPainting | undefined, receipts: ReceiptLedger, sourcePath?: string): Runs {
121
+ export function applyTakenRegions(runs: Runs, painting: Raster, cfg: Pick<AssembleConfig, 'depth'> & {
122
+ seethrough: Pick<AssembleConfig['seethrough'], 'head_box'> | undefined;
123
+ assemble: Pick<AssembleConfig['assemble'], 'take' | 'plan'>;
124
+ }, configPath: string, setup: SetupPainting | undefined, receipts: ReceiptLedger, sourcePath?: string): Runs {
122
125
  const declarations = (cfg.assemble.take ?? []).filter((item): item is TakeRegion => 'seed' in item);
123
126
  if (declarations.length === 0) return runs;
124
127
  const tolerance = setup?.rgb_tolerance;
@@ -108,26 +108,35 @@ function unchanged(target: ConfigWriteTarget): void {
108
108
  } catch { /* Removal is also a change, never a reason to create a new config. */ }
109
109
  if (!same) refusal('CONFIG_WRITE_CHANGED', target.path, 'changed after it was read; nothing was replaced — rerun against the current config');
110
110
  }
111
+
112
+ function configWriteDoor(patch: ConfigWritePatch, receiptDoor: 'full' | 'assemble'): 'layers' | 'assemble' | 'full' {
113
+ if (patch.kind === 'head-box') return 'layers';
114
+ if (patch.kind === 'assemble-plan') return 'assemble';
115
+ return patch.kind === 'edited-part-receipt' ? receiptDoor : 'full';
116
+ }
117
+
111
118
  /** One file-writing adapter for all --write-config modes. Existing-file ownership
112
119
  * produces whole-value edits for splicedEdits, the engine clothConfigEdits uses.
113
120
  * Fresh cloth text already passed writtenClothConfig's splice check: it is never
114
121
  * sent through a full loader that would reject an intentional partial config.
115
122
  */
116
- export function stageConfigWrite(target: ConfigWriteTarget | FreshConfigWrite, patch?: ConfigWritePatch, files: ConfigWriteFiles = {}): StagedConfigWrite {
123
+ export function stageConfigWrite(target: ConfigWriteTarget | FreshConfigWrite, patch?: ConfigWritePatch, files: ConfigWriteFiles = {}, receiptDoor: 'full' | 'assemble' = 'full'): StagedConfigWrite {
117
124
  const fresh = 'kind' in target;
118
125
  const path = resolve(target.path);
119
126
  let text: string;
120
127
  let changes: readonly ConfigWriteChange[];
128
+ let door: ReturnType<typeof configWriteDoor> | undefined;
121
129
  if (fresh) {
122
130
  text = target.text;
123
131
  changes = [];
124
132
  } else {
125
133
  if (patch === undefined) return refusal('CONFIG_FIELD_TYPE', path, 'has no config patch; a supported proposal operation is required');
126
- const merged = mergeConfigProposal(target.raw, patch);
134
+ const merged = mergeConfigProposal(target.raw, patch, receiptDoor);
127
135
  const spliced = merged.changes.length === 0 ? { text: target.original, moved: null } : splicedEdits(target.original, merged.edits);
128
136
  if (spliced.moved !== null) return refusal('CONFIG_WRITE_FAILED', path, `spliced proposal values moved ${spliced.moved}; the original was not replaced`);
129
137
  text = spliced.text;
130
138
  changes = merged.changes;
139
+ door = configWriteDoor(patch, receiptDoor);
131
140
  }
132
141
  const freshAbsent = (): void => {
133
142
  try { lstatSync(path); }
@@ -155,11 +164,9 @@ export function stageConfigWrite(target: ConfigWriteTarget | FreshConfigWrite, p
155
164
  if (!fresh) fchmodSync(fd, target.mode);
156
165
  closeSync(fd);
157
166
  fd = undefined;
158
- if (!fresh) {
159
- if (patch?.kind === 'head-box') loadEarlyConfig(temp, 'layers');
160
- else if (patch?.kind === 'assemble-plan') loadEarlyConfig(temp, 'assemble');
161
- else loadConfigAndAnimations(temp);
162
- }
167
+ if (door === 'layers') loadEarlyConfig(temp, 'layers');
168
+ else if (door === 'assemble') loadEarlyConfig(temp, 'assemble');
169
+ else if (door === 'full') loadConfigAndAnimations(temp);
163
170
  } catch (error) {
164
171
  if (fd !== undefined) {
165
172
  try { closeSync(fd); }
@@ -204,7 +211,7 @@ export function configWriteLines(target: ConfigWriteTarget, changes: readonly Co
204
211
  return changes.length === 0 ? [`config ${target.path}: unchanged`] : changes.map((c) => `config ${target.path}: ${c.kind} ${c.path}${c.value === undefined ? '' : ` ${c.value}`}`);
205
212
  }
206
213
 
207
- export interface ConfigWriteRequest { target: ConfigWriteTarget; patch: ConfigWritePatch }
214
+ export interface ConfigWriteRequest { target: ConfigWriteTarget; patch: ConfigWritePatch; receiptDoor?: 'full' | 'assemble' }
208
215
  export interface StagedConfigWriteBatch {
209
216
  writes: ReadonlyArray<{ target: ConfigWriteTarget; changes: readonly ConfigWriteChange[] }>;
210
217
  commit(): void;
@@ -231,14 +238,15 @@ export function stageConfigWriteBatch(requests: readonly ConfigWriteRequest[], f
231
238
  }
232
239
  // Candidate shape refusals precede even temporary writes. The existing
233
240
  // stage loader then validates each real same-directory staged file, including
234
- // relative sidecars. Edited receipts are full-config updates, not early drafts.
235
- for (const { target, patch } of requests) {
236
- const candidate = mergeConfigProposal(target.raw, patch).config;
237
- if (patch.kind === 'head-box') parseEarlyConfig(candidate, 'layers');
238
- else if (patch.kind === 'assemble-plan') parseEarlyConfig(candidate, 'assemble');
241
+ // relative sidecars.
242
+ for (const { target, patch, receiptDoor = 'full' } of requests) {
243
+ const candidate = mergeConfigProposal(target.raw, patch, receiptDoor).config;
244
+ const door = configWriteDoor(patch, receiptDoor);
245
+ if (door === 'layers') parseEarlyConfig(candidate, 'layers');
246
+ else if (door === 'assemble') parseEarlyConfig(candidate, 'assemble');
239
247
  else parseConfig(candidate);
240
248
  }
241
- for (const { target, patch } of requests) entries.push({ target, staged: stageConfigWrite(target, patch, files), backup: null, committed: false, restoreFailed: false });
249
+ for (const { target, patch, receiptDoor } of requests) entries.push({ target, staged: stageConfigWrite(target, patch, files, receiptDoor), backup: null, committed: false, restoreFailed: false });
242
250
  } catch (error) {
243
251
  throw new PartsError([...problemsOf(error, 'config batch', 'staging configs failed'), ...cancelAll()]);
244
252
  }
@@ -2,16 +2,20 @@
2
2
  import { createHash } from 'node:crypto';
3
3
  import { readFileSync } from 'node:fs';
4
4
  import { dirname, relative, resolve } from 'node:path';
5
- import { parseConfig } from '../src/config.ts';
5
+ import { refuseStaleAssembly } from '../src/assembly-reading.ts';
6
+ import { CONFIG_REQUIRES, parseConfig, parseEarlyConfig } from '../src/config.ts';
7
+ import type { ConfigObject } from '../src/configwrite.ts';
6
8
  import type { EditedPartReceipt } from '../src/editedparts.ts';
7
9
  import { receiptProducerJson } from '../src/receiptproducer.ts';
8
10
  import { PartsError } from '../src/errors.ts';
11
+ import { readParts } from '../src/parts.ts';
9
12
  import { decodePngBytes } from '../src/raster/png.ts';
10
- import { readConfigWriteTarget, stageConfigWriteBatch, type StagedConfigWriteBatch } from './configwrite.ts';
13
+ import { readConfigWriteTarget, stageConfigWriteBatch, type ConfigWriteRequest, type StagedConfigWriteBatch } from './configwrite.ts';
11
14
 
12
15
  export interface EditedPartInput {
13
16
  config: string;
14
17
  rigConfig?: string;
18
+ parts?: string;
15
19
  part: string;
16
20
  file: string;
17
21
  from: string;
@@ -33,6 +37,7 @@ function png(path: string, flag: string): { bytes: Buffer; width: number; height
33
37
  }
34
38
  }
35
39
  const hash = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');
40
+ const rigSections = CONFIG_REQUIRES.full.filter(field => !CONFIG_REQUIRES.assemble.includes(field));
36
41
  export interface EditedPartWriteResult { receipt: EditedPartReceipt; writes: StagedConfigWriteBatch['writes'] }
37
42
 
38
43
  /** Prepare every replacement before even temporary files are written. No assembly or filename discovery. */
@@ -42,6 +47,7 @@ export function writeEditedPart(input: EditedPartInput): EditedPartWriteResult {
42
47
  ['--from', input.from],
43
48
  ...(input.editor === undefined ? [] : [['--editor', input.editor]]),
44
49
  ...(input.rigConfig === undefined ? [] : [['--rig-config', input.rigConfig]]),
50
+ ...(input.parts === undefined ? [] : [['--parts', input.parts]]),
45
51
  ]) if (typeof value !== 'string' || value.trim() === '') refuse('EDITED_PART_ARGUMENT', flag, 'is missing or blank; a non-empty value is required');
46
52
  if ((input.editor === undefined) === (input.producer === undefined)) {
47
53
  refuse('EDITED_PART_ARGUMENT', 'edited-part', 'requires exactly one of --producer or --editor');
@@ -55,15 +61,20 @@ export function writeEditedPart(input: EditedPartInput): EditedPartWriteResult {
55
61
  const receipt = { part: input.part, file: input.file, sha256: hash(edited.bytes), from_sha256: hash(from.bytes), ...author };
56
62
  const targets = [input.config, ...(input.rigConfig === undefined ? [] : [input.rigConfig])].map(readConfigWriteTarget);
57
63
  const receipts: EditedPartReceipt[] = [];
58
- const requests = targets.map(target => {
59
- const config = parseConfig(target.raw as Parameters<typeof parseConfig>[0]);
64
+ const requests = targets.map((target, index): ConfigWriteRequest => {
65
+ const raw = target.raw as ConfigObject;
66
+ const receiptDoor = index === 0 && Object.hasOwn(raw, 'seethrough') && !rigSections.every(section => Object.hasOwn(raw, section))
67
+ ? 'assemble' : 'full';
68
+ const config = receiptDoor === 'assemble' ? parseEarlyConfig(raw, 'assemble') : parseConfig(raw);
60
69
  const spec = config.assemble.edited_parts;
61
70
  if (spec === undefined) return refuse('EDITED_PART_BLOCK', target.path, 'has no assemble.edited_parts; declare {dir, receipts: []} before recording an edited part');
62
71
  const file = relative(resolve(dirname(target.path), spec.dir), resolve(input.file)).replaceAll('\\', '/');
63
72
  const value: EditedPartReceipt = { ...receipt, file };
64
73
  receipts.push(value);
65
- return { target, patch: { kind: 'edited-part-receipt' as const, receipt: value } };
74
+ const patch = { kind: 'edited-part-receipt' as const, receipt: value };
75
+ return { target, patch, receiptDoor };
66
76
  });
77
+ if (input.parts !== undefined) refuseStaleAssembly(targets[0].path, readParts(input.parts));
67
78
  const staged = stageConfigWriteBatch(requests);
68
79
  staged.commit();
69
80
  return { receipt: receipts[0], writes: staged.writes };
@@ -1,6 +1,7 @@
1
1
  /** Filesystem adapter for the explicit --write-config sampled-turn context. */
2
2
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
3
3
  import { dirname, join, resolve } from 'node:path';
4
+ import { readAssemblyConfig } from '../src/assembly-reading.ts';
4
5
  import { loadConfig, parseConfig } from '../src/config.ts';
5
6
  import { draftIndependentNeck } from '../src/neckdraft.ts';
6
7
  import { readRigInputs, readUnders, readCaps } from '../src/build.ts';
@@ -23,6 +24,7 @@ export function proposeNeck(target: ConfigWriteTarget, args: { source: string; f
23
24
  try {
24
25
  const out = join(args.out, 'rig');
25
26
  mkdirSync(join(out, 'parts'), { recursive: true });
27
+ draft.assembled.parts.assembly_config = readAssemblyConfig(draft.config, draft.assembled.parts, target.path);
26
28
  writeParts(join(out, 'parts.json'), draft.assembled.parts);
27
29
  for (const p of draft.assembled.images) {
28
30
  writePng(join(out, 'parts', `${p.record.name}.png`), p.image);