@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/bin/cad.mjs CHANGED
@@ -1,9 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  // cad: make, check, preview, export and show rule-driven designs. Run `cad help`.
3
+ // First of all: on a Node older than cad runs on, one plain line and exit 1 (lib/node-version.mjs), before the rest loads
4
+ import '../lib/node-version.mjs';
3
5
  import fs from 'node:fs';
4
6
  import path from 'node:path';
5
- import { execFileSync } from 'node:child_process';
7
+ import { runProgram } from '../lib/programs.mjs';
6
8
  import { fmt, loadRuleSet, insideWorkspace } from '../lib/rules.mjs';
9
+ import { estimatesFinding } from '../lib/estimates.mjs';
7
10
  import { WS, TOOL, paths, configError, printerOf, asks, trust } from '../lib/workspace.mjs';
8
11
  import { isPlainName, plainName } from '../lib/names.mjs';
9
12
  import { fromKLE } from '@rulecad/keyboard-layout';
@@ -19,9 +22,11 @@ import {
19
22
  pcbEngine,
20
23
  objectSets,
21
24
  boardChecks,
25
+ readTexts,
22
26
  } from '../lib/design.mjs';
23
27
  import {
24
28
  git,
29
+ gitAsByHand,
25
30
  tags,
26
31
  bump,
27
32
  bigger,
@@ -30,6 +35,7 @@ import {
30
35
  snapshot,
31
36
  materialise,
32
37
  files,
38
+ readsLine,
33
39
  prints,
34
40
  printsFile,
35
41
  engineId,
@@ -38,11 +44,20 @@ import { check } from '@rulecad/printcheck';
38
44
  import { preview } from '../lib/preview.mjs';
39
45
  import { measure, match } from '../lib/meshcmd.mjs';
40
46
  import { cloneBoard } from '../lib/clone.mjs';
41
- import { isAssembly, buildAssembly, checkAssembly, shapes, sweep, wireTubesOf } from '../lib/assembly.mjs';
47
+ import {
48
+ isAssembly,
49
+ buildAssembly,
50
+ assemblyOverrides,
51
+ checkAssembly,
52
+ shapes,
53
+ sweep,
54
+ wireTubesOf,
55
+ } from '../lib/assembly.mjs';
42
56
  import { valuesOf, why } from '../lib/explain.mjs';
43
- import { errorData, near } from '../lib/errors.mjs';
57
+ import { CadError, errorData, near } from '../lib/errors.mjs';
44
58
  import { schemaFindings } from '../lib/schema.mjs';
45
59
  import { readJson, readOwnText, cached } from '../lib/host.mjs';
60
+ import { writeCacheFile, readCacheJson } from '../lib/cache-file.mjs';
46
61
  import {
47
62
  optimised,
48
63
  ownResults,
@@ -59,6 +74,7 @@ import {
59
74
  addToAssembly,
60
75
  fastenFromFitsEdit,
61
76
  parseValue,
77
+ valueFor,
62
78
  parseSetting,
63
79
  newProject,
64
80
  setProject,
@@ -71,8 +87,9 @@ import {
71
87
  import { setAt } from '../lib/jsonedit.mjs';
72
88
  import { threemf, slotOf } from '../lib/threemf.mjs';
73
89
  import { liveView, recorder, endOnly } from '../lib/live.mjs';
74
- import { checkSets, drawSet, draftSet, draftPart, draftParts } from '../lib/sheet.mjs';
90
+ import { checkSets, drawSet, draftSet, draftPart, draftParts, updateSet } from '../lib/sheet.mjs';
75
91
  import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW, viewNote } from '../lib/links.mjs';
92
+ import { endSandbox } from '../lib/sandbox.mjs';
76
93
 
77
94
  // What the print file asks of the AMS: which filament each kind of part prints in
78
95
  function filamentNotes(parts, fil) {
@@ -91,11 +108,19 @@ function filamentNotes(parts, fil) {
91
108
  ];
92
109
  }
93
110
 
94
- // --open: the 3MF in Bambu Studio (macOS), else whatever opens .3mf files
111
+ // --open: the 3MF in Bambu Studio (macOS), else whatever opens .3mf files (each found on PATH, never in the workspace:
112
+ // lib/programs.mjs)
95
113
  const openInSlicer = (f) =>
96
114
  process.platform === 'darwin'
97
- ? execFileSync('open', ['-a', 'Bambu Studio', f])
98
- : execFileSync(process.platform === 'win32' ? 'explorer' : 'xdg-open', [f]);
115
+ ? runProgram('open', ['-a', 'Bambu Studio', f], {}, 'open, which opens the file in Bambu Studio,')
116
+ : runProgram(
117
+ process.platform === 'win32' ? 'explorer' : 'xdg-open',
118
+ [f],
119
+ {},
120
+ process.platform === 'win32'
121
+ ? "explorer, Windows' file browser,"
122
+ : 'xdg-open, which opens a file in its program,',
123
+ );
99
124
 
100
125
  const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
101
126
 
@@ -103,14 +128,19 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
103
128
  cad new <project> a project: its project.json [--title …] [--description …] [--material PLA] [--printer x1c]
104
129
  cad new <project>/<assembly> --assembly an empty assembly that checks [--title …] (makes the project if needed); with
105
130
  --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
131
+ [--join blind] [--fitting printed] [--estimate] [--feet levelling] [--caps false]: a generated frame
132
+ cad coupons the kit's test prints as projects/coupons: the fixings, holds and slot coupons, and
133
+ MEASURE.md, which says how to read each and the cad measured command that writes it back
107
134
  cad import-kle <file> <project>/<name> a keyboard layout from keyboard-layout-editor.com, into layouts/
108
135
  cad clone <board.kicad_pcb | GitHub link> <name> a published circuit board into rules/<name>.json, to redraw by rules [--source, --licence]
109
136
  cad agents AGENTS.md: how an AI agent should design in this workspace
110
137
  cad trust allow what this workspace's cad.config.json asks (no sandbox, its own targets)
111
138
  cad rules <project>/<object> every variable: value, the rule behind it, its source
112
139
  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
140
+ never failures: an alias in "interface", what the kit's set has that your copy lacks or
141
+ has newer, and a copy that is the kit's word for word
142
+ cad rules update <set> your copy in rules/ brought up to the kit's: its newer figures and new rules, keeping
143
+ your measured figures, those you checked since, and rules of your own [--dry-run] [--json]
114
144
  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
145
  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
146
  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 +195,8 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
165
195
  cad release <project>/<object> -m "what changed" [--bump major|minor|patch] [--dry-run] [--push]
166
196
  check it, compare with the last release, suggest the bump, then commit, tag and log it in CHANGELOG.md
167
197
  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
198
+ cad history <project>[/<object>] releases, with what changed and what was printed (cad history alone: the figures
199
+ written with no assembly)
169
200
  cad diff <project>/<object> <from> [<to>] what changed between two releases (or a release and now)
170
201
  cad printed <project>/<object> --result ok|failed [--note "…"] [--material PETG] [--version 0.1.0]
171
202
  cad release <project> --all -m "…" release every object that changed (each with this message), then the project
@@ -190,7 +221,17 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
190
221
  cad measured <project>/<assembly> <name>=<value> … a measurement, where the estimate was: a rule (x1c.press=0.08) or a
191
222
  check's prediction (task.accuracy=0.8): says what moved, and keeps a ledger of predicted
192
223
  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]
224
+ [--force: a figure of the other sign, or under half or over twice the one it replaces (a tenth
225
+ to ten times, an estimate's), refused as a slip without it]
226
+ [--table: every estimate, community figure and default the assembly still rests on, the coupon
227
+ that measures each, and its predictions, as Markdown; --json: as data; --out MEASURE.md: kept there]
228
+ [--strike <date> <name>[=<figure>]: a row taken out of the ledger; the rule set it went into is
229
+ left as it is, and the command says what it still holds]
230
+ cad measured <name>=<value> … the same with no assembly: a rule measured on a coupon (x1c.pilot_m3=2.9), written to
231
+ your copy of its set and kept in the workspace's ledger, shown by cad history alone
232
+ (--strike <date> <name> takes a row out of it)
233
+ cad measured --export every figure measured here that the kit lacks, as a diff of the kit's rule sets
234
+ (packages/rules/<set>.json), to send to the kit [--json]
194
235
  The fixings coupon's rules need no --rule: x1c.pilot_m4, x1c.insert_m3 (and _petg for one
195
236
  plastic), x1c.nut_fit, x1c.nut_slip, x1c.thread_gap, x1c.thread_flank (45 or 60)
196
237
  The slot coupon's need no --rule: x1c.slot_fit, x1c.printed_slot_fit; a slot measured by
@@ -217,6 +258,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
217
258
 
218
259
  <project>/<object>@<version> any command but release works on a release: cad export keyboard/keycap@0.1.0
219
260
  --set name=value,name=value change variables that have a tweak range (any command)
261
+ --set item.name=value on an assembly: that item's variable (check, preview, export, show, link, list)
220
262
  --part <name> only that part (check, preview, export, link): e.g. --part cap
221
263
  --explode preview: parts moved apart, so each can be seen
222
264
  --trailer "Co-Authored-By: …" added to release commits (for agents)
@@ -225,6 +267,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
225
267
  // Every command and option there is: a misspelt one is refused by name, not passed over
226
268
  const COMMANDS = [
227
269
  'new',
270
+ 'coupons',
228
271
  'remove',
229
272
  'move',
230
273
  'import-kle',
@@ -267,6 +310,8 @@ const COMMANDS = [
267
310
  ];
268
311
  const OPTIONS = [
269
312
  'table',
313
+ 'export',
314
+ 'strike',
270
315
  'calibrate',
271
316
  'check',
272
317
  'turns',
@@ -366,6 +411,7 @@ const OPTIONS = [
366
411
  'inside',
367
412
  'outside',
368
413
  'join',
414
+ 'estimate',
369
415
  'feet',
370
416
  'caps',
371
417
  'with-refs',
@@ -376,9 +422,10 @@ const OPTIONS = [
376
422
  // it passed over would let the command write
377
423
  const takesDryRun = (cmd) =>
378
424
  ['new', 'set', 'add', 'remove', 'move', 'release'].includes(cmd) ||
425
+ (cmd === 'rules' && positional()[1] === 'update') ||
379
426
  (cmd === 'frame' && (opt('expand') || (opt('size') && opt('write'))));
380
427
  const DRY_RUNS =
381
- 'the commands that take one are cad new, set, add, remove, move, release, frame --expand and frame --size --write';
428
+ 'the commands that take one are cad new, set, add, remove, move, release, rules update, frame --expand and frame --size --write';
382
429
  // What a command takes, where that isn't <project>/<object>
383
430
  const USAGE = {
384
431
  add: 'fit|joint|item|beam|loop|pose|fasten|join|guide|load|wire <project>/<assembly> --key value … [field=value …]',
@@ -402,6 +449,7 @@ const args = process.argv.slice(2);
402
449
  const FLAGS = [
403
450
  'with-refs',
404
451
  'table',
452
+ 'export',
405
453
  'calibrate',
406
454
  'check',
407
455
  'preview',
@@ -430,6 +478,7 @@ const FLAGS = [
430
478
  'expand',
431
479
  'size',
432
480
  'write',
481
+ 'estimate',
433
482
  ];
434
483
  // The options whose value may be left out; a field=value after one is a field to set, not its value (cad new
435
484
  // frame/box --assembly title=Box)
@@ -612,10 +661,7 @@ async function optimiseProblem(ref, { preview: previewing = false } = {}) {
612
661
  // The run, to watch again: kept by the densities' key when it was recorded here, else its end alone
613
662
  const done = `finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`,
614
663
  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
- }
664
+ if (rec.steps()) writeCacheFile(kept, rec.page(`cad optimise ${ref}`, done));
619
665
  const run = paths.preview(project, `${name.replace(':', '-')}-run.html`),
620
666
  recorded = cached(kept);
621
667
  fs.mkdirSync(path.dirname(run), { recursive: true });
@@ -1022,6 +1068,69 @@ async function analyses(b, d, tag) {
1022
1068
  return all;
1023
1069
  }
1024
1070
 
1071
+ // cad rules update <set>: the workspace's copy of a kit set given the kit's newer figures and new rules (sheet.mjs
1072
+ // kitDifference says which are the kit's to take), keeping the measured, the newer and the copy's own, and saying each
1073
+ function updateRules(name) {
1074
+ plainName(name, 'rule set name');
1075
+ const u = updateSet(name),
1076
+ rel = `rules/${name}.json`;
1077
+ if (!u.copy) {
1078
+ const text = `no ${rel} in this workspace: the first design to use ${name} copies in the kit's as it is then`;
1079
+ return console.log(opt('json') ? JSON.stringify({ set: name, file: null, updated: false, text }, null, 2) : text);
1080
+ }
1081
+ const d = u.difference,
1082
+ taken = d.changed.length + d.refreshed.length + d.added.length + u.fields.length > 0,
1083
+ dry = !!opt('dry-run'),
1084
+ said = (v) => (typeof v === 'number' || typeof v === 'string' ? String(v) : JSON.stringify(v)),
1085
+ was = (k) => `${said(u.copy.rules[k]?.value)} here, ${said(u.kit.rules[k]?.value)} in the kit's`;
1086
+ if (taken && !dry) {
1087
+ insideWorkspace(u.file); // (never written through a link out of rules/)
1088
+ fs.writeFileSync(u.file, JSON.stringify(u.set, null, 2) + '\n');
1089
+ }
1090
+ if (opt('json'))
1091
+ return console.log(
1092
+ JSON.stringify(
1093
+ {
1094
+ set: name,
1095
+ file: rel,
1096
+ updated: taken && !dry,
1097
+ ...(dry ? { dryRun: true } : {}),
1098
+ changed: d.changed.map((k) => ({ rule: k, from: u.copy.rules[k]?.value, to: u.kit.rules[k]?.value })),
1099
+ added: d.added,
1100
+ refreshed: d.refreshed,
1101
+ fields: u.fields,
1102
+ kept: { measured: d.measured, newer: d.newer, own: d.own },
1103
+ },
1104
+ null,
1105
+ 2,
1106
+ ),
1107
+ );
1108
+ const lines = [
1109
+ ...d.changed.map(
1110
+ (k) =>
1111
+ ` ${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})`,
1112
+ ),
1113
+ ...(d.added.length ? [` added from the kit's: ${d.added.join(', ')}`] : []),
1114
+ ...(d.refreshed.length
1115
+ ? [
1116
+ ` the same figure, with what the kit's adds or has newer (its source, words, date or range): ${d.refreshed.join(', ')}`,
1117
+ ]
1118
+ : []),
1119
+ ...(u.fields.length ? [` the set's own fields, as the kit's: ${u.fields.join(', ')}`] : []),
1120
+ ...(d.measured.length ? [` kept as measured: ${d.measured.map((k) => `${k} (${was(k)})`).join(', ')}`] : []),
1121
+ ...(d.newer.length
1122
+ ? [` kept as yours, checked on or after the kit's date: ${d.newer.map((k) => `${k} (${was(k)})`).join(', ')}`]
1123
+ : []),
1124
+ ...(d.own.length ? [` kept, the kit has none: ${d.own.join(', ')}`] : []),
1125
+ ];
1126
+ console.log(
1127
+ taken
1128
+ ? `${dry ? 'would update' : 'updated'} ${rel} from the kit's ${name}${dry ? ' (--dry-run: nothing written)' : ''}:`
1129
+ : `${rel} is up to date with the kit's ${name}${lines.length ? ':' : ''}`,
1130
+ );
1131
+ for (const l of lines) console.log(l);
1132
+ }
1133
+
1025
1134
  // cad rules check / draw / draft: rule sets themselves, not a design's use of them
1026
1135
  function ruleSheets(what, names) {
1027
1136
  if (what === 'check') {
@@ -1066,6 +1175,7 @@ function ruleSheets(what, names) {
1066
1175
  throw new Error(
1067
1176
  `usage: cad rules ${what} <set>${what === 'draft' ? ` --from <file.pdf>, or cad rules draft ${draftParts().join('|')} <name>` : ''}`,
1068
1177
  );
1178
+ if (what === 'update') return updateRules(name);
1069
1179
  if (what === 'draw') {
1070
1180
  const to = opt('out') || `${name}.svg`;
1071
1181
  fs.writeFileSync(to, drawSet(name));
@@ -1135,7 +1245,7 @@ async function main() {
1135
1245
  return edited(r, 'new', {}, `${r.dryRun ? 'would make' : 'made'} projects/${project}/objects/${name}.{js,json}`);
1136
1246
  }
1137
1247
 
1138
- if (cmd === 'rules' && ['check', 'draw', 'draft'].includes(ref)) return ruleSheets(ref, pos.slice(2));
1248
+ if (cmd === 'rules' && ['check', 'draw', 'draft', 'update'].includes(ref)) return ruleSheets(ref, pos.slice(2));
1139
1249
 
1140
1250
  if (cmd === 'trust') {
1141
1251
  // this workspace may do what its cad.config.json asks (designs outside the sandbox, its own targets)
@@ -1148,14 +1258,16 @@ async function main() {
1148
1258
  }
1149
1259
 
1150
1260
  if (cmd === 'agents') {
1151
- // the notes for AI agents, into this workspace (AGENTS.md, and CLAUDE.md pointing at it)
1152
- const to = path.join(WS, 'AGENTS.md'),
1261
+ // the notes for AI agents, into this workspace (AGENTS.md, and CLAUDE.md pointing at it): neither written through
1262
+ // a link, which in a workspace from someone else could lead to a file of the user's elsewhere (rules.mjs)
1263
+ const to = insideWorkspace(path.join(WS, 'AGENTS.md')),
1153
1264
  ours = fs.readFileSync(path.join(TOOL, 'AGENTS.md'), 'utf8'),
1154
1265
  record = paths.cache('agents.md');
1266
+ insideWorkspace(path.join(WS, 'CLAUDE.md'));
1155
1267
  // 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
1268
  // brought up to date; one edited here is kept, unless --force
1157
1269
  const mine = fs.existsSync(to) ? fs.readFileSync(to, 'utf8') : null,
1158
- last = fs.existsSync(record) ? fs.readFileSync(record, 'utf8') : null;
1270
+ last = cached(record) ? fs.readFileSync(record, 'utf8') : null; // (never read through a link out)
1159
1271
  const ourCopy =
1160
1272
  mine === null || mine === ours || (last !== null ? mine === last : mine.startsWith(ours.split('\n')[0]));
1161
1273
  if (!ourCopy && !opt('force'))
@@ -1163,8 +1275,7 @@ async function main() {
1163
1275
  "AGENTS.md here has been edited (or isn't rulecad's): it is kept as it is (cad agents --force replaces it)",
1164
1276
  );
1165
1277
  fs.writeFileSync(to, ours);
1166
- fs.mkdirSync(path.dirname(record), { recursive: true });
1167
- fs.writeFileSync(record, ours);
1278
+ writeCacheFile(record, ours);
1168
1279
  const claude = path.join(WS, 'CLAUDE.md');
1169
1280
  if (!fs.existsSync(claude)) fs.writeFileSync(claude, '@AGENTS.md\n');
1170
1281
  else if (!fs.readFileSync(claude, 'utf8').includes('@AGENTS.md')) fs.appendFileSync(claude, '\n@AGENTS.md\n');
@@ -1237,11 +1348,20 @@ async function main() {
1237
1348
  pictures: !opt('no-pictures'),
1238
1349
  });
1239
1350
  }
1351
+ if (cmd === 'coupons') return couponsCommand();
1352
+ // (cad measured with no assembly: --export, or a figure written as it is; cad history alone: those figures)
1353
+ if (cmd === 'measured' && !ref) return measuredCommand(null);
1354
+ if (cmd === 'history' && !ref) return history(null);
1240
1355
  if (!ref || (cmd === 'add' && !pos[2])) throw new Error(`usage: cad ${cmd} ${USAGE[cmd] || '<project>/<object>'}`);
1241
1356
  if (cmd === 'release')
1242
1357
  return ref.includes('/') ? releaseObject(locate(ref)) : opt('all') ? releaseAll(ref) : releaseProject(ref);
1243
1358
  if (cmd === 'variants') return variants(locate(ref));
1244
1359
  if (cmd === 'compare') return compareVariants(locate(ref), pos[2], pos[3]);
1360
+ // These build an assembly as its file says: a --set would be passed over, so it is refused by name
1361
+ if (opt('set') !== undefined && ['measured', 'frame', 'machine', 'plot', 'plates', 'order', 'kit'].includes(cmd))
1362
+ throw new Error(
1363
+ `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`,
1364
+ );
1245
1365
  if (cmd === 'measured') return measuredCommand(ref);
1246
1366
  if (cmd === 'list' || cmd === 'wires' || cmd === 'beams') return listCommand(cmd, ref);
1247
1367
  if (cmd === 'frame') return frameCommand(ref);
@@ -1390,7 +1510,12 @@ async function main() {
1390
1510
  : await printChecks(b, d)),
1391
1511
  ...(b.mechanism?.findings || []), // a lamina mechanism's own: it prints free, stops, holds, clears in every state
1392
1512
  ...(b.fixings || []), // what v.fixings drew: each hole and seat, what it was drawn to and the rule it rests on
1513
+ ...(b.seats || []), // what v.shapes' seat helpers drew (a shaft's bore, a bearing's pocket), as v.fixings's
1393
1514
  ...(await analyses(b, d, tag)),
1515
+ // what rests on estimates, as an assembly's check says it (an object's check is where one looks first)
1516
+ ...[estimatesFinding([b], { ref: `${d.project}/${d.name}` })]
1517
+ .filter(Boolean)
1518
+ .map(({ short, ...x }) => ({ ...x, card: short })),
1394
1519
  ],
1395
1520
  {
1396
1521
  object: `${d.project}/${d.name}`,
@@ -1525,10 +1650,16 @@ async function editVariables(ref) {
1525
1650
  throw new Error(
1526
1651
  `--${extra.rule ? 'rule' : 'label'} describes one variable: set ${pairs.map((p) => p.split('=')[0]).join(' and ')} one at a time`,
1527
1652
  );
1653
+ // each value read by its variable's kind: text stays as typed (a legend 007), a number where the variable is one
1654
+ const vars = readObject(locate(ref)).variables || {};
1528
1655
  const changes = Object.fromEntries(
1529
1656
  pairs.map((p) => {
1530
- const i = p.indexOf('=');
1531
- return [p.slice(0, i).trim(), { value: parseValue(p.slice(i + 1).trim()), ...extra }];
1657
+ const i = p.indexOf('='),
1658
+ name = p.slice(0, i).trim();
1659
+ return [
1660
+ name,
1661
+ { value: valueFor(Object.hasOwn(vars, name) ? vars[name] : undefined, p.slice(i + 1).trim()), ...extra },
1662
+ ];
1532
1663
  }),
1533
1664
  );
1534
1665
  const r = await setVariables(ref, changes, { create: !!opt('new'), dryRun: !!opt('dry-run') });
@@ -1536,6 +1667,21 @@ async function editVariables(ref) {
1536
1667
  console.log(`${r.dryRun ? `dry run, nothing written: would set` : 'set'} ${r.changed.join(', ')} in ${rel(r.file)}`);
1537
1668
  }
1538
1669
 
1670
+ // cad add item --object tray --set legend=007: each value read by the object's variable's kind, as cad set reads it
1671
+ // (text stays as typed); an object that can't be read yet leaves the values as parseValue reads them
1672
+ function itemSet(ref) {
1673
+ let vars = {};
1674
+ try {
1675
+ if (typeof opt('object') === 'string')
1676
+ vars = readObject(locateIn(ref.split('/')[0], String(opt('object')).split(/[:@]/)[0])).variables || {};
1677
+ } catch {
1678
+ // (no such object: cad add names it when it checks the item)
1679
+ }
1680
+ return Object.fromEntries(
1681
+ Object.entries(sets()).map(([k, v]) => [k, valueFor(Object.hasOwn(vars, k) ? vars[k] : undefined, v)]),
1682
+ );
1683
+ }
1684
+
1539
1685
  // cad add fit|joint|item|loop|pose|fasten|join <project>/<assembly> --key value …: add to an assembly, keeping its layout
1540
1686
  async function editAssembly(what, ref) {
1541
1687
  const list = (k) =>
@@ -1591,9 +1737,7 @@ async function editAssembly(what, ref) {
1591
1737
  ...text(['id', 'object', 'assembly', 'variant']),
1592
1738
  ...at(),
1593
1739
  ...(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
- : {}),
1740
+ ...(typeof opt('set') === 'string' ? { set: itemSet(ref) } : {}),
1597
1741
  };
1598
1742
  else if (what === 'loop') entry = text(['a', 'b', 'label']);
1599
1743
  else if (what === 'fasten' && opt('from-fits')) {
@@ -1735,29 +1879,37 @@ async function newCommand(ref) {
1735
1879
  );
1736
1880
  let frame;
1737
1881
  // 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'],
1882
+ const FRAME_OPTS = ['inside', 'outside', 'profile', 'join', 'fitting', 'screw', 'estimate', 'feet', 'caps'],
1739
1883
  loose = FRAME_OPTS.filter((k) => opt(k) !== undefined);
1740
1884
  if (!opt('frame') && loose.length)
1741
1885
  throw new Error(
1742
1886
  `--${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
1887
  );
1744
- if (opt('frame') && !str('join') && (str('fitting') || str('screw')))
1888
+ const how = ['fitting', 'screw', 'estimate'].filter((k) => opt(k) !== undefined);
1889
+ if (opt('frame') && !str('join') && how.length)
1745
1890
  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`,
1891
+ `--${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
1892
  );
1748
1893
  if (opt('frame')) {
1749
- const nums = (k) =>
1750
- str(k)
1751
- ? str(k)
1752
- .split(',')
1753
- .map((x) => parseValue(x.trim()))
1754
- : undefined;
1894
+ // a size is numbers in mm, one for each of the frame's sides, as 300,300,350
1895
+ const nums = (k) => {
1896
+ if (opt(k) === undefined) return undefined;
1897
+ const v = str(k)
1898
+ ?.split(',')
1899
+ .map((x) => parseValue(x.trim()));
1900
+ if (!v?.length || !v.every((x) => typeof x === 'number' && Number.isFinite(x)))
1901
+ throw new Error(
1902
+ `--${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))})`,
1903
+ );
1904
+ return v;
1905
+ };
1755
1906
  const join =
1756
- str('join') && (str('fitting') || str('screw'))
1907
+ str('join') && how.length
1757
1908
  ? {
1758
1909
  kind: str('join'),
1759
1910
  ...(str('fitting') ? { fitting: str('fitting') } : {}),
1760
1911
  ...(str('screw') ? { screw: str('screw') } : {}),
1912
+ ...(opt('estimate') ? { estimate: true } : {}),
1761
1913
  }
1762
1914
  : str('join');
1763
1915
  frame = Object.fromEntries(
@@ -1998,9 +2150,13 @@ async function board(cmd, d, b, { title, version, tag }) {
1998
2150
  // ---------- assemblies ----------
1999
2151
  async function assembly(cmd, ref) {
2000
2152
  const pose = typeof opt('pose') === 'string' ? opt('pose') : undefined;
2001
- const s = await buildAssembly(ref, [], {}, { pose, progress: showProgress }),
2153
+ // --set item.variable=value: that item built at the value (an unknown item or variable is refused by name)
2154
+ const set = sets(),
2155
+ overrides = assemblyOverrides(ref, set),
2156
+ setTag = suffix(set); // (in file names, as an object's)
2157
+ const s = await buildAssembly(ref, [], overrides, { pose, progress: showProgress }),
2002
2158
  a = s.a,
2003
- title = `${a.title || s.name}${pose ? ` (${pose})` : ''}`;
2159
+ title = `${a.title || s.name}${pose ? ` (${pose})` : ''}${setTag ? ` (${setTag.slice(1)})` : ''}`;
2004
2160
  const versions = [...new Map(s.objects.map((o) => [o.objName, `${o.objName} ${o.version}`])).values()].join(', ');
2005
2161
  const rules = (ns) => Object.fromEntries(Object.keys(loadRuleSet(ns).rules).map((k) => [k, s.num(`${ns}.${k}`)]));
2006
2162
  const printed = s.parts.filter((p) => p.role !== 'reference');
@@ -2034,7 +2190,7 @@ async function assembly(cmd, ref) {
2034
2190
  if (!s.gait) {
2035
2191
  // a motor turning what it drives: the gears cut across their shafts, the load's part turning with them
2036
2192
  const { driveSvg } = await import('../lib/drive.mjs'),
2037
- out = paths.preview(s.project, `${s.name}-drive.svg`);
2193
+ out = paths.preview(s.project, `${s.name}${setTag}-drive.svg`);
2038
2194
  fs.mkdirSync(path.dirname(out), { recursive: true });
2039
2195
  fs.writeFileSync(out, driveSvg(s, { title, ...(opt('turns') ? { turns: Number(opt('turns')) } : {}) }));
2040
2196
  return console.log(out);
@@ -2044,8 +2200,8 @@ async function assembly(cmd, ref) {
2044
2200
  r = framesOf(s);
2045
2201
  if (!r.frames.length)
2046
2202
  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`);
2203
+ const svg = paths.preview(s.project, `${s.name}${setTag}-gait.svg`),
2204
+ json = paths.preview(s.project, `${s.name}${setTag}-gait.json`);
2049
2205
  fs.mkdirSync(path.dirname(svg), { recursive: true });
2050
2206
  fs.writeFileSync(
2051
2207
  svg,
@@ -2059,7 +2215,7 @@ async function assembly(cmd, ref) {
2059
2215
  const check = !!opt('check'); // the check view: each motor's torque labelled at its joints, never on the rest view
2060
2216
  const out = paths.preview(
2061
2217
  s.project,
2062
- `${s.name}${pose ? `-${pose}` : ''}${opt('explode') ? '-exploded' : ''}${check ? '-check' : ''}.png`,
2218
+ `${s.name}${pose ? `-${pose}` : ''}${setTag}${opt('explode') ? '-exploded' : ''}${check ? '-check' : ''}.png`,
2063
2219
  );
2064
2220
  let marks = null;
2065
2221
  if (check) {
@@ -2109,7 +2265,7 @@ async function assembly(cmd, ref) {
2109
2265
  throw new Error(
2110
2266
  `${ref} is a fit assembly, for checking: export its objects, or make a plate (kind: plate) to print them together`,
2111
2267
  );
2112
- const out = paths.exports(s.project, `${s.name}.3mf`);
2268
+ const out = paths.exports(s.project, `${s.name}${setTag}.3mf`);
2113
2269
  fs.mkdirSync(path.dirname(out), { recursive: true });
2114
2270
  // One object per printed thing (a keycap with its legend and supports), a part per part, each in its filament
2115
2271
  const fil = filaments(s.project),
@@ -2137,6 +2293,12 @@ async function assembly(cmd, ref) {
2137
2293
  noRules: !!opt('no-rules'),
2138
2294
  steps: opt('no-steps') ? false : opt('steps'),
2139
2295
  });
2296
+ // 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
2297
+ if (Object.keys(set).length)
2298
+ model.set = Object.entries(set)
2299
+ .map(([k, v]) => `${k}=${v}`)
2300
+ .join(',')
2301
+ .replace(/[^\w.=+,-]/g, '_');
2140
2302
  if (model.steps)
2141
2303
  say(
2142
2304
  `carries the drawing ${model.steps.name ?? '(unnamed)'} (${model.steps.b.length} blocks; --no-steps to leave it out)`,
@@ -2156,7 +2318,7 @@ async function assembly(cmd, ref) {
2156
2318
  if (cmd === 'show') {
2157
2319
  // Each shape once, placed for every copy: nine keys cost one keycap in the mirror's link. Built with each object's
2158
2320
  // 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 });
2321
+ const m = await buildAssembly(ref, [], overrides, { mirror: true, pose });
2160
2322
  const placed = shapes(m.parts.filter((p) => p.role !== 'support' && p.mirror !== false));
2161
2323
  // The card: what the checks found, one short line each
2162
2324
  const items = checkAssembly(s)
@@ -2213,11 +2375,11 @@ async function shorten(l) {
2213
2375
  const token = l.view.split('#m=')[1],
2214
2376
  hash = (await import('node:crypto')).createHash('sha256').update(token).digest('hex').slice(0, 16);
2215
2377
  const file = paths.cache('links.json'),
2216
- cache = cached(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
2378
+ kept = readCacheJson(file),
2379
+ cache = kept && typeof kept === 'object' && !Array.isArray(kept) ? kept : {};
2217
2380
  if (!cache[hash]) {
2218
2381
  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));
2382
+ writeCacheFile(file, JSON.stringify(cache, null, 2));
2221
2383
  }
2222
2384
  const url = `${VIEW}#s=${cache[hash]}`;
2223
2385
  return { ...l, view: url, stl: `${url}&get=stl`, '3mf': `${url}&get=3mf`, short: true };
@@ -2250,11 +2412,11 @@ async function printLinks(l) {
2250
2412
  // keyboard is megabytes: in a terminal or an agent's context it's only noise)
2251
2413
  if (!l.short && !opt('long')) {
2252
2414
  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
- );
2415
+ // (where .cache/links can't be written, a link in a cloned workspace's .cache, the links are printed instead)
2416
+ if (writeCacheFile(f, `view ${l.view}\nstl ${l.stl}\n3mf ${l['3mf']}\n`))
2417
+ return console.log(
2418
+ ` links in ${path.relative(WS, f)} (--md: one ${hasTarget('shorten') ? 'short ' : ''}link for chat; --long: print them)`,
2419
+ );
2258
2420
  }
2259
2421
  console.log(` view ${l.view}`);
2260
2422
  console.log(` stl ${l.stl}`);
@@ -2266,44 +2428,172 @@ const KINDS = ['patch', 'minor', 'major'];
2266
2428
  const today = () => new Date().toISOString().slice(0, 10);
2267
2429
 
2268
2430
  // 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);
2431
+ // A design that reads other objects is resolved with their numbers (each side with the objects it named then: a
2432
+ // release with them as its tag holds them). And the files it read besides its own (`reads`, as the release recorded
2433
+ // them: its helpers, and the rule sets v.fixings and v.frames read) are compared file by file, the design now with
2434
+ // the same files as the release, so an edited helper or thread set counts as a change.
2435
+ const snap = async (d, reads) =>
2436
+ snapshot(d, (await objectSets(d, readObject(d))).sets, reads ? readTexts(d, reads) : null);
2271
2437
  async function since(d) {
2272
2438
  const last = tags(d.project, d.name).at(-1);
2273
2439
  if (!last) return { last: null, kind: 'first', reasons: [] };
2274
- return { last, ...compare(await snap(materialise(d, last.version)), await snap(d)) };
2440
+ const was = materialise(d, last.version);
2441
+ return { last, ...compare(await snap(was, was.reads), await snap(d, was.reads)) };
2275
2442
  }
2276
2443
 
2277
2444
  // Only the design's own files (and its project's changelog and print log) may have uncommitted changes.
2278
2445
  // A release commits only its own files, so other work in progress can stay as it is (another object, an assembly, the
2279
2446
  // docs). What it can't release past is uncommitted shared code (lib/, bin/) or a rule or layout it uses: those would
2280
2447
  // be in the build but not in the release.
2448
+ // git names the files from the repository's root, which may be above the workspace (a workspace in a folder of a larger
2449
+ // repository): only the workspace's own files are asked for (-- .), and named from the workspace.
2281
2450
  function onlyChanged(allowed) {
2282
- const dirty = git('status', '--porcelain', '--untracked-files=all')
2451
+ let porcelain, prefix;
2452
+ try {
2453
+ // (--ignore-submodules=dirty: a submodule's own git, with its own settings, is not asked what changed in it; a
2454
+ // submodule moved to another commit still counts)
2455
+ porcelain = git('status', '--porcelain', '--untracked-files=all', '--ignore-submodules=dirty', '--', '.');
2456
+ prefix = git('rev-parse', '--show-prefix');
2457
+ } catch (e) {
2458
+ if (/not a git repository/.test(e.stderr || e.message)) return; // (a dry run outside git: a release is refused first)
2459
+ throw e;
2460
+ }
2461
+ const dirty = porcelain
2283
2462
  .split('\n')
2284
2463
  .filter(Boolean)
2285
- .map((l) => l.slice(3).replace(/^"|"$/g, ''));
2464
+ .map((l) => l.slice(3).replace(/^"|"$/g, ''))
2465
+ .map((f) => (f.startsWith(prefix) ? f.slice(prefix.length) : f));
2286
2466
  const shared = dirty.filter((f) => !allowed.includes(f) && /^(lib|bin)\//.test(f));
2287
2467
  if (shared.length)
2288
2468
  throw new Error(`commit shared code first (the release would build with it): ${shared.join(', ')}`);
2289
2469
  }
2290
2470
 
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);
2471
+ // A release is a git commit and a tag, so before anything is written: git is there, the workspace is in a repository,
2472
+ // 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.
2473
+ function releasable() {
2474
+ try {
2475
+ git('rev-parse', '--is-inside-work-tree');
2476
+ } catch (e) {
2477
+ if (e.code === 'ENOENT')
2478
+ throw new Error(
2479
+ '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',
2480
+ );
2481
+ throw new Error(
2482
+ `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`,
2483
+ );
2484
+ }
2485
+ try {
2486
+ git('var', 'GIT_AUTHOR_IDENT');
2487
+ git('var', 'GIT_COMMITTER_IDENT');
2488
+ } catch {
2489
+ throw new Error(
2490
+ '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',
2491
+ );
2492
+ }
2493
+ }
2494
+
2495
+ // What git said when it refused, without its hints: the hook's own words, or git's reason
2496
+ const gitSaid = (e) =>
2497
+ String(e.stderr || e.stdout || e.message)
2498
+ .split('\n')
2499
+ .map((l) => l.trim().replace(/^(fatal|error): /, ''))
2500
+ .filter((l) => l && !/^hint:/.test(l) && !/^Command failed/.test(l))
2501
+ .join('; ')
2502
+ .replace(/\.$/, '') || 'no reason given';
2503
+
2504
+ // The files a release is about to change, as they are now (null: not there yet), to put back if git refuses it
2505
+ const keep = (list) => new Map(list.map((f) => [f, fs.existsSync(f) ? readOwnText(f) : null]));
2506
+
2507
+ // Commit the release's files and tag the commit. If git refuses either (a hook that fails, a tag that can't be
2508
+ // signed), everything is put back as it was before the release: the commit (if it was made), what was staged, and the
2509
+ // files in kept (its version and changelog), so that the release can simply be run again.
2510
+ function commitAndTag(paths, subject, tag, message, kept) {
2511
+ const head = (() => {
2512
+ try {
2513
+ return git('rev-parse', '--verify', '-q', 'HEAD');
2514
+ } catch {
2515
+ return null; // (a repository with no commit yet)
2516
+ }
2517
+ })();
2518
+ let index = null;
2519
+ try {
2520
+ index = git('write-tree'); // what is staged now, to stage again
2521
+ } catch {
2522
+ // (an index git can't write as a tree: the release's files are unstaged instead)
2298
2523
  }
2524
+ let step = 'commit';
2525
+ try {
2526
+ gitAsByHand('add', '--', ...paths);
2527
+ gitAsByHand(
2528
+ 'commit',
2529
+ '-q',
2530
+ '-m',
2531
+ subject,
2532
+ ...(opt('trailer') ? ['--trailer', opt('trailer')] : []),
2533
+ '--',
2534
+ ...paths,
2535
+ ); // only these, whatever else is staged
2536
+ step = 'tag';
2537
+ gitAsByHand('tag', '-a', tag, '-m', message);
2538
+ } catch (e) {
2539
+ let undone = true;
2540
+ try {
2541
+ if (step === 'tag') head ? git('reset', '-q', '--soft', head) : git('update-ref', '-d', 'HEAD');
2542
+ if (index) git('read-tree', index);
2543
+ else if (head) git('reset', '-q', '--', ...paths);
2544
+ else git('rm', '-q', '--cached', '--ignore-unmatch', '--', ...paths);
2545
+ } catch {
2546
+ undone = false;
2547
+ }
2548
+ for (const [f, text] of kept) text == null ? fs.rmSync(f, { force: true }) : fs.writeFileSync(f, text);
2549
+ throw new Error(
2550
+ `not released: git refused the release's ${step} (${gitSaid(e)}). ${
2551
+ undone
2552
+ ? 'Your files are as they were before the release'
2553
+ : `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' : ''}`
2554
+ }. Put that right, then release again`,
2555
+ );
2556
+ }
2557
+ if (opt('push'))
2558
+ try {
2559
+ gitAsByHand('push', '-q', 'origin', 'HEAD');
2560
+ gitAsByHand('push', '-q', 'origin', tag);
2561
+ } catch (e) {
2562
+ throw new Error(
2563
+ `released and tagged ${tag} here, but not pushed: git said ${gitSaid(e)}. Push it when you can: git push --follow-tags`,
2564
+ );
2565
+ }
2299
2566
  }
2300
2567
 
2568
+ // Add a release's entry at the top of its project's changelog. An entry for the same name and version that was never
2569
+ // committed (left by a release that went wrong part way) is replaced, never repeated. One that was committed is a real
2570
+ // release and stays: an object named as its project (lamp/lamp) has entries headed as the project's own (lamp 0.1.0).
2301
2571
  function changelog(dir, heading, message, reasons) {
2302
2572
  const f = path.join(dir, 'CHANGELOG.md');
2303
- const old = fs.existsSync(insideWorkspace(f)) ? readOwnText(f).replace(/^# .*\n+/, '') : '';
2573
+ const same = `## ${heading.slice(0, heading.indexOf(' ('))} (`,
2574
+ logFile = path.relative(WS, f).split(path.sep).join('/');
2575
+ const entries = (text) => text.replace(/^# .*\n+/, '').split(/^(?=## )/m);
2576
+ const committed = new Map(); // heading -> how many committed entries have it
2577
+ try {
2578
+ for (const e of entries(git('show', `HEAD:./${logFile}`)))
2579
+ if (e.startsWith(same)) committed.set(e.split('\n')[0], (committed.get(e.split('\n')[0]) || 0) + 1);
2580
+ } catch {
2581
+ // (no commit yet, or the changelog was never committed: every entry for this release is a leftover)
2582
+ }
2583
+ const old = fs.existsSync(insideWorkspace(f))
2584
+ ? entries(readOwnText(f))
2585
+ .filter((e) => {
2586
+ if (!e.startsWith(same)) return true;
2587
+ const h = e.split('\n')[0],
2588
+ n = committed.get(h) || 0;
2589
+ committed.set(h, n - 1);
2590
+ return n > 0;
2591
+ })
2592
+ .join('')
2593
+ : '';
2304
2594
  const entry = `## ${heading}\n\n${message}\n${reasons.length ? `\n${reasons.map((r) => `- ${r.text} (${r.kind})`).join('\n')}\n` : ''}`;
2305
2595
  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)
2596
+ return logFile; // (git's terms: forward slashes)
2307
2597
  }
2308
2598
 
2309
2599
  // An object's print checks: printcheck's, and for parts printed in place, theirs (lib/inplace.mjs)
@@ -2352,18 +2642,25 @@ async function releaseObject(d, { batch = false } = {}) {
2352
2642
  for (const r of reasons) console.log(` ${r.kind.padEnd(5)} ${r.text}`);
2353
2643
  if (opt('dry-run')) return;
2354
2644
  const allowed = [
2355
- ...files(d, object),
2645
+ ...files(d, object, b),
2356
2646
  `projects/${d.project}/CHANGELOG.md`,
2357
2647
  path.relative(WS, printsFile(d)).split(path.sep).join('/'),
2358
2648
  ];
2359
- if (!batch) onlyChanged(allowed); // releaseAll checked the whole tree first
2649
+ if (!batch) {
2650
+ releasable(); // releaseAll checked these first
2651
+ onlyChanged(allowed);
2652
+ }
2653
+ const kept = keep([d.json, path.join(d.dir, 'CHANGELOG.md')]);
2360
2654
  fs.writeFileSync(d.json, setAt(readOwnText(d.json), ['version'], version)); // the object's own version (added, if it had none), nothing else
2361
2655
  const log = changelog(d.dir, `${d.name} ${version} (${kind}), ${today()}`, message, reasons);
2656
+ // (the tag records what the build read besides the design's own files: lib/versions.mjs readsLine)
2657
+ const notes = [b.circuit ? `engine: ${engineId()}` : '', readsLine(b)].filter(Boolean);
2362
2658
  commitAndTag(
2363
- [...files(d, object), log].filter((f) => fs.existsSync(path.join(WS, f))),
2659
+ [...files(d, object, b), log].filter((f) => fs.existsSync(path.join(WS, f))),
2364
2660
  `${tag}: ${message}`,
2365
2661
  tag,
2366
- `${kind}: ${message}${b.circuit ? `\n\nengine: ${engineId()}` : ''}`,
2662
+ `${kind}: ${message}${notes.length ? `\n\n${notes.join('\n')}` : ''}`,
2663
+ kept,
2367
2664
  );
2368
2665
  console.log(`tagged ${tag}${opt('push') ? ' and pushed' : ' (not pushed: --push, or git push --follow-tags)'}`);
2369
2666
  }
@@ -2435,20 +2732,22 @@ async function releaseProject(project) {
2435
2732
  .join(', ')}`,
2436
2733
  );
2437
2734
  if (opt('dry-run')) return;
2735
+ releasable();
2438
2736
  onlyChanged([
2439
2737
  `projects/${project}/project.json`,
2440
2738
  `projects/${project}/CHANGELOG.md`,
2441
2739
  `projects/${project}/prints.jsonl`,
2442
2740
  ]);
2443
- p.version = version;
2444
- p.release = manifest;
2445
- fs.writeFileSync(pj, JSON.stringify(p, null, 2) + '\n');
2741
+ const kept = keep([pj, path.join(dir, 'CHANGELOG.md')]);
2742
+ // The release's version and the versions of its objects (fields of the project schema), the rest of the file as it was
2743
+ fs.writeFileSync(pj, setAt(setAt(readOwnText(pj), ['version'], version), ['release'], manifest));
2446
2744
  const log = changelog(dir, `${project} ${version} (${kind}), ${today()}`, message, reasons);
2447
2745
  commitAndTag(
2448
2746
  [`projects/${project}/project.json`, log],
2449
2747
  `${project}@${version}: ${message}`,
2450
2748
  `${project}@${version}`,
2451
2749
  `${kind}: ${message}\n\n${JSON.stringify(manifest)}`,
2750
+ kept,
2452
2751
  );
2453
2752
  console.log(`tagged ${project}@${version}`);
2454
2753
  }
@@ -2465,8 +2764,9 @@ async function releaseAll(project) {
2465
2764
  `projects/${project}/project.json`,
2466
2765
  `projects/${project}/CHANGELOG.md`,
2467
2766
  `projects/${project}/prints.jsonl`,
2468
- ...changed.flatMap((d) => files(d, readObject(d))),
2469
2767
  ]);
2768
+ for (const d of changed) for (const f of files(d, readObject(d), await build(d))) allowed.add(f);
2769
+ if (!opt('dry-run')) releasable(); // (before any object is released)
2470
2770
  onlyChanged([...allowed]);
2471
2771
  for (const d of changed) await releaseObject(d, { batch: true });
2472
2772
  if (!opt('dry-run')) await releaseProject(project);
@@ -2935,7 +3235,7 @@ async function frameCommand(ref) {
2935
3235
  async function listCommand(what, ref) {
2936
3236
  if (!isAssembly(ref))
2937
3237
  throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
2938
- const s = await buildAssembly(ref);
3238
+ const s = await buildAssembly(ref, [], assemblyOverrides(ref, sets())); // (--set item.variable=value, as cad check)
2939
3239
  if (what === 'list') {
2940
3240
  const { shoppingList, listText } = await import('../lib/list.mjs'),
2941
3241
  l = shoppingList(s);
@@ -3015,9 +3315,46 @@ async function listCommand(what, ref) {
3015
3315
  say(path.relative(WS, file));
3016
3316
  }
3017
3317
 
3318
+ // cad coupons: the kit's coupons as a project of this workspace's own, projects/coupons, with the MEASURE.md that says
3319
+ // how to read each and the cad measured command that writes it back. Copied, never linked: the maker prints and keeps
3320
+ // them as they are, and a workspace that has the project already keeps it (a newer kit's comes in under another name)
3321
+ function couponsCommand() {
3322
+ const to = paths.project('coupons'),
3323
+ from = path.join(TOOL, 'templates', 'coupons');
3324
+ if (fs.existsSync(to))
3325
+ throw new CadError(
3326
+ 'coupons.exists',
3327
+ "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",
3328
+ );
3329
+ fs.cpSync(from, to, { recursive: true });
3330
+ say(
3331
+ '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',
3332
+ );
3333
+ say(' npx cad export coupons/fixings-coupon (and holds-coupon, slot-coupon): each as a 3MF to print');
3334
+ say(' npx cad measured x1c.pilot_m3=<figure>: a result written back, for every design here to follow');
3335
+ say(' npx cad measured --export: what you measured, as a change to send to the kit');
3336
+ const drawsFor = printerOf(null);
3337
+ if (drawsFor !== 'x1c')
3338
+ say(
3339
+ ` 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`,
3340
+ );
3341
+ }
3342
+
3343
+ // cad measured [<project>/<assembly>] <name>=<value> …: with an assembly, its checks run either side and what moved is
3344
+ // said; without one (the first word a name=value, or no word at all for --export and --strike), a rule measured on a
3345
+ // coupon is written all the same, into the workspace's ledger
3018
3346
  async function measuredCommand(ref) {
3019
- const { recordMeasured, assumptionsTable, writeTable, ledgerLines } = await import('../lib/measured.mjs');
3347
+ const { recordMeasured, assumptions, assumptionsTable, writeTable, ledgerLines, strikeLedger, exportMeasured } =
3348
+ await import('../lib/measured.mjs');
3349
+ const onto = ref && ref.includes('/') ? ref : null;
3350
+ if (opt('export')) return exportCommand(exportMeasured);
3351
+ if (opt('table') && !onto)
3352
+ throw new CadError(
3353
+ 'measured.usage',
3354
+ 'usage: cad measured <project>/<assembly> --table: the figures that assembly rests on (a table is of one assembly)',
3355
+ );
3020
3356
  if (opt('table')) {
3357
+ if (opt('json')) return console.log(JSON.stringify(await assumptions(ref), null, 2));
3021
3358
  const table = await assumptionsTable(ref);
3022
3359
  if (opt('out')) {
3023
3360
  writeTable(path.resolve(opt('out')), table);
@@ -3025,16 +3362,32 @@ async function measuredCommand(ref) {
3025
3362
  }
3026
3363
  return console.log(table);
3027
3364
  }
3365
+ if (args.includes('--strike')) return strikeCommand(onto, strikeLedger);
3028
3366
  const values = Object.fromEntries(
3029
3367
  positional()
3030
- .slice(2)
3368
+ .slice(onto ? 2 : 1)
3031
3369
  .map((x) => {
3032
3370
  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))];
3371
+ if (i < 1)
3372
+ throw new Error(
3373
+ `usage: cad measured [<project>/<assembly>] <name>=<value> … (got "${x}"): an assembly is <project>/<assembly>`,
3374
+ );
3375
+ const v = x.slice(i + 1).trim();
3376
+ // (Number('') is 0: an empty figure would be written as 0, the most trusted kind)
3377
+ if (!v)
3378
+ throw new CadError(
3379
+ 'measured.value',
3380
+ `${x.slice(0, i)} has no figure after its "=": give the one measured (${x.slice(0, i)}=0.25)`,
3381
+ );
3382
+ return [x.slice(0, i), Number(v)];
3035
3383
  }),
3036
3384
  );
3037
- const r = await recordMeasured(ref, values, { unit: opt('unit'), source: opt('source'), rule: opt('rule') });
3385
+ const r = await recordMeasured(onto, values, {
3386
+ unit: opt('unit'),
3387
+ source: opt('source'),
3388
+ rule: opt('rule'),
3389
+ force: !!opt('force'),
3390
+ });
3038
3391
  if (opt('json')) return console.log(JSON.stringify({ entries: r.entries, moved: r.moved }, null, 2));
3039
3392
  for (const l of ledgerLines(r.entries)) say(l);
3040
3393
  for (const m of r.moved)
@@ -3043,16 +3396,72 @@ async function measuredCommand(ref) {
3043
3396
  ? ` ${m.figure}: ${Number(m.from.toFixed(4))} ${m.unit} to ${Number(m.to.toFixed(4))} ${m.unit}`
3044
3397
  : ` ${m.code}: ${m.text}`,
3045
3398
  );
3046
- if (!r.moved.length) say(' nothing the checks say has moved');
3399
+ if (!onto)
3400
+ say(
3401
+ ` 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]}=…)`,
3402
+ );
3403
+ else if (!r.moved.length) say(' nothing the checks say has moved');
3404
+ }
3405
+
3406
+ // cad measured --export: what this workspace measured that the kit lacks, as a diff of the kit's rule sets to send it
3407
+ function exportCommand(exportMeasured) {
3408
+ const r = exportMeasured();
3409
+ if (opt('json')) return console.log(JSON.stringify(r, null, 2));
3410
+ if (!r.sets.length && !r.alone.length)
3411
+ return say(
3412
+ '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',
3413
+ );
3414
+ if (r.diff) process.stdout.write(r.diff);
3415
+ // (on stderr, so the diff alone goes to a file: cad measured --export > measured.diff)
3416
+ for (const a of r.alone)
3417
+ console.error(
3418
+ `${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(', ')}`,
3419
+ );
3420
+ if (r.sets.length)
3421
+ console.error(
3422
+ `${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`,
3423
+ );
3424
+ }
3425
+
3426
+ // cad measured <project>/<assembly> --strike <date> <name>: a row taken out of the ledger (a slip written as measured).
3427
+ // 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
3428
+ // (with no assembly, a row written without one: the workspace's ledger)
3429
+ async function strikeCommand(ref, strikeLedger) {
3430
+ const date = opt('strike'),
3431
+ names = positional().slice(ref ? 2 : 1);
3432
+ if (names.length !== 1)
3433
+ throw new CadError(
3434
+ 'measured.usage',
3435
+ `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`,
3436
+ );
3437
+ const r = strikeLedger(ref, date, names[0]);
3438
+ if (opt('json')) return console.log(JSON.stringify(r, null, 2));
3439
+ say(
3440
+ `struck ${r.struck.length === 1 ? 'a row' : `${r.struck.length} rows`} from ${ref ? `projects/${ref.split('/')[0]}/` : ''}ledger.jsonl:`,
3441
+ );
3442
+ for (const l of r.lines) say(` ${l}`);
3443
+ if (r.rule) say(r.rule.said);
3047
3444
  }
3048
3445
 
3049
3446
  async function ledger(project, name) {
3050
3447
  const { readLedger, ledgerLines } = await import('../lib/measured.mjs');
3051
- const rows = readLedger(project).filter((e) => !name || e.assembly === name);
3448
+ const rows = readLedger(project).filter((e) => !name || e.assembly === name); // (project null: the workspace's)
3052
3449
  return { rows, lines: ledgerLines(rows) };
3053
3450
  }
3054
3451
 
3055
3452
  async function history(ref) {
3453
+ // cad history alone: the figures written with no assembly (cad measured x1c.pilot_m3=2.9), the workspace's ledger
3454
+ if (!ref) {
3455
+ const { rows, lines } = await ledger(null);
3456
+ if (opt('json')) return console.log(JSON.stringify({ ledger: rows }, null, 2));
3457
+ if (!lines.length)
3458
+ return say(
3459
+ "nothing measured here without an assembly yet (cad measured x1c.pilot_m3=<value>); cad history <project> shows a project's",
3460
+ );
3461
+ say('measured on coupons, predicted against measured:');
3462
+ for (const l of lines) say(` ${l}`);
3463
+ return;
3464
+ }
3056
3465
  const [project, name] = ref.split('/');
3057
3466
  if (name && isAssembly(ref)) {
3058
3467
  const { rows, lines } = await ledger(project, name);
@@ -3105,9 +3514,9 @@ async function history(ref) {
3105
3514
 
3106
3515
  async function diff(d, from, to) {
3107
3516
  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);
3517
+ const A = materialise(d, from),
3518
+ B = to ? materialise(d, to) : d;
3519
+ const r = compare(await snap(A, A.reads), await snap(B, B.reads || A.reads));
3111
3520
  console.log(`${d.project}/${d.name} ${from} → ${to || 'now'}: ${r.kind ? `a ${r.kind} change` : 'no changes'}`);
3112
3521
  for (const x of r.reasons) console.log(` ${x.kind.padEnd(5)} ${x.text}`);
3113
3522
  }
@@ -3136,7 +3545,7 @@ function printed(d) {
3136
3545
  console.log(`logged in ${path.relative(WS, printsFile(d))}: ${d.name}@${version} ${result}`);
3137
3546
  }
3138
3547
 
3139
- main().catch((e) => {
3548
+ main().catch(async (e) => {
3140
3549
  if (opt('json'))
3141
3550
  console.log(
3142
3551
  JSON.stringify(
@@ -3149,5 +3558,9 @@ main().catch((e) => {
3149
3558
  console.error(
3150
3559
  `${e.message}${e.file ? ` (${path.relative(WS, e.file)}${e.line ? `:${e.line}` : ''}${e.path ? `: ${e.path}` : ''})` : ''}`,
3151
3560
  );
3561
+ // Nothing of this command is left running in the workspace once it returns (a script may move or remove the folder
3562
+ // straight after, which Windows refuses while a process sits in it): a command that ends by itself waits in
3563
+ // sandbox.mjs; this one exits here, so it waits here
3564
+ await endSandbox();
3152
3565
  process.exit(1);
3153
3566
  });