@rig-c/parts 1.57.1 → 1.59.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/parts.ts CHANGED
@@ -293,10 +293,22 @@ export interface AlternateSetMap {
293
293
  threshold?: { yaw: number; pitch: number };
294
294
  }
295
295
 
296
+ /**
297
+ * Issue #664: the suffix of a limb segment part's front slot — a second slot on
298
+ * the segment's bone, empty at setup, that a gesture set draws the part on.
299
+ */
300
+ export const FRONT_SUFFIX = '_front';
301
+
296
302
  export interface AlternatePartsRecord {
297
303
  name: string;
298
304
  parts?: string[];
299
305
  hides?: string[];
306
+ /**
307
+ * Issue #664: the covered parts this set draws on their front slot: each `p`
308
+ * is mapped as `slots["<p>_front"]` (never `slots[p]`) and listed in `hides`.
309
+ * Written only when the set declares `front`.
310
+ */
311
+ front?: string[];
300
312
  slots: Record<string, string>;
301
313
  records: PartRecord[];
302
314
  ghost_px: Record<string, number>;
@@ -451,6 +463,7 @@ export function serializeParts(file: PartsFile): string {
451
463
  name: a.name,
452
464
  ...(a.parts === undefined ? {} : { parts: a.parts }),
453
465
  ...(a.hides === undefined ? {} : { hides: a.hides }),
466
+ ...(a.front === undefined ? {} : { front: a.front }),
454
467
  slots: a.slots,
455
468
  records: serializePartList(a.records),
456
469
  ghost_px: Object.fromEntries(Object.keys(a.ghost_px).sort().map((k) => [k, a.ghost_px[k]])),
@@ -697,6 +710,20 @@ function checkParts(raw: unknown, path: string): PartsFile {
697
710
  }
698
711
  }
699
712
  }
713
+ // Issue #664: each front part is drawn on its front slot and hidden on its base slot, never both.
714
+ if ('front' in set) {
715
+ const slots = typeof set.slots === 'object' && set.slots !== null && !Array.isArray(set.slots) ? (set.slots as Record<string, unknown>) : {};
716
+ const hides = Array.isArray(set.hides) ? set.hides : [];
717
+ if (!Array.isArray(set.front) || set.front.length === 0 || !set.front.every((p) => typeof p === 'string')) {
718
+ fail('PARTS_FIELD_TYPE', `${at} front`, `is ${show(set.front)}; a nonempty array of part names is required`);
719
+ } else {
720
+ for (const p of set.front as string[]) {
721
+ if (!Object.hasOwn(slots, `${p}${FRONT_SUFFIX}`) || !hides.includes(p)) {
722
+ fail('PARTS_FIELD_TYPE', `${at} front "${p}"`, `requires slots."${p}${FRONT_SUFFIX}" and "${p}" in hides; re-run assemble`);
723
+ }
724
+ }
725
+ }
726
+ }
700
727
  if (!Array.isArray(set.records)) return;
701
728
  set.records.forEach((p, j) => {
702
729
  if (typeof p !== 'object' || p === null || Array.isArray(p)) return;
package/src/propose.ts CHANGED
@@ -5486,6 +5486,14 @@ function lintBasis(bones: readonly BoneEntry[], joints: RigJoints): LintBasis {
5486
5486
  if (from[0] === to[0] && from[1] === to[1]) return { chain, joints: [a, b], line: null, why: `${a} and ${b} are one point, ${fmtAt(from)}, so they declare no line` };
5487
5487
  return { chain, joints: [a, b], line: { from, to }, why: null };
5488
5488
  });
5489
+ // Leg joints place a bent chain; projecting all links onto hip -> ankle is
5490
+ // not a rule for that bend. Say why that check does not read these chains.
5491
+ for (const side of ['r', 'l'] as const) {
5492
+ const chain = `leg_${side}`;
5493
+ if (bones.some((e) => 'chain' in e && e.chain === chain)) {
5494
+ chains.push({ chain, joints: [`${side}_hip`, `${side}_ankle`], line: null, why: 'chain-not-advancing reads sleeve chains only; a bent knee need not advance along hip -> ankle' });
5495
+ }
5496
+ }
5489
5497
  return { person: joints.person, torso, chains };
5490
5498
  }
5491
5499
 
package/src/rig.ts CHANGED
@@ -172,7 +172,7 @@ import { coalesceLimbSlots } from './limbslots.ts';
172
172
  import { layoutAlias, placeLimbLayouts, type LayoutPlan } from './limblayout.ts';
