@rig-c/parts 2.43.0 → 2.45.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/remesh.ts CHANGED
@@ -64,6 +64,7 @@
64
64
  import { createHash } from 'node:crypto';
65
65
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
66
66
  import { dirname, join, relative, resolve, sep } from 'node:path';
67
+ import { inspect } from 'node:util';
67
68
  import { checkStage, gateThroughRigc, type Log, RIGC_MODEL_DOCUMENT, rigStage } from './build.ts';
68
69
  import { barsNotMet, type CheckReport, checkStatuses, type CheckStatus, checkSummaryLine, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackMode, type PackShape, type PageEdges, parsePageSize, rigcRanClause, type RigcRunner } from './check.ts';
69
70
  import { loadConfigAndAnimations } from './config.ts';
@@ -71,7 +72,7 @@ import { PartsError, type Problem, problemLine, refuseIfAny } from './errors.ts'
71
72
  import { jsonValueSpan, scratchConfig } from './meshdraft.ts';
72
73
  import { type BoneTransform, computeExactFrameTransforms } from './coords.ts';
73
74
  import { type PartsFile } from './parts.ts';
74
- import { applyMeshEdit, type DeltaApplied, type DeltaPlant, deltaSourceProblems, type MeshEditDocument, readMeshEdit } from './remeshdelta.ts';
75
+ import { applyMeshEdit, type DeltaApplied, type DeltaPlant, deltaSourceProblems, deltaTargetProblems, isSha256, meshEditActProblems, type MeshEditActValue, type MeshEditDocument, meshEditPositionProblems, readMeshEdit } from './remeshdelta.ts';
75
76
  import { DEFAULT_IDLE_KEYS, type IdleKeys, type MeshAttachment, meshBoundBones, rigJsonText, type RigSpec } from './rig.ts';
76
77
  import { readRequirements } from './requirements.ts';
77
78
  import { pyRound } from './round.ts';
@@ -121,6 +122,14 @@ export interface RemeshInput {
121
122
  recordInputCheck?: boolean;
122
123
  }
123
124
 
125
+ /** The Parts revision and one edit from a finalized act. */
126
+ export interface ApplyMeshEditActInput extends Pick<RemeshInput, 'rig' | 'config' | 'parts' | 'part' | 'out'> {
127
+ edit: MeshEditActValue;
128
+ actId: string;
129
+ actSourceHash: string;
130
+ payloadSha256: string;
131
+ }
132
+
124
133
  /**
125
134
  * Planted faults for the selftest (issue #495, bar 4) — never set by the CLI: `perturb` changes the first uv of the
126
135
  * named part's attachment in the revision after the splice, and `skipPreserve` takes the preserve assertion out, so
@@ -184,7 +193,8 @@ export interface RemeshProvenance {
184
193
  spec: typeof REMESH_SPEC;
185
194
  request:
186
195
  | { part: string; mesh: unknown; mesh_sha256: string; idle_keys: IdleKeys; page_edges: PageEdges; pack_shape: PackShape }
187
- | { part: string; delta: MeshEditDocument; delta_sha256: string; ops: number; applied: Omit<DeltaApplied, 'ops'>; idle_keys: IdleKeys; page_edges: PageEdges; pack_shape: PackShape };
196
+ | { part: string; delta: MeshEditDocument; delta_sha256: string; ops: number; applied: Omit<DeltaApplied, 'ops'>; idle_keys: IdleKeys; page_edges: PageEdges; pack_shape: PackShape }
197
+ | { part: string; edit: MeshEditActValue; act_id: string; act_source_hash: string; payload_sha256: string; ops: number; applied: Omit<DeltaApplied, 'ops'>; idle_keys: IdleKeys; page_edges: PageEdges; pack_shape: PackShape };
188
198
  versions: RemeshVersions;
189
199
  input: { rig: HashRow[]; config_sha256: string; parts_json_sha256: string; provenance?: ParentProvenance[] };
190
200
  baseline: { reproduced: string[]; not_compared: string };
@@ -229,13 +239,16 @@ export function hashRows(tree: FileTree): HashRow[] {
229
239
  /** A previous root record, recoverable byte for byte at its content-addressed path (issue #531). */
230
240
  export interface ParentProvenance extends HashRow { source: 'remesh.json' | 'retune.json' }
231
241
 
242
+ const provenancePath = (source: ParentProvenance['source'], digest: string): string =>
243
+ `provenance/${source.slice(0, -5)}-${digest}.json`;
244
+
232
245
  /** Keep prior records before replacing the current root record; no rig, motion or hold input is changed. */
