@rulecad/cad 0.9.0 → 0.10.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 (53) hide show
  1. package/AGENTS.md +21 -6
  2. package/CHANGELOG.md +320 -0
  3. package/EXAMPLES.md +22 -17
  4. package/README.md +192 -40
  5. package/bin/cad.mjs +465 -80
  6. package/lib/assembly.mjs +68 -33
  7. package/lib/cache-file.mjs +105 -0
  8. package/lib/code-text.mjs +28 -0
  9. package/lib/design-imports.mjs +127 -0
  10. package/lib/design.mjs +251 -55
  11. package/lib/designshapes.mjs +142 -0
  12. package/lib/edit.mjs +24 -2
  13. package/lib/estimates.mjs +51 -0
  14. package/lib/fasten.mjs +11 -5
  15. package/lib/fe-key.mjs +29 -0
  16. package/lib/fittings.mjs +20 -15
  17. package/lib/fixings.mjs +17 -4
  18. package/lib/framebuild.mjs +1 -1
  19. package/lib/framegen.mjs +9 -1
  20. package/lib/frames.mjs +6 -2
  21. package/lib/framesize.mjs +8 -81
  22. package/lib/host.mjs +7 -3
  23. package/lib/kit.mjs +5 -5
  24. package/lib/list.mjs +29 -21
  25. package/lib/loads.mjs +35 -23
  26. package/lib/measured.mjs +738 -98
  27. package/lib/motors.mjs +9 -29
  28. package/lib/names.mjs +15 -0
  29. package/lib/optimise.mjs +34 -25
  30. package/lib/order.mjs +4 -10
  31. package/lib/parts.mjs +3 -0
  32. package/lib/rules.mjs +2 -1
  33. package/lib/sandbox-hooks.mjs +109 -15
  34. package/lib/sandbox-lock.mjs +225 -0
  35. package/lib/sandbox-preload.mjs +2 -2
  36. package/lib/sandbox-run.mjs +22 -24
  37. package/lib/sandbox.mjs +173 -30
  38. package/lib/sheet.mjs +114 -3
  39. package/lib/versions.mjs +195 -32
  40. package/lib/workspace.mjs +3 -2
  41. package/package.json +11 -11
  42. package/schemas/assembly.schema.json +1 -1
  43. package/schemas/project.schema.json +6 -0
  44. package/templates/coupons/MEASURE.md +109 -0
  45. package/templates/coupons/assemblies/fixings-test.json +20 -0
  46. package/templates/coupons/assemblies/slot-test.json +11 -0
  47. package/templates/coupons/objects/fixings-coupon.js +88 -0
  48. package/templates/coupons/objects/fixings-coupon.json +26 -0
  49. package/templates/coupons/objects/holds-coupon.js +130 -0
  50. package/templates/coupons/objects/holds-coupon.json +42 -0
  51. package/templates/coupons/objects/slot-coupon.js +89 -0
  52. package/templates/coupons/objects/slot-coupon.json +29 -0
  53. package/templates/coupons/project.json +10 -0
package/bin/cad.mjs CHANGED
@@ -4,6 +4,7 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { execFileSync } from 'node:child_process';
6
6
  import { fmt, loadRuleSet, insideWorkspace } from '../lib/rules.mjs';
7
+ import { estimatesFinding } from '../lib/estimates.mjs';
7
8
  import { WS, TOOL, paths, configError, printerOf, asks, trust } from '../lib/workspace.mjs';
8
9
  import { isPlainName, plainName } from '../lib/names.mjs';
9
10
  import { fromKLE } from '@rulecad/keyboard-layout';
@@ -19,6 +20,7 @@ import {
19
20
  pcbEngine,
20
21
  objectSets,
21
22
  boardChecks,
23
+ readTexts,
22
24
  } from '../lib/design.mjs';