173
173
  import { artCoverage, ART_ALPHA, latticeCells, latticeMesh, latticeStray, ONE_LOOP_PASSES } from './mesh.ts';
174
174
  import { bindFaceSurfaceDeform, BLINK, blinkHoldMisses, blinkSpan, CONTROL_SUFFIX, controlledBones, IDLE_FPS, idleMotion, type MotionSpec, moveKeysToControls } from './motion.ts';
175
- import { type AlternateSetMap, PAINTING_RUN, type PartsFile, readFrom, tagOf } from './parts.ts';
175
+ import { type AlternateSetMap, FRONT_SUFFIX, PAINTING_RUN, type PartsFile, readFrom, tagOf } from './parts.ts';
176
176
  import { readTag } from './tags.ts';
177
177
  import { EYE_GROUP_TAGS } from './propose.ts';
178
178
  import { alphaAbove, crop, pad, type Raster } from './raster/index.ts';
@@ -507,7 +507,8 @@ export interface RigSpec {
507
507
  images: 'images';
508
508
  skeleton: { x: number; y: number; width: number; height: number };
509
509
  bones: RigBone[];
510
- slots: Array<{ name: string; bone: string; attachment: string }>;
510
+ /** `attachment` null only on a limb segment's front slot (issue #664), which shows nothing at setup. */
511
+ slots: Array<{ name: string; bone: string; attachment: string | null }>;
511
512
  skins: { default: Record<string, Record<string, MeshAttachment | RegionAttachment>> };
512
513
  /**
513
514
  * `config.constraints`, in the order written, each as the config wrote it
@@ -669,6 +670,7 @@ function applyTurn(
669
670
  slots: RigSpec['slots'],
670
671
  skin: RigSpec['skins']['default'],
671
672
  constraints: readonly ConfigConstraint[],
673
+ frontSlots: ReadonlySet<string> = new Set(),
672
674
  ): { constraints: Array<Record<string, unknown>>; detached: DetachedRule[]; rows: TurnRow[] } {
673
675
  const problems: Problem[] = [];
674
676
  const taken = new Set(bones.map((b) => b.name));
@@ -679,7 +681,8 @@ function applyTurn(
679
681
  const row: TurnRow = { ...f, twins: [] };
680
682
  rows.push(row);
681
683
  if (f.fraction === 0) continue;
682
- const mine = slots.filter((sl) => sl.name === f.part || sl.name === `${f.part}${STILL_SUFFIX}`);
684
+ // A declared front slot (issue #664) rides its part; a part merely named `<part>_front` is a part of its own.
685
+ const mine = slots.filter((sl) => sl.name === f.part || sl.name === `${f.part}${STILL_SUFFIX}` || (sl.name === `${f.part}${FRONT_SUFFIX}` && frontSlots.has(sl.name)));
683
686
  const bound: string[] = [];
684
687
  const bind = (b: string): void => {
685
688
  if (!bound.includes(b)) bound.push(b);
@@ -706,7 +709,7 @@ function applyTurn(
706
709
  const twinOf = new Map(row.twins.map((t) => [t.bone, t.twin]));
707
710
  for (const t of row.twins) bones.push({ name: t.twin, parent: t.bone, x: 0, y: 0 });
708
711
  for (const sl of slots) {
709
- if (sl.name !== row.part && sl.name !== `${row.part}${STILL_SUFFIX}`) continue;
712
+ if (sl.name !== row.part && sl.name !== `${row.part}${STILL_SUFFIX}` && !(sl.name === `${row.part}${FRONT_SUFFIX}` && frontSlots.has(sl.name))) continue;
710
713
  sl.bone = twinOf.get(sl.bone) as string;
711
714
  const atts = skin[sl.name] ?? {};
712
715
  for (const [k, att] of Object.entries(atts)) {
@@ -2394,6 +2397,28 @@ export function buildRig(
2394
2397
  });
2395
2398
  }
2396
2399
  refuseIfAny(problems);
2400
+ // ---- front slots (issue #664) ------------------------------------------
2401
+ // Only when a limb declares `front`: each named segment part gets `<part>_front` on its base slot's bone, showing
2402
+ // nothing at setup. They ride with every slot through stops and turn, but stay out of the limb closure (#646) and
2403
+ // are placed after their target's family once the setup order is final.
2404
+ const frontSlots: RigSpec['slots'] = [];
2405
+ const frontTargets: Array<{ slot: string; after: string; at: string }> = [];
2406
+ for (const [limbName, limb] of Object.entries(cfg.limbs ?? {})) {
2407
+ if (limb.front === undefined) continue;
2408
+ for (const part of limb.front.parts) {
2409
+ const at = `config.limbs.${limbName}.front`;
2410
+ const base = slots.find((sl) => sl.name === part);
2411
+ if (base === undefined) {
2412
+ fail('RIG_NAME_RESOLVES', `${at}.parts`, `names "${part}", which has no slot in the base rig; a front slot rides its segment's base slot bone`);
2413
+ continue;
2414
+ }
2415
+ frontSlots.push({ name: `${part}${FRONT_SUFFIX}`, bone: base.bone, attachment: null });
2416
+ frontTargets.push({ slot: `${part}${FRONT_SUFFIX}`, after: limb.front.after, at });
2417
+ }
2418
+ }
2419
+ refuseIfAny(problems);
2420
+ // Only declared front slots are front slots: a part authored as `<part>_front` is an ordinary part (review of #667).
2421
+ const declaredFront = new Set(frontSlots.map((sl) => sl.name));
2397
2422
  // ---- alternate painting sets (issues #454, #465) ------------------------
2398
2423
  // Only when `parts.alternates` is present: each alternate set's `<set>_<part>`
2399
2424
  // attachments are added to `skins.default[<part>]` on the existing bones and
@@ -2413,13 +2438,21 @@ export function buildRig(
2413
2438
  fail('RIG_ALT_TIP_POINT', `parts.json alternates[${altIdx}].tips.${bone}`, 'requires a finite [x, y] endpoint in rig-crop pixels');
2414
2439
  }
2415
2440
  }
2441
+ // Issue #664: one segment is drawn by one slot of a set, its base slot or its front slot, never both.
2442
+ for (const slotName of Object.keys(alt.slots)) {
2443
+ if (declaredFront.has(`${slotName}${FRONT_SUFFIX}`) && Object.hasOwn(alt.slots, `${slotName}${FRONT_SUFFIX}`)) {
2444
+ fail('RIG_SET_FRONT_BOTH', `parts.json alternates[${altIdx}] (set "${alt.name}") part "${slotName}"`, `maps both slot "${slotName}" and its front slot "${slotName}${FRONT_SUFFIX}"; a set draws a segment on its base slot or on its front slot, not both — re-run assemble`);
2445
+ }
2446
+ }
2447
+ const altFront = new Set(alt.front ?? []);
2416
2448
  refuseIfAny(problems);
2417
2449
  const explicitDrawn = alt.drawn ?? cfgAlt?.drawn;
2418
2450
  const isSubsetSet = alt.parts !== undefined || cfgAlt?.parts !== undefined;
2419
2451
  let coveredBones: Set<string> | null = null;
2420
2452
  if (isSubsetSet) {
2421
2453
  coveredBones = new Set<string>();
2422
- for (const pName of Object.keys(alt.slots)) {
2454
+ for (const slotName of Object.keys(alt.slots)) {
2455
+ const pName = declaredFront.has(slotName) && altFront.has(slotName.slice(0, -FRONT_SUFFIX.length)) ? slotName.slice(0, -FRONT_SUFFIX.length) : slotName;
2423
2456
  if (pName in cfg.regions) coveredBones.add(cfg.regions[pName]);
2424
2457
  for (const s of meshSegments.get(pName) ?? []) coveredBones.add(s.bone);
2425
2458
  const m = cfg.meshes[pName];
@@ -2477,13 +2510,16 @@ export function buildRig(
2477
2510
  const attName = `${alt.name}_${p.name}`;
2478
2511
  const rawImg = images.get(attName);
2479
2512
  if (rawImg === undefined) continue;
2513
+ // Issue #664: a part the set draws on its front slot files its attachment under that slot; bones are shared.
2514
+ const skinSlot = altFront.has(p.name) ? `${p.name}${FRONT_SUFFIX}` : p.name;
2515
+ skin[skinSlot] ??= {};
2480
2516
  const img = pad(rawImg, PAD, PAD, PAD, PAD, [0, 0, 0, 0]);
2481
2517
  const file = `${attName}.png`;
2482
2518
  outImages.push([file, img]);
2483
2519
  const mesh = cfg.meshes[p.name];
2484
2520
  if (mesh === undefined) {
2485
2521
  const bone = B.get(cfg.regions[p.name]) as Bone;
2486
- skin[p.name][attName] = altRegion(file, bone.name, p.x + p.w / 2, p.y + p.h / 2);
2522
+ skin[skinSlot][attName] = altRegion(file, bone.name, p.x + p.w / 2, p.y + p.h / 2);
2487
2523
  continue;
2488
2524
  }
2489
2525
  const fullSegs = meshSegments.get(p.name) as Segment[];
@@ -2535,7 +2571,7 @@ export function buildRig(
2535
2571
  const r = 'r' in mesh ? mesh.r : 80;
2536
2572
  const lm = latticeMesh(attName, art, grid, maxLoopPasses);
2537
2573
  if ('code' in lm) {
2538
- skin[p.name][attName] = altRegion(file, segs[0].bone, p.x + p.w / 2, p.y + p.h / 2);
2574
+ skin[skinSlot][attName] = altRegion(file, segs[0].bone, p.x + p.w / 2, p.y + p.h / 2);
2539
2575
  continue;
2540
2576
  }
2541
2577
  const ox = p.x - PAD;
@@ -2598,7 +2634,7 @@ export function buildRig(
2598
2634
  }
2599
2635
  const uvs: number[] = [];
2600
2636
  for (const [x, y] of lm.vertices) uvs.push(pyRound(x / w, 6), pyRound(y / h, 6));
2601
- skin[p.name][attName] = { type: 'mesh', image: file, width: w, height: h, uvs, triangles: lm.triangles, hull: lm.hull, weights };
2637
+ skin[skinSlot][attName] = { type: 'mesh', image: file, width: w, height: h, uvs, triangles: lm.triangles, hull: lm.hull, weights };
2602
2638
  }
2603
2639
  const slotMap: Record<string, string> = {};
2604
2640
  for (const [slotName, att] of Object.entries(alt.slots)) slotMap[slotName] = att;
@@ -2635,11 +2671,12 @@ export function buildRig(
2635
2671
  // ---- leg stops (issue #404) --------------------------------------------
2636
2672
  // Only when the config has `stops`: each link after the first (and any bone hanging from a stopped link) hangs
2637
2673
  // from the drawn link `<link>_d` above it, and slots and weights on a stopped link bind `<link>_d`.
2638
- const stops = cfg.stops === undefined ? null : applyStops(cfg.stops, chains, bones, slots, skin, (original, emitted) => layoutAlias(explicitLayout.plan, original, emitted));
2674
+ const rebound = frontSlots.length === 0 ? slots : [...slots, ...frontSlots];
2675
+ const stops = cfg.stops === undefined ? null : applyStops(cfg.stops, chains, bones, rebound, skin, (original, emitted) => layoutAlias(explicitLayout.plan, original, emitted));
2639
2676
  // ---- the turn control (issue #251) -------------------------------------
2640
2677
  // Only when the config has `turn`: every other build adds nothing here, so no byte moves.
2641
2678
  if (cfg.turn !== undefined) refuseIfAny(turnRiderProblems(cfg.turn, cfg, parts.parts));
2642
- const turned = cfg.turn === undefined ? null : applyTurn(cfg.turn, parts.parts.map((p) => p.name), bones, slots, skin, cfg.constraints ?? []);
2679
+ const turned = cfg.turn === undefined ? null : applyTurn(cfg.turn, parts.parts.map((p) => p.name), bones, rebound, skin, cfg.constraints ?? [], declaredFront);
2643
2680
  for (const row of turned?.rows ?? []) for (const t of row.twins) layoutAlias(explicitLayout.plan, t.bone, t.twin);
2644
2681
  // issue #536: every row names the bones the emitted attachment binds, read once the turn and the stops have
2645
2682
  // rebound the weights; a rig with neither rebinds nothing, so this reads back the names each row already holds.
@@ -2655,7 +2692,7 @@ export function buildRig(
2655
2692
  images: 'images',
2656
2693
  skeleton: { x: -CX, y: 0, width: W, height: H },
2657
2694
  bones,
2658
- slots: explicitLayout.slots,
2695
+ slots: frontSlots.length === 0 ? explicitLayout.slots : spliceFrontSlots(explicitLayout.slots, frontSlots, frontTargets, slotFamilies),
2659
2696
  skins: { default: skin },
2660
2697
  };
2661
2698
  if (cfg.constraints !== undefined) rig.constraints = cfg.constraints.map(constraintForRig);
@@ -2712,6 +2749,32 @@ export function buildRig(
2712
2749
  };
2713
2750
  }
2714
2751
 
2752
+ /**
2753
+ * Issue #664: the final setup slot order with each front slot placed
2754
+ * immediately after its target part's whole slot family (the part's slot and
2755
+ * its `<part>_still`), wherever the closure (#646) left that family's last
2756
+ * member; several front slots after one family keep the order the config
2757
+ * declares them in. A target with no slot in the order is refused by name.
2758
+ */
2759
+ function spliceFrontSlots(order: RigSpec['slots'], fronts: RigSpec['slots'], targets: ReadonlyArray<{ slot: string; after: string; at: string }>, families: ReadonlyMap<string, readonly string[]>): RigSpec['slots'] {
2760
+ const problems: Problem[] = [];
2761
+ const out = [...order];
2762
+ for (const [i, f] of fronts.entries()) {
2763
+ const t = targets[i];
2764
+ const family = families.get(t.after) ?? [];
2765
+ const last = Math.max(-1, ...family.map((n) => out.findIndex((s) => s.name === n)));
2766
+ if (last < 0) {
2767
+ problems.push({ code: 'RIG_NAME_RESOLVES', object: `${t.at}.after`, detail: `names "${t.after}", which has no slot in the rig's setup order; a front slot is placed after a part's slot family` });
2768
+ continue;
2769
+ }
2770
+ let at = last + 1;
2771
+ while (at < out.length && fronts.slice(0, i).includes(out[at])) at++;
2772
+ out.splice(at, 0, f);
2773
+ }
2774
+ refuseIfAny(problems);
2775
+ return out;
2776
+ }
2777
+
2715
2778
  /**
2716
2779
  * Issue #473: expand `{"t": …, "set": "<name>" | null}` keys on slot attachment
2717
2780
  * tracks in `merged.animations` into `{"t": …, "v": "<attachment>" | null}`
@@ -2844,6 +2907,23 @@ export function expandSetAttachmentKeys(rig: RigSpec, sets: AttachmentSetsFile |
2844
2907
  });
2845
2908
  return;
2846
2909
  }
2910
+ // Issue #664: a set that draws this track's part on its front slot moves the part in the draw order, which a
2911
+ // keyed attachment swap cannot do; keyed draw-order changes are out of scope.
2912
+ // A declared front slot is the one slot the rig writes with no setup attachment.
2913
+ const isFront = (name: string): boolean => rig.slots.some((sl) => sl.name === name && sl.attachment === null);
2914
+ const frontBase = slot.endsWith(FRONT_SUFFIX) && isFront(slot) ? slot.slice(0, -FRONT_SUFFIX.length) : null;
2915
+ const drawsFront =
2916
+ (isFront(`${slot}${FRONT_SUFFIX}`) && Object.hasOwn(entry.slots, `${slot}${FRONT_SUFFIX}`) && entry.hides?.includes(slot) === true) ||
2917
+ (frontBase !== null && Object.hasOwn(entry.slots, slot) && entry.hides?.includes(frontBase) === true);
2918
+ if (drawsFront) {
2919
+ const part = frontBase ?? slot;
2920
+ problems.push({
2921
+ code: 'CONFIG_SET_FRONT_KEYED',
2922
+ object: keyAt,
2923
+ detail: `names alternate set "${setVal}" on slot "${slot}", and set "${setVal}" draws "${part}" on its front slot "${part}${FRONT_SUFFIX}" (hiding "${part}"); a keyed set switch on a front part would change the draw order mid-clip, which is out of scope — show the set with setSet, or key a part the set draws on its base slot`,
2924
+ });
2925
+ return;
2926
+ }
2847
2927
  if (Object.hasOwn(entry.slots, slot)) {
2848
2928
  resolvedV = entry.slots[slot];
2849
2929
  } else if (entry.hides?.includes(slot) === true) {
package/src/scene.ts CHANGED
@@ -1115,7 +1115,7 @@ export function composeScene(
1115
1115
  const sized = s === 1 ? {} : { x: scaledBy(bone.x, s), y: scaledBy(bone.y, s), ...(bone.length === undefined ? {} : { length: scaledBy(bone.length, s) }) };
1116
1116
  bones.push({ ...bone, name: P(id, bone.name), ...(bone.parent === undefined ? {} : { parent: P(id, bone.parent) }), ...sized, ...(first ? { x: placed(bone.x, dx, s), y: placed(bone.y, dy, s) } : {}) });
1117
1117
  }
1118
- for (const s of b.rig.slots) slotDefs.set(prefixed(id, s.name), { ...s, name: prefixed(id, s.name), bone: P(id, s.bone), attachment: prefixed(id, s.attachment) });
1118
+ for (const s of b.rig.slots) slotDefs.set(prefixed(id, s.name), { ...s, name: prefixed(id, s.name), bone: P(id, s.bone), attachment: s.attachment === null ? null : prefixed(id, s.attachment) });
1119
1119
  // Everything the character places in root's own frame moves with it: a region on a slot root carries, and a
1120
1120
  // weight bound to root. Every other offset is local to a bone the shift already moved.
1121
1121
  const slotBone = new Map(b.rig.slots.map((s) => [s.name, s.bone]));
@@ -1305,7 +1305,8 @@ export function unprefixedNames(rig: RigSpec, motion: MotionSpec, ids: readonly
1305
1305
  for (const s of rig.slots) {
1306
1306
  name('slot', s.name);
1307
1307
  name(`slot ${s.name} bone`, s.bone);
1308
- name(`slot ${s.name} attachment`, s.attachment);
1308
+ // Issue #664: a front slot shows nothing at setup; null names nothing.
1309
+ if (s.attachment !== null) name(`slot ${s.name} attachment`, s.attachment);
1309
1310
  }
1310
1311
  for (const [slot, atts] of Object.entries(rig.skins.default)) {
1311
1312
  name('skin slot', slot);
@@ -0,0 +1,203 @@
1
+ /** Same-directory staging for every CLI config writer (issue #356).
2
+ * Ownership is pure; this adapter alone owns files. Existing updates use their
3
+ * stage loaders; fresh cloth text retains its intentional partial-config contract.
4
+ */
5
+ import { closeSync, fchmodSync, linkSync, mkdirSync, lstatSync, openSync, readFileSync, realpathSync, statSync, renameSync, rmSync, writeFileSync } from 'node:fs';
6
+ import { randomBytes } from 'node:crypto';
7
+ import { basename, dirname, join, resolve } from 'node:path';
8
+ import { loadConfigAndAnimations, loadEarlyConfig, repeatedKeys } from '../src/config.ts';
9
+ import { mergeConfigProposal, type ConfigWriteChange, type ConfigWritePatch } from '../src/configwrite.ts';
10
+ import { PartsError, type Problem } from '../src/errors.ts';
11
+ import { splicedEdits } from '../src/meshdraft.ts';
12
+
13
+ export interface ConfigWriteTarget { path: string; original: string; mode: number; raw: unknown }
14
+ /** Cloth supplies already checked splice text; a partial config is intentional. */
15
+ export interface FreshConfigWrite { kind: 'fresh'; path: string; text: string }
16
+ export interface ConfigWriteFiles {
17
+ /** Narrow filesystem operations, supplied only by failure controls; CLI uses the real defaults. */
18
+ replace?: (from: string, to: string) => void;
19
+ remove?: (path: string) => void;
20
+ publish?: (from: string, to: string) => void;
21
+ }
22
+ export interface StagedConfigWrite {
23
+ changes: readonly ConfigWriteChange[];
24
+ commit(): void;
25
+ cancel(): void;
26
+ /** Combine a caller artifact failure with cleanup before its catch prints it. */
27
+ abort(error: unknown): never;
28
+ }
29
+ function refusal(code: string, path: string, detail: string): never {
30
+ throw new PartsError([{ code, object: path, detail }]);
31
+ }
32
+ function ioProblem(path: string, action: string, error: unknown): Problem {
33
+ return { code: 'CONFIG_WRITE_FAILED', object: path, detail: `${action}: ${error instanceof Error ? error.message : String(error)}; check the destination directory and permissions` };
34
+ }
35
+ function ioFailure(path: string, action: string, error: unknown): never {
36
+ throw new PartsError([ioProblem(path, action, error)]);
37
+ }
38
+ function failedOperation(path: string, action: string, error: unknown, cancel: () => void): never {
39
+ const problems = error instanceof PartsError ? [...error.problems] : [ioProblem(path, action, error)];
40
+ try { cancel(); }
41
+ catch (cleanup) { problems.push(...(cleanup instanceof PartsError ? cleanup.problems : [ioProblem(path, 'removing the staged config failed', cleanup)])); }
42
+ throw new PartsError(problems);
43
+ }
44
+ export function readConfigWriteTarget(path: string): ConfigWriteTarget {
45
+ const target = resolve(path);
46
+ let stat: ReturnType<typeof lstatSync>;
47
+ try { stat = lstatSync(target); }
48
+ catch (error) { return refusal('CONFIG_FILE_PRESENT', target, `cannot read the existing config: ${error instanceof Error ? error.message : String(error)}`); }
49
+ if (!stat.isFile()) return refusal('CONFIG_FIELD_TYPE', target, 'is not a regular file (symlinks are not replaced); --write-config updates an existing config file in place');
50
+ let original: string;
51
+ try { original = readFileSync(target, 'utf8'); }
52
+ catch (error) { return ioFailure(target, 'reading the destination failed', error); }
53
+ let raw: unknown;
54
+ try { raw = JSON.parse(original); }
55
+ catch (error) { return refusal('CONFIG_IS_JSON', target, `does not parse as JSON: ${error instanceof Error ? error.message : String(error)}`); }
56
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return refusal('CONFIG_FIELD_TYPE', target, 'must hold a config JSON object');
57
+ const duplicates = repeatedKeys(original);
58
+ if (duplicates.length > 0) throw new PartsError(duplicates.map((r) => ({ code: 'CONFIG_KEY_UNIQUE', object: `config${r.at === '' ? '' : `.${r.at}`}`, detail: `names ${JSON.stringify(r.key)} ${r.count} times; each key must occur once before an in-place update` })));
59
+ return { path: target, original, raw, mode: stat.mode & 0o777 };
60
+ }
61
+ /** Resolve existing ancestors too: an output parent may be an alias or not exist yet. */
62
+ function canonical(path: string): string {
63
+ let at = resolve(path);
64
+ const tail: string[] = [];
65
+ for (;;) {
66
+ try { return join(realpathSync(at), ...tail); }
67
+ catch (error) {
68
+ if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') throw error;
69
+ const parent = dirname(at);
70
+ if (parent === at) throw error;
71
+ tail.unshift(basename(at));
72
+ at = parent;
73
+ }
74
+ }
75
+ }
76
+ /** Refuse before ordinary propose writes any artifact that could overwrite its config. */
77
+ export function separateConfigWriteTarget(target: Pick<ConfigWriteTarget, 'path'>, artifacts: readonly string[], code = 'CONFIG_WRITE_TARGET'): void {
78
+ try {
79
+ let identity: ReturnType<typeof statSync> | null = null;
80
+ try { identity = statSync(target.path); }
81
+ catch (error) {
82
+ if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') throw error;
83
+ }
84
+ const targetPath = canonical(target.path);
85
+ for (const artifact of artifacts) {
86
+ let alias = canonical(artifact) === targetPath;
87
+ try {
88
+ const existing = statSync(artifact);
89
+ alias ||= identity !== null && existing.dev === identity.dev && existing.ino === identity.ino;
90
+ } catch (error) {
91
+ if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') throw error;
92
+ }
93
+ if (alias) refusal(code, target.path, `is also the proposal output ${resolve(artifact)}; choose a config outside the command's proposal, basis and landmark artifact paths — nothing was written`);
94
+ }
95
+ } catch (error) {
96
+ if (error instanceof PartsError) throw error;
97
+ ioFailure(target.path, 'checking output collisions failed', error);
98
+ }
99
+ }
100
+
101
+ function unchanged(target: ConfigWriteTarget): void {
102
+ let same = false;
103
+ try {
104
+ const stat = lstatSync(target.path);
105
+ same = stat.isFile() && (stat.mode & 0o777) === target.mode && readFileSync(target.path, 'utf8') === target.original;
106
+ } catch { /* Removal is also a change, never a reason to create a new config. */ }
107
+ if (!same) refusal('CONFIG_WRITE_CHANGED', target.path, 'changed after it was read; nothing was replaced — rerun against the current config');
108
+ }
109
+ /** One file-writing adapter for all --write-config modes. Existing-file ownership
110
+ * produces whole-value edits for splicedEdits, the engine clothConfigEdits uses.
111
+ * Fresh cloth text already passed writtenClothConfig's splice check: it is never
112
+ * sent through a full loader that would reject an intentional partial config.
113
+ */
114
+ export function stageConfigWrite(target: ConfigWriteTarget | FreshConfigWrite, patch?: ConfigWritePatch, files: ConfigWriteFiles = {}): StagedConfigWrite {
115
+ const fresh = 'kind' in target;
116
+ const path = resolve(target.path);
117
+ let text: string;
118
+ let changes: readonly ConfigWriteChange[];
119
+ if (fresh) {
120
+ text = target.text;
121
+ changes = [];
122
+ } else {
123
+ if (patch === undefined) return refusal('CONFIG_FIELD_TYPE', path, 'has no config patch; a supported proposal operation is required');
124
+ const merged = mergeConfigProposal(target.raw, patch);
125
+ const spliced = merged.changes.length === 0 ? { text: target.original, moved: null } : splicedEdits(target.original, merged.edits);
126
+ if (spliced.moved !== null) return refusal('CONFIG_WRITE_FAILED', path, `spliced proposal values moved ${spliced.moved}; the original was not replaced`);
127
+ text = spliced.text;
128
+ changes = merged.changes;
129
+ }
130
+ const freshAbsent = (): void => {
131
+ try { lstatSync(path); }
132
+ catch (error) {
133
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return;
134
+ return ioFailure(path, 'checking the fresh destination failed', error);
135
+ }
136
+ refusal('PROPOSE_WRITE_CONFIG_FRESH', path, 'exists; the config is written to a new file, never over the --cloth config or an earlier one');
137
+ };
138
+ if (fresh) freshAbsent();
139
+ const temp = join(dirname(path), `.${basename(path)}.rig-parts-${randomBytes(8).toString('hex')}.tmp`);
140
+ let owned = false;
141
+ const cancel = (): void => {
142
+ if (!owned) return;
143
+ owned = false;
144
+ try { if (files.remove === undefined) rmSync(temp, { force: true }); else files.remove(temp); }
145
+ catch (error) { ioFailure(temp, 'removing the staged config failed; remove this temporary after restoring directory permissions', error); }
146
+ };
147
+ let fd: number | undefined;
148
+ try {
149
+ if (fresh) mkdirSync(dirname(path), { recursive: true });
150
+ fd = openSync(temp, 'wx', fresh ? 0o666 : target.mode);
151
+ owned = true;
152
+ writeFileSync(fd, text);
153
+ if (!fresh) fchmodSync(fd, target.mode);
154
+ closeSync(fd);
155
+ fd = undefined;
156
+ if (!fresh) {
157
+ if (patch?.kind === 'head-box') loadEarlyConfig(temp, 'layers');
158
+ else if (patch?.kind === 'assemble-plan') loadEarlyConfig(temp, 'assemble');
159
+ else loadConfigAndAnimations(temp);
160
+ }
161
+ } catch (error) {
162
+ if (fd !== undefined) {
163
+ try { closeSync(fd); }
164
+ catch (cleanup) {
165
+ const primary = error instanceof PartsError ? [...error.problems] : [ioProblem(path, 'staging the config failed', error)];
166
+ error = new PartsError([...primary, ioProblem(temp, 'closing the staged config failed', cleanup)]);
167
+ }
168
+ }
169
+ return failedOperation(path, 'staging the config failed; the destination was not written', error, cancel);
170
+ }
171
+ return {
172
+ changes,
173
+ cancel,
174
+ abort(error: unknown): never {
175
+ return failedOperation(path, 'writing proposal artifacts failed', error, cancel);
176
+ },
177
+ commit(): void {
178
+ try {
179
+ if (fresh) {
180
+ freshAbsent();
181
+ // Linking the same-directory staged file publishes complete bytes and
182
+ // refuses an intervening creator atomically; rename would overwrite it.
183
+ try { (files.publish ?? linkSync)(temp, path); }
184
+ catch (error) {
185
+ if (error instanceof Error && 'code' in error && error.code === 'EEXIST') refusal('PROPOSE_WRITE_CONFIG_FRESH', path, 'exists; the config is written to a new file, never over the --cloth config or an earlier one');
186
+ throw error;
187
+ }
188
+ cancel();
189
+ } else {
190
+ unchanged(target);
191
+ if (changes.length > 0) { (files.replace ?? renameSync)(temp, path); owned = false; }
192
+ else cancel();
193
+ }
194
+ } catch (error) {
195
+ failedOperation(path, 'committing the config failed', error, cancel);
196
+ }
197
+ },
198
+ };
199
+ }
200
+ /** Print to stderr so proposal JSON on stdout remains machine-readable. */
201
+ export function configWriteLines(target: ConfigWriteTarget, changes: readonly ConfigWriteChange[]): string[] {
202
+ return changes.length === 0 ? [`config ${target.path}: unchanged`] : changes.map((c) => `config ${target.path}: ${c.kind} ${c.path}`);
203
+ }