@rulecad/cad 0.9.0 → 0.11.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.
Files changed (68) hide show
  1. package/AGENTS.md +29 -10
  2. package/CHANGELOG.md +604 -0
  3. package/EXAMPLES.md +122 -105
  4. package/README.md +292 -63
  5. package/bin/cad.mjs +500 -87
  6. package/lib/assembly.mjs +486 -134
  7. package/lib/bays.mjs +124 -0
  8. package/lib/cache-file.mjs +148 -0
  9. package/lib/clone.mjs +93 -11
  10. package/lib/code-text.mjs +28 -0
  11. package/lib/design-imports.mjs +127 -0
  12. package/lib/design.mjs +291 -59
  13. package/lib/designshapes.mjs +142 -0
  14. package/lib/edit.mjs +29 -5
  15. package/lib/estimates.mjs +51 -0
  16. package/lib/fasten.mjs +11 -5
  17. package/lib/fe-key.mjs +29 -0
  18. package/lib/fittings.mjs +20 -15
  19. package/lib/fixings.mjs +17 -4
  20. package/lib/framebuild.mjs +73 -92
  21. package/lib/framecheck.mjs +154 -77
  22. package/lib/framegen.mjs +9 -1
  23. package/lib/frames.mjs +6 -2
  24. package/lib/framesize.mjs +45 -82
  25. package/lib/gait.mjs +17 -7
  26. package/lib/guides.mjs +84 -50
  27. package/lib/host.mjs +7 -3
  28. package/lib/kit.mjs +5 -5
  29. package/lib/list.mjs +29 -21
  30. package/lib/live-guard.mjs +18 -8
  31. package/lib/loads.mjs +35 -23
  32. package/lib/measured.mjs +740 -99
  33. package/lib/mesh.mjs +156 -56
  34. package/lib/motors.mjs +26 -33
  35. package/lib/names.mjs +15 -0
  36. package/lib/node-version.mjs +52 -0
  37. package/lib/optimise.mjs +34 -25
  38. package/lib/order.mjs +5 -12
  39. package/lib/parts.mjs +3 -0
  40. package/lib/picture-servers.mjs +66 -0
  41. package/lib/power.mjs +14 -7
  42. package/lib/preview.mjs +12 -25
  43. package/lib/programs.mjs +113 -0
  44. package/lib/rules.mjs +2 -1
  45. package/lib/sandbox-guard.mjs +43 -0
  46. package/lib/sandbox-hooks.mjs +109 -15
  47. package/lib/sandbox-lock.mjs +225 -0
  48. package/lib/sandbox-preload.mjs +2 -2
  49. package/lib/sandbox-run.mjs +22 -24
  50. package/lib/sandbox.mjs +345 -42
  51. package/lib/sheet.mjs +114 -3
  52. package/lib/targets/gist.mjs +9 -6
  53. package/lib/versions.mjs +294 -35
  54. package/lib/workspace.mjs +6 -3
  55. package/package.json +14 -14
  56. package/schemas/assembly.schema.json +6 -5
  57. package/schemas/object.schema.json +1 -1
  58. package/schemas/project.schema.json +6 -0
  59. package/templates/coupons/MEASURE.md +109 -0
  60. package/templates/coupons/assemblies/fixings-test.json +20 -0
  61. package/templates/coupons/assemblies/slot-test.json +11 -0
  62. package/templates/coupons/objects/fixings-coupon.js +88 -0
  63. package/templates/coupons/objects/fixings-coupon.json +26 -0
  64. package/templates/coupons/objects/holds-coupon.js +130 -0
  65. package/templates/coupons/objects/holds-coupon.json +42 -0
  66. package/templates/coupons/objects/slot-coupon.js +89 -0
  67. package/templates/coupons/objects/slot-coupon.json +29 -0
  68. package/templates/coupons/project.json +10 -0
package/lib/measured.mjs CHANGED
@@ -11,12 +11,16 @@
11
11
  // to its plastic's set (beam_modulus, beam_strength; _z standing up). The holds coupon's fits (a snap pin's socket, a
12
12
  // plain pin's press and slip, a magnet's press, glue and crush ribs, and the snap pins' barb as a record) need no --rule
13
13
  // either, and each is refused outside what a fit of its kind can be; its pull bolt writes the plastic's strength_z.
14
+ // A rule measured on a coupon needs no assembly: written the same, its row goes in the workspace's own ledger, with
15
+ // nothing said to have moved. The coupons come into a maker's workspace with cad coupons (packages/cad/templates/
16
+ // coupons), and each source names the coupon's MEASURE.md there. exportMeasured gives what a workspace measured that
17
+ // the kit lacks, as a diff of the kit's rule sets, to send upstream.
14
18
  import fs from 'node:fs';
15
19
  import path from 'node:path';
16
20
  import { setAt } from './jsonedit.mjs';
17
21
  import { CadError } from './errors.mjs';
18
22
  import { paths, WS, RULE_DIRS, printerOf } from './workspace.mjs';
19
- import { loadRuleSet, peekRuleSet, insideWorkspace } from './rules.mjs';
23
+ import { peekRuleSet, insideWorkspace } from './rules.mjs';
20
24
  import { readOwnText } from './host.mjs';
21
25
  import { buildAssembly, checkAssembly, assemblyPath } from './assembly.mjs';
22
26
  import { slotModel, JOIN_SET, joinRuleSet } from '@rulecad/frames';
@@ -27,7 +31,53 @@ import { springFor } from './joins.mjs';
27
31
 
28
32
  const today = () => new Date().toISOString().slice(0, 10),
29
33
  n = (x) => String(Number(Number(x).toFixed(4)));