233
246
  export function carryProvenance(input: FileTree, revision: FileTree, replacing: 'remesh.json' | 'retune.json'): { revision: FileTree; parents: ParentProvenance[] } {
234
247
  const next = new Map(revision), parents: ParentProvenance[] = [];
235
248
  for (const source of ['remesh.json', 'retune.json'] as const) {
236
249
  const bytes = input.get(source);
237
250
  if (bytes === undefined) continue;
238
- const digest = sha256(bytes), path = `provenance/${source.slice(0, -5)}-${digest}.json`;
251
+ const digest = sha256(bytes), path = provenancePath(source, digest);
239
252
  const existing = next.get(path);
240
253
  if (existing !== undefined && !bytesEqual(existing, bytes)) {
241
254
  throw new PartsError([{ code: replacing === 'remesh.json' ? 'REMESH_PRESERVED' : 'RETUNE_PRESERVED', object: path,
@@ -251,6 +264,16 @@ export function carryProvenance(input: FileTree, revision: FileTree, replacing:
251
264
  const text = (b: Uint8Array): string => new TextDecoder().decode(b);
252
265
  const bytesOf = (s: string): Uint8Array => new TextEncoder().encode(s);
253
266
 
267
+ /** Canonical act payload bytes as text. The caller supplies a value in the signed JSON domain. */
268
+ export function encodeMeshEditPayload(value: unknown): string {
269
+ return JSON.stringify(value, (_key, entry: unknown) =>
270
+ isRecord(entry) ? Object.fromEntries(Object.keys(entry).sort().map(key => [key, entry[key]])) : entry);
271
+ }
272
+
273
+ export function meshEditPayloadSha256(value: unknown): string {
274
+ return sha256(bytesOf(encodeMeshEditPayload(value)));
275
+ }
276
+
254
277
  /** The first leaf at which `a` and `b` differ, as `path: a vs b`, or null when they are equal as JSON. */
255
278
  export function firstDifference(a: unknown, b: unknown, at = ''): string | null {
256
279
  if (Array.isArray(a) && Array.isArray(b)) {
@@ -904,11 +927,130 @@ export function deltaRow(row: Json, att: MeshAttachment): Json {
904
927
  return out;
905
928
  }
906
929
 
930
+ type ActBinding = Pick<ApplyMeshEditActInput, 'edit' | 'actId' | 'actSourceHash' | 'payloadSha256'>;
931
+
932
+ interface PreparedMeshEditAct {
933
+ input: Pick<RemeshInput, 'rig' | 'config' | 'parts' | 'part' | 'out'>;
934
+ tree: FileTree;
935
+ act: ActBinding;
936
+ }
937
+
938
+ const PROVENANCE_SPECS = { [PROVENANCE_FILE]: REMESH_SPEC, 'retune.json': 'rig-parts-retune/1' } as const;
939
+
940
+ function provenanceRecord(bytes: Uint8Array | undefined, source: ParentProvenance['source']): Json | null {
941
+ if (bytes === undefined) return null;
942
+ let value: unknown;
943
+ try { value = JSON.parse(text(bytes)); } catch { return null; }
944
+ return isRecord(value) && value.spec === PROVENANCE_SPECS[source] ? value : null;
945
+ }
946
+
947
+ function revisionBinds(record: Json, rows: HashRow[], source: ParentProvenance['source']): boolean {
948
+ return firstDifference(record.revision, rows.filter(row => row.path !== source)) === null;
949
+ }
950
+
951
+ function storedAct(record: Json | null, actId: string, part: string): Json | null {
952
+ const req = record?.request;
953
+ // Parts writes one editable identity per part: default skin, and slot and attachment both named after the part.
954
+ return record?.spec === REMESH_SPEC && isRecord(req) && req.act_id === actId && req.part === part ? req : null;
955
+ }
956
+
957
+ function refuseAct(object: string, detail: string): never {
958
+ throw new PartsError([{ code: 'REMESH_DELTA_ACT', object, detail }]);
959
+ }
960
+
961
+ function assertActDigest(supplied: string, computed: string): void {
962
+ if (supplied !== computed) throw new PartsError([{ code: 'REMESH_DELTA_DIGEST', object: 'payloadSha256', detail: `is ${supplied}; the canonical edit hashes to ${computed}` }]);
963
+ }
964
+
965
+ function assertStoredAct(req: Json, act: ActBinding, object: string): void {
966
+ if (req.act_source_hash !== act.actSourceHash || req.payload_sha256 !== act.payloadSha256) {
967
+ refuseAct(object, `act "${act.actId}" for "${String(req.part)}" records source hash ${JSON.stringify(req.act_source_hash)} and payload digest ${JSON.stringify(req.payload_sha256)}; received ${act.actSourceHash} and ${act.payloadSha256}; the same act key requires the same binding`);
968
+ }
969
+ if (meshEditActProblems(req.edit, object).length > 0 || meshEditPayloadSha256(req.edit) !== act.payloadSha256) {
970
+ refuseAct(object, `act "${act.actId}" for "${String(req.part)}" does not hold a valid edit matching payload digest ${act.payloadSha256}`);
971
+ }
972
+ }
973
+
974
+ /**
975
+ * A receipt can authorize a replay only over its exact output tree. Follow archived receipts through the
976
+ * hash-bound predecessor trees so a key known to an earlier revision cannot be applied again.
977
+ */
978
+ function actReplay(tree: FileTree, rig: string, part: string, act: ActBinding, digest: string): RemeshResult | null {
979
+ const sources = [PROVENANCE_FILE, 'retune.json'] as const;
980
+ const roots = sources.flatMap(source => {
981
+ const record = provenanceRecord(tree.get(source), source);
982
+ return record === null ? [] : [{ path: source, source, record }];
983
+ });
984
+ if (roots.length === 0) return null;
985
+ const rows = hashRows(tree);
986
+ const current = roots.find(root => revisionBinds(root.record, rows, root.source));
987
+ if (current === undefined) {
988
+ const unbound = roots.find(root => storedAct(root.record, act.actId, part) !== null);
989
+ if (unbound !== undefined) refuseAct(join(rig, unbound.path), `records act "${act.actId}" for "${part}", but its revision hashes do not bind the current rig files`);
990
+ return null;
991
+ }
992
+ const byPath = new Map(rows.map(row => [row.path, row]));
993
+ const pending: Array<{ path: string; record: Json }> = [current];
994
+ const visited = new Set<string>();
995
+ while (pending.length > 0) {
996
+ const { path, record } = pending.pop()!;
997
+ if (visited.has(path)) continue;
998
+ visited.add(path);
999
+ const req = storedAct(record, act.actId, part);
1000
+ if (req !== null) {
1001
+ const object = join(rig, path);
1002
+ assertStoredAct(req, act, object);
1003
+ assertActDigest(act.payloadSha256, digest);
1004
+ if (path !== current.path) {
1005
+ throw new PartsError([{ code: 'REMESH_DELTA_ACT_SUPERSEDED', object: join(rig, current.path),
1006
+ detail: `binds the current revision; act "${act.actId}" for "${part}" was applied on an earlier revision recorded at ${path}; replay requires that revision as the input` }]);
1007
+ }
1008
+ return { provenance: record as unknown as RemeshProvenance, written: [] };
1009
+ }
1010
+ const input = record.input;
1011
+ if (!isRecord(input) || !Array.isArray(input.rig) || !Array.isArray(input.provenance)) continue;
1012
+ for (const ref of input.provenance as unknown[]) {
1013
+ if (!isRecord(ref) || (ref.source !== PROVENANCE_FILE && ref.source !== 'retune.json') || !isSha256(ref.sha256)) continue;
1014
+ const path = provenancePath(ref.source, ref.sha256);
1015
+ const archive = byPath.get(path);
1016
+ if (ref.path !== path || archive?.sha256 !== ref.sha256 || archive.bytes !== ref.bytes) continue;
1017
+ const previousRows = input.rig as HashRow[];
1018
+ if (!previousRows.some(row => row?.path === ref.source && row.sha256 === ref.sha256 && row.bytes === ref.bytes)) continue;
1019
+ const parent = provenanceRecord(tree.get(path), ref.source);
1020
+ if (parent !== null && revisionBinds(parent, previousRows, ref.source)) pending.push({ path, record: parent });
1021
+ }
1022
+ }
1023
+ return null;
1024
+ }
1025
+
1026
+ /** Validate the in-memory request and inspect the input before a build, scratch directory or output is needed. */
1027
+ export function prepareMeshEditAct(input: ApplyMeshEditActInput): PreparedMeshEditAct | RemeshResult {
1028
+ const { rig, config, parts, part, out, actId, actSourceHash, payloadSha256 } = input;
1029
+ const show = (value: unknown): string => inspect(value, { depth: 0, customInspect: false, breakLength: Infinity });
1030
+ if (typeof actId !== 'string' || actId.trim() === '') refuseAct('actId', `is ${show(actId)}; a non-empty finalized act ID is required`);
1031
+ if (!isSha256(actSourceHash)) refuseAct('actSourceHash', `is ${show(actSourceHash)}; the finalized act source hash must be 64 lowercase hex digits`);
1032
+ refuseIfAny(meshEditActProblems(input.edit, 'edit'));
1033
+ if (!isSha256(payloadSha256)) throw new PartsError([{ code: 'REMESH_DELTA_DIGEST', object: 'payloadSha256', detail: `is ${show(payloadSha256)}; the canonical edit digest must be 64 lowercase hex digits` }]);
1034
+ const payload = encodeMeshEditPayload(input.edit);
1035
+ const edit = JSON.parse(payload) as MeshEditActValue;
1036
+ const act = { edit, actId, actSourceHash, payloadSha256 };
1037
+ const digest = sha256(bytesOf(payload));
1038
+ const rigAt = resolve(rig);
1039
+ if (!existsSync(rigAt) || !statSync(rigAt).isDirectory()) throw new PartsError([{ code: 'REMESH_INPUT_PRESENT', object: rig, detail: 'is not a directory; the input revision is the directory rig writes' }]);
1040
+ const tree = readTree(rigAt);
1041
+ if (deltaTargetProblems(edit, part, 'edit').length === 0) {
1042
+ const replay = actReplay(tree, rig, part, act, digest);
1043
+ if (replay !== null) return replay;
1044
+ }
1045
+ assertActDigest(payloadSha256, digest);
1046
+ return { input: { rig, config, parts, part, out }, tree, act };
1047
+ }
1048
+
907
1049
  /**
908
1050
  * The stage: steps 1–8 of the module header. Writes `input.out` only when every step is green; refuses with every
909
1051
  * problem of the first step that found one.
910
1052
  */
911
- export function remeshStage(input: RemeshInput, rigc: RigcRunner, checkBin: string, versions: RemeshVersions, scratch: string, log: Log, plant: RemeshPlant = {}): RemeshResult {
1053
+ export function remeshStage(input: RemeshInput, rigc: RigcRunner, checkBin: string, versions: RemeshVersions, scratch: string, log: Log, plant: RemeshPlant = {}, preparedAct?: PreparedMeshEditAct): RemeshResult {
912
1054
  const part = input.part;
913
1055
  const idleKeys = input.idleKeys ?? DEFAULT_IDLE_KEYS;
914
1056
  const pageEdges = input.pageEdges ?? DEFAULT_PAGE_EDGES;
@@ -921,9 +1063,9 @@ export function remeshStage(input: RemeshInput, rigc: RigcRunner, checkBin: stri
921
1063
  if (existsSync(outAt)) throw new PartsError([{ code: 'REMESH_OUT_FRESH', object: input.out, detail: 'exists; a revision is written into a new directory, never over the input or an earlier revision' }]);
922
1064
  if (!existsSync(rigAt) || !statSync(rigAt).isDirectory()) throw new PartsError([{ code: 'REMESH_INPUT_PRESENT', object: input.rig, detail: 'is not a directory; the input revision is the directory rig writes' }]);
923
1065
  if (outAt.startsWith(`${rigAt}${sep}`)) throw new PartsError([{ code: 'REMESH_OUT_FRESH', object: input.out, detail: `is inside the input ${input.rig}; a revision is written beside the input, never into it` }]);
924
- const tree = readTree(rigAt);
1066
+ const tree = preparedAct?.tree ?? readTree(rigAt);
925
1067
  refuseIfAny(inputTreeProblems(tree, input.rig));
926
- if ((input.mesh === undefined) === (input.delta === undefined)) throw new Error('remeshStage: exactly one of mesh, delta is required');
1068
+ if (preparedAct === undefined && (input.mesh === undefined) === (input.delta === undefined)) throw new Error('remeshStage: exactly one of mesh, delta is required');
927
1069
  const recorded = inputCheckOf(input, rigAt, tree, pageEdges, packShape, versions.parts, rigc, 'remesh', pageSize);
928
1070
  const meshReq = input.mesh === undefined ? null : readMeshRequest(input.mesh);
929
1071
  const deltaReq = input.delta === undefined ? null : readDeltaRequest(input.delta);
@@ -978,26 +1120,56 @@ export function remeshStage(input: RemeshInput, rigc: RigcRunner, checkBin: stri
978
1120
  } else {
979
1121
  // 3–4 on the delta path (issue #526): no config entry to build, so the baseline is the input itself, held to the
980
1122
  // delta by its source counts and its source.hash, and the candidate is the delta replayed over the input's mesh.
981
- const deltaPath = input.delta as string;
982
- const { doc, bytes } = deltaReq as { doc: MeshEditDocument; bytes: Uint8Array };
1123
+ const act = preparedAct?.act;
1124
+ const deltaPath = act === undefined ? input.delta as string : 'edit';
1125
+ const doc = act?.edit ?? deltaReq!.doc;
983
1126
  const inAtt = targetAttachment(inRig, part) as MeshAttachment;
984
- refuseIfAny(deltaSourceProblems(doc, part, inAtt, deltaPath));
1127
+ const sourceProblems = deltaSourceProblems(doc, part, inAtt, deltaPath);
1128
+ if (act === undefined) refuseIfAny(sourceProblems);
985
1129
  log(`rig-parts remesh: ${part} of ${input.rig}, ${tree.size} file(s); the request is a mesh edit of ${doc.ops.length} op(s), the baseline is the input itself`);
986
1130
  let model = null as string | null;
987
1131
  const inGate = gateThroughRigc(pngsOf(tree), textsOf(tree, plant.unfilteredGateTexts === true), rigc, join(scratch, 'gate-input'), mode, (dir) => {
988
1132
  const p = join(dir, RIGC_MODEL_DOCUMENT);
989
1133
  model = existsSync(p) ? readFileSync(p, 'utf8') : null;
990
1134
  });
991
- refuseIfAny(inGate.filter((g) => g.status !== 0).map((g) => ({ code: 'REMESH_RIGC_GREEN', object: `rigc ${g.label} over the input`, detail: `exited ${g.status}${g.lines.length > 0 ? `: ${g.lines.map((l) => l.trim()).join(' | ')}` : ''}${rigcRanClause(g)}; the delta's source.hash is read off the input's own build, and nothing was written` })));
992
- if (model === null) throw new PartsError([{ code: 'REMESH_DELTA_SOURCE', object: `rigc's build over the input`, detail: `wrote no ${RIGC_MODEL_DOCUMENT}, so the delta's source.hash cannot be verified; nothing was written` }]);
993
- const hash = modelAttachmentHash(model, part);
994
- if (hash !== doc.source.hash) {
995
- throw new PartsError([{ code: 'REMESH_DELTA_SOURCE', object: `${deltaPath} source.hash`, detail: `is ${doc.source.hash.slice(0, 16)}…; the input's ${part} in its ${RIGC_MODEL_DOCUMENT} hashes to ${hash === null ? 'nothing (no such entry)' : `${hash.slice(0, 16)}…`} — the delta was drawn over another mesh` }]);
1135
+ const gateProblems = inGate.filter((g) => g.status !== 0).map((g) => ({ code: 'REMESH_RIGC_GREEN', object: `rigc ${g.label} over the input`, detail: `exited ${g.status}${g.lines.length > 0 ? `: ${g.lines.map((l) => l.trim()).join(' | ')}` : ''}${rigcRanClause(g)}; the delta's source.hash is read off the input's own build, and nothing was written` }));
1136
+ if (gateProblems.length > 0) sourceProblems.push(...gateProblems);
1137
+ else if (model === null) sourceProblems.push({ code: 'REMESH_DELTA_SOURCE', object: `rigc's build over the input`, detail: `wrote no ${RIGC_MODEL_DOCUMENT}, so the delta's source.hash cannot be verified; nothing was written` });
1138
+ else {
1139
+ const hash = modelAttachmentHash(model, part);
1140
+ const displayHash = (digest: string): string => act === undefined ? `${digest.slice(0, 16)}…` : digest;
1141
+ if (hash !== doc.source.hash) {
1142
+ sourceProblems.push({ code: 'REMESH_DELTA_SOURCE', object: `${deltaPath} source.hash`, detail: `is ${displayHash(doc.source.hash)}; the input's ${part} in its ${RIGC_MODEL_DOCUMENT} hashes to ${hash === null ? 'nothing (no such entry)' : displayHash(hash)} — the delta was drawn over another mesh` });
1143
+ } else if (sourceProblems.length === 0) {
1144
+ log(` source: ${part}'s entry in the input's ${RIGC_MODEL_DOCUMENT} hashes to ${hash.slice(0, 16)}…, the delta's source.hash; counts v=${before.vertices} t=${before.triangles} hull=${before.hull} as it states`);
1145
+ }
1146
+ }
1147
+ if (act === undefined) refuseIfAny(sourceProblems);
1148
+ const partsPath = join(input.parts, 'parts.json');
1149
+ let partsFile: PartsFile | undefined;
1150
+ try {
1151
+ const value = JSON.parse(readFileSync(partsPath, 'utf8')) as PartsFile;
1152
+ if (act !== undefined && (!Array.isArray(value?.parts) || !Array.isArray(value.rig_size))) throw new Error('requires a parts array and a rig_size pair');
1153
+ partsFile = value;
1154
+ } catch (err) {
1155
+ if (act === undefined || !(err instanceof Error)) throw err;
1156
+ sourceProblems.push({ code: 'REMESH_DELTA_SOURCE', object: partsPath, detail: `cannot read the Parts placement: ${err.message}` });
1157
+ }
1158
+ const rec = partsFile?.parts.find((p) => p?.name === part);
1159
+ if (partsFile !== undefined && rec === undefined) sourceProblems.push({ code: 'REMESH_DELTA_SOURCE', object: `${input.parts}/parts.json`, detail: `names no part "${part}"; its box is where rig placed the image, which the delta's crop px are read against` });
1160
+ if (act !== undefined) {
1161
+ const { width, height } = act.edit.source.frame;
1162
+ const rigFrame = (inRig as unknown as RigSpec).skeleton;
1163
+ const partFrame = partsFile?.rig_size;
1164
+ if (width !== rigFrame?.width || height !== rigFrame?.height || (partFrame !== undefined && (partFrame.length !== 2 || width !== partFrame[0] || height !== partFrame[1]))) {
1165
+ sourceProblems.push({ code: 'REMESH_DELTA_SOURCE', object: 'edit source.frame', detail: `is ${width}×${height} px; requires the input rig size (${rigFrame?.width}×${rigFrame?.height} px)${partFrame === undefined ? '' : ` and Parts placement frame (${partFrame.join('×')} px)`}` });
1166
+ }
1167
+ if (rec !== undefined) {
1168
+ if (Number.isFinite(rec.x) && Number.isFinite(rec.y)) sourceProblems.push(...meshEditPositionProblems({ attachment: inAtt, box: [rec.x, rec.y] }, act.edit.source.positions, deltaPath));
1169
+ else sourceProblems.push({ code: 'REMESH_DELTA_SOURCE', object: `${partsPath} part "${part}"`, detail: `has box origin (${rec.x}, ${rec.y}); finite x and y are required` });
1170
+ }
996
1171
  }
997
- log(` source: ${part}'s entry in the input's ${RIGC_MODEL_DOCUMENT} hashes to ${hash.slice(0, 16)}…, the delta's source.hash; counts v=${before.vertices} t=${before.triangles} hull=${before.hull} as it states`);
998
- const partsFile = JSON.parse(readFileSync(join(input.parts, 'parts.json'), 'utf8')) as PartsFile;
999
- const rec = partsFile.parts.find((p) => p.name === part);
1000
- if (rec === undefined) throw new PartsError([{ code: 'REMESH_DELTA_SOURCE', object: `${input.parts}/parts.json`, detail: `names no part "${part}"; its box is where rig placed the image, which the delta's crop px are read against` }]);
1172
+ if (partsFile === undefined || rec === undefined || sourceProblems.length > 0) throw new PartsError(sourceProblems);
1001
1173
  const world = deltaFrames(inRig, `${input.rig}/rig.json`, plant.unexpandedStops === true);
1002
1174
  if (Array.isArray(world)) throw new PartsError(world);
1003
1175
  const r = applyMeshEdit({ part, attachment: inAtt, box: [rec.x, rec.y], rigSize: [partsFile.rig_size[0], partsFile.rig_size[1]], world }, doc, deltaPath, plant.delta);
@@ -1009,7 +1181,13 @@ export function remeshStage(input: RemeshInput, rigc: RigcRunner, checkBin: stri
1009
1181
  const { ops, ...applied } = r.applied;
1010
1182
  log(` delta: ${ops} op(s) — moved ${applied.moved}, added ${applied.added}, removed ${applied.removed}, constrained ${applied.constrained}; ${r.untouched.length} source vertex(es) untouched; interior edges not locally Delaunay ${r.delaunay.before} -> ${r.delaunay.after}`);
1011
1183
  reproduced = ['none built: the delta path builds no config entry, so the baseline is the input itself, held to the delta by source.vertexCount, source.triangleCount, source.hullLength and source.hash'];
1012
- deltaRequest = { part, delta: doc, delta_sha256: sha256(bytes), ops, applied, idle_keys: idleKeys, page_edges: pageEdges, pack_shape: packShape };
1184
+ const measured = { ops, applied, idle_keys: idleKeys, page_edges: pageEdges, pack_shape: packShape };
1185
+ if (act === undefined) {
1186
+ const { doc, bytes } = deltaReq!;
1187
+ deltaRequest = { part, delta: doc, delta_sha256: sha256(bytes), ...measured };
1188
+ } else {
1189
+ deltaRequest = { part, edit: act.edit, act_id: act.actId, act_source_hash: act.actSourceHash, payload_sha256: act.payloadSha256, ...measured };
1190
+ }
1013
1191
  }
1014
1192
  const after = meshCounts(candAtt);
1015
1193
  // 5–6. The splice and the preserve assertion.
@@ -40,6 +40,7 @@
40
40
  * weight entries byte for byte; only its index may change, since the hull loop is written first.
41
41
  */
42
42
  import { contourTopologyProblems, delaunayViolations, GRID, inCircle } from './contour.ts';
43
+ import { inspect } from 'node:util';
43
44
  import { type BoneTransform, cropToSpineY, toBoneLocal } from './coords.ts';
44
45
  import type { Problem } from './errors.ts';
45
46
  import { type MeshAttachment, OFFSET_PLACES, PAD, roundShares, type WeightEntry } from './rig.ts';
@@ -83,11 +84,50 @@ export interface MeshEditDocument {
83
84
  ops: MeshEditOp[];
84
85
  }
85
86
 
87
+ /** An attachment edit carried by a finalized act. Positions are unrounded crop pixels in vertex order. */
88
+ export interface MeshEditActValue {
89
+ slot: string;
90
+ skin: string;
91
+ attachment: string;
92
+ basis: typeof MESH_EDIT_BASIS;
93
+ source: MeshEditDocument['source'] & { frame: { width: number; height: number }; positions: Vec[] };
94
+ ops: MeshEditOp[];
95
+ }
96
+
86
97
  type Json = Record<string, unknown>;
87
98
  const isRecord = (v: unknown): v is Json => typeof v === 'object' && v !== null && !Array.isArray(v);
88
- const isVec = (v: unknown): v is Vec => Array.isArray(v) && v.length === 2 && v.every((n) => typeof n === 'number' && Number.isFinite(n));
99
+ const isNumber = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
100
+ const isVec = (v: unknown): v is Vec => Array.isArray(v) && v.length === 2 && isNumber(v[0]) && isNumber(v[1]);
89
101
  const isId = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
102
+ export const isSha256 = (v: unknown): v is string => typeof v === 'string' && v.length === 64 && /^[0-9a-f]+$/.test(v);
90
103
  const OP_FIELDS: Record<MeshEditOp['op'], readonly string[]> = { move: ['op', 'v', 'from', 'to'], add: ['op', 'at', 'onEdge'], remove: ['op', 'v'], edge: ['op', 'a', 'b'], unedge: ['op', 'a', 'b'] };
104
+ const ACT_FIELDS = ['slot', 'skin', 'attachment', 'source', 'basis', 'ops'];
105
+ const ACT_SOURCE_FIELDS = ['vertexCount', 'triangleCount', 'hullLength', 'hash', 'frame', 'positions'];
106
+
107
+ function ownData(value: object, key: PropertyKey): boolean {
108
+ const desc = Object.getOwnPropertyDescriptor(value, key);
109
+ return desc !== undefined && desc.enumerable === true && Object.hasOwn(desc, 'value');
110
+ }
111
+
112
+ function isActRecord(value: unknown): value is Json {
113
+ if (!isRecord(value)) return false;
114
+ const proto: unknown = Object.getPrototypeOf(value);
115
+ return (proto === null || proto === Object.prototype) &&
116
+ Reflect.ownKeys(value).every(key => typeof key === 'string' && ownData(value, key));
117
+ }
118
+
119
+ function isActArray(value: unknown): value is unknown[] {
120
+ if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype || Reflect.ownKeys(value).length !== value.length + 1) return false;
121
+ for (let i = 0; i < value.length; i++) if (!ownData(value, i)) return false;
122
+ return true;
123
+ }
124
+
125
+ function hasFields(value: Json, required: readonly string[]): boolean {
126
+ return Object.keys(value).length === required.length && required.every(k => Object.hasOwn(value, k));
127
+ }
128
+
129
+ const isActVec = (v: unknown): v is Vec => isActArray(v) && isVec(v) && !v.some(n => Object.is(n, -0));
130
+ const isRoundedActVec = (v: Vec): boolean => v.every(n => Number(n.toFixed(2)) === n);
91
131
 
92
132
  /**
93
133
  * The document, read and held to its shape: `schema` (`REMESH_DELTA_JSON`), `basis` (`REMESH_DELTA_BASIS`), `ops` an
@@ -95,7 +135,6 @@ const OP_FIELDS: Record<MeshEditOp['op'], readonly string[]> = { move: ['op', 'v
95
135
  * whole ids (`REMESH_DELTA_OP`). Every problem is collected and thrown once; whether an id is live is the replay's.
96
136
  */
97
137
  export function readMeshEdit(text: string, object: string): { doc: MeshEditDocument | null; problems: Problem[] } {
98
- const problems: Problem[] = [];
99
138
  let value: unknown;
100
139
  try {
101
140
  value = JSON.parse(text);
@@ -103,43 +142,91 @@ export function readMeshEdit(text: string, object: string): { doc: MeshEditDocum
103
142
  return { doc: null, problems: [{ code: 'REMESH_DELTA_JSON', object, detail: `does not parse as JSON: ${(err as Error).message}` }] };
104
143
  }
105
144
  if (!isRecord(value)) return { doc: null, problems: [{ code: 'REMESH_DELTA_JSON', object, detail: `is ${Array.isArray(value) ? 'an array' : JSON.stringify(value)}; one ${MESH_EDIT_SCHEMA} document is required` }] };
106
- if (value.schema !== MESH_EDIT_SCHEMA) problems.push({ code: 'REMESH_DELTA_JSON', object: `${object} schema`, detail: `is ${JSON.stringify(value.schema)}; "${MESH_EDIT_SCHEMA}" (rig-c/review's mesh edit) is required` });
107
- for (const k of ['slot', 'skin', 'attachment']) if (typeof value[k] !== 'string') problems.push({ code: 'REMESH_DELTA_JSON', object: `${object} ${k}`, detail: `is ${JSON.stringify(value[k])}; a string is required` });
108
- const src = value.source;
109
- if (!isRecord(src) || !isId(src.vertexCount) || !isId(src.triangleCount) || !isId(src.hullLength) || typeof src.hash !== 'string') {
110
- problems.push({ code: 'REMESH_DELTA_JSON', object: `${object} source`, detail: `is ${JSON.stringify(src)}; { vertexCount, triangleCount, hullLength: whole numbers, hash: a string } is required` });
145
+ const problems = meshEditProblems(value, object, false);
146
+ return { doc: problems.length === 0 ? (value as unknown as MeshEditDocument) : null, problems };
147
+ }
148
+
149
+ export function meshEditActProblems(value: unknown, object: string): Problem[] {
150
+ if (!isActRecord(value)) return [{ code: 'REMESH_DELTA_JSON', object, detail: 'must be one plain mesh edit JSON object with enumerable data fields' }];
151
+ return meshEditProblems(value, object, true);
152
+ }
153
+
154
+ function meshEditProblems(value: Json, object: string, act: boolean): Problem[] {
155
+ const problems: Problem[] = [];
156
+ const show = act ? (v: unknown): string => inspect(v, { depth: 1, breakLength: Infinity, customInspect: false }) : JSON.stringify;
157
+ if (act) {
158
+ // Let the field-specific refusals below name missing required data.
159
+ const extra = Object.keys(value).filter(k => !ACT_FIELDS.includes(k));
160
+ if (extra.length > 0) problems.push({ code: 'REMESH_DELTA_JSON', object, detail: `has keys ${extra.join(', ')}; only ${ACT_FIELDS.join(', ')} are allowed` });
161
+ } else if (value.schema !== MESH_EDIT_SCHEMA) problems.push({ code: 'REMESH_DELTA_JSON', object: `${object} schema`, detail: `is ${JSON.stringify(value.schema)}; "${MESH_EDIT_SCHEMA}" (rig-c/review's mesh edit) is required` });
162
+ for (const k of ['slot', 'skin', 'attachment']) {
163
+ const name = value[k];
164
+ if (typeof name !== 'string' || (act && (!Object.hasOwn(value, k) || name.length === 0))) problems.push({ code: 'REMESH_DELTA_JSON', object: `${object} ${k}`, detail: `is ${show(name)}; a ${act ? 'non-empty ' : ''}string is required` });
165
+ }
166
+ const src = act && !Object.hasOwn(value, 'source') ? undefined : value.source;
167
+ const validId = act ? (v: unknown): v is number => isId(v) && !Object.is(v, -0) : isId;
168
+ if (!isRecord(src) || (act && !isActRecord(src)) || !validId(src.vertexCount) || !validId(src.triangleCount) || !validId(src.hullLength) || (act ? !isSha256(src.hash) : typeof src.hash !== 'string')) {
169
+ const required = act ? 'vertexCount, triangleCount and hullLength must be whole numbers and hash must be 64 lowercase hex digits' : '{ vertexCount, triangleCount, hullLength: whole numbers, hash: a string } is required';
170
+ problems.push({ code: 'REMESH_DELTA_JSON', object: `${object} source`, detail: `is ${show(src)}; ${required}` });
171
+ } else if (act) {
172
+ if (!hasFields(src, ACT_SOURCE_FIELDS)) problems.push({ code: 'REMESH_DELTA_JSON', object: `${object} source`, detail: `has keys ${Object.keys(src).join(', ')}; requires exactly ${ACT_SOURCE_FIELDS.join(', ')}` });
173
+ const { frame, positions } = src;
174
+ if (!isActRecord(frame) || !hasFields(frame, ['width', 'height']) || !isNumber(frame.width) || frame.width <= 0 || !isNumber(frame.height) || frame.height <= 0) {
175
+ problems.push({ code: 'REMESH_DELTA_JSON', object: `${object} source.frame`, detail: `is ${show(frame)}; width and height must each be positive finite numbers` });
176
+ }
177
+ if (!isActArray(positions)) problems.push({ code: 'REMESH_DELTA_JSON', object: `${object} source.positions`, detail: 'must be a dense array of unrounded crop-pixel coordinate pairs in source-vertex order' });
178
+ else if (positions.length !== src.vertexCount) problems.push({ code: 'REMESH_DELTA_SOURCE', object: `${object} source.positions`, detail: `holds ${positions.length} positions; source.vertexCount requires ${src.vertexCount}` });
179
+ else {
180
+ const bad = positions.findIndex(p => !isActVec(p));
181
+ if (bad >= 0) problems.push({ code: 'REMESH_DELTA_JSON', object: `${object} source.positions[${bad}]`, detail: `is ${show(positions[bad])}; two finite coordinates without negative zero are required` });
182
+ }
111
183
  }
112
- if (value.basis !== MESH_EDIT_BASIS) {
113
- problems.push({ code: 'REMESH_DELTA_BASIS', object: `${object} basis`, detail: `is ${JSON.stringify(value.basis)}; "${MESH_EDIT_BASIS}" is required — the producer binds setup positions, and a delta drawn over a pose (review before rig-c/review #100) is refused rather than posed back` });
184
+ if (value.basis !== MESH_EDIT_BASIS || (act && !Object.hasOwn(value, 'basis'))) {
185
+ problems.push({ code: 'REMESH_DELTA_BASIS', object: `${object} basis`, detail: `is ${show(value.basis)}; "${MESH_EDIT_BASIS}" is required — the producer binds setup positions, and a delta drawn over a pose (review before rig-c/review #100) is refused rather than posed back` });
114
186
  }
115
- const ops = value.ops;
116
- if (!Array.isArray(ops)) problems.push({ code: 'REMESH_DELTA_OPS', object: `${object} ops`, detail: `is ${JSON.stringify(ops)}; an array of ops is required` });
187
+ const ops = act && !Object.hasOwn(value, 'ops') ? undefined : value.ops;
188
+ if (!Array.isArray(ops)) problems.push({ code: 'REMESH_DELTA_OPS', object: `${object} ops`, detail: `is ${show(ops)}; an array of ops is required` });
117
189
  else if (ops.length > MESH_EDIT_MAX_OPS) problems.push({ code: 'REMESH_DELTA_OPS', object: `${object} ops`, detail: `holds ${ops.length} ops; at most ${MESH_EDIT_MAX_OPS} (review's own cap per attachment) are read` });
190
+ else if (act && !isActArray(ops)) problems.push({ code: 'REMESH_DELTA_OPS', object: `${object} ops`, detail: 'must be a dense array of ops' });
191
+ else if (act && ops.length === 0) problems.push({ code: 'REMESH_DELTA_OPS', object: `${object} ops`, detail: 'holds 0 ops; at least 1 is required' });
118
192
  else {
119
- ops.forEach((op: unknown, i: number) => {
193
+ const vec = act ? isActVec : isVec;
194
+ for (const [i, op] of ops.entries()) {
120
195
  const bad = (why: string): void => {
121
- problems.push({ code: 'REMESH_DELTA_OP', object: `${object} ops[${i}]`, detail: `${JSON.stringify(op)} ${why}` });
196
+ problems.push({ code: 'REMESH_DELTA_OP', object: `${object} ops[${i}]`, detail: `${show(op)} ${why}` });
122
197
  };
123
- if (!isRecord(op) || typeof op.op !== 'string' || !(op.op in OP_FIELDS)) {
124
- bad(`has an unknown op kind ${isRecord(op) ? JSON.stringify(op.op) : ''}; one of move, add, remove, edge, unedge is required`);
125
- return;
198
+ if (!isRecord(op) || (act && !isActRecord(op))) {
199
+ bad(act ? 'must be a plain JSON object with enumerable data fields' : 'has an unknown op kind ; one of move, add, remove, edge, unedge is required');
200
+ continue;
201
+ }
202
+ if (typeof op.op !== 'string' || !Object.hasOwn(OP_FIELDS, op.op) || (act && !Object.hasOwn(op, 'op'))) {
203
+ bad(`has an unknown op kind ${show(op.op)}; one of move, add, remove, edge, unedge is required`);
204
+ continue;
126
205
  }
127
206
  const kind = op.op as MeshEditOp['op'];
128
- const extra = Object.keys(op).filter((k) => !OP_FIELDS[kind].includes(k));
207
+ const fields = OP_FIELDS[kind];
208
+ const extra = Object.keys(op).filter(k => !fields.includes(k));
129
209
  if (extra.length > 0) bad(`carries ${extra.join(', ')}, which a ${kind} op does not take`);
210
+ if (act) {
211
+ const required = kind === 'add' ? ['op', 'at'] : fields;
212
+ const missing = required.filter(k => !Object.hasOwn(op, k));
213
+ if (missing.length > 0) bad(`is missing the required field(s) ${missing.join(', ')}`);
214
+ }
130
215
  if (kind === 'move') {
131
- if (!isId(op.v)) bad('needs a whole vertex id v');
132
- if (!isVec(op.from) || !isVec(op.to)) bad('needs finite from and to pairs');
216
+ if (!validId(op.v)) bad('needs a whole vertex id v');
217
+ if (!vec(op.from) || !vec(op.to)) bad('needs finite from and to pairs');
218
+ else if (act && !isRoundedActVec(op.to)) bad('needs a to pair rounded to 0.01 px');
133
219
  } else if (kind === 'add') {
134
- if (!isVec(op.at)) bad('needs a finite at pair');
135
- if (op.onEdge !== undefined && !(Array.isArray(op.onEdge) && op.onEdge.length === 2 && op.onEdge.every(isId))) bad('needs onEdge as a pair of whole vertex ids, when it is given');
220
+ if (!vec(op.at)) bad('needs a finite at pair');
221
+ else if (act && !isRoundedActVec(op.at)) bad('needs an at pair rounded to 0.01 px');
222
+ if ((op.onEdge !== undefined || (act && Object.hasOwn(op, 'onEdge'))) && !(Array.isArray(op.onEdge) && (!act || isActArray(op.onEdge)) && op.onEdge.length === 2 && validId(op.onEdge[0]) && validId(op.onEdge[1]))) bad('needs onEdge as a pair of whole vertex ids, when it is given');
136
223
  } else if (kind === 'remove') {
137
- if (!isId(op.v)) bad('needs a whole vertex id v');
138
- } else if (!isId(op.a) || !isId(op.b)) bad('needs whole vertex ids a and b');
224
+ if (!validId(op.v)) bad('needs a whole vertex id v');
225
+ } else if (!validId(op.a) || !validId(op.b)) bad('needs whole vertex ids a and b');
139
226
  else if (op.a === op.b) bad('joins a vertex to itself');
140
- });
227
+ }
141
228
  }
142
- return { doc: problems.length === 0 ? (value as unknown as MeshEditDocument) : null, problems };
229
+ return problems;
143
230
  }
144
231
 
145
232
  /** The input the replay reads: the part's attachment, where `rig` placed it, and the setup frames of the rig's bones. */
@@ -205,10 +292,15 @@ class OpRefused extends Error {
205
292
  * The source checks a document is held to before any op is replayed: it names this part's attachment in the default
206
293
  * skin, and its source counts are this attachment's (`REMESH_DELTA_SOURCE`, naming the field and both figures).
207
294
  */
208
- export function deltaSourceProblems(doc: MeshEditDocument, part: string, att: MeshAttachment, object: string): Problem[] {
295
+ export function deltaTargetProblems(doc: Pick<MeshEditDocument, 'slot' | 'skin' | 'attachment'>, part: string, object: string): Problem[] {
209
296
  const out: Problem[] = [];
210
297
  for (const k of ['slot', 'attachment'] as const) if (doc[k] !== part) out.push({ code: 'REMESH_DELTA_SOURCE', object: `${object} ${k}`, detail: `is "${doc[k]}"; the delta must name --part "${part}", whose slot and attachment the rig stage names after the part` });
211
298
  if (doc.skin !== 'default') out.push({ code: 'REMESH_DELTA_SOURCE', object: `${object} skin`, detail: `is "${doc.skin}"; this package writes every mesh into the default skin, so "default" is required` });
299
+ return out;
300
+ }
301
+
302
+ export function deltaSourceProblems(doc: Pick<MeshEditDocument, 'source' | 'slot' | 'skin' | 'attachment'>, part: string, att: MeshAttachment, object: string): Problem[] {
303
+ const out = deltaTargetProblems(doc, part, object);
212
304
  const counts: Array<[string, number, number]> = [
213
305
  ['vertexCount', doc.source.vertexCount, att.uvs.length / 2],
214
306
  ['triangleCount', doc.source.triangleCount, att.triangles.length / 3],
@@ -218,16 +310,36 @@ export function deltaSourceProblems(doc: MeshEditDocument, part: string, att: Me
218
310
  return out;
219
311
  }
220
312
 
313
+ const partOrigin = ([x, y]: Vec): Vec => [x - PAD, y - PAD];
314
+ const vertexPartPosition = (att: MeshAttachment, i: number): Vec => [att.uvs[2 * i] * att.width, att.uvs[2 * i + 1] * att.height];
315
+
316
+ /** Name the first position that misses, even when an independent count check has already found a difference. */
317
+ export function meshEditPositionProblems(input: Pick<DeltaInput, 'attachment' | 'box'>, positions: readonly Vec[], object: string): Problem[] {
318
+ const { attachment } = input;
319
+ const [ox, oy] = partOrigin(input.box);
320
+ const available = Math.min(positions.length, attachment.uvs.length / 2);
321
+ for (let i = 0; i < available; i++) {
322
+ const [px, py] = vertexPartPosition(attachment, i);
323
+ const [x, y] = positions[i];
324
+ const wantedX = px + ox;
325
+ const wantedY = py + oy;
326
+ if (Math.abs(x - wantedX) > FROM_TOLERANCE_PX || Math.abs(y - wantedY) > FROM_TOLERANCE_PX) {
327
+ return [{ code: 'REMESH_DELTA_SOURCE', object: `${object} source.positions[${i}]`,
328
+ detail: `vertex ${i} is (${x}, ${y}); this input requires (${wantedX}, ${wantedY}) within ${FROM_TOLERANCE_PX} px` }];
329
+ }
330
+ }
331
+ return [];
332
+ }
333
+
221
334
  /**
222
335
  * The replay: the document's ops over the input's mesh, in order, and the result held to the outline and Delaunay
223
336
  * rules. Returns the problems (the first op that does not apply ends the replay, since every later op reads its
224
337
  * state) or the new attachment.
225
338
  */
226
- export function applyMeshEdit(input: DeltaInput, doc: MeshEditDocument, object: string, plant: DeltaPlant = {}): DeltaResult | Problem[] {
339
+ export function applyMeshEdit(input: DeltaInput, doc: MeshEditDocument | MeshEditActValue, object: string, plant: DeltaPlant = {}): DeltaResult | Problem[] {
227
340
  const att = input.attachment;
228
341
  const { width: w, height: h } = att;
229
- const ox = input.box[0] - PAD;
230
- const oy = input.box[1] - PAD;
342
+ const [ox, oy] = partOrigin(input.box);
231
343
  const CX = input.rigSize[0] / 2;
232
344
  const H = input.rigSize[1];
233
345
  const V0 = att.uvs.length / 2;
@@ -258,7 +370,8 @@ export function applyMeshEdit(input: DeltaInput, doc: MeshEditDocument, object:
258
370
  });
259
371
  const problems: Problem[] = [];
260
372
  for (let i = 0; i < V0; i++) {
261
- setPos(i, att.uvs[2 * i] * w, att.uvs[2 * i + 1] * h);
373
+ const [x, y] = vertexPartPosition(att, i);
374
+ setPos(i, x, y);
262
375
  uv.push([att.uvs[2 * i], att.uvs[2 * i + 1]]);
263
376
  wt.push(att.weights[i]);
264
377
  live.push(true);