23
25
  import {
24
26
  git,
@@ -30,6 +32,7 @@ import {
30
32
  snapshot,
31
33
  materialise,
32
34
  files,
35
+ readsLine,
33
36
  prints,
34
37
  printsFile,
35
38
  engineId,
@@ -38,11 +41,20 @@ import { check } from '@rulecad/printcheck';
38
41
  import { preview } from '../lib/preview.mjs';
39
42
  import { measure, match } from '../lib/meshcmd.mjs';
40
43
  import { cloneBoard } from '../lib/clone.mjs';
41
- import { isAssembly, buildAssembly, checkAssembly, shapes, sweep, wireTubesOf } from '../lib/assembly.mjs';
44
+ import {
45
+ isAssembly,
46
+ buildAssembly,
47
+ assemblyOverrides,
48
+ checkAssembly,
49
+ shapes,
50
+ sweep,
51
+ wireTubesOf,
52
+ } from '../lib/assembly.mjs';
42
53
  import { valuesOf, why } from '../lib/explain.mjs';
43
- import { errorData, near } from '../lib/errors.mjs';
54
+ import { CadError, errorData, near } from '../lib/errors.mjs';
44
55
  import { schemaFindings } from '../lib/schema.mjs';
45
56
  import { readJson, readOwnText, cached } from '../lib/host.mjs';
57
+ import { writeCacheFile, readCacheJson } from '../lib/cache-file.mjs';
46
58
  import {
47
59
  optimised,
48
60
  ownResults,
@@ -59,6 +71,7 @@ import {
59
71
  addToAssembly,
60
72
  fastenFromFitsEdit,
61
73
  parseValue,
74
+ valueFor,
62
75
  parseSetting,
63
76
  newProject,
64
77
  setProject,
@@ -71,7 +84,7 @@ import {
71
84
  import { setAt } from '../lib/jsonedit.mjs';
72
85
  import { threemf, slotOf } from '../lib/threemf.mjs';
73
86
  import { liveView, recorder, endOnly } from '../lib/live.mjs';
74
- import { checkSets, drawSet, draftSet, draftPart, draftParts } from '../lib/sheet.mjs';
87
+ import { checkSets, drawSet, draftSet, draftPart, draftParts, updateSet } from '../lib/sheet.mjs';
75
88
  import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW, viewNote } from '../lib/links.mjs';
76
89
 
77
90
  // What the print file asks of the AMS: which filament each kind of part prints in
@@ -103,14 +116,19 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
103
116
  cad new <project> a project: its project.json [--title …] [--description …] [--material PLA] [--printer x1c]
104
117
  cad new <project>/<assembly> --assembly an empty assembly that checks [--title …] (makes the project if needed); with
105
118
  --frame box|portal|table|gantry|shelf --inside 300,300,350 (or --outside) --profile <set>
106
- [--join blind] [--fitting printed] [--feet levelling] [--caps false]: a generated frame
119
+ [--join blind] [--fitting printed] [--estimate] [--feet levelling] [--caps false]: a generated frame
120
+ cad coupons the kit's test prints as projects/coupons: the fixings, holds and slot coupons, and
121
+ MEASURE.md, which says how to read each and the cad measured command that writes it back
107
122
  cad import-kle <file> <project>/<name> a keyboard layout from keyboard-layout-editor.com, into layouts/
108
123
  cad clone <board.kicad_pcb | GitHub link> <name> a published circuit board into rules/<name>.json, to redraw by rules [--source, --licence]
109
124
  cad agents AGENTS.md: how an AI agent should design in this workspace
110
125
  cad trust allow what this workspace's cad.config.json asks (no sandbox, its own targets)
111
126
  cad rules <project>/<object> every variable: value, the rule behind it, its source
112
127
  cad rules check [set …] rule sets held to what makes them traceable (exit 1 on a failure) [--json]; notes,
113
- never failures: an alias in "interface", and what the kit's set has that your copy lacks
128
+ never failures: an alias in "interface", what the kit's set has that your copy lacks or
129
+ has newer, and a copy that is the kit's word for word
130
+ cad rules update <set> your copy in rules/ brought up to the kit's: its newer figures and new rules, keeping
131
+ your measured figures, those you checked since, and rules of your own [--dry-run] [--json]
114
132
  cad rules draw <set> a dimension drawing of what a set says a part mounts by, <set>.svg, to compare with its datasheet [--out file]
115
133
  cad rules draft <name> --from <file.pdf> the figures in a datasheet's text, into rules/<name>.json for you to name and check (all kind estimate)
116
134
  cad rules draft profile|slot|slot_nut <name> every field a beam's profile, a slot family or a slot nut has, to fill from its sheet
@@ -165,7 +183,8 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
165
183
  cad release <project>/<object> -m "what changed" [--bump major|minor|patch] [--dry-run] [--push]
166
184
  check it, compare with the last release, suggest the bump, then commit, tag and log it in CHANGELOG.md
167
185
  cad release <project> -m "…" a project release: records the version of each object
168
- cad history <project>[/<object>] releases, with what changed and what was printed
186
+ cad history <project>[/<object>] releases, with what changed and what was printed (cad history alone: the figures
187
+ written with no assembly)
169
188
  cad diff <project>/<object> <from> [<to>] what changed between two releases (or a release and now)
170
189
  cad printed <project>/<object> --result ok|failed [--note "…"] [--material PETG] [--version 0.1.0]
171
190
  cad release <project> --all -m "…" release every object that changed (each with this message), then the project
@@ -190,7 +209,17 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
190
209
  cad measured <project>/<assembly> <name>=<value> … a measurement, where the estimate was: a rule (x1c.press=0.08) or a
191
210
  check's prediction (task.accuracy=0.8): says what moved, and keeps a ledger of predicted
192
211
  against measured, shown by cad history [--unit mm] [--source "how"] [--rule "what it is"]
193
- [--table: what the assembly still assumes, as Markdown; --out MEASURE.md: kept in that file]
212
+ [--force: a figure of the other sign, or under half or over twice the one it replaces (a tenth
213
+ to ten times, an estimate's), refused as a slip without it]
214
+ [--table: every estimate, community figure and default the assembly still rests on, the coupon
215
+ that measures each, and its predictions, as Markdown; --json: as data; --out MEASURE.md: kept there]
216
+ [--strike <date> <name>[=<figure>]: a row taken out of the ledger; the rule set it went into is
217
+ left as it is, and the command says what it still holds]
218
+ cad measured <name>=<value> … the same with no assembly: a rule measured on a coupon (x1c.pilot_m3=2.9), written to
219
+ your copy of its set and kept in the workspace's ledger, shown by cad history alone
220
+ (--strike <date> <name> takes a row out of it)
221
+ cad measured --export every figure measured here that the kit lacks, as a diff of the kit's rule sets
222
+ (packages/rules/<set>.json), to send to the kit [--json]
194
223
  The fixings coupon's rules need no --rule: x1c.pilot_m4, x1c.insert_m3 (and _petg for one
195
224
  plastic), x1c.nut_fit, x1c.nut_slip, x1c.thread_gap, x1c.thread_flank (45 or 60)
196
225
  The slot coupon's need no --rule: x1c.slot_fit, x1c.printed_slot_fit; a slot measured by
@@ -217,6 +246,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
217
246
 
218
247
  <project>/<object>@<version> any command but release works on a release: cad export keyboard/keycap@0.1.0
219
248
  --set name=value,name=value change variables that have a tweak range (any command)
249
+ --set item.name=value on an assembly: that item's variable (check, preview, export, show, link, list)
220
250
  --part <name> only that part (check, preview, export, link): e.g. --part cap
221
251
  --explode preview: parts moved apart, so each can be seen
222
252
  --trailer "Co-Authored-By: …" added to release commits (for agents)
@@ -225,6 +255,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
225
255
  // Every command and option there is: a misspelt one is refused by name, not passed over
226
256
  const COMMANDS = [
227
257
  'new',
258
+ 'coupons',
228
259
  'remove',
229
260
  'move',
230
261
  'import-kle',
@@ -267,6 +298,8 @@ const COMMANDS = [
267
298
  ];
268
299
  const OPTIONS = [
269
300
  'table',
301
+ 'export',
302
+ 'strike',
270
303
  'calibrate',
271
304
  'check',
272
305
  'turns',
@@ -366,6 +399,7 @@ const OPTIONS = [
366
399
  'inside',
367
400
  'outside',
368
401
  'join',
402
+ 'estimate',
369
403
  'feet',
370
404
  'caps',
371
405
  'with-refs',
@@ -376,9 +410,10 @@ const OPTIONS = [
376
410
  // it passed over would let the command write
377
411
  const takesDryRun = (cmd) =>
378
412
  ['new', 'set', 'add', 'remove', 'move', 'release'].includes(cmd) ||
413
+ (cmd === 'rules' && positional()[1] === 'update') ||
379
414
  (cmd === 'frame' && (opt('expand') || (opt('size') && opt('write'))));
380
415
  const DRY_RUNS =
381
- 'the commands that take one are cad new, set, add, remove, move, release, frame --expand and frame --size --write';
416
+ 'the commands that take one are cad new, set, add, remove, move, release, rules update, frame --expand and frame --size --write';
382
417
  // What a command takes, where that isn't <project>/<object>
383
418
  const USAGE = {
384
419
  add: 'fit|joint|item|beam|loop|pose|fasten|join|guide|load|wire <project>/<assembly> --key value … [field=value …]',
@@ -402,6 +437,7 @@ const args = process.argv.slice(2);
402
437
  const FLAGS = [
403
438
  'with-refs',
404
439
  'table',
440
+ 'export',
405
441
  'calibrate',
406
442
  'check',
407
443
  'preview',
@@ -430,6 +466,7 @@ const FLAGS = [
430
466
  'expand',
431
467
  'size',
432
468
  'write',
469
+ 'estimate',
433
470
  ];
434
471
  // The options whose value may be left out; a field=value after one is a field to set, not its value (cad new
435
472
  // frame/box --assembly title=Box)
@@ -612,10 +649,7 @@ async function optimiseProblem(ref, { preview: previewing = false } = {}) {
612
649
  // The run, to watch again: kept by the densities' key when it was recorded here, else its end alone
613
650
  const done = `finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`,
614
651
  kept = paths.cache('runs', `${densitiesKey(p.problem)}.html`);
615
- if (rec.steps()) {
616
- fs.mkdirSync(path.dirname(kept), { recursive: true });
617
- fs.writeFileSync(kept, rec.page(`cad optimise ${ref}`, done));
618
- }
652
+ if (rec.steps()) writeCacheFile(kept, rec.page(`cad optimise ${ref}`, done));
619
653
  const run = paths.preview(project, `${name.replace(':', '-')}-run.html`),
620
654
  recorded = cached(kept);
621
655
  fs.mkdirSync(path.dirname(run), { recursive: true });
@@ -1022,6 +1056,69 @@ async function analyses(b, d, tag) {
1022
1056
  return all;
1023
1057
  }
1024
1058
 
1059
+ // cad rules update <set>: the workspace's copy of a kit set given the kit's newer figures and new rules (sheet.mjs
1060
+ // kitDifference says which are the kit's to take), keeping the measured, the newer and the copy's own, and saying each
1061
+ function updateRules(name) {
1062
+ plainName(name, 'rule set name');
1063
+ const u = updateSet(name),
1064
+ rel = `rules/${name}.json`;
1065
+ if (!u.copy) {
1066
+ const text = `no ${rel} in this workspace: the first design to use ${name} copies in the kit's as it is then`;
1067
+ return console.log(opt('json') ? JSON.stringify({ set: name, file: null, updated: false, text }, null, 2) : text);
1068
+ }
1069
+ const d = u.difference,
1070
+ taken = d.changed.length + d.refreshed.length + d.added.length + u.fields.length > 0,
1071
+ dry = !!opt('dry-run'),
1072
+ said = (v) => (typeof v === 'number' || typeof v === 'string' ? String(v) : JSON.stringify(v)),
1073
+ was = (k) => `${said(u.copy.rules[k]?.value)} here, ${said(u.kit.rules[k]?.value)} in the kit's`;
1074
+ if (taken && !dry) {
1075
+ insideWorkspace(u.file); // (never written through a link out of rules/)
1076
+ fs.writeFileSync(u.file, JSON.stringify(u.set, null, 2) + '\n');
1077
+ }
1078
+ if (opt('json'))
1079
+ return console.log(
1080
+ JSON.stringify(
1081
+ {
1082
+ set: name,
1083
+ file: rel,
1084
+ updated: taken && !dry,
1085
+ ...(dry ? { dryRun: true } : {}),
1086
+ changed: d.changed.map((k) => ({ rule: k, from: u.copy.rules[k]?.value, to: u.kit.rules[k]?.value })),
1087
+ added: d.added,
1088
+ refreshed: d.refreshed,
1089
+ fields: u.fields,
1090
+ kept: { measured: d.measured, newer: d.newer, own: d.own },
1091
+ },
1092
+ null,
1093
+ 2,
1094
+ ),
1095
+ );
1096
+ const lines = [
1097
+ ...d.changed.map(
1098
+ (k) =>
1099
+ ` ${k}: ${said(u.copy.rules[k]?.value)} → ${said(u.kit.rules[k]?.value)} (the kit's, ${u.kit.rules[k].kind ?? 'no kind'}, checked ${u.kit.rules[k].checked})`,
1100
+ ),
1101
+ ...(d.added.length ? [` added from the kit's: ${d.added.join(', ')}`] : []),
1102
+ ...(d.refreshed.length
1103
+ ? [
1104
+ ` the same figure, with what the kit's adds or has newer (its source, words, date or range): ${d.refreshed.join(', ')}`,
1105
+ ]
1106
+ : []),
1107
+ ...(u.fields.length ? [` the set's own fields, as the kit's: ${u.fields.join(', ')}`] : []),
1108
+ ...(d.measured.length ? [` kept as measured: ${d.measured.map((k) => `${k} (${was(k)})`).join(', ')}`] : []),
1109
+ ...(d.newer.length
1110
+ ? [` kept as yours, checked on or after the kit's date: ${d.newer.map((k) => `${k} (${was(k)})`).join(', ')}`]
1111
+ : []),
1112
+ ...(d.own.length ? [` kept, the kit has none: ${d.own.join(', ')}`] : []),
1113
+ ];
1114
+ console.log(
1115
+ taken
1116
+ ? `${dry ? 'would update' : 'updated'} ${rel} from the kit's ${name}${dry ? ' (--dry-run: nothing written)' : ''}:`
1117
+ : `${rel} is up to date with the kit's ${name}${lines.length ? ':' : ''}`,
1118
+ );
1119
+ for (const l of lines) console.log(l);
1120
+ }
1121
+
1025
1122
  // cad rules check / draw / draft: rule sets themselves, not a design's use of them
1026
1123
  function ruleSheets(what, names) {
1027
1124
  if (what === 'check') {
@@ -1066,6 +1163,7 @@ function ruleSheets(what, names) {
1066
1163
  throw new Error(
1067
1164
  `usage: cad rules ${what} <set>${what === 'draft' ? ` --from <file.pdf>, or cad rules draft ${draftParts().join('|')} <name>` : ''}`,
1068
1165
  );
1166
+ if (what === 'update') return updateRules(name);
1069
1167
  if (what === 'draw') {
1070
1168
  const to = opt('out') || `${name}.svg`;
1071
1169
  fs.writeFileSync(to, drawSet(name));
@@ -1135,7 +1233,7 @@ async function main() {
1135
1233
  return edited(r, 'new', {}, `${r.dryRun ? 'would make' : 'made'} projects/${project}/objects/${name}.{js,json}`);
1136
1234
  }
1137
1235
 
1138
- if (cmd === 'rules' && ['check', 'draw', 'draft'].includes(ref)) return ruleSheets(ref, pos.slice(2));
1236
+ if (cmd === 'rules' && ['check', 'draw', 'draft', 'update'].includes(ref)) return ruleSheets(ref, pos.slice(2));
1139
1237
 
1140
1238
  if (cmd === 'trust') {
1141
1239
  // this workspace may do what its cad.config.json asks (designs outside the sandbox, its own targets)
@@ -1155,7 +1253,7 @@ async function main() {
1155
1253
  // An AGENTS.md as cad agents last wrote it (or, with no record of that, one that is an earlier copy of ours) is
1156
1254
  // brought up to date; one edited here is kept, unless --force
1157
1255
  const mine = fs.existsSync(to) ? fs.readFileSync(to, 'utf8') : null,
1158
- last = fs.existsSync(record) ? fs.readFileSync(record, 'utf8') : null;
1256
+ last = cached(record) ? fs.readFileSync(record, 'utf8') : null; // (never read through a link out)
1159
1257
  const ourCopy =
1160
1258
  mine === null || mine === ours || (last !== null ? mine === last : mine.startsWith(ours.split('\n')[0]));
1161
1259
  if (!ourCopy && !opt('force'))
@@ -1163,8 +1261,7 @@ async function main() {
1163
1261
  "AGENTS.md here has been edited (or isn't rulecad's): it is kept as it is (cad agents --force replaces it)",
1164
1262
  );
1165
1263
  fs.writeFileSync(to, ours);
1166
- fs.mkdirSync(path.dirname(record), { recursive: true });
1167
- fs.writeFileSync(record, ours);
1264
+ writeCacheFile(record, ours);
1168
1265
  const claude = path.join(WS, 'CLAUDE.md');
1169
1266
  if (!fs.existsSync(claude)) fs.writeFileSync(claude, '@AGENTS.md\n');
1170
1267
  else if (!fs.readFileSync(claude, 'utf8').includes('@AGENTS.md')) fs.appendFileSync(claude, '\n@AGENTS.md\n');
@@ -1237,11 +1334,20 @@ async function main() {
1237
1334
  pictures: !opt('no-pictures'),
1238
1335
  });
1239
1336
  }
1337
+ if (cmd === 'coupons') return couponsCommand();
1338
+ // (cad measured with no assembly: --export, or a figure written as it is; cad history alone: those figures)
1339
+ if (cmd === 'measured' && !ref) return measuredCommand(null);
1340
+ if (cmd === 'history' && !ref) return history(null);
1240
1341
  if (!ref || (cmd === 'add' && !pos[2])) throw new Error(`usage: cad ${cmd} ${USAGE[cmd] || '<project>/<object>'}`);
1241
1342
  if (cmd === 'release')
1242
1343
  return ref.includes('/') ? releaseObject(locate(ref)) : opt('all') ? releaseAll(ref) : releaseProject(ref);
1243
1344
  if (cmd === 'variants') return variants(locate(ref));
1244
1345
  if (cmd === 'compare') return compareVariants(locate(ref), pos[2], pos[3]);
1346
+ // These build an assembly as its file says: a --set would be passed over, so it is refused by name
1347
+ if (opt('set') !== undefined && ['measured', 'frame', 'machine', 'plot', 'plates', 'order', 'kit'].includes(cmd))
1348
+ throw new Error(
1349
+ `cad ${cmd} builds ${ref} as its file says and takes no --set: try the value with cad check ${ref} --set <item>.<variable>=<value>, then write it into the file with cad set`,
1350
+ );
1245
1351
  if (cmd === 'measured') return measuredCommand(ref);
1246
1352
  if (cmd === 'list' || cmd === 'wires' || cmd === 'beams') return listCommand(cmd, ref);
1247
1353
  if (cmd === 'frame') return frameCommand(ref);
@@ -1390,7 +1496,12 @@ async function main() {
1390
1496
  : await printChecks(b, d)),
1391
1497
  ...(b.mechanism?.findings || []), // a lamina mechanism's own: it prints free, stops, holds, clears in every state
1392
1498
  ...(b.fixings || []), // what v.fixings drew: each hole and seat, what it was drawn to and the rule it rests on
1499
+ ...(b.seats || []), // what v.shapes' seat helpers drew (a shaft's bore, a bearing's pocket), as v.fixings's
1393
1500
  ...(await analyses(b, d, tag)),
1501
+ // what rests on estimates, as an assembly's check says it (an object's check is where one looks first)
1502
+ ...[estimatesFinding([b], { ref: `${d.project}/${d.name}` })]
1503
+ .filter(Boolean)
1504
+ .map(({ short, ...x }) => ({ ...x, card: short })),
1394
1505
  ],
1395
1506
  {
1396
1507
  object: `${d.project}/${d.name}`,
@@ -1525,10 +1636,16 @@ async function editVariables(ref) {
1525
1636
  throw new Error(
1526
1637
  `--${extra.rule ? 'rule' : 'label'} describes one variable: set ${pairs.map((p) => p.split('=')[0]).join(' and ')} one at a time`,
1527
1638
  );
1639
+ // each value read by its variable's kind: text stays as typed (a legend 007), a number where the variable is one
1640
+ const vars = readObject(locate(ref)).variables || {};
1528
1641
  const changes = Object.fromEntries(
1529
1642
  pairs.map((p) => {
1530
- const i = p.indexOf('=');
1531
- return [p.slice(0, i).trim(), { value: parseValue(p.slice(i + 1).trim()), ...extra }];
1643
+ const i = p.indexOf('='),
1644
+ name = p.slice(0, i).trim();
1645
+ return [
1646
+ name,
1647
+ { value: valueFor(Object.hasOwn(vars, name) ? vars[name] : undefined, p.slice(i + 1).trim()), ...extra },
1648
+ ];
1532
1649
  }),
1533
1650
  );
1534
1651
  const r = await setVariables(ref, changes, { create: !!opt('new'), dryRun: !!opt('dry-run') });
@@ -1536,6 +1653,21 @@ async function editVariables(ref) {
1536
1653
  console.log(`${r.dryRun ? `dry run, nothing written: would set` : 'set'} ${r.changed.join(', ')} in ${rel(r.file)}`);
1537
1654
  }
1538
1655
 
1656
+ // cad add item --object tray --set legend=007: each value read by the object's variable's kind, as cad set reads it
1657
+ // (text stays as typed); an object that can't be read yet leaves the values as parseValue reads them
1658
+ function itemSet(ref) {
1659
+ let vars = {};
1660
+ try {
1661
+ if (typeof opt('object') === 'string')
1662
+ vars = readObject(locateIn(ref.split('/')[0], String(opt('object')).split(/[:@]/)[0])).variables || {};
1663
+ } catch {
1664
+ // (no such object: cad add names it when it checks the item)
1665
+ }
1666
+ return Object.fromEntries(
1667
+ Object.entries(sets()).map(([k, v]) => [k, valueFor(Object.hasOwn(vars, k) ? vars[k] : undefined, v)]),
1668
+ );
1669
+ }
1670
+
1539
1671
  // cad add fit|joint|item|loop|pose|fasten|join <project>/<assembly> --key value …: add to an assembly, keeping its layout
1540
1672
  async function editAssembly(what, ref) {
1541
1673
  const list = (k) =>
@@ -1591,9 +1723,7 @@ async function editAssembly(what, ref) {
1591
1723
  ...text(['id', 'object', 'assembly', 'variant']),
1592
1724
  ...at(),
1593
1725
  ...(list('rotate') ? { rotate: list('rotate') } : {}),
1594
- ...(typeof opt('set') === 'string'
1595
- ? { set: Object.fromEntries(sets() && Object.entries(sets()).map(([k, v]) => [k, parseValue(v)])) }
1596
- : {}),
1726
+ ...(typeof opt('set') === 'string' ? { set: itemSet(ref) } : {}),
1597
1727
  };
1598
1728
  else if (what === 'loop') entry = text(['a', 'b', 'label']);
1599
1729
  else if (what === 'fasten' && opt('from-fits')) {
@@ -1735,29 +1865,37 @@ async function newCommand(ref) {
1735
1865
  );
1736
1866
  let frame;
1737
1867
  // the frame's options go with --frame, and a join's fitting and screw with --join: none is dropped unsaid
1738
- const FRAME_OPTS = ['inside', 'outside', 'profile', 'join', 'fitting', 'screw', 'feet', 'caps'],
1868
+ const FRAME_OPTS = ['inside', 'outside', 'profile', 'join', 'fitting', 'screw', 'estimate', 'feet', 'caps'],
1739
1869
  loose = FRAME_OPTS.filter((k) => opt(k) !== undefined);
1740
1870
  if (!opt('frame') && loose.length)
1741
1871
  throw new Error(
1742
1872
  `--${loose.join(', --')} ${loose.length === 1 ? 'is a frame option' : 'are frame options'}: give --frame box|portal|table|gantry|shelf with ${loose.length === 1 ? 'it' : 'them'}, or set the fields after with cad set ${ref} frame.<field>=…`,
1743
1873
  );
1744
- if (opt('frame') && !str('join') && (str('fitting') || str('screw')))
1874
+ const how = ['fitting', 'screw', 'estimate'].filter((k) => opt(k) !== undefined);
1875
+ if (opt('frame') && !str('join') && how.length)
1745
1876
  throw new Error(
1746
- `--${['fitting', 'screw'].filter((k) => str(k)).join(' and --')} ${str('fitting') && str('screw') ? 'say' : 'says'} how the join is made: give the join's kind with ${str('fitting') && str('screw') ? 'them' : 'it'}, as --join blind`,
1877
+ `--${how.join(' and --')} ${how.length > 1 ? 'say' : 'says'} how the join is made: give the join's kind with ${how.length > 1 ? 'them' : 'it'}, as --join blind`,
1747
1878
  );
1748
1879
  if (opt('frame')) {
1749
- const nums = (k) =>
1750
- str(k)
1751
- ? str(k)
1752
- .split(',')
1753
- .map((x) => parseValue(x.trim()))
1754
- : undefined;
1880
+ // a size is numbers in mm, one for each of the frame's sides, as 300,300,350
1881
+ const nums = (k) => {
1882
+ if (opt(k) === undefined) return undefined;
1883
+ const v = str(k)
1884
+ ?.split(',')
1885
+ .map((x) => parseValue(x.trim()));
1886
+ if (!v?.length || !v.every((x) => typeof x === 'number' && Number.isFinite(x)))
1887
+ throw new Error(
1888
+ `--${k} is numbers in mm, the frame's width, depth and height, as --${k} 300,300,350 (a portal's width and height, as 500,400) (got ${JSON.stringify(opt(k))})`,
1889
+ );
1890
+ return v;
1891
+ };
1755
1892
  const join =
1756
- str('join') && (str('fitting') || str('screw'))
1893
+ str('join') && how.length
1757
1894
  ? {
1758
1895
  kind: str('join'),
1759
1896
  ...(str('fitting') ? { fitting: str('fitting') } : {}),
1760
1897
  ...(str('screw') ? { screw: str('screw') } : {}),
1898
+ ...(opt('estimate') ? { estimate: true } : {}),
1761
1899
  }
1762
1900
  : str('join');
1763
1901
  frame = Object.fromEntries(
@@ -1998,9 +2136,13 @@ async function board(cmd, d, b, { title, version, tag }) {
1998
2136
  // ---------- assemblies ----------
1999
2137
  async function assembly(cmd, ref) {
2000
2138
  const pose = typeof opt('pose') === 'string' ? opt('pose') : undefined;
2001
- const s = await buildAssembly(ref, [], {}, { pose, progress: showProgress }),
2139
+ // --set item.variable=value: that item built at the value (an unknown item or variable is refused by name)
2140
+ const set = sets(),
2141
+ overrides = assemblyOverrides(ref, set),
2142
+ setTag = suffix(set); // (in file names, as an object's)
2143
+ const s = await buildAssembly(ref, [], overrides, { pose, progress: showProgress }),
2002
2144
  a = s.a,
2003
- title = `${a.title || s.name}${pose ? ` (${pose})` : ''}`;
2145
+ title = `${a.title || s.name}${pose ? ` (${pose})` : ''}${setTag ? ` (${setTag.slice(1)})` : ''}`;
2004
2146
  const versions = [...new Map(s.objects.map((o) => [o.objName, `${o.objName} ${o.version}`])).values()].join(', ');
2005
2147
  const rules = (ns) => Object.fromEntries(Object.keys(loadRuleSet(ns).rules).map((k) => [k, s.num(`${ns}.${k}`)]));
2006
2148
  const printed = s.parts.filter((p) => p.role !== 'reference');
@@ -2034,7 +2176,7 @@ async function assembly(cmd, ref) {
2034
2176
  if (!s.gait) {
2035
2177
  // a motor turning what it drives: the gears cut across their shafts, the load's part turning with them
2036
2178
  const { driveSvg } = await import('../lib/drive.mjs'),
2037
- out = paths.preview(s.project, `${s.name}-drive.svg`);
2179
+ out = paths.preview(s.project, `${s.name}${setTag}-drive.svg`);
2038
2180
  fs.mkdirSync(path.dirname(out), { recursive: true });
2039
2181
  fs.writeFileSync(out, driveSvg(s, { title, ...(opt('turns') ? { turns: Number(opt('turns')) } : {}) }));
2040
2182
  return console.log(out);
@@ -2044,8 +2186,8 @@ async function assembly(cmd, ref) {
2044
2186
  r = framesOf(s);
2045
2187
  if (!r.frames.length)
2046
2188
  throw new Error(`${ref}'s gait has nothing to play: ${r.findings.map((x) => x.text).join('; ')}`);
2047
- const svg = paths.preview(s.project, `${s.name}-gait.svg`),
2048
- json = paths.preview(s.project, `${s.name}-gait.json`);
2189
+ const svg = paths.preview(s.project, `${s.name}${setTag}-gait.svg`),
2190
+ json = paths.preview(s.project, `${s.name}${setTag}-gait.json`);
2049
2191
  fs.mkdirSync(path.dirname(svg), { recursive: true });
2050
2192
  fs.writeFileSync(
2051
2193
  svg,
@@ -2059,7 +2201,7 @@ async function assembly(cmd, ref) {
2059
2201
  const check = !!opt('check'); // the check view: each motor's torque labelled at its joints, never on the rest view
2060
2202
  const out = paths.preview(
2061
2203
  s.project,
2062
- `${s.name}${pose ? `-${pose}` : ''}${opt('explode') ? '-exploded' : ''}${check ? '-check' : ''}.png`,
2204
+ `${s.name}${pose ? `-${pose}` : ''}${setTag}${opt('explode') ? '-exploded' : ''}${check ? '-check' : ''}.png`,
2063
2205
  );
2064
2206
  let marks = null;
2065
2207
  if (check) {
@@ -2109,7 +2251,7 @@ async function assembly(cmd, ref) {
2109
2251
  throw new Error(
2110
2252
  `${ref} is a fit assembly, for checking: export its objects, or make a plate (kind: plate) to print them together`,
2111
2253
  );
2112
- const out = paths.exports(s.project, `${s.name}.3mf`);
2254
+ const out = paths.exports(s.project, `${s.name}${setTag}.3mf`);
2113
2255
  fs.mkdirSync(path.dirname(out), { recursive: true });
2114
2256
  // One object per printed thing (a keycap with its legend and supports), a part per part, each in its filament
2115
2257
  const fil = filaments(s.project),
@@ -2137,6 +2279,12 @@ async function assembly(cmd, ref) {
2137
2279
  noRules: !!opt('no-rules'),
2138
2280
  steps: opt('no-steps') ? false : opt('steps'),
2139
2281
  });
2282
+ // built with --set: the link says so, as an object's does (a.width=80,b.depth=20), and its downloads are named with it
2283
+ if (Object.keys(set).length)
2284
+ model.set = Object.entries(set)
2285
+ .map(([k, v]) => `${k}=${v}`)
2286
+ .join(',')
2287
+ .replace(/[^\w.=+,-]/g, '_');
2140
2288
  if (model.steps)
2141
2289
  say(
2142
2290
  `carries the drawing ${model.steps.name ?? '(unnamed)'} (${model.steps.b.length} blocks; --no-steps to leave it out)`,
@@ -2156,7 +2304,7 @@ async function assembly(cmd, ref) {
2156
2304
  if (cmd === 'show') {
2157
2305
  // Each shape once, placed for every copy: nine keys cost one keycap in the mirror's link. Built with each object's
2158
2306
  // mirror settings (fewer segments), so the display gets a lighter mesh; checks and links use the real one
2159
- const m = await buildAssembly(ref, [], {}, { mirror: true, pose });
2307
+ const m = await buildAssembly(ref, [], overrides, { mirror: true, pose });
2160
2308
  const placed = shapes(m.parts.filter((p) => p.role !== 'support' && p.mirror !== false));
2161
2309
  // The card: what the checks found, one short line each
2162
2310
  const items = checkAssembly(s)
@@ -2213,11 +2361,11 @@ async function shorten(l) {
2213
2361
  const token = l.view.split('#m=')[1],
2214
2362
  hash = (await import('node:crypto')).createHash('sha256').update(token).digest('hex').slice(0, 16);
2215
2363
  const file = paths.cache('links.json'),
2216
- cache = cached(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
2364
+ kept = readCacheJson(file),
2365
+ cache = kept && typeof kept === 'object' && !Array.isArray(kept) ? kept : {};
2217
2366
  if (!cache[hash]) {
2218
2367
  cache[hash] = await (await target('shorten'))(token, { desc: `model: ${l.src}` });
2219
- fs.mkdirSync(path.dirname(file), { recursive: true });
2220
- fs.writeFileSync(file, JSON.stringify(cache, null, 2));
2368
+ writeCacheFile(file, JSON.stringify(cache, null, 2));
2221
2369
  }
2222
2370
  const url = `${VIEW}#s=${cache[hash]}`;
2223
2371
  return { ...l, view: url, stl: `${url}&get=stl`, '3mf': `${url}&get=3mf`, short: true };
@@ -2250,11 +2398,11 @@ async function printLinks(l) {
2250
2398
  // keyboard is megabytes: in a terminal or an agent's context it's only noise)
2251
2399
  if (!l.short && !opt('long')) {
2252
2400
  const f = paths.cache('links', `${l.src.replace(/[^\w@.+-]+/g, '-')}.txt`);
2253
- fs.mkdirSync(path.dirname(f), { recursive: true });
2254
- fs.writeFileSync(f, `view ${l.view}\nstl ${l.stl}\n3mf ${l['3mf']}\n`);
2255
- return console.log(
2256
- ` links in ${path.relative(WS, f)} (--md: one ${hasTarget('shorten') ? 'short ' : ''}link for chat; --long: print them)`,
2257
- );
2401
+ // (where .cache/links can't be written, a link in a cloned workspace's .cache, the links are printed instead)
2402
+ if (writeCacheFile(f, `view ${l.view}\nstl ${l.stl}\n3mf ${l['3mf']}\n`))
2403
+ return console.log(
2404
+ ` links in ${path.relative(WS, f)} (--md: one ${hasTarget('shorten') ? 'short ' : ''}link for chat; --long: print them)`,
2405
+ );
2258
2406
  }
2259
2407
  console.log(` view ${l.view}`);
2260
2408
  console.log(` stl ${l.stl}`);
@@ -2266,44 +2414,162 @@ const KINDS = ['patch', 'minor', 'major'];
2266
2414
  const today = () => new Date().toISOString().slice(0, 10);
2267
2415
 
2268
2416
  // Unreleased changes: compare with the last release. -> { last, kind, reasons } (kind null: nothing changed)
2269
- // A design that reads other objects is resolved with their numbers (each side with the objects it named then).
2270
- const snap = async (d) => snapshot(d, (await objectSets(d, readObject(d))).sets);
2417
+ // A design that reads other objects is resolved with their numbers (each side with the objects it named then: a
2418
+ // release with them as its tag holds them). And the files it read besides its own (`reads`, as the release recorded
2419
+ // them: its helpers, and the rule sets v.fixings and v.frames read) are compared file by file, the design now with
2420
+ // the same files as the release, so an edited helper or thread set counts as a change.
2421
+ const snap = async (d, reads) =>
2422
+ snapshot(d, (await objectSets(d, readObject(d))).sets, reads ? readTexts(d, reads) : null);
2271
2423
  async function since(d) {
2272
2424
  const last = tags(d.project, d.name).at(-1);
2273
2425
  if (!last) return { last: null, kind: 'first', reasons: [] };
2274
- return { last, ...compare(await snap(materialise(d, last.version)), await snap(d)) };
2426
+ const was = materialise(d, last.version);
2427
+ return { last, ...compare(await snap(was, was.reads), await snap(d, was.reads)) };
2275
2428
  }
2276
2429
 
2277
2430
  // Only the design's own files (and its project's changelog and print log) may have uncommitted changes.
2278
2431
  // A release commits only its own files, so other work in progress can stay as it is (another object, an assembly, the
2279
2432
  // docs). What it can't release past is uncommitted shared code (lib/, bin/) or a rule or layout it uses: those would
2280
2433
  // be in the build but not in the release.
2434
+ // git names the files from the repository's root, which may be above the workspace (a workspace in a folder of a larger
2435
+ // repository): only the workspace's own files are asked for (-- .), and named from the workspace.
2281
2436
  function onlyChanged(allowed) {
2282
- const dirty = git('status', '--porcelain', '--untracked-files=all')
2437
+ let porcelain, prefix;
2438
+ try {
2439
+ porcelain = git('status', '--porcelain', '--untracked-files=all', '--', '.');
2440
+ prefix = git('rev-parse', '--show-prefix');
2441
+ } catch (e) {
2442
+ if (/not a git repository/.test(e.stderr || e.message)) return; // (a dry run outside git: a release is refused first)
2443
+ throw e;
2444
+ }
2445
+ const dirty = porcelain
2283
2446
  .split('\n')
2284
2447
  .filter(Boolean)
2285
- .map((l) => l.slice(3).replace(/^"|"$/g, ''));
2448
+ .map((l) => l.slice(3).replace(/^"|"$/g, ''))
2449
+ .map((f) => (f.startsWith(prefix) ? f.slice(prefix.length) : f));
2286
2450
  const shared = dirty.filter((f) => !allowed.includes(f) && /^(lib|bin)\//.test(f));
2287
2451
  if (shared.length)
2288
2452
  throw new Error(`commit shared code first (the release would build with it): ${shared.join(', ')}`);
2289
2453
  }
2290
2454
 
2291
- function commitAndTag(paths, subject, tag, message) {
2292
- git('add', '--', ...paths);
2293
- git('commit', '-q', '-m', subject, ...(opt('trailer') ? ['--trailer', opt('trailer')] : []), '--', ...paths); // only these, whatever else is staged
2294
- git('tag', '-a', tag, '-m', message);
2295
- if (opt('push')) {
2296
- git('push', '-q', 'origin', 'HEAD');
2297
- git('push', '-q', 'origin', tag);
2455
+ // A release is a git commit and a tag, so before anything is written: git is there, the workspace is in a repository,
2456
+ // and git has a name and email address to put on the commit. Each missing one is said in plain words, with what to run.
2457
+ function releasable() {
2458
+ try {
2459
+ git('rev-parse', '--is-inside-work-tree');
2460
+ } catch (e) {
2461
+ if (e.code === 'ENOENT')
2462
+ throw new Error(
2463
+ 'not released: a release is kept in git (a commit and a tag), and git is not installed on this computer. Install it (https://git-scm.com), then release again',
2464
+ );
2465
+ throw new Error(
2466
+ `not released: a release is kept in git (a commit and a tag), and ${WS} is not a git repository yet. Make it one and commit your designs (git init, then git add -A and git commit -m "My designs"), then release again`,
2467
+ );
2468
+ }
2469
+ try {
2470
+ git('var', 'GIT_AUTHOR_IDENT');
2471
+ git('var', 'GIT_COMMITTER_IDENT');
2472
+ } catch {
2473
+ throw new Error(
2474
+ 'not released: git has no name and email address to put on the release. Run git config user.name "Your Name" and git config user.email "you@example.com" (add --global to use them in every repository), then release again',
2475
+ );
2476
+ }
2477
+ }
2478
+
2479
+ // What git said when it refused, without its hints: the hook's own words, or git's reason
2480
+ const gitSaid = (e) =>
2481
+ String(e.stderr || e.stdout || e.message)
2482
+ .split('\n')
2483
+ .map((l) => l.trim().replace(/^(fatal|error): /, ''))
2484
+ .filter((l) => l && !/^hint:/.test(l) && !/^Command failed/.test(l))
2485
+ .join('; ')
2486
+ .replace(/\.$/, '') || 'no reason given';
2487
+
2488
+ // The files a release is about to change, as they are now (null: not there yet), to put back if git refuses it
2489
+ const keep = (list) => new Map(list.map((f) => [f, fs.existsSync(f) ? readOwnText(f) : null]));
2490
+
2491
+ // Commit the release's files and tag the commit. If git refuses either (a hook that fails, a tag that can't be
2492
+ // signed), everything is put back as it was before the release: the commit (if it was made), what was staged, and the
2493
+ // files in kept (its version and changelog), so that the release can simply be run again.
2494
+ function commitAndTag(paths, subject, tag, message, kept) {
2495
+ const head = (() => {
2496
+ try {
2497
+ return git('rev-parse', '--verify', '-q', 'HEAD');
2498
+ } catch {
2499
+ return null; // (a repository with no commit yet)
2500
+ }
2501
+ })();
2502
+ let index = null;
2503
+ try {
2504
+ index = git('write-tree'); // what is staged now, to stage again
2505
+ } catch {
2506
+ // (an index git can't write as a tree: the release's files are unstaged instead)
2298
2507
  }
2508
+ let step = 'commit';
2509
+ try {
2510
+ git('add', '--', ...paths);
2511
+ git('commit', '-q', '-m', subject, ...(opt('trailer') ? ['--trailer', opt('trailer')] : []), '--', ...paths); // only these, whatever else is staged
2512
+ step = 'tag';
2513
+ git('tag', '-a', tag, '-m', message);
2514
+ } catch (e) {
2515
+ let undone = true;
2516
+ try {
2517
+ if (step === 'tag') head ? git('reset', '-q', '--soft', head) : git('update-ref', '-d', 'HEAD');
2518
+ if (index) git('read-tree', index);
2519
+ else if (head) git('reset', '-q', '--', ...paths);
2520
+ else git('rm', '-q', '--cached', '--ignore-unmatch', '--', ...paths);
2521
+ } catch {
2522
+ undone = false;
2523
+ }
2524
+ for (const [f, text] of kept) text == null ? fs.rmSync(f, { force: true }) : fs.writeFileSync(f, text);
2525
+ throw new Error(
2526
+ `not released: git refused the release's ${step} (${gitSaid(e)}). ${
2527
+ undone
2528
+ ? 'Your files are as they were before the release'
2529
+ : `Your files are as they were before the release, but git's own record may not be: see git status${step === 'tag' ? ' and git log' : ''}`
2530
+ }. Put that right, then release again`,
2531
+ );
2532
+ }
2533
+ if (opt('push'))
2534
+ try {
2535
+ git('push', '-q', 'origin', 'HEAD');
2536
+ git('push', '-q', 'origin', tag);
2537
+ } catch (e) {
2538
+ throw new Error(
2539
+ `released and tagged ${tag} here, but not pushed: git said ${gitSaid(e)}. Push it when you can: git push --follow-tags`,
2540
+ );
2541
+ }
2299
2542
  }
2300
2543
 
2544
+ // Add a release's entry at the top of its project's changelog. An entry for the same name and version that was never
2545
+ // committed (left by a release that went wrong part way) is replaced, never repeated. One that was committed is a real
2546
+ // release and stays: an object named as its project (lamp/lamp) has entries headed as the project's own (lamp 0.1.0).
2301
2547
  function changelog(dir, heading, message, reasons) {
2302
2548
  const f = path.join(dir, 'CHANGELOG.md');
2303
- const old = fs.existsSync(insideWorkspace(f)) ? readOwnText(f).replace(/^# .*\n+/, '') : '';
2549
+ const same = `## ${heading.slice(0, heading.indexOf(' ('))} (`,
2550
+ logFile = path.relative(WS, f).split(path.sep).join('/');
2551
+ const entries = (text) => text.replace(/^# .*\n+/, '').split(/^(?=## )/m);
2552
+ const committed = new Map(); // heading -> how many committed entries have it
2553
+ try {
2554
+ for (const e of entries(git('show', `HEAD:./${logFile}`)))
2555
+ if (e.startsWith(same)) committed.set(e.split('\n')[0], (committed.get(e.split('\n')[0]) || 0) + 1);
2556
+ } catch {
2557
+ // (no commit yet, or the changelog was never committed: every entry for this release is a leftover)
2558
+ }
2559
+ const old = fs.existsSync(insideWorkspace(f))
2560
+ ? entries(readOwnText(f))
2561
+ .filter((e) => {
2562
+ if (!e.startsWith(same)) return true;
2563
+ const h = e.split('\n')[0],
2564
+ n = committed.get(h) || 0;
2565
+ committed.set(h, n - 1);
2566
+ return n > 0;
2567
+ })
2568
+ .join('')
2569
+ : '';
2304
2570
  const entry = `## ${heading}\n\n${message}\n${reasons.length ? `\n${reasons.map((r) => `- ${r.text} (${r.kind})`).join('\n')}\n` : ''}`;
2305
2571
  fs.writeFileSync(f, `# ${path.basename(dir)} changelog\n\n${entry}\n${old}`);
2306
- return path.relative(WS, f).split(path.sep).join('/'); // (git's terms: forward slashes)
2572
+ return logFile; // (git's terms: forward slashes)
2307
2573
  }
2308
2574
 
2309
2575
  // An object's print checks: printcheck's, and for parts printed in place, theirs (lib/inplace.mjs)
@@ -2352,18 +2618,25 @@ async function releaseObject(d, { batch = false } = {}) {
2352
2618
  for (const r of reasons) console.log(` ${r.kind.padEnd(5)} ${r.text}`);
2353
2619
  if (opt('dry-run')) return;
2354
2620
  const allowed = [
2355
- ...files(d, object),
2621
+ ...files(d, object, b),
2356
2622
  `projects/${d.project}/CHANGELOG.md`,
2357
2623
  path.relative(WS, printsFile(d)).split(path.sep).join('/'),
2358
2624
  ];
2359
- if (!batch) onlyChanged(allowed); // releaseAll checked the whole tree first
2625
+ if (!batch) {
2626
+ releasable(); // releaseAll checked these first
2627
+ onlyChanged(allowed);
2628
+ }
2629
+ const kept = keep([d.json, path.join(d.dir, 'CHANGELOG.md')]);
2360
2630
  fs.writeFileSync(d.json, setAt(readOwnText(d.json), ['version'], version)); // the object's own version (added, if it had none), nothing else
2361
2631
  const log = changelog(d.dir, `${d.name} ${version} (${kind}), ${today()}`, message, reasons);
2632
+ // (the tag records what the build read besides the design's own files: lib/versions.mjs readsLine)
2633
+ const notes = [b.circuit ? `engine: ${engineId()}` : '', readsLine(b)].filter(Boolean);
2362
2634
  commitAndTag(
2363
- [...files(d, object), log].filter((f) => fs.existsSync(path.join(WS, f))),
2635
+ [...files(d, object, b), log].filter((f) => fs.existsSync(path.join(WS, f))),
2364
2636
  `${tag}: ${message}`,
2365
2637
  tag,
2366
- `${kind}: ${message}${b.circuit ? `\n\nengine: ${engineId()}` : ''}`,
2638
+ `${kind}: ${message}${notes.length ? `\n\n${notes.join('\n')}` : ''}`,
2639
+ kept,
2367
2640
  );
2368
2641
  console.log(`tagged ${tag}${opt('push') ? ' and pushed' : ' (not pushed: --push, or git push --follow-tags)'}`);
2369
2642
  }
@@ -2435,20 +2708,22 @@ async function releaseProject(project) {
2435
2708
  .join(', ')}`,
2436
2709
  );
2437
2710
  if (opt('dry-run')) return;
2711
+ releasable();
2438
2712
  onlyChanged([
2439
2713
  `projects/${project}/project.json`,
2440
2714
  `projects/${project}/CHANGELOG.md`,
2441
2715
  `projects/${project}/prints.jsonl`,
2442
2716
  ]);
2443
- p.version = version;
2444
- p.release = manifest;
2445
- fs.writeFileSync(pj, JSON.stringify(p, null, 2) + '\n');
2717
+ const kept = keep([pj, path.join(dir, 'CHANGELOG.md')]);
2718
+ // The release's version and the versions of its objects (fields of the project schema), the rest of the file as it was
2719
+ fs.writeFileSync(pj, setAt(setAt(readOwnText(pj), ['version'], version), ['release'], manifest));
2446
2720
  const log = changelog(dir, `${project} ${version} (${kind}), ${today()}`, message, reasons);
2447
2721
  commitAndTag(
2448
2722
  [`projects/${project}/project.json`, log],
2449
2723
  `${project}@${version}: ${message}`,
2450
2724
  `${project}@${version}`,
2451
2725
  `${kind}: ${message}\n\n${JSON.stringify(manifest)}`,
2726
+ kept,
2452
2727
  );
2453
2728
  console.log(`tagged ${project}@${version}`);
2454
2729
  }
@@ -2465,8 +2740,9 @@ async function releaseAll(project) {
2465
2740
  `projects/${project}/project.json`,
2466
2741
  `projects/${project}/CHANGELOG.md`,
2467
2742
  `projects/${project}/prints.jsonl`,
2468
- ...changed.flatMap((d) => files(d, readObject(d))),
2469
2743
  ]);
2744
+ for (const d of changed) for (const f of files(d, readObject(d), await build(d))) allowed.add(f);
2745
+ if (!opt('dry-run')) releasable(); // (before any object is released)
2470
2746
  onlyChanged([...allowed]);
2471
2747
  for (const d of changed) await releaseObject(d, { batch: true });
2472
2748
  if (!opt('dry-run')) await releaseProject(project);
@@ -2935,7 +3211,7 @@ async function frameCommand(ref) {
2935
3211
  async function listCommand(what, ref) {
2936
3212
  if (!isAssembly(ref))
2937
3213
  throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
2938
- const s = await buildAssembly(ref);
3214
+ const s = await buildAssembly(ref, [], assemblyOverrides(ref, sets())); // (--set item.variable=value, as cad check)
2939
3215
  if (what === 'list') {
2940
3216
  const { shoppingList, listText } = await import('../lib/list.mjs'),
2941
3217
  l = shoppingList(s);
@@ -3015,9 +3291,46 @@ async function listCommand(what, ref) {
3015
3291
  say(path.relative(WS, file));
3016
3292
  }
3017
3293
 
3294
+ // cad coupons: the kit's coupons as a project of this workspace's own, projects/coupons, with the MEASURE.md that says
3295
+ // how to read each and the cad measured command that writes it back. Copied, never linked: the maker prints and keeps
3296
+ // them as they are, and a workspace that has the project already keeps it (a newer kit's comes in under another name)
3297
+ function couponsCommand() {
3298
+ const to = paths.project('coupons'),
3299
+ from = path.join(TOOL, 'templates', 'coupons');
3300
+ if (fs.existsSync(to))
3301
+ throw new CadError(
3302
+ 'coupons.exists',
3303
+ "projects/coupons is here already, and is kept as it is: to get the kit's newest, rename yours first (projects/coupons-old) and run cad coupons again",
3304
+ );
3305
+ fs.cpSync(from, to, { recursive: true });
3306
+ say(
3307
+ 'made projects/coupons: the fixings, holds and slot coupons, and MEASURE.md, which says how to print and read each and the command that writes it back',
3308
+ );
3309
+ say(' npx cad export coupons/fixings-coupon (and holds-coupon, slot-coupon): each as a 3MF to print');
3310
+ say(' npx cad measured x1c.pilot_m3=<figure>: a result written back, for every design here to follow');
3311
+ say(' npx cad measured --export: what you measured, as a change to send to the kit');
3312
+ const drawsFor = printerOf(null);
3313
+ if (drawsFor !== 'x1c')
3314
+ say(
3315
+ ` note: the coupons are drawn from the X1C's rules (x1c), and this workspace prints on ${drawsFor}: their figures are the X1C's until they are drawn from yours`,
3316
+ );
3317
+ }
3318
+
3319
+ // cad measured [<project>/<assembly>] <name>=<value> …: with an assembly, its checks run either side and what moved is
3320
+ // said; without one (the first word a name=value, or no word at all for --export and --strike), a rule measured on a
3321
+ // coupon is written all the same, into the workspace's ledger
3018
3322
  async function measuredCommand(ref) {
3019
- const { recordMeasured, assumptionsTable, writeTable, ledgerLines } = await import('../lib/measured.mjs');
3323
+ const { recordMeasured, assumptions, assumptionsTable, writeTable, ledgerLines, strikeLedger, exportMeasured } =
3324
+ await import('../lib/measured.mjs');
3325
+ const onto = ref && ref.includes('/') ? ref : null;
3326
+ if (opt('export')) return exportCommand(exportMeasured);
3327
+ if (opt('table') && !onto)
3328
+ throw new CadError(
3329
+ 'measured.usage',
3330
+ 'usage: cad measured <project>/<assembly> --table: the figures that assembly rests on (a table is of one assembly)',
3331
+ );
3020
3332
  if (opt('table')) {
3333
+ if (opt('json')) return console.log(JSON.stringify(await assumptions(ref), null, 2));
3021
3334
  const table = await assumptionsTable(ref);
3022
3335
  if (opt('out')) {
3023
3336
  writeTable(path.resolve(opt('out')), table);
@@ -3025,16 +3338,32 @@ async function measuredCommand(ref) {
3025
3338
  }
3026
3339
  return console.log(table);
3027
3340
  }
3341
+ if (args.includes('--strike')) return strikeCommand(onto, strikeLedger);
3028
3342
  const values = Object.fromEntries(
3029
3343
  positional()
3030
- .slice(2)
3344
+ .slice(onto ? 2 : 1)
3031
3345
  .map((x) => {
3032
3346
  const i = x.indexOf('=');
3033
- if (i < 1) throw new Error(`usage: cad measured <project>/<assembly> <name>=<value> … (got "${x}")`);
3034
- return [x.slice(0, i), Number(x.slice(i + 1))];
3347
+ if (i < 1)
3348
+ throw new Error(
3349
+ `usage: cad measured [<project>/<assembly>] <name>=<value> … (got "${x}"): an assembly is <project>/<assembly>`,
3350
+ );
3351
+ const v = x.slice(i + 1).trim();
3352
+ // (Number('') is 0: an empty figure would be written as 0, the most trusted kind)
3353
+ if (!v)
3354
+ throw new CadError(
3355
+ 'measured.value',
3356
+ `${x.slice(0, i)} has no figure after its "=": give the one measured (${x.slice(0, i)}=0.25)`,
3357
+ );
3358
+ return [x.slice(0, i), Number(v)];
3035
3359
  }),
3036
3360
  );
3037
- const r = await recordMeasured(ref, values, { unit: opt('unit'), source: opt('source'), rule: opt('rule') });
3361
+ const r = await recordMeasured(onto, values, {
3362
+ unit: opt('unit'),
3363
+ source: opt('source'),
3364
+ rule: opt('rule'),
3365
+ force: !!opt('force'),
3366
+ });
3038
3367
  if (opt('json')) return console.log(JSON.stringify({ entries: r.entries, moved: r.moved }, null, 2));
3039
3368
  for (const l of ledgerLines(r.entries)) say(l);
3040
3369
  for (const m of r.moved)
@@ -3043,16 +3372,72 @@ async function measuredCommand(ref) {
3043
3372
  ? ` ${m.figure}: ${Number(m.from.toFixed(4))} ${m.unit} to ${Number(m.to.toFixed(4))} ${m.unit}`
3044
3373
  : ` ${m.code}: ${m.text}`,
3045
3374
  );
3046
- if (!r.moved.length) say(' nothing the checks say has moved');
3375
+ if (!onto)
3376
+ say(
3377
+ ` kept in ledger.jsonl (cad history shows it); give an assembly first to see what it moves there (cad measured <project>/<assembly> ${Object.keys(values)[0]}=…)`,
3378
+ );
3379
+ else if (!r.moved.length) say(' nothing the checks say has moved');
3380
+ }
3381
+
3382
+ // cad measured --export: what this workspace measured that the kit lacks, as a diff of the kit's rule sets to send it
3383
+ function exportCommand(exportMeasured) {
3384
+ const r = exportMeasured();
3385
+ if (opt('json')) return console.log(JSON.stringify(r, null, 2));
3386
+ if (!r.sets.length && !r.alone.length)
3387
+ return say(
3388
+ 'nothing measured here that the kit lacks: cad measured writes a figure from a coupon (cad coupons adds them), and this lists it once it is',
3389
+ );
3390
+ if (r.diff) process.stdout.write(r.diff);
3391
+ // (on stderr, so the diff alone goes to a file: cad measured --export > measured.diff)
3392
+ for (const a of r.alone)
3393
+ console.error(
3394
+ `${a.file} is a set the kit has no file for; send its measured figures as they are: ${a.rules.map((x) => `${x.name} = ${x.value}${x.unit ? ` ${x.unit}` : ''}`).join(', ')}`,
3395
+ );
3396
+ if (r.sets.length)
3397
+ console.error(
3398
+ `${r.sets.reduce((t, x) => t + x.rules.length, 0)} measured figure(s) the kit lacks, as a change to ${r.sets.map((x) => x.file).join(', ')}: send it to https://github.com/JoniBach/rulecad/issues with the printer and plastic you printed in`,
3399
+ );
3400
+ }
3401
+
3402
+ // cad measured <project>/<assembly> --strike <date> <name>: a row taken out of the ledger (a slip written as measured).
3403
+ // The rule set it went into is a file of its own: the command says what it still holds, and leaves it as it is
3404
+ // (with no assembly, a row written without one: the workspace's ledger)
3405
+ async function strikeCommand(ref, strikeLedger) {
3406
+ const date = opt('strike'),
3407
+ names = positional().slice(ref ? 2 : 1);
3408
+ if (names.length !== 1)
3409
+ throw new CadError(
3410
+ 'measured.usage',
3411
+ `usage: cad measured [<project>/<assembly>] --strike <date> <name>[=<figure>]: the date and the name of the row to take out, as cad history${ref ? ` ${ref}` : ''} shows them`,
3412
+ );
3413
+ const r = strikeLedger(ref, date, names[0]);
3414
+ if (opt('json')) return console.log(JSON.stringify(r, null, 2));
3415
+ say(
3416
+ `struck ${r.struck.length === 1 ? 'a row' : `${r.struck.length} rows`} from ${ref ? `projects/${ref.split('/')[0]}/` : ''}ledger.jsonl:`,
3417
+ );
3418
+ for (const l of r.lines) say(` ${l}`);
3419
+ if (r.rule) say(r.rule.said);
3047
3420
  }
3048
3421
 
3049
3422
  async function ledger(project, name) {
3050
3423
  const { readLedger, ledgerLines } = await import('../lib/measured.mjs');
3051
- const rows = readLedger(project).filter((e) => !name || e.assembly === name);
3424
+ const rows = readLedger(project).filter((e) => !name || e.assembly === name); // (project null: the workspace's)
3052
3425
  return { rows, lines: ledgerLines(rows) };
3053
3426
  }
3054
3427
 
3055
3428
  async function history(ref) {
3429
+ // cad history alone: the figures written with no assembly (cad measured x1c.pilot_m3=2.9), the workspace's ledger
3430
+ if (!ref) {
3431
+ const { rows, lines } = await ledger(null);
3432
+ if (opt('json')) return console.log(JSON.stringify({ ledger: rows }, null, 2));
3433
+ if (!lines.length)
3434
+ return say(
3435
+ "nothing measured here without an assembly yet (cad measured x1c.pilot_m3=<value>); cad history <project> shows a project's",
3436
+ );
3437
+ say('measured on coupons, predicted against measured:');
3438
+ for (const l of lines) say(` ${l}`);
3439
+ return;
3440
+ }
3056
3441
  const [project, name] = ref.split('/');
3057
3442
  if (name && isAssembly(ref)) {
3058
3443
  const { rows, lines } = await ledger(project, name);
@@ -3105,9 +3490,9 @@ async function history(ref) {
3105
3490
 
3106
3491
  async function diff(d, from, to) {
3107
3492
  if (!from) throw new Error('usage: cad diff <project>/<object> <from> [<to>]');
3108
- const a = await snap(materialise(d, from)),
3109
- b = await snap(to ? materialise(d, to) : d);
3110
- const r = compare(a, b);
3493
+ const A = materialise(d, from),
3494
+ B = to ? materialise(d, to) : d;
3495
+ const r = compare(await snap(A, A.reads), await snap(B, B.reads || A.reads));
3111
3496
  console.log(`${d.project}/${d.name} ${from} → ${to || 'now'}: ${r.kind ? `a ${r.kind} change` : 'no changes'}`);
3112
3497
  for (const x of r.reasons) console.log(` ${x.kind.padEnd(5)} ${x.text}`);
3113
3498
  }