30
- export const ledgerFile = (project) => path.join(paths.project(project), 'ledger.jsonl');
34
+ /**
35
+ * The ledger a measurement is kept in: its project's, beside its assemblies, or with no project (a figure measured on
36
+ * a coupon and written back without an assembly) the workspace's own, ledger.jsonl beside cad.config.json.
37
+ * @param {string | null} project
38
+ */
39
+ export const ledgerFile = (project) =>
40
+ project ? path.join(paths.project(project), 'ledger.jsonl') : path.join(WS, 'ledger.jsonl');
41
+ // a project's folder, or with no project the workspace (whose printer is cad.config.json's, and which has no plastic)
42
+ const projectDir = (project) => (project ? paths.project(project) : WS);
43
+
44
+ // The coupons that settle a figure, each as a source names it: where it is in this workspace (the MEASURE.md of the
45
+ // project that holds it: the project measured first, then the one cad coupons adds, then any other), so a rule set
46
+ // names a file the maker has, never a path in the kit's repository. One that no project here holds is said by how to
47
+ // get it: cad coupons for the three it adds, the kit's bench for the rig and the beam coupon (the beam coupon is in the
48
+ // assembly measured, so only that project is looked in).
49
+ const COUPON_AT = {
50
+ fixings: { said: 'the fixings coupon', object: 'fixings-coupon', from: 'cad coupons adds it to your workspace' },
51
+ holds: { said: 'the holds coupon', object: 'holds-coupon', from: 'cad coupons adds it to your workspace' },
52
+ slot: { said: 'the slot coupon', object: 'slot-coupon', from: 'cad coupons adds it to your workspace' },
53
+ rig: {
54
+ said: 'the joint rig',
55
+ object: 'joint-hanger',
56
+ from: "the kit's bench, examples/bench/projects/benchmarks/MEASURE.md in the rulecad repository",
57
+ },
58
+ beam: {
59
+ said: 'the beam coupon',
60
+ object: null,
61
+ from: "the kit's bench, examples/bench/projects/benchmarks/MEASURE.md in the rulecad repository",
62
+ },
63
+ };
64
+ function couponAt(which, project) {
65
+ const { said, object, from } = COUPON_AT[which];
66
+ let all = [];
67
+ try {
68
+ all = object ? fs.readdirSync(paths.projects).sort() : [];
69
+ } catch {
70
+ // (no projects folder: none holds it)
71
+ }
72
+ const at = [...new Set([project, ...(object ? ['coupons', ...all] : [])])].filter(Boolean).find((p) => {
73
+ const dir = path.join(paths.projects, p);
74
+ return (
75
+ fs.existsSync(path.join(dir, 'MEASURE.md')) &&
76
+ (!object || fs.existsSync(path.join(dir, 'objects', `${object}.json`)))
77
+ );
78
+ });
79
+ return `${said} (${at ? `projects/${at}/MEASURE.md` : from})`;
80
+ }
31
81
  export const readLedger = (project) => {
32
82
  const f = ledgerFile(project);
33
83
  return fs.existsSync(f)
@@ -39,7 +89,104 @@ export const readLedger = (project) => {
39
89
  };
40
90
 
41
91
  const findingsOf = async (ref) => checkAssembly(await buildAssembly(ref));
42
- const keyOf = (x) => `${x.code}|${JSON.stringify(x.refs ?? {})}`;
92
+
93
+ // A finding's identity, to pair it with itself on the other side of a measurement: its code and the refs that name
94
+ // what it is about (a fasten's index, a fit's a and b, a join, a beam, a part), never the refs that hold its results.
95
+ // Those move with the measurement: a fasten's list of screws comes in another order once its holes change size, a
96
+ // fit's outOfRange and a deflection's springs change with the figures. A finding about one screw of several names it.
97
+ const NAMING = [
98
+ 'fasten',
99
+ 'fit',
100
+ 'join',
101
+ 'joint',
102
+ 'item',
103
+ 'items',
104
+ 'beam',
105
+ 'part',
106
+ 'a',
107
+ 'b',
108
+ 'through',
109
+ 'into',
110
+ 'screw',
111
+ 'where',
112
+ 'pose',
113
+ 'place',
114
+ 'side',
115
+ 'fitting',
116
+ 'set',
117
+ 'profile',
118
+ 'rule',
119
+ 'guide',
120
+ 'motor',
121
+ 'wire',
122
+ 'panel',
123
+ 'mount',
124
+ 'object',
125
+ 'nut',
126
+ 'kind',
127
+ 'name',
128
+ ];
129
+ const naming = (v) =>
130
+ typeof v === 'string' ||
131
+ Number.isInteger(v) ||
132
+ (Array.isArray(v) && v.every((x) => typeof x === 'string' || Number.isInteger(x)));
133
+ /**
134
+ * A finding's identity for matching before and after: its code and what it is about.
135
+ * @param {{ code?: string, refs?: Record<string, any> }} x a finding
136
+ * @returns {string}
137
+ */
138
+ export function identityOf(x) {
139
+ const r = x.refs ?? {},
140
+ own = NAMING.filter((k) => naming(r[k])).map((k) => [k, r[k]]);
141
+ if (Array.isArray(r.screws) && r.screws.length === 1) own.push(['screws', r.screws]);
142
+ return `${x.code}|${JSON.stringify(own)}`;
143
+ }
144
+ /**
145
+ * The findings before and after a change, paired like with like: by identity, and where several share one (a fasten's
146
+ * two clearance findings, its hole's and its slot's), in the order the checks gave them, which is the same each run.
147
+ * @param {object[]} before
148
+ * @param {object[]} after
149
+ * @returns {[object, object][]} each finding after with its own before (findings on one side only are left out)
150
+ */
151
+ export function pairFindings(before, after) {
152
+ const was = new Map();
153
+ for (const x of before) {
154
+ const k = identityOf(x);
155
+ was.set(k, [...(was.get(k) ?? []), x]);
156
+ }
157
+ const taken = new Map(),
158
+ pairs = [];
159
+ for (const x of after) {
160
+ const k = identityOf(x),
161
+ i = taken.get(k) ?? 0,
162
+ y = was.get(k)?.[i];
163
+ taken.set(k, i + 1);
164
+ if (y) pairs.push([y, x]);
165
+ }
166
+ return pairs;
167
+ }
168
+ /**
169
+ * What moved between two runs of an assembly's checks: each prediction whose figure changed, and each other finding
170
+ * whose words changed.
171
+ * @param {object[]} before
172
+ * @param {object[]} after
173
+ */
174
+ export function movedBetween(before, after) {
175
+ const moved = [];
176
+ for (const [y, x] of pairFindings(before, after)) {
177
+ if (x.predict && y.predict) {
178
+ if (Math.abs(x.predict.value - y.predict.value) > 1e-9)
179
+ moved.push({
180
+ code: x.code,
181
+ figure: x.predict.figure,
182
+ unit: x.predict.unit,
183
+ from: y.predict.value,
184
+ to: x.predict.value,
185
+ });
186
+ } else if (y.text !== x.text) moved.push({ code: x.code, text: x.text, was: y.text });
187
+ }
188
+ return moved;
189
+ }
43
190
  // A prediction's name, as cad measured takes it: the check's code, and the part or joint it's about if there are several
44
191
  export const predictionsOf = (findings) => findings.filter((x) => x.predict);
45
192
 
@@ -82,8 +229,8 @@ function ruleFile(name) {
82
229
  // The slot coupon (examples/bench/projects/benchmarks/MEASURE.md, rows 29 to 33): the two fits it measures, which a
83
230
  // printer's set may not hold yet, each with what it is and what the kit drew before (the printer's fit), so the ledger
84
231
  // shows predicted against measured; and a slot's own figures, measured by caliper on the person's beam
85
- const SLOT_COUPON = 'the slot coupon (examples/bench/projects/benchmarks/MEASURE.md)';
86
232
  function slotRule(project, set, key, data) {
233
+ const slotAt = couponAt('slot', project);
87
234
  if (set === printerOf(project) && ['slot_fit', 'printed_slot_fit'].includes(key)) {
88
235
  const fit = data.rules?.fit,
89
236
  was = typeof fit?.value === 'number' ? fit.value : null;
@@ -91,36 +238,35 @@ function slotRule(project, set, key, data) {
91
238
  unit: 'mm',
92
239
  predicted: was,
93
240
  was: `${set}.fit, ${fit?.kind ?? 'none'}`,
94
- source: SLOT_COUPON,
241
+ source: slotAt,
95
242
  rule:
96
243
  key === 'slot_fit'
97
- ? `Clearance each side between a printed part and a bought beam's slot it slides in (a tongue in the opening, a carrier in the cavity): the tightest on ${SLOT_COUPON} that slid the beam's length by hand without rattling. Printed carriers are drawn with it (@rulecad/frames carrierModel) before the general fit`
98
- : `Clearance each side a slot printed in a part is opened by, so a bought slot nut slides in it: the tightest printed slot on ${SLOT_COUPON} a slide-in nut ran the length of by hand without catching. For printed beams and plates with slots`,
244
+ ? `Clearance each side between a printed part and a bought beam's slot it slides in (a tongue in the opening, a carrier in the cavity): the tightest on ${slotAt} that slid the beam's length by hand without rattling. Printed carriers are drawn with it (@rulecad/frames carrierModel) before the general fit`
245
+ : `Clearance each side a slot printed in a part is opened by, so a bought slot nut slides in it: the tightest printed slot on ${slotAt} a slide-in nut ran the length of by hand without catching. For printed beams and plates with slots`,
99
246
  kind: 'measured',
100
247
  };
101
248
  }
102
- if (data.part === 'slot' && data.rules?.[key])
103
- return { source: `calipers on your own beam (${SLOT_COUPON}, row 32)` };
249
+ if (data.part === 'slot' && data.rules?.[key]) return { source: `calipers on your own beam (${slotAt}, row 32)` };
104
250
  return null;
105
251
  }
106
252
 
107
253
  // The joint rig (examples/bench/projects/benchmarks/MEASURE.md, rows 34 to 37): a join's bending spring, written to the
108
254
  // joins set or a bought fitting's set, and a slot nut's hold along its slot, which no maker publishes, so a nut's set
109
255
  // has no rule for it until it is measured
110
- const RIG_SAID = 'the joint rig (examples/bench/projects/benchmarks/MEASURE.md)';
111
- function rigRule(set, key, data, frame = null) {
256
+ function rigRule(project, set, key, data, frame = null) {
257
+ const rigAt = couponAt('rig', project);
112
258
  if (data.part === 'slot_nut' && key === 'hold_along')
113
259
  return {
114
260
  unit: 'N',
115
261
  predicted: null,
116
262
  was: 'no figure: no maker publishes it',
117
- source: `${RIG_SAID}, a luggage scale`,
118
- rule: `The pull along its slot at which this nut slips, its screw tightened as its maker says (or firmly by hand with a hex key where it says nothing): the reading on ${RIG_SAID}'s luggage scale as the nut moved`,
263
+ source: `${rigAt}, a luggage scale`,
264
+ rule: `The pull along its slot at which this nut slips, its screw tightened as its maker says (or firmly by hand with a hex key where it says nothing): the reading on ${rigAt}'s luggage scale as the nut moved`,
119
265
  };
120
266
  // what a spring measured on the rig is, in place of the estimate's sentence ("a working guess ... until the joint rig
121
267
  // measures it"); the drop it came from goes in its source
122
268
  // (or on a frame of the maker's own: the spring that gives the drop read in that frame's solve)
123
- const RIG = frame ? `the frame ${frame}, a dial on a beam held out by the join` : RIG_SAID,
269
+ const RIG = frame ? `the frame ${frame}, a dial on a beam held out by the join` : rigAt,
124
270
  how = frame
125
271
  ? `measured on the frame ${frame}: a beam held out by the join, the drop of its end under a hung mass, and the spring that gives that drop in the frame's own solve`
126
272
  : `measured on ${RIG}: a beam held out by the join, the drop of its end under a hung mass less the beam's own bending (F L² / that)`;
@@ -153,20 +299,20 @@ function rigRule(set, key, data, frame = null) {
153
299
  // The beam coupon (examples/bench/projects/benchmarks/MEASURE.md, rows 38 and 39): the modulus a printed beam bends at
154
300
  // and the stress it breaks at, which no plastic's data sheet gives for a beam of walls and infill, so a plastic's set has
155
301
  // no rule for them until the coupon is measured
156
- const BEAM_COUPON = 'the beam coupon (examples/bench/projects/benchmarks/MEASURE.md)';
157
- function couponRule(set, key, data) {
302
+ function couponRule(project, set, key, data) {
158
303
  const m = key.match(/^beam_(modulus|strength)(_z)?$/);
159
304
  if (!m || data.rules?.density == null) return null;
305
+ const beamAt = couponAt('beam', project);
160
306
  const how = m[2] ? 'printed standing up, bent across its layers' : 'printed lying down, its layers along it';
161
307
  return {
162
308
  unit: 'MPa',
163
- source: BEAM_COUPON,
309
+ source: beamAt,
164
310
  predicted: data.rules?.[m[2] && data.rules[`${m[1]}_z`] ? `${m[1]}_z` : m[1]]?.value ?? null,
165
311
  was: `${set}.${m[1]}${m[2] && data.rules[`${m[1]}_z`] ? '_z' : ''}, the data sheet's`,
166
312
  measuredRule:
167
313
  m[1] === 'modulus'
168
- ? `The modulus a printed beam of ${set.toUpperCase()} bends at, ${how}, with its section counted from its walls and infill (@rulecad/frames printedSection): the sag of ${BEAM_COUPON} under a hung mass, measured with a dial, and the solve's sag scaled to it. A printed beam takes it before the plastic's own modulus`
169
- : `The stress a printed beam of ${set.toUpperCase()} breaks at in bending, ${how}, its section counted from its walls and infill: the mass ${BEAM_COUPON} broke at, as the stress the solve gives under it. A printed beam takes it before the plastic's own strength, and its creep limit follows it`,
314
+ ? `The modulus a printed beam of ${set.toUpperCase()} bends at, ${how}, with its section counted from its walls and infill (@rulecad/frames printedSection): the sag of ${beamAt} under a hung mass, measured with a dial, and the solve's sag scaled to it. A printed beam takes it before the plastic's own modulus`
315
+ : `The stress a printed beam of ${set.toUpperCase()} breaks at in bending, ${how}, its section counted from its walls and infill: the mass ${beamAt} broke at, as the stress the solve gives under it. A printed beam takes it before the plastic's own strength, and its creep limit follows it`,
170
316
  };
171
317
  }
172
318
 
@@ -174,16 +320,17 @@ function couponRule(set, key, data) {
174
320
  // (examples/bench/projects/benchmarks/MEASURE.md): what it is, its unit, and what the kit drew before it was measured,
175
321
  // so the ledger shows predicted against measured. A pilot or an insert hole is per thread, and may name a plastic
176
322
  // (x1c.pilot_m4, x1c.pilot_m4_petg); the rest are one per printer.
177
- const COUPON = 'the fixings coupon (examples/bench/projects/benchmarks/MEASURE.md)';
178
323
  function fixingsRule(project, set, key) {
179
324
  if (set !== printerName(project)) return null;
325
+ const fixAt = couponAt('fixings', project),
326
+ holdsAt = couponAt('holds', project);
180
327
  let fx;
181
328
  const f = () =>
182
329
  (fx ||= (() => {
183
- const { context } = fixingsContext({ project, dir: paths.project(project) });
330
+ const { context } = fixingsContext({ project, dir: projectDir(project) });
184
331
  return { ...fixingsFor({ sets: context.sets, printer: context.printer }), material: context.material };
185
332
  })());
186
- const plastic = (p) => (p ?? f().material ?? "the project's plastic").toUpperCase();
333
+ const plastic = (p) => (p ?? f().material)?.toUpperCase() ?? 'the plastic it was printed in';
187
334
  const hole = key.match(/^(pilot|insert)_(.+)$/);
188
335
  if (hole) {
189
336
  const bySet = new Map(threads().map((t) => [fixingsFor().fixingModel(t).set, t]));
@@ -201,9 +348,9 @@ function fixingsRule(project, set, key) {
201
348
  was: `${h.basis.rule}, ${h.basis.kind}`,
202
349
  rule:
203
350
  hole[1] === 'pilot'
204
- ? `Hole to draw for ${/^(M|8|11|18)/.test(thread) ? 'an' : 'a'} ${thread} screw to form its own thread in ${plastic(own)}, standing upright: the one on ${COUPON} the screw went into straight and held in, turned by hand. Drawn as it is: no hole compensation`
205
- : `Hole to draw for ${/^(M|8|11|18)/.test(thread) ? 'an' : 'a'} ${thread} heat-set insert in ${plastic(own)}: the one on ${COUPON} the insert went into straight and flush, and held when a screw was tightened in it. Drawn as it is: no hole compensation`,
206
- source: COUPON,
351
+ ? `Hole to draw for ${/^(M|8|11|18)/.test(thread) ? 'an' : 'a'} ${thread} screw to form its own thread in ${plastic(own)}, standing upright: the one on ${fixAt} the screw went into straight and held in, turned by hand. Drawn as it is: no hole compensation`
352
+ : `Hole to draw for ${/^(M|8|11|18)/.test(thread) ? 'an' : 'a'} ${thread} heat-set insert in ${plastic(own)}: the one on ${fixAt} the insert went into straight and flush, and held when a screw was tightened in it. Drawn as it is: no hole compensation`,
353
+ source: fixAt,
207
354
  };
208
355
  }
209
356
  if (key === 'nut_fit')
@@ -211,8 +358,8 @@ function fixingsRule(project, set, key) {
211
358
  unit: 'mm',
212
359
  predicted: f().nutPocketModel('M3').clearance,
213
360
  was: 'snug, no clearance',
214
- source: COUPON,
215
- rule: `Clearance across the flats of a nut pocket let in from a face, on top of hole_comp: the tightest on ${COUPON} a hex nut dropped into by hand and did not turn in as its screw was tightened. A nut pocket's snug fit`,
361
+ source: fixAt,
362
+ rule: `Clearance across the flats of a nut pocket let in from a face, on top of hole_comp: the tightest on ${fixAt} a hex nut dropped into by hand and did not turn in as its screw was tightened. A nut pocket's snug fit`,
216
363
  };
217
364
  if (key === 'nut_slip') {
218
365
  const t = f().nutTrapModel('M3', { depth: 1 });
@@ -220,8 +367,8 @@ function fixingsRule(project, set, key) {
220
367
  unit: 'mm',
221
368
  predicted: t.clearance,
222
369
  was: t.rests.find((r) => /slip$/.test(r.name))?.name ?? 'slip',
223
- source: COUPON,
224
- rule: `Clearance across the flats of a nut slot a nut slides into from the side, on top of hole_comp: the tightest on ${COUPON} a hex nut slid into by hand, stayed in turned over, and did not turn as its screw was tightened. A nut slot's slip fit`,
370
+ source: fixAt,
371
+ rule: `Clearance across the flats of a nut slot a nut slides into from the side, on top of hole_comp: the tightest on ${fixAt} a hex nut slid into by hand, stayed in turned over, and did not turn as its screw was tightened. A nut slot's slip fit`,
225
372
  };
226
373
  }
227
374
  // The holds coupon's fits (rows 40 to 45): each the printer's rule a pin, a snap pin's socket or a magnet's pocket is
@@ -235,8 +382,8 @@ function fixingsRule(project, set, key) {
235
382
  unit: 'mm',
236
383
  predicted: r?.value ?? fit.kit,
237
384
  was: r ? `${r.name}, ${r.kind}` : fit.was,
238
- source: HOLDS_COUPON,
239
- measuredRule: fit.rule,
385
+ source: holdsAt,
386
+ measuredRule: fit.rule(holdsAt),
240
387
  check: (x) =>
241
388
  x < fit.range[0] || x > fit.range[1] || (fit.above && x === 0)
242
389
  ? `is ${fit.above ? 'above' : 'from'} ${fit.range[0]}${fit.above ? ' and up' : ''} to ${fit.range[1]} mm: ${fit.why}`
@@ -249,52 +396,57 @@ function fixingsRule(project, set, key) {
249
396
  unit: '°',
250
397
  predicted: t.overhang.drawn,
251
398
  was: 'flanks: printed, the default',
252
- source: COUPON,
399
+ source: fixAt,
253
400
  allowed: [t.overhang.drawn, t.overhang.standard],
254
- rule: `The down-facing flank of a printed thread standing upright, as an overhang from upright: ${t.overhang.drawn} is the form laid back to the printer's overhang (flanks: 'printed', the kit's default), ${t.overhang.standard} the standard's own form (flanks: 'standard'). The one on ${COUPON} that held, turned smoothly and printed clean. A record for choosing the default: designs still draw flanks: 'printed' unless they say otherwise`,
401
+ rule: `The down-facing flank of a printed thread standing upright, as an overhang from upright: ${t.overhang.drawn} is the form laid back to the printer's overhang (flanks: 'printed', the kit's default), ${t.overhang.standard} the standard's own form (flanks: 'standard'). The one on ${fixAt} that held, turned smoothly and printed clean. A record for choosing the default: designs still draw flanks: 'printed' unless they say otherwise`,
255
402
  };
256
403
  }
257
404
  return null;
258
405
  }
259
406
  // The holds coupon's fits: the rule each writes once measured, what bounds it, and the model that draws from it
260
- const HOLDS_COUPON = 'the holds coupon (examples/bench/projects/benchmarks/MEASURE.md)';
261
407
  const HOLDS = {
262
408
  snap_clearance: {
263
409
  range: [0, 0.5],
264
410
  above: true,
265
411
  model: (f) => f.pinModel('snap pin 4x6'),
266
412
  why: 'its gap is drawn with no hole compensation, so at 0 the printed socket comes out smaller than the peg and pinches it: a press, not a snap. Past half a millimetre a pin rocks; the coupon prints 0.1 to 0.3, and never a socket at 0',
267
- rule: `Gap round a printed snap pin's peg in its socket, each side, as drawn (no hole compensation): the socket on ${HOLDS_COUPON} a snap pin clicked through by hand and then held without rocking`,
413
+ rule: (holdsAt) =>
414
+ `Gap round a printed snap pin's peg in its socket, each side, as drawn (no hole compensation): the socket on ${holdsAt} a snap pin clicked through by hand and then held without rocking`,
268
415
  },
269
416
  pin_press: {
270
417
  range: [0, 0.3],
271
418
  model: (f) => f.pinModel('dowel 3x12', { fit: 'press' }),
272
419
  why: 'how much smaller a hole is drawn than the pin it grips, past hole_comp, and more than 0.3 mm splits a printed boss; the coupon prints 0 to 0.1',
273
- rule: `How much smaller across a printed hole is drawn than a plain pin pressed into it, past hole_comp: the hole on ${HOLDS_COUPON} a 3 mm dowel (or 1.75 mm filament) pressed into by hand or in a vice, stood straight, and could not be pulled out by hand`,
420
+ rule: (holdsAt) =>
421
+ `How much smaller across a printed hole is drawn than a plain pin pressed into it, past hole_comp: the hole on ${holdsAt} a 3 mm dowel (or 1.75 mm filament) pressed into by hand or in a vice, stood straight, and could not be pulled out by hand`,
274
422
  },
275
423
  pin_slip: {
276
424
  range: [0, 0.6],
277
425
  model: (f) => f.pinModel('dowel 3x12', { fit: 'slip' }),
278
426
  why: "how much larger a hole is drawn than the pin that turns in it, past hole_comp, and past 0.6 mm it is a loose hole. At 0 the hole is the pin and hole_comp, the pin's own size once printed: a close slip; the coupon prints 0.1 to 0.3, and 0 once it is centred on 0.1",
279
- rule: `How much larger across a printed hole is drawn than a plain pin that turns in it, past hole_comp: the tightest hole on ${HOLDS_COUPON} a 3 mm dowel (or 1.75 mm filament) slid into by hand and turned freely in`,
427
+ rule: (holdsAt) =>
428
+ `How much larger across a printed hole is drawn than a plain pin that turns in it, past hole_comp: the tightest hole on ${holdsAt} a 3 mm dowel (or 1.75 mm filament) slid into by hand and turned freely in`,
280
429
  },
281
430
  magnet_press: {
282
431
  range: [0, 0.4],
283
432
  model: (f) => f.magnetSeatModel('disc magnet 8x3', { fit: 'press' }),
284
433
  why: 'how much smaller a pocket is drawn than the magnet it grips, past hole_comp, and more than 0.4 mm splits its wall; the coupon prints 0 to 0.2',
285
- rule: `How much smaller across a printed pocket is drawn than a disc magnet pressed into it, past hole_comp: the pocket on ${HOLDS_COUPON} a 6x3 and an 8x3 magnet went into with a thumb or a vice, flush, without splitting the wall, and stayed in when the plate was turned over and tapped`,
434
+ rule: (holdsAt) =>
435
+ `How much smaller across a printed pocket is drawn than a disc magnet pressed into it, past hole_comp: the pocket on ${holdsAt} a 6x3 and an 8x3 magnet went into with a thumb or a vice, flush, without splitting the wall, and stayed in when the plate was turned over and tapped`,
286
436
  },
287
437
  magnet_glue: {
288
438
  range: [0, 0.6],
289
439
  model: (f) => f.magnetSeatModel('disc magnet 8x3', { fit: 'glue' }),
290
440
  why: "room for a film of glue across the pocket, past hole_comp, and past 0.6 mm the magnet sits off centre; the coupon's press row shows where a magnet drops in",
291
- rule: `How much larger across a printed pocket is drawn than a magnet glued into it, past hole_comp: the least on ${HOLDS_COUPON} a magnet dropped into freely, which leaves room for glue`,
441
+ rule: (holdsAt) =>
442
+ `How much larger across a printed pocket is drawn than a magnet glued into it, past hole_comp: the least on ${holdsAt} a magnet dropped into freely, which leaves room for glue`,
292
443
  },
293
444
  magnet_crush: {
294
445
  range: [0, 0.6],
295
446
  model: (f) => f.magnetSeatModel('disc magnet 8x3', { fit: 'ribs' }),
296
447
  why: "how far inside the magnet the crush ribs' tips stand, past hole_comp, and past 0.6 mm a rib no longer crushes but splits. At 0 the ribs' tips stand at the magnet and hole_comp, a light crush once printed; the coupon prints 0.1 to 0.3, and 0 once it is centred on 0.1",
297
- rule: `With crush ribs, how much smaller across the ribs' tips stand than the magnet, past hole_comp: the ribbed pocket on ${HOLDS_COUPON} an 8x3 magnet pressed into by hand, flush, and held when the plate was turned over and tapped`,
448
+ rule: (holdsAt) =>
449
+ `With crush ribs, how much smaller across the ribs' tips stand than the magnet, past hole_comp: the ribbed pocket on ${holdsAt} an 8x3 magnet pressed into by hand, flush, and held when the plate was turned over and tapped`,
298
450
  },
299
451
  snap_barb: {
300
452
  range: [0, 1],
@@ -303,24 +455,27 @@ const HOLDS = {
303
455
  was: 'barb 0.4, the default',
304
456
  model: () => ({ rests: [] }),
305
457
  why: "a snap pin's barb past its peg, and past a millimetre the halves cannot close enough to let it through; the coupon prints 0.3 to 0.5",
306
- rule: `A snap pin's barb past its peg: the one on ${HOLDS_COUPON} that clicked through its socket by hand and held when pulled. A record for choosing the default: pins are still drawn with a 0.4 mm barb unless their name says barb N`,
458
+ rule: (holdsAt) =>
459
+ `A snap pin's barb past its peg: the one on ${holdsAt} that clicked through its socket by hand and held when pulled. A record for choosing the default: pins are still drawn with a 0.4 mm barb unless their name says barb N`,
307
460
  },
308
461
  };
309
462
 
310
463
  // The pull bolt on the holds coupon (row 46): an M8 printed bolt whose waist breaks across its layers, so it measures
311
- // how strongly a plastic holds across its layers, which PLA's data sheet does not give. It goes in the plastic's set
464
+ // how strongly a plastic holds across its layers on the user's printer, where the data sheet's figure comes from test
465
+ // bars printed at 100% infill (or a plastic of their own gives none). It goes in the plastic's set
312
466
  // as strength_z, which a printed bolt standing on its head, and every part pulled across its layers, then reads
313
- function boltRule(set, key, data) {
467
+ function boltRule(project, set, key, data) {
314
468
  if (key !== 'strength_z' || data.rules?.density == null || typeof data.rules?.strength?.value !== 'number')
315
469
  return null;
470
+ const holdsAt = couponAt('holds', project);
316
471
  const along = data.rules.strength.value,
317
472
  z = data.rules.strength_z;
318
473
  return {
319
474
  unit: 'MPa',
320
475
  predicted: z?.value ?? along,
321
476
  was: z ? `${set}.strength_z, ${z.kind}` : `${set}.strength, along the layers: no figure across them`,
322
- source: `${HOLDS_COUPON}, the pull bolt broken on a luggage scale`,
323
- measuredRule: `Tensile strength of ${set.toUpperCase()} across its printed layers: the pull bolt on ${HOLDS_COUPON}, printed standing, broken on a luggage scale at its 3.5 mm waist (the kilograms × 9.81 over 9.62 mm²). A printed bolt standing on its head, and any part pulled across its layers, takes it before the along-layer strength`,
477
+ source: `${holdsAt}, the pull bolt broken on a luggage scale`,
478
+ measuredRule: `Tensile strength of ${set.toUpperCase()} across its printed layers: the pull bolt on ${holdsAt}, printed standing, broken on a luggage scale at its 3.5 mm waist (the kilograms × 9.81 over 9.62 mm²). A printed bolt standing on its head, and any part pulled across its layers, takes it before the along-layer strength`,
324
479
  check: (x) =>
325
480
  !(x > 0) || x > along
326
481
  ? `is above 0 and no more than ${set}.strength, ${along} MPa: a print holds less across its layers than along them, so read the scale's peak again, and work it as kilograms × 9.81 over the waist's 9.62 mm²`
@@ -329,7 +484,7 @@ function boltRule(set, key, data) {
329
484
  }
330
485
  const printerName = (project) => {
331
486
  try {
332
- return fixingsContext({ project, dir: paths.project(project) }).context.printer?.name ?? 'x1c';
487
+ return fixingsContext({ project, dir: projectDir(project) }).context.printer?.name ?? 'x1c';
333
488
  } catch {
334
489
  return 'x1c';
335
490
  }
@@ -343,39 +498,66 @@ function kitRule(set, key) {
343
498
  }
344
499
  }
345
500
 
501
+ // A typed figure that is most likely a slip: of the other sign from the one it replaces, or under half or over twice it.
502
+ // An estimate is a guess the measurement is there to correct, so it may move further: a tenth to ten times, which
503
+ // still catches a figure in the wrong unit or a diameter for a clearance. Nothing is said where there is no figure to
504
+ // compare with (a new rule, a fit the kit drew at 0)
505
+ const RATIO = { settled: [0.5, 2, 'half to twice it'], estimate: [0.1, 10, 'a tenth to ten times it, as an estimate'] };
506
+ function slipOf(value, prior, unit, kind) {
507
+ if (typeof prior !== 'number' || !Number.isFinite(prior) || prior === 0) return null;
508
+ const was = `${n(prior)}${unit ? ` ${unit}` : ''}`;
509
+ if (value !== 0 && Math.sign(value) !== Math.sign(prior)) return `is of the other sign from the ${was} it replaces`;
510
+ const r = value / prior,
511
+ [least, most, said] = kind === 'estimate' ? RATIO.estimate : RATIO.settled;
512
+ if (r < least || r > most) return `is ${n(r)} times the ${was} it replaces, outside ${said}`;
513
+ return null;
514
+ }
515
+
516
+ // The assembly a measurement is for, from <project>/<assembly>; or with no ref, none: a coupon's figure, kept in the
517
+ // workspace's ledger. `what` says what the assembly is for, where it is not there
518
+ function assemblyOf(ref, what) {
519
+ if (ref == null) return { project: null, assembly: null, shown: 'ledger.jsonl', history: 'cad history' };
520
+ const [project, assembly] = String(ref).split('/');
521
+ if (!project || !assembly || !fs.existsSync(assemblyPath(ref)))
522
+ throw new CadError('measured.assembly', `no assembly "${ref}": give <project>/<assembly>, ${what}`);
523
+ return { project, assembly, shown: ref, history: `cad history ${ref}` };
524
+ }
525
+
346
526
  /**
347
527
  * Write measurements back.
348
- * @param {string} ref project/assembly
528
+ * @param {string | null} ref project/assembly, the one whose predictions it moves and whose checks are run either
529
+ * side; or null for a rule measured on a coupon with no assembly to run: written the same, kept in the workspace's
530
+ * ledger, with nothing said to have moved
349
531
  * @param {Record<string, number>} values name → measured value
350
- * @param {{ unit?: string, source?: string, rule?: string, date?: string }} [options]
532
+ * @param {{ unit?: string, source?: string, rule?: string, date?: string, force?: boolean }} [options] force: write
533
+ * a figure under half or over twice the one it replaces, or of the other sign, which is otherwise refused as a slip
351
534
  * @returns {Promise<{ entries: object[], moved: { from: string, to: string }[] }>}
352
535
  */
353
- export async function recordMeasured(ref, values, { unit, source, rule, date = today() } = {}) {
354
- const [project, name] = String(ref).split('/');
355
- if (!project || !name || !fs.existsSync(assemblyPath(ref)))
356
- throw new CadError(
357
- 'measured.assembly',
358
- `no assembly "${ref}": give <project>/<assembly>, the one whose predictions it moves`,
359
- );
536
+ export async function recordMeasured(ref, values, { unit, source, rule, date = today(), force = false } = {}) {
537
+ const { project, assembly: name } = assemblyOf(
538
+ ref,
539
+ 'the one whose predictions it moves, or leave it out to write a rule measured on a coupon (cad measured x1c.pilot_m3=2.9)',
540
+ );
360
541
  if (!Object.keys(values).length)
361
542
  throw new CadError(
362
543
  'measured.usage',
363
- 'usage: cad measured <project>/<assembly> <name>=<value> … [--unit mm] [--source "how it was measured"]',
544
+ 'usage: cad measured [<project>/<assembly>] <name>=<value> … [--unit mm] [--source "how it was measured"]',
364
545
  );
365
- const before = await findingsOf(ref),
546
+ const before = ref == null ? [] : await findingsOf(ref),
366
547
  entries = [],
367
548
  predictions = predictionsOf(before);
368
549
  const writes = [],
369
- slots = new Map(); // (every value is checked before any is written, so a refusal leaves the rule sets as they were)
550
+ slots = new Map(), // (every value is checked before any is written, so a refusal leaves the rule sets as they were)
551
+ slips = [];
370
552
  // a rule's new value, checked before anything is written (a refusal leaves the rule sets as they were)
371
553
  const writeRule = (k, value, { from = null, unit: u = unit, frame = null } = {}) => {
372
554
  const { set, rule: key, data, file, text, copied } = ruleFile(k);
373
555
  const old = data.rules?.[key],
374
556
  known =
375
557
  slotRule(project, set, key, data) ??
376
- rigRule(set, key, data, frame) ??
377
- couponRule(set, key, data) ??
378
- boltRule(set, key, data) ??
558
+ rigRule(project, set, key, data, frame) ??
559
+ couponRule(project, set, key, data) ??
560
+ boltRule(project, set, key, data) ??
379
561
  fixingsRule(project, set, key) ??
380
562
  (old ? null : kitRule(set, key));
381
563
  if (known?.allowed && !known.allowed.includes(value))
@@ -388,12 +570,30 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
388
570
  if (!old && !rule && !known)
389
571
  throw new CadError(
390
572
  'measured.rule',
391
- `${set} has no rule "${key}" (and no check here predicts "${k}"): --rule "what it is" to add it (checks: ${[...new Set(predictions.map((x) => x.code))].join(', ') || 'none'})`,
573
+ ref == null
574
+ ? `${set} has no rule "${key}": --rule "what it is" to add it, or give the assembly first to measure one of its checks' predictions (cad measured <project>/<assembly> ${k}=${value})`
575
+ : `${set} has no rule "${key}" (and no check here predicts "${k}"): --rule "what it is" to add it (checks: ${[...new Set(predictions.map((x) => x.code))].join(', ') || 'none'})`,
392
576
  );
393
577
  const had = old ?? known,
394
578
  prior = typeof had?.value === 'number' ? had.value : (known?.predicted ?? null);
395
579
  if (u && had?.unit && u !== had.unit)
396
580
  throw new CadError('measured.unit', `${k} is in ${had.unit}, and this is in ${u}: give it in ${had.unit}`);
581
+ // a figure typed for a rule, held to the one it replaces (a figure worked out from a drop or a sag is not: the
582
+ // estimate it replaces may be far out, and the drop or sag is checked where it is read; nor is a fit the coupon
583
+ // bounds by what a fit of its kind can be, where 0 may be right). Said once every firmer check has had its say
584
+ if (!from && !force && !known?.check && !known?.allowed) {
585
+ // (a 0 where a coupon in the kit measures the figure is one it prints: it steps either side of the kit's figure,
586
+ // and the fixings coupon's nut slots start at 0. An empty figure, which reads as 0, is refused at the command line)
587
+ const kind = old?.kind ?? (/\bestimate\b/.test(known?.was ?? '') ? 'estimate' : null),
588
+ slip =
589
+ value === 0 && couponOf(set, key, data, printerName(project))
590
+ ? null
591
+ : slipOf(value, prior, had?.unit ?? u ?? '', kind);
592
+ if (slip)
593
+ slips.push(
594
+ `${k}=${value} ${slip} (${old ? old.kind : (known?.was ?? 'the kit')}). That is most often a slip of the pen: a diameter for a clearance, a point in the wrong place. Measure it again; if it is right, give --force to write it as it is`,
595
+ );
596
+ }
397
597
  // its sentence: what was measured, never the estimate's "until it is measured": the one given, else the rig's, else the rule's own
398
598
  const entry = {
399
599
  value,
@@ -500,6 +700,7 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
500
700
  throw new CadError('measured.value', `${set}: ${e.message.replace(/^slotModel: /, '')}`);
501
701
  }
502
702
  }
703
+ if (slips.length) throw new CadError('measured.value', slips.join('\n'));
503
704
  // every value checked: now each set is written, the workspace's copy made from where it started where there is none
504
705
  const texts = new Map();
505
706
  for (const w of writes)
@@ -509,21 +710,9 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
509
710
  fs.writeFileSync(file, w.text);
510
711
  if (w.copied) console.error(w.copied);
511
712
  }
512
- const after = await findingsOf(ref),
513
- was = new Map(before.map((x) => [keyOf(x), x])),
514
- moved = [];
515
- for (const x of after) {
516
- const y = was.get(keyOf(x));
517
- if (x.predict && y?.predict && Math.abs(x.predict.value - y.predict.value) > 1e-9)
518
- moved.push({
519
- code: x.code,
520
- figure: x.predict.figure,
521
- unit: x.predict.unit,
522
- from: y.predict.value,
523
- to: x.predict.value,
524
- });
525
- else if (y && y.text !== x.text && !x.predict) moved.push({ code: x.code, text: x.text, was: y.text });
526
- }
713
+ // (with no assembly there are no checks to run again: nothing is said to have moved)
714
+ const after = ref == null ? [] : await findingsOf(ref),
715
+ moved = movedBetween(before, after);
527
716
  fs.appendFileSync(
528
717
  insideWorkspace(ledgerFile(project)), // (never through a link: rules.mjs)
529
718
  entries.map((e) => JSON.stringify({ ...e, moved: moved.filter((m) => m.figure) })).join('\n') + '\n',
@@ -531,32 +720,484 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
531
720
  return { entries, moved, findings: after };
532
721
  }
533
722
 
534
- // What the kit assumes, as a Markdown table: each rule used that is only an estimate, what measures it, and what it feeds
723
+ // The coupons that settle a printer's or a plastic's figures (examples/bench/projects/benchmarks/MEASURE.md): the
724
+ // object printed, its rows there, and the rules it measures (a pattern for one per thread). `names` are the ones it
725
+ // settles that a set may not hold yet, listed for an assembly the coupon is in until each is measured
726
+ const COUPONS = [
727
+ { object: 'fit-bar', said: 'the fit bar', rows: '4', printer: ['hole_comp'] },
728
+ { object: 'seats-coupon', said: 'the seats coupon', rows: '21', printer: ['press', 'slip'] },
729
+ {
730
+ object: 'fixings-coupon',
731
+ said: 'the fixings coupon',
732
+ rows: '22 to 28',
733
+ printer: [
734
+ /^pilot_m[\d_]+(_[a-z][a-z0-9]*)?$/,
735
+ /^insert_m[\d_]+(_[a-z][a-z0-9]*)?$/,
736
+ 'nut_fit',
737
+ 'nut_slip',
738
+ 'thread_gap',
739
+ 'thread_flank',
740
+ ],
741
+ names: [
742
+ 'pilot_m2',
743
+ 'pilot_m2_5',
744
+ 'pilot_m3',
745
+ 'pilot_m4',
746
+ 'pilot_m5',
747
+ 'insert_m2',
748
+ 'insert_m3',
749
+ 'nut_fit',
750
+ 'nut_slip',
751
+ 'thread_gap',
752
+ 'thread_flank',
753
+ ],
754
+ // (a thread set's pilot and insert hole are the starting figures the coupon's x1c.pilot_m3 and the like replace)
755
+ other: (set, key) => /^m\d[\d_]*$/.test(set) && ['pilot', 'insert_hole'].includes(key),
756
+ },
757
+ {
758
+ object: 'holds-coupon',
759
+ said: 'the holds coupon',
760
+ rows: '40 to 46',
761
+ printer: ['snap_barb', 'snap_clearance', 'pin_press', 'pin_slip', 'magnet_press', 'magnet_crush'],
762
+ plastic: ['strength_z'],
763
+ names: ['snap_barb', 'snap_clearance', 'pin_press', 'pin_slip', 'magnet_press', 'magnet_crush'],
764
+ },
765
+ {
766
+ object: 'slot-coupon',
767
+ said: 'the slot coupon',
768
+ rows: '29 to 33',
769
+ printer: ['slot_fit', 'printed_slot_fit'],
770
+ names: ['slot_fit', 'printed_slot_fit'],
771
+ },
772
+ // (these two are settled through the drops and sags their assemblies predict: cad measured <ref> c1.drop=<mm>)
773
+ {
774
+ object: 'joint-hanger',
775
+ said: 'the joint rig',
776
+ rows: '34 to 37',
777
+ other: (set, key, data) =>
778
+ set === JOIN_SET || (data?.part === 'fitting' && /_stiffness$/.test(key)) || key === 'hold_along',
779
+ },
780
+ {
781
+ said: 'the beam coupon',
782
+ rows: '38 and 39',
783
+ plastic: [/^beam_(modulus|strength)(_z)?$/],
784
+ here: (findings) => findings.some((x) => x.code === 'beam.coupon'),
785
+ },
786
+ ];
787
+ const SETTLED = new Set(['measured', 'spec', 'derived']); // (a derived rule follows others, which are listed themselves)
788
+ const UNSETTLED = ['estimate', 'community', 'default'];
789
+ // the coupon that measures a rule, if one in the kit does
790
+ function couponOf(set, key, data, printer) {
791
+ const is = (list) => (list ?? []).some((p) => (typeof p === 'string' ? p === key : p.test(key)));
792
+ return (
793
+ COUPONS.find(
794
+ (c) =>
795
+ (set === printer && is(c.printer)) ||
796
+ (data?.rules?.density != null && is(c.plastic)) ||
797
+ c.other?.(set, key, data),
798
+ ) ?? null
799
+ );
800
+ }
801
+ // whether an assembly is that coupon: it prints the coupon's object, or makes its predictions
802
+ const isHere = (c, objects, findings) => (c.object ? objects.has(c.object) : !!c.here?.(findings));
803
+ // every rule an assembly's build and checks read: its objects' own (estimates among their variables too), the rules
804
+ // its positions and checks named, the holes v.fixings drew (and the hole compensation added to them), and what its
805
+ // findings say they rest on
806
+ function rulesUsed(s, findings, printer) {
807
+ const names = new Set();
808
+ for (const o of s.objects) {
809
+ for (const e of o.built?.entries ?? [])
810
+ if (e.used || (!e.name.includes('.') && e.kind === 'estimate')) names.add(e.name);
811
+ for (const h of o.built?.fixings ?? []) {
812
+ if (typeof h.refs?.rule === 'string') names.add(h.refs.rule);
813
+ if (h.values?.comp > 0) names.add(`${printer}.hole_comp`);
814
+ }
815
+ }
816
+ for (const x of s.seen ?? []) names.add(x);
817
+ for (const x of findings) {
818
+ const r = x.refs ?? {};
819
+ for (const v of [
820
+ r.rule,
821
+ ...(Array.isArray(r.rests) ? r.rests : []),
822
+ ...(x.code === 'rules.estimate' ? (r.rules ?? []) : []),
823
+ ])
824
+ if (typeof v === 'string') names.add(v);
825
+ }
826
+ return names;
827
+ }
828
+ // a rule set read and not written: the workspace's copy, else the kit's, else for the joins set @rulecad/frames' estimates
829
+ const setOf = (name) => {
830
+ try {
831
+ return peekRuleSet(name);
832
+ } catch (e) {
833
+ if (name === JOIN_SET) return joinRuleSet();
834
+ throw e;
835
+ }
836
+ };
837
+ const ruleAt = (name) => {
838
+ const dot = name.indexOf('.');
839
+ if (dot < 1) return null;
840
+ try {
841
+ const set = setOf(name.slice(0, dot));
842
+ return {
843
+ set: name.slice(0, dot),
844
+ key: name.slice(dot + 1),
845
+ data: set,
846
+ rule: set.rules?.[name.slice(dot + 1)] ?? null,
847
+ };
848
+ } catch {
849
+ return null; // (an item's or another object's value, not a rule set's)
850
+ }
851
+ };
852
+
853
+ /**
854
+ * What an assembly still assumes: every rule it reads that is an estimate, a community figure or a default (its
855
+ * figure, what it is, the coupon in the kit that measures it, and whether this assembly is that coupon), each figure
856
+ * a coupon in it measures that its set does not hold yet, and each prediction its checks make.
857
+ * @param {string} ref project/assembly
858
+ * @returns {Promise<{ assembly: string, rows: { name: string, value: any, unit: string, rule: string, trust: string,
859
+ * coupon: string | null, here: boolean, settle: string, was?: string, code?: string }[] }>} trust is the rule's kind
860
+ * (estimate, community, default), "none yet" for a coupon's figure the set lacks, or "prediction" (code: the check's)
861
+ */
862
+ export async function assumptions(ref) {
863
+ const [project] = String(ref).split('/');
864
+ if (!fs.existsSync(assemblyPath(ref)))
865
+ throw new CadError(
866
+ 'measured.assembly',
867
+ `no assembly "${ref}": give <project>/<assembly>, the one whose figures it lists`,
868
+ );
869
+ const s = await buildAssembly(ref),
870
+ findings = checkAssembly(s),
871
+ printer = printerName(project),
872
+ objects = new Set(s.objects.map((o) => o.objName)),
873
+ settle = (name) => `cad measured ${ref} ${name}=<value>`,
874
+ rows = [],
875
+ listed = new Set();
876
+ const est = new Set(findings.find((x) => x.code === 'rules.estimate')?.refs?.rules ?? []);
877
+ const row = (name, { set, key, data, was, ...shown }) => {
878
+ const c = set ? couponOf(set, key, data, printer) : null;
879
+ listed.add(name);
880
+ rows.push({
881
+ name,
882
+ ...shown,
883
+ coupon: c ? `${c.said} (MEASURE.md ${c.rows.includes(' ') ? 'rows' : 'row'} ${c.rows})` : null,
884
+ here: !!c && isHere(c, objects, findings),
885
+ settle: settle(name),
886
+ ...(was ? { was } : {}),
887
+ });
888
+ };
889
+ for (const name of rulesUsed(s, findings, printer)) {
890
+ const r = unsettledRow(name, est);
891
+ if (r) row(name, r);
892
+ }
893
+ // what a coupon in this assembly measures that the printer's set does not hold as measured yet
894
+ for (const c of COUPONS.filter((x) => x.names && isHere(x, objects, findings)))
895
+ for (const key of c.names) {
896
+ const r = listed.has(`${printer}.${key}`) ? null : couponFigureRow(project, printer, key);
897
+ if (r) row(`${printer}.${key}`, r);
898
+ }
899
+ // the least settled first: what the set has no figure for, then estimates, community figures and defaults
900
+ const order = ['none yet', ...UNSETTLED];
901
+ rows.sort((a, b) => order.indexOf(a.trust) - order.indexOf(b.trust));
902
+ for (const x of predictionsOf(findings))
903
+ rows.push({
904
+ name: x.predict.name ?? x.code,
905
+ value: x.predict.value,
906
+ unit: x.predict.unit ?? '',
907
+ rule: x.predict.figure,
908
+ trust: 'prediction',
909
+ code: x.code,
910
+ coupon: null,
911
+ here: true,
912
+ settle: settle(x.predict.name ?? x.code),
913
+ });
914
+ return { assembly: ref, rows };
915
+ }
916
+ // a rule the assembly reads, as a row of the table if it is not settled (an estimate, a community figure, a default)
917
+ function unsettledRow(name, est) {
918
+ const at = ruleAt(name);
919
+ // (an object's own estimate, or a rule that could not be read)
920
+ if (!at?.rule) return est.has(name) ? { value: null, unit: '', rule: '', trust: 'estimate' } : null;
921
+ const kind = at.rule.kind ?? (est.has(name) ? 'estimate' : null);
922
+ if (!UNSETTLED.includes(kind) && !est.has(name)) return null;
923
+ return {
924
+ value: at.rule.value,
925
+ unit: at.rule.unit ?? '',
926
+ rule: at.rule.rule ?? '',
927
+ trust: kind ?? 'estimate',
928
+ set: at.set,
929
+ key: at.key,
930
+ data: at.data,
931
+ };
932
+ }
933
+ // a figure a coupon measures, as a row of the table unless the printer's set holds it settled: what the set holds, else
934
+ // what the kit draws in its place (the model's figure, or the kit's own set's where the workspace's copy is older)
935
+ function couponFigureRow(project, printer, key) {
936
+ const name = `${printer}.${key}`,
937
+ at = ruleAt(name);
938
+ if (at?.rule) {
939
+ if (SETTLED.has(at.rule.kind)) return null;
940
+ const { value, unit = '', rule = '', kind } = at.rule;
941
+ return { value, unit, rule, trust: kind ?? 'estimate', set: printer, key, data: at.data };
942
+ }
943
+ let known = null;
944
+ try {
945
+ known = at ? (slotRule(project, printer, key, at.data) ?? fixingsRule(project, printer, key)) : null;
946
+ } catch {
947
+ // (a figure the fixings cannot work out here: listed without what it was drawn with)
948
+ }
949
+ const kit = known ? null : kitRule(printer, key); // (a set copied before the kit had the rule)
950
+ const from = known
951
+ ? { value: known.predicted, unit: known.unit, rule: known.rule ?? known.measuredRule, was: known.was }
952
+ : { value: kit?.value, unit: kit?.unit, rule: kit?.rule, was: kit ? `the kit's ${name}, ${kit.kind}` : undefined };
953
+ return {
954
+ value: from.value ?? null,
955
+ unit: from.unit ?? '',
956
+ rule: from.rule ?? '',
957
+ trust: 'none yet',
958
+ set: printer,
959
+ key,
960
+ data: at?.data,
961
+ was: from.was,
962
+ };
963
+ }
964
+
965
+ // What the kit assumes, as a Markdown table: each rule used that is not yet settled, its trust, what measures it (this
966
+ // assembly, where it is that coupon), and each prediction to measure
535
967
  export async function assumptionsTable(ref) {
536
- const findings = await findingsOf(ref),
537
- estimates = findings.find((x) => x.code === 'rules.estimate')?.refs?.rules ?? [],
538
- preds = predictionsOf(findings);
539
- const rows = estimates.map((name) => {
540
- let rule = '';
968
+ const { rows } = await assumptions(ref),
969
+ figure = (r) =>
970
+ r.value == null ? '' : `${typeof r.value === 'number' ? n(r.value) : r.value}${r.unit ? ` ${r.unit}` : ''}`;
971
+ const cell = (t) => String(t ?? '').replace(/\|/g, '\\|');
972
+ return [
973
+ '| What the kit assumes | What it is | Trust | Measured by | How to settle it |',
974
+ '|---|---|---|---|---|',
975
+ ...rows.map((r) =>
976
+ r.trust === 'prediction'
977
+ ? `| ${cell(r.rule)} | ${figure(r)}, predicted by \`${r.code}\` | prediction | this assembly | \`${r.settle}\` |`
978
+ : `| \`${r.name}\` | ${[figure(r), cell(r.rule)].filter(Boolean).join(': ')}${r.was ? ` (drawn with ${cell(r.was)})` : ''} | ${r.trust} | ${r.here ? `this assembly, ${r.coupon}` : (r.coupon ?? 'no coupon in the kit: a test print of your own')} | \`${r.settle}\` |`,
979
+ ),
980
+ ].join('\n');
981
+ }
982
+ /**
983
+ * Take a row out of an assembly's ledger: a figure written by mistake. The rule it went into is in a file of its own
984
+ * (rules/<set>.json), which this leaves as it is: what that file still holds for the name is returned, so the person
985
+ * can set it back there.
986
+ * @param {string | null} ref project/assembly, or null for a row written with no assembly (the workspace's ledger)
987
+ * @param {string} date the row's date, YYYY-MM-DD, as cad history shows it
988
+ * @param {string} which the row's name (x1c.fit, c1.drop), or its name and figure (x1c.fit=0.9) where the ledger holds
989
+ * that name more than once that day
990
+ * @returns {{ struck: object[], lines: string[], rule: { file: string, name: string, value: any, kind: string | null,
991
+ * same: boolean, said: string } | null }}
992
+ */
993
+ export function strikeLedger(ref, date, which) {
994
+ // (rows written with no assembly: the workspace's ledger, which cad history alone shows)
995
+ const { project, assembly, shown, history } = assemblyOf(ref, 'the one the row is for');
996
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(String(date)))
997
+ throw new CadError(
998
+ 'measured.usage',
999
+ `--strike takes the row's date, as ${history} shows it (2026-12-01), then its name (got "${date}")`,
1000
+ );
1001
+ const eq = String(which).indexOf('='),
1002
+ name = eq > 0 ? which.slice(0, eq) : String(which),
1003
+ figure = eq > 0 ? Number(which.slice(eq + 1)) : null;
1004
+ if (eq > 0 && (!which.slice(eq + 1).trim() || !Number.isFinite(figure)))
1005
+ throw new CadError('measured.usage', `${which}: give the row's figure after the "=", as cad history shows it`);
1006
+ const rows = readLedger(project),
1007
+ hit = (e) =>
1008
+ (e.assembly ?? null) === assembly &&
1009
+ e.date === date &&
1010
+ e.name === name &&
1011
+ (figure == null || Math.abs(e.measured - figure) < 1e-9);
1012
+ const struck = rows.filter(hit);
1013
+ if (!struck.length) {
1014
+ const dates = rows.filter((e) => (e.assembly ?? null) === assembly && e.name === name).map((e) => e.date);
1015
+ throw new CadError(
1016
+ 'measured.strike',
1017
+ `${shown}: no row for ${which} on ${date} in the ledger` +
1018
+ (dates.length ? ` (it has ${name} on ${[...new Set(dates)].join(', ')})` : ` (${history} lists its rows)`),
1019
+ );
1020
+ }
1021
+ // two measurements of one figure on one day: which is the slip is the person's to say
1022
+ if (figure == null && new Set(struck.map((e) => e.measured)).size > 1)
1023
+ throw new CadError(
1024
+ 'measured.strike',
1025
+ `${shown}: the ledger has ${name} ${struck.length} times on ${date} (${struck.map((e) => n(e.measured)).join(', ')}): name the one to strike with its figure, ${name}=${n(struck.at(-1).measured)}`,
1026
+ );
1027
+ const kept = rows.filter((e) => !hit(e));
1028
+ fs.writeFileSync(
1029
+ insideWorkspace(ledgerFile(project)), // (never through a link: rules.mjs)
1030
+ kept.map((e) => JSON.stringify(e)).join('\n') + (kept.length ? '\n' : ''),
1031
+ );
1032
+ // the rule set the figure went into: the workspace's copy, if the name is a rule's
1033
+ let rule = null;
1034
+ const dot = name.indexOf('.'),
1035
+ file = dot > 0 ? path.join(WS, 'rules', `${name.slice(0, dot)}.json`) : null;
1036
+ if (file && fs.existsSync(file)) {
1037
+ let held;
541
1038
  try {
542
- const [u, k] = name.split('.');
543
- rule = loadRuleSet(u).rules[k]?.rule ?? '';
1039
+ held = JSON.parse(readOwnText(file)).rules?.[name.slice(dot + 1)];
544
1040
  } catch {
545
- // (no such rule set or rule: the table leaves its rule blank)
1041
+ held = undefined; // (a set that does not read: nothing to say of it)
546
1042
  }
547
- return `| \`${name}\` | ${rule} | estimate | \`cad measured ${ref} ${name}=<value>\` |`;
548
- });
549
- const out = [
550
- '| What the kit assumes | What it is | Trust | How to settle it |',
551
- '|---|---|---|---|',
552
- ...rows,
553
- ...preds.map(
554
- (x) =>
555
- `| ${x.predict.figure} | ${n(x.predict.value)} ${x.predict.unit}, predicted by \`${x.code}\` | prediction | \`cad measured ${ref} ${x.predict.name ?? x.code}=<value>\` |`,
556
- ),
557
- ];
558
- return out.join('\n');
1043
+ if (held) {
1044
+ const rel = path.relative(WS, file).split(path.sep).join('/'),
1045
+ same = struck.some((e) => e.measured === held.value);
1046
+ rule = {
1047
+ file: rel,
1048
+ name,
1049
+ value: held.value,
1050
+ kind: held.kind ?? null,
1051
+ same,
1052
+ said: same
1053
+ ? `${rel} still holds ${name} = ${held.value} (${held.kind ?? 'no kind'}): the ledger and the rule set are kept apart, so set it back there too (git checkout ${rel}, or cad measured with the right figure)`
1054
+ : `${rel} holds ${name} = ${held.value} (${held.kind ?? 'no kind'}), not the struck figure: the rule set is as it was`,
1055
+ };
1056
+ }
1057
+ }
1058
+ return { struck, lines: ledgerLines(struck), rule };
559
1059
  }
1060
+
1061
+ /**
1062
+ * What this workspace measured that the kit does not hold yet, to send to the kit: each rule written as measured in a
1063
+ * rule set of the workspace's (rules/<set>.json) whose figure the kit's own set lacks, or holds as anything but a
1064
+ * measurement checked that day or since, as a change to the kit's file (a unified diff against
1065
+ * packages/rules/<set>.json, its layout kept, the rest of the file as the kit has it). A set the kit has no file for
1066
+ * (the joins set, a part of the maker's own) cannot be a change to one: its measured rules are listed apart, to send as
1067
+ * they are.
1068
+ * @returns {{ sets: { set: string, file: string, rules: { name: string, value: any, unit: string, checked: string |
1069
+ * null, source: string, kit: { value: any, kind: string | null } | null }[] }[], alone: { set: string, file: string,
1070
+ * rules: { name: string, value: any, unit: string, checked: string | null, source: string }[] }[], diff: string }}
1071
+ */
1072
+ export function exportMeasured() {
1073
+ const own = path.join(WS, 'rules'),
1074
+ kitDir = RULE_DIRS.at(-1),
1075
+ sets = [],
1076
+ alone = [],
1077
+ diffs = [];
1078
+ let files = [];
1079
+ try {
1080
+ files =
1081
+ own === kitDir
1082
+ ? []
1083
+ : fs
1084
+ .readdirSync(own)
1085
+ .filter((f) => f.endsWith('.json'))
1086
+ .sort();
1087
+ } catch {
1088
+ // (no rules folder: nothing measured here)
1089
+ }
1090
+ for (const f of files) {
1091
+ let data;
1092
+ try {
1093
+ data = JSON.parse(readOwnText(path.join(own, f)));
1094
+ } catch {
1095
+ continue; // (a set that does not read is cad rules check's to name)
1096
+ }
1097
+ const set = f.slice(0, -5),
1098
+ kitFile = path.join(kitDir, f),
1099
+ kitText = fs.existsSync(kitFile) ? fs.readFileSync(kitFile, 'utf8') : null,
1100
+ kit = kitText ? (JSON.parse(kitText).rules ?? {}) : null;
1101
+ const row = (key, r) => ({
1102
+ name: `${set}.${key}`,
1103
+ value: r.value,
1104
+ unit: r.unit ?? '',
1105
+ checked: r.checked ?? null,
1106
+ source: r.source ?? '',
1107
+ });
1108
+ // a measured figure the kit has as well as this, or measured since, is the kit's already
1109
+ const theirs = (key, r) =>
1110
+ kit?.[key]?.kind === 'measured' &&
1111
+ (JSON.stringify(kit[key]) === JSON.stringify(r) || String(kit[key].checked ?? '') >= String(r.checked ?? ''));
1112
+ const mine = Object.entries(data.rules ?? {}).filter(([key, r]) => r?.kind === 'measured' && !theirs(key, r));
1113
+ if (!mine.length) continue;
1114
+ if (!kitText) {
1115
+ alone.push({ set, file: `rules/${f}`, rules: mine.map(([key, r]) => row(key, r)) });
1116
+ continue;
1117
+ }
1118
+ let text = kitText;
1119
+ for (const [key, r] of mine) text = setAt(text, ['rules', key], r);
1120
+ sets.push({
1121
+ set,
1122
+ file: `packages/rules/${f}`,
1123
+ rules: mine.map(([key, r]) => ({
1124
+ ...row(key, r),
1125
+ kit: kit[key] ? { value: kit[key].value, kind: kit[key].kind ?? null } : null,
1126
+ })),
1127
+ });
1128
+ diffs.push(unifiedDiff(`packages/rules/${f}`, kitText, text));
1129
+ }
1130
+ return { sets, alone, diff: diffs.join('') };
1131
+ }
1132
+
1133
+ // The lines of two texts as a shortest list of steps, each [' ', line] kept, ['-', line] gone or ['+', line] new:
1134
+ // Myers' method, quick where two texts differ in a few places, as a rule set with a few figures changed does
1135
+ function editScript(a, b) {
1136
+ const trace = [];
1137
+ let v = new Map([[1, 0]]);
1138
+ search: for (let d = 0; d <= a.length + b.length; d++) {
1139
+ trace.push(v);
1140
+ v = new Map(v);
1141
+ for (let k = -d; k <= d; k += 2) {
1142
+ let x = k === -d || (k !== d && v.get(k - 1) < v.get(k + 1)) ? v.get(k + 1) : v.get(k - 1) + 1,
1143
+ y = x - k;
1144
+ while (x < a.length && y < b.length && a[x] === b[y]) (x++, y++);
1145
+ v.set(k, x);
1146
+ if (x >= a.length && y >= b.length) break search;
1147
+ }
1148
+ }
1149
+ const steps = [];
1150
+ let x = a.length,
1151
+ y = b.length;
1152
+ for (let d = trace.length - 1; d >= 0; d--) {
1153
+ const t = trace[d],
1154
+ k = x - y,
1155
+ back = k === -d || (k !== d && t.get(k - 1) < t.get(k + 1)) ? k + 1 : k - 1,
1156
+ px = t.get(back),
1157
+ py = px - back;
1158
+ for (; x > px && y > py; x--, y--) steps.push([' ', a[x - 1]]);
1159
+ if (d > 0) steps.push(x === px ? ['+', b[py]] : ['-', a[px]]);
1160
+ x = px;
1161
+ y = py;
1162
+ }
1163
+ return steps.reverse();
1164
+ }
1165
+
1166
+ // Two texts' difference as a unified diff of one file, three lines kept round each change (what git apply and patch read)
1167
+ function unifiedDiff(file, before, after) {
1168
+ const lines = (t) => (t.endsWith('\n') ? t.slice(0, -1) : t).split('\n'),
1169
+ steps = editScript(lines(before), lines(after)),
1170
+ at = [], // each step's line in the old text and in the new, counted from 0
1171
+ C = 3;
1172
+ let i = 0,
1173
+ j = 0;
1174
+ for (const [op] of steps) {
1175
+ at.push([i, j]);
1176
+ if (op !== '+') i++;
1177
+ if (op !== '-') j++;
1178
+ }
1179
+ const changed = steps.flatMap(([op], s) => (op === ' ' ? [] : [s]));
1180
+ if (!changed.length) return '';
1181
+ const hunks = [];
1182
+ for (const s of changed) {
1183
+ const last = hunks.at(-1);
1184
+ if (last && s - last[1] <= 2 * C) last[1] = s;
1185
+ else hunks.push([s, s]);
1186
+ }
1187
+ const out = [`--- a/${file}`, `+++ b/${file}`];
1188
+ for (const [s, e] of hunks) {
1189
+ const from = Math.max(0, s - C),
1190
+ to = Math.min(steps.length - 1, e + C),
1191
+ part = steps.slice(from, to + 1),
1192
+ olds = part.filter(([op]) => op !== '+').length,
1193
+ news = part.filter(([op]) => op !== '-').length;
1194
+ const [oi, nj] = at[from];
1195
+ out.push(`@@ -${olds ? oi + 1 : oi},${olds} +${news ? nj + 1 : nj},${news} @@`);
1196
+ for (const [op, line] of part) out.push(`${op}${line}`);
1197
+ }
1198
+ return out.join('\n') + '\n';
1199
+ }
1200
+
560
1201
  // A table kept in a file, between two markers: the rest of the file stays as written
561
1202
  export const MARK = ['<!-- cad measured: start -->', '<!-- cad measured: end -->'];
562
1203
  export function writeTable(file, table) {
@@ -575,7 +1216,7 @@ export function writeTable(file, table) {
575
1216
  export const ledgerLines = (entries) =>
576
1217
  entries.map(
577
1218
  (e) =>
578
- `${e.date} ${e.assembly} ${e.name}: measured ${n(e.measured)} ${e.unit || ''}`.trimEnd() +
1219
+ `${e.date} ${e.assembly ? `${e.assembly} ` : ''}${e.name}: measured ${n(e.measured)} ${e.unit || ''}`.trimEnd() +
579
1220
  (e.predicted != null
580
1221
  ? `, predicted ${n(e.predicted)}${e.was ? ` (${e.was})` : ''}${e.ratio != null ? `, ratio ${n(e.ratio)}` : ''}`
581
1222
  : '') +