@floless/app 0.137.3 → 0.138.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 (47) hide show
  1. package/dist/floless-server.cjs +47890 -27033
  2. package/dist/internal-workflows/floless-rfi-gmail-send/.floless-owner.json +1 -0
  3. package/dist/internal-workflows/floless-rfi-gmail-send/floless-rfi-gmail-send.flo +32 -0
  4. package/dist/schemas/steel.model.v2.schema.json +218 -27
  5. package/dist/skills/floless-app-knowledge/SKILL.md +5 -2
  6. package/dist/skills/floless-app-rfi/SKILL.md +410 -0
  7. package/dist/skills/floless-app-routines/SKILL.md +7 -2
  8. package/dist/skills/floless-app-routines/references/routines-api.md +14 -5
  9. package/dist/skills/floless-app-steel-model/SKILL.md +34 -32
  10. package/dist/skills/floless-app-steel-takeoff/SKILL.md +498 -34
  11. package/dist/skills/floless-app-steel-takeoff/references/elevation-registration.md +6 -6
  12. package/dist/skills/floless-app-tweak-contract/SKILL.md +6 -2
  13. package/dist/templates/floless-workspace-knowledge.flo +20 -4
  14. package/dist/templates/steel-model.flo +27 -15
  15. package/dist/web/app.css +559 -131
  16. package/dist/web/app.js +216 -54
  17. package/dist/web/aware.js +982 -128
  18. package/dist/web/checkpoint-standard.js +218 -0
  19. package/dist/web/commands-filter.js +23 -0
  20. package/dist/web/commands-shell.js +237 -5
  21. package/dist/web/commands-steel.js +172 -47
  22. package/dist/web/connection-review-client.js +2 -2
  23. package/dist/web/display-units.js +243 -0
  24. package/dist/web/grid-core.js +474 -58
  25. package/dist/web/grid-display.js +344 -0
  26. package/dist/web/index.html +106 -66
  27. package/dist/web/instructor-reporter.js +5 -0
  28. package/dist/web/instructor.js +175 -33
  29. package/dist/web/json-schema-subset.js +145 -25
  30. package/dist/web/steel-3d-core.js +237 -151
  31. package/dist/web/steel-3d-view.js +366 -113
  32. package/dist/web/steel-catalog-picker.js +98 -15
  33. package/dist/web/steel-detail-refs.js +1 -1
  34. package/dist/web/steel-editor.html +6479 -921
  35. package/dist/web/steel-filter.html +404 -57
  36. package/dist/web/steel-model-adapter.js +1 -1
  37. package/dist/web/steel-model-commands.js +72 -66
  38. package/dist/web/steel-model-v2-client-validation.js +10 -3
  39. package/dist/web/steel-model-v2-commands.js +269 -77
  40. package/dist/web/steel-model-v2-projection.js +18 -17
  41. package/dist/web/steel-plan-transform.js +52 -9
  42. package/dist/web/steel-plan-view-id.js +1 -7
  43. package/dist/web/steel-read-confidence.js +454 -5
  44. package/dist/web/steel-units.js +39 -0
  45. package/dist/web/steel-view-generation.js +21 -7
  46. package/dist/web/workspaces.js +2178 -497
  47. package/package.json +5 -1
@@ -17,8 +17,107 @@
17
17
  * `lines` holds individual free-angle grid/reference lines, used for skewed grids or partial one-offs.
18
18
  */
19
19
 
20
- export const IN_MM = 25.4;
21
- export const FT_MM = 304.8;
20
+ // The same two constants `steel-3d-core` publishes, under this module's historic names (#951). One
21
+ // definition, in `steel-units`; the aliases are what every caller here already reads.
22
+ import { FT_TO_MM as FT_MM, IN_TO_MM as IN_MM } from './steel-units.js';
23
+ export { FT_MM, IN_MM };
24
+
25
+ /**
26
+ * THE AUTHORING QUANTUM a grid snaps to, in millimetres — by grade, then by the project's units (#1148).
27
+ *
28
+ * Two grades, because the module already had two: `fine` is the direct-manipulation quantum (a grid-line
29
+ * drag, and the printed grid read off a drawing), `coarse` is the proposal quantum (a grid inferred from
30
+ * the columns, where a clean string matters more than the last millimetre).
31
+ *
32
+ * THE METRIC VALUES ARE THE OWNER'S RULING, not a measurement (Pawel, 2026-09-06: "use 1mm (as 1/16 in
33
+ * us) and 10mm (as 1/2 is us)"). #1148 had asked for a histogram of the UK reference sets first; the
34
+ * ruling settles it directly and supersedes that step. Both are FINER than the imperial quantum they
35
+ * replace (1/16" is 1.5875 mm, 1/2" is 12.7 mm), so the change can only ever move a line less than
36
+ * today's behaviour does — the safe direction for a quantum chosen without the histogram.
37
+ *
38
+ * What it fixes: an authored 3000 mm snapped to sixteenths comes back 3000.375 — a grid line a third of
39
+ * a millimetre off where the drawing put it, and a spacing string that no longer reads as `3000mm`.
40
+ */
41
+ /**
42
+ * Physical bounds, NOT unit conventions — which is why they are the same in a metric job.
43
+ *
44
+ * They were spelled `2 * FT_MM`, `20 * FT_MM` and `IN_MM`, and #1205 asked whether a metric sheet
45
+ * should get different ones. The answer is no: how far a bubble overhangs its grid, and how thin a
46
+ * bay may get before it is a mis-drag, are facts about drawings rather than about feet. Naming them
47
+ * in millimetres is what stops the next reader having to re-ask. What DOES follow the job is how a
48
+ * bound is SPELLED once it is written into a contract — see `gridExtBoundsMm` below (#1238).
49
+ */
50
+ const GRID_EXT_MIN_MM = 2 * FT_MM; // ≈610 mm
51
+ const GRID_EXT_MAX_MM = 20 * FT_MM; // ≈6096 mm
52
+ const GRID_MIN_BAY_MM = IN_MM; // ≈25.4 mm
53
+
54
+ /**
55
+ * THE ONE UNITS GATE for this module's units-aware writers: is this a metric job, and is the value
56
+ * even a units value? Returns `true` for `'mm'`, `false` for `'ft-in'`, and THROWS for anything else.
57
+ *
58
+ * Its own function because `gridDatumFor` proved the shape and three more writers then needed it.
59
+ * Every one of them has the same failure mode if it defaults instead: `undefined`, `'metric'` and
60
+ * `'MM'` would all quietly seed or spell a US grid, which is silent and permanent in the stored
61
+ * contract (#1205 item 4, and the `snapQuantumMm` comment above for why a default is how the previous
62
+ * attempt at units-awareness shipped as a no-op). The message names the CALLER, so a stack-less
63
+ * assertion in a test still says which writer was left unwired.
64
+ */
65
+ function requireMetric(fn, units) {
66
+ if (units !== 'mm' && units !== 'ft-in') {
67
+ throw new Error('grid-core: ' + fn + ' needs units "mm" or "ft-in", got "' + units + '"');
68
+ }
69
+ return units === 'mm';
70
+ }
71
+
72
+ /**
73
+ * The overhang clamp as the job's own contract may state it — the SAME physical window, spelled to
74
+ * the precision that system writes (#1238).
75
+ *
76
+ * WHY THIS IS NOT #1205 BEING REOPENED. That decision — keep one physical window rather than invent
77
+ * round metric endpoints — stands, and this does not touch it: 609.6 and 6096 mm remain the bounds.
78
+ * What #1238 found is downstream of it. `2 * FT_MM` is 609.6, so a metric job whose overhang fell
79
+ * under the floor stored `ext: 609.6` — a tenth of a millimetre, in a contract whose every other
80
+ * length is whole (`z: '0mm'`, `ext: 2000`, spacings on the 1 mm quantum). The number is not wrong;
81
+ * its SPELLING claims a precision a metric drawing does not state.
82
+ *
83
+ * NEVER WIDER THAN THE PHYSICAL WINDOW: the floor rounds UP and the ceiling DOWN, so the metric
84
+ * window is contained by the imperial one rather than straddling it. Both endpoints move by less than
85
+ * a millimetre (609.6 → 610; 6096 is already whole and does not move at all), which is four orders
86
+ * below the "arbitrary within an order of magnitude" the bounds themselves are chosen to.
87
+ */
88
+ export function gridExtBoundsMm(units) {
89
+ return requireMetric('gridExtBoundsMm', units)
90
+ ? { min: Math.ceil(GRID_EXT_MIN_MM), max: Math.floor(GRID_EXT_MAX_MM) }
91
+ : { min: GRID_EXT_MIN_MM, max: GRID_EXT_MAX_MM };
92
+ }
93
+
94
+ const SNAP_QUANTUM_MM = {
95
+ fine: { 'ft-in': IN_MM / 16, mm: 1 },
96
+ coarse: { 'ft-in': IN_MM / 2, mm: 10 },
97
+ };
98
+
99
+ /**
100
+ * The quantum for one grade and one unit system.
101
+ *
102
+ * BOTH ARGUMENTS ARE REQUIRED and an unknown value THROWS, deliberately. The obvious alternative — a
103
+ * `units = 'ft-in'` default — is how the previous attempt at this failed: every call site kept
104
+ * compiling, nothing passed the option, and the test asserted only that the option was ACCEPTED, so it
105
+ * stayed green for as long as the defect was still there. A grid quantised in the wrong system is
106
+ * silent and permanent; a missing argument should not be.
107
+ */
108
+ export function snapQuantumMm(grade, units) {
109
+ const row = SNAP_QUANTUM_MM[grade];
110
+ if (!row) throw new Error('grid-core: unknown snap grade "' + grade + '"');
111
+ const mm = row[units];
112
+ if (!(mm > 0)) throw new Error('grid-core: snapQuantumMm needs units "mm" or "ft-in", got "' + units + '"');
113
+ return mm;
114
+ }
115
+
116
+ /** Round `mm` to the authoring quantum for `grade` in `units`. */
117
+ export function snapToQuantum(mm, grade, units) {
118
+ const q = snapQuantumMm(grade, units);
119
+ return Math.round(mm / q) * q;
120
+ }
22
121
 
23
122
  const gcd = (a, b) => { while (b) { const t = a % b; a = b; b = t; } return a; };
24
123
  export const truncateText = (value, maxLength = 40) => Array.from(String(value == null ? '' : value)).slice(0, maxLength).join('');
@@ -40,17 +139,29 @@ const parseInches = (raw) => {
40
139
  };
41
140
 
42
141
  /**
43
- * mm per display px for a plan scale — THE one implementation of the plan display scale.
142
+ * A view's mm-per-display-px scale, guarded — THE one gate every plan-scale read passes through.
44
143
  *
45
- * It lives in this leaf module because five copies of `FT_MM / (ptPerFt > 0 ? ptPerFt : 1)` had grown
46
- * (here, steel-3d-core's `kOf`, steel-model-adapter's and steel-model-commands' `scaleOf`, and inline
47
- * in steel-plan-transform and server/contract-to-scene), each carrying a comment telling the next
48
- * reader to keep it in lock-step with the others by hand. They all import this now.
144
+ * It lives in this leaf module because five copies of the same expression had grown (here,
145
+ * steel-3d-core's `kOf`, steel-model-adapter's and steel-model-commands' `scaleOf`, and inline in
146
+ * steel-plan-transform and server/contract-to-scene), each carrying a comment telling the next reader
147
+ * to keep it in lock-step with the others by hand. They all import this now.
49
148
  *
50
- * A missing, zero or negative `pt_per_ft` reads as 1 pt/ft rather than dividing by it, so an
51
- * unscaled sheet degrades to a 1:1 map instead of putting Infinity or a mirrored scale into geometry.
149
+ * IT NO LONGER COMPUTES ANYTHING (UK epic, slice 0). The contract used to store `mm_per_px` — display
150
+ * points per FOOT — and this divided `FT_MM` by it on every read. A scale measured per foot cannot
151
+ * describe a metric sheet at all: a 1:100 drawing has no natural points-per-foot, which is why
152
+ * `steel-scale-fit` refuses one outright. So the stored quantity IS mm-per-px now and this only
153
+ * validates it.
154
+ *
155
+ * RENAMED DELIBERATELY, from `mmPerPx`. Keeping the name while inverting the meaning of its argument
156
+ * is the one change a caller cannot notice: `mmPerPx(12)` would have quietly answered 12 where it
157
+ * used to answer 25.4, and every such site still compiles. Under the new name a caller that was not
158
+ * revisited does not exist.
159
+ *
160
+ * A missing, zero or negative scale reads as `FT_MM` — the same 1 pt/ft degenerate the old guard
161
+ * produced — so an unscaled sheet degrades to a 1:1 map instead of putting Infinity, 0 or a mirrored
162
+ * scale into geometry.
52
163
  */
53
- export const mmPerPx = (ptPerFt) => FT_MM / (ptPerFt > 0 ? ptPerFt : 1);
164
+ export const sheetScaleMm = (mmPerPx) => (mmPerPx > 0 ? mmPerPx : FT_MM);
54
165
 
55
166
  /** One length token → mm, or NaN. Accepts 25' | 25'-6 1/2" | 6 1/2" | 1/2" | 7.5m | 6096 (mm) | 6096mm; leading '-' negates. */
56
167
  export function parseLen(tok) {
@@ -131,11 +242,127 @@ export function parseSpacings(str) {
131
242
  return { offsets, err: null };
132
243
  }
133
244
 
134
- /** Cumulative offsets (mm) → a canonical comma-separated string; equal runs compress to n*d. */
135
- export function formatSpacings(offsets) {
245
+ /**
246
+ * Refuse anything that is not a real, finite number of millimetres — BEFORE either spelling is tried.
247
+ *
248
+ * The code this guards used to do `mm.toFixed(6)`, which threw a TypeError on a non-number and emitted
249
+ * the unparseable `NaNmm` for NaN: either way the caller found out. A tolerant `Number(...)` would
250
+ * remove both signals, because the fallback is `fmtLen`, whose own `Number(mm) || 0` turns NaN into
251
+ * **zero** — so a NaN or null elevation would be persisted into `grid.z` as ground level with nothing
252
+ * said anywhere.
253
+ *
254
+ * `typeof`, not `Number(...)`: `Number(null)` is 0, so a null would otherwise spell `0'-0"`, match the
255
+ * round trip exactly, and return before any check could see it. That is the value a malformed document
256
+ * is likeliest to carry.
257
+ *
258
+ * Every live caller passes `parseLevels`/`parseSpacings` output, which is finite by construction, so
259
+ * this throws for a programming error rather than for data.
260
+ */
261
+ function finiteMm(mm) {
262
+ if (typeof mm !== 'number' || !Number.isFinite(mm)) {
263
+ throw new TypeError(`grid notation needs a finite length in mm, got ${typeof mm === 'string' ? JSON.stringify(mm) : String(mm)}`);
264
+ }
265
+ return mm;
266
+ }
267
+
268
+ /**
269
+ * A length (mm) as an exact decimal millimetre token, or `null` when it has no such spelling.
270
+ *
271
+ * `toFixed(6)` goes exponential past ~1e21 and `parseLen` has no exponent in its grammar, so a token
272
+ * like `1e+21mm` would not lose one value — it would make the WHOLE grid string unreadable, because
273
+ * one unparseable token fails the parse of the string it sits in. `formatLevels` has been able to emit
274
+ * exactly that since it was written (its own comment claimed `parseLen` refuses such values on the way
275
+ * in; it does not, and a COMPUTED offset can reach it). Returning `null` lets each caller fall back to
276
+ * the architectural form, which always parses.
277
+ *
278
+ * EXPORTED because `grid-display.js` needs the identical rule on the way IN. Rewriting a typed metric
279
+ * elevation into storage grammar (`+4.200` -> `4200mm`) has exactly this failure mode, and a token that
280
+ * stringifies exponentially would not lose one value - it would make the whole grid string unreadable,
281
+ * from a token that PARSED FINE, so a scheme that maps failures back to what the user typed cannot see
282
+ * it. One definition of "a length as an exact millimetre token", for the writer and the reader both.
283
+ */
284
+ export function millimetreToken(mm) {
285
+ const fixed = mm.toFixed(6).replace(/\.?0+$/, '');
286
+ return /^-?\d+(?:\.\d+)?$/.test(fixed) ? `${fixed}mm` : null;
287
+ }
288
+
289
+ /**
290
+ * How far a SPACING may sit from what its architectural spelling means and still be written that way.
291
+ *
292
+ * FLOAT DUST, NOT A QUANTUM. A nanometre is nine orders below the 1/16" (1.5875 mm) the architectural
293
+ * notation resolves, and four orders above the error that accumulates across a real sheet. Nothing on
294
+ * a drawing lives in that gap; only arithmetic does.
295
+ *
296
+ * EXPORTED so `grid-display.js` compresses a metric run on the SAME tolerance this file spells one with.
297
+ * A metric display token resolves to a tenth of a millimetre, so compressing over the spelled tokens
298
+ * would fuse bays of 6000.75 and 6000.79 into one `2*6000.8` - the pane asserting an equality that is
299
+ * false. Comparing the offsets on this tolerance instead keeps a genuinely uniform run compressed while
300
+ * refusing to invent one.
301
+ */
302
+ export const SPACING_DUST_MM = 1e-6;
303
+
304
+ /**
305
+ * One BAY (mm) -> its authoring token. The spacing half of the serialisation rule.
306
+ *
307
+ * WHY IT EXISTS. The architectural spelling quantises to a sixteenth of an inch, which is not a
308
+ * lattice a metric drawing sits on: an authored 6000 mm bay spells `19'-8 1/4"` and reads back as
309
+ * 6000.75, and across five axes the error compounds to 3 mm. `formatLevels` has always guarded against
310
+ * that; `formatSpacings` never did, so a grid's SPACINGS lost what its LEVELS kept.
311
+ *
312
+ * WHY THIS IS A TOLERANCE WHERE `formatLevels` USES EQUALITY — the two are not the same question, and
313
+ * trying to make them one rule failed twice before this comment was written:
314
+ *
315
+ * - A bay is a DIFFERENCE of cumulative offsets, so it carries accumulated float error: `3 * 1.5875`
316
+ * is 4.762499999999999, whose implied bay is 1.5874999999999986. Under a strict equality that
317
+ * exactly-imperial bay fails its own round trip and takes the millimetre branch — measured, that
318
+ * rewrites 65,245 of 96,000 exactly-imperial grids into metric notation.
319
+ * - Worse, the dust is not uniform across one run. In `[0, d, 2d, 3d, 4d]` at d = 112.7125, bays 1, 2
320
+ * and 4 land a hair BELOW the exact double and bay 3 lands exactly on it. Any rule keyed on
321
+ * exactness therefore spells bay 3 differently from its neighbours and splits a uniform US run
322
+ * into `2*0'-4 7/16", 112.7125mm, 0'-4 7/16"`. Notation stability across a run is the property a
323
+ * spacing needs, and only a tolerance delivers it.
324
+ *
325
+ * A LEVEL has neither problem: it is an authored absolute, not a difference, and it has no run to stay
326
+ * uniform with. What it needs is that it persists exactly, which equality gives it and a tolerance
327
+ * takes away (3657.6 mm is twelve feet, and `12'-0"` reads back 3657.6000000000004 — caught by
328
+ * `grid-level-persistence.test.ts`). So the two policies stay separate on purpose, and share only the
329
+ * token construction above.
330
+ *
331
+ * `units` DECIDES WHICH NOTATION IS THE DEFAULT, and that is #1238. Until it did, this function asked
332
+ * only "does this bay happen to land on a sixteenth of an inch", so a metric job's leading ZERO — which
333
+ * lands on every lattice there is — came back `0'-0"` beside metric bays, and any bay that happened to
334
+ * be exactly imperial (6096 mm is twenty feet) came back architectural too. `defaultGrid` had spelled
335
+ * the same field `0mm, 3*6000mm` since #1134, so the module contradicted its own precedent in the one
336
+ * field a stored grid is mostly made of. A metric job now prefers the millimetre token everywhere and
337
+ * keeps the architectural spelling only as the fallback for a value no fixed-notation token can state
338
+ * (see `millimetreToken`); an imperial job is untouched, token for token.
339
+ */
340
+ export function spacingToken(mm, units) {
341
+ const metric = requireMetric('spacingToken', units);
342
+ finiteMm(mm);
343
+ const architectural = fmtLen(mm);
344
+ if (metric) return millimetreToken(mm) ?? architectural;
345
+ if (Math.abs(parseLen(architectural) - mm) <= SPACING_DUST_MM) return architectural;
346
+ return millimetreToken(mm) ?? architectural;
347
+ }
348
+
349
+ /**
350
+ * Cumulative offsets (mm) → a canonical comma-separated string; equal runs compress to n*d.
351
+ *
352
+ * `units` is REQUIRED and is validated FIRST, ahead of the empty-offsets exit: an empty axis is the
353
+ * one input that would otherwise let an unwired call site return a plausible `''` forever.
354
+ */
355
+ export function formatSpacings(offsets, units) {
356
+ requireMetric('formatSpacings', units);
136
357
  if (!offsets || !offsets.length) return '';
358
+ // THE OFFSETS, not the differences. A bad value is consumed by the subtraction before any token is
359
+ // spelled - `null - 0` is a clean `0` - so guarding the diffs would let a null offset through as a
360
+ // perfectly ordinary `0'-0"` bay while NaN and undefined were refused.
361
+ offsets.forEach(finiteMm);
137
362
  const diffs = offsets.map((v, i) => v - (i ? offsets[i - 1] : 0));
138
- const tokens = diffs.map(fmtLen);
363
+ // Per BAY, then compressed - the compression runs over the TOKENS, so deriving a token differently
364
+ // leaves `n*d` intact.
365
+ const tokens = diffs.map((mm) => spacingToken(mm, units));
139
366
  const out = [];
140
367
  for (let i = 0; i < tokens.length;) {
141
368
  let j = i + 1;
@@ -157,14 +384,26 @@ export function parseLevels(str, labelsZ = []) {
157
384
  const token = split.tokens[sourceIndex];
158
385
  const rawMm = parseLen(token);
159
386
  if (!isFinite(rawMm)) return { levels: [], err: 'can’t read “' + token + '”', warnings, tokens: split.tokens };
160
- const mm = parseLen(fmtLen(rawMm)); // persist the same 1/16" value the panel displays, so two authored values can never serialize identically and collapse on the next read
387
+ // THE AUTHORED VALUE, not a rounded copy of it. This used to round-trip through `fmtLen`, which
388
+ // quantises to a sixteenth of an inch — so an authored `3000` came back 3000.3750000000005 and the
389
+ // 3D grid plane sat a third of a millimetre off the level the drawing states. The round trip was
390
+ // there to keep serialisation injective (two authored values must never write the same string and
391
+ // collapse on the next read); `formatLevels` now guarantees that directly, which is the right place
392
+ // for it: a persistence rule enforced by rounding the DATA corrupts the data to protect the format.
393
+ const mm = rawMm;
161
394
  const authored = truncateText(String(labels[sourceIndex] == null ? '' : labels[sourceIndex]).trim());
162
- const duplicate = levels.find((z) => Math.abs(z.mm - mm) < 0.5);
395
+ const duplicate = levels.find((z) => Math.abs(z.mm - mm) < LEVEL_SAME_MM);
163
396
  if (duplicate) {
164
397
  warnings.push({ kind: authored && authored !== duplicate.label ? 'duplicate-label' : 'duplicate-level', sourceIndex, keptSourceIndex: duplicate.sourceIndex });
165
398
  continue;
166
399
  }
167
- levels.push({ mm, label: authored || fmtLen(mm), sourceIndex });
400
+ // `authored` is ADDITIVE and `label` is unchanged, deliberately. `label` is persistence-grade - it
401
+ // becomes a saved view's NAME (`steel-view-generation.js`), so it must not vary with anyone's display
402
+ // preference. `authored` is the same value minus the fallback, which is the only thing a display layer
403
+ // needs: it says "was this level NAMED", so a units-aware renderer can spell the elevation itself
404
+ // rather than guess by comparing against `fmtLen(mm)` - a guess that is wrong the moment someone names
405
+ // a level `0'-0"`.
406
+ levels.push({ mm, label: authored || fmtLen(mm), authored, sourceIndex });
168
407
  }
169
408
  for (let i = split.tokens.length; i < labels.length; i++) {
170
409
  if (String(labels[i] == null ? '' : labels[i]).trim()) warnings.push({ kind: 'orphan-label', sourceIndex: i });
@@ -173,8 +412,32 @@ export function parseLevels(str, labelsZ = []) {
173
412
  return { levels, err: null, warnings, tokens: split.tokens };
174
413
  }
175
414
 
176
- /** Stable identity for a canonical level elevation: integer sixteenths of an inch. */
177
- export const gridLevelKey = (mm) => typeof mm === 'number' && Number.isFinite(mm) ? Math.round(mm / (IN_MM / 16)) : null;
415
+ /**
416
+ * HOW FAR APART TWO ELEVATIONS MUST BE TO BE TWO LEVELS. This is the single authority on level identity:
417
+ * `parseLevels` drops anything nearer than this to a level it already kept, and every other rule below
418
+ * is subordinate to it.
419
+ *
420
+ * Half a millimetre, which is finer than any real drawing states a level to and coarser than float
421
+ * noise. Unchanged in value — it is what the de-duplication already used — but it had no name, so a
422
+ * second, DIFFERENT identity rule (`gridLevelKey`, at a sixteenth of an inch) grew up beside it and the
423
+ * two disagreed about pairs between 0.5 mm and 1.5875 mm apart.
424
+ */
425
+ export const LEVEL_SAME_MM = 0.5;
426
+
427
+ /**
428
+ * A stable numeric handle for a canonical level elevation — integer HUNDREDTHS of a millimetre.
429
+ *
430
+ * DELIBERATELY FINER THAN `LEVEL_SAME_MM`, and that relationship is the whole design: this key must
431
+ * never merge two levels the de-duplication decided to keep apart. Any pair at least half a millimetre
432
+ * apart differs by at least fifty here, so it cannot. The de-duplication decides identity; this only
433
+ * names it.
434
+ *
435
+ * It used to be integer sixteenths of an INCH, which was coarser than the de-duplication — so two levels
436
+ * 0.8 mm apart survived as two and then collided here, and hiding one hid the other. It was also an
437
+ * imperial quantum standing in for a rule about millimetres, which is the shape of thing this epic
438
+ * exists to remove.
439
+ */
440
+ export const gridLevelKey = (mm) => typeof mm === 'number' && Number.isFinite(mm) ? Math.round(mm * 100) : null;
178
441
 
179
442
  /**
180
443
  * Keep only hidden elevations that still exist in the authored level list, returning the authored
@@ -278,10 +541,13 @@ export function reconcileLevelLabels(previousParsed, normalizedLabels = [], next
278
541
  ? normalizedLabels.map((label) => truncateText(String(label == null ? '' : label).trim()))
279
542
  : [];
280
543
  const byElevation = new Map();
281
- previous.forEach((level, index) => byElevation.set(fmtLen(level.mm), { index, label: labels[index] || '' }));
544
+ // Keyed on the NUMERIC identity. It used to key on `fmtLen(level.mm)` — a display string, and one
545
+ // that is not injective: two distinct levels inside the same sixteenth of an inch shared a key, so one
546
+ // label was silently reassigned to the other's level.
547
+ previous.forEach((level, index) => byElevation.set(gridLevelKey(level.mm), { index, label: labels[index] || '' }));
282
548
  const used = new Set();
283
549
  const matched = next.map((level) => {
284
- const prior = byElevation.get(fmtLen(level.mm));
550
+ const prior = byElevation.get(gridLevelKey(level.mm));
285
551
  if (!prior) return '';
286
552
  used.add(prior.index);
287
553
  return prior.label;
@@ -294,8 +560,94 @@ export function reconcileLevelLabels(previousParsed, normalizedLabels = [], next
294
560
  return { labels: [...matched, ...extras], extraCount: extras.length };
295
561
  }
296
562
 
563
+ /**
564
+ * Canonical level elevations -> the string `grid.z` stores. LOSSLESS and INJECTIVE, which the old
565
+ * `levels.map(fmtLen)` was neither.
566
+ *
567
+ * `fmtLen` rounds to a sixteenth of an inch, so it lost the value (an authored 3000 mm came back as
568
+ * 3000.375) AND collapsed distinct levels onto one token. Both mattered: the first moved a grid plane,
569
+ * and the second is what the parser's own quantisation was bolted on to hide.
570
+ *
571
+ * THE RULE: keep the architectural form when it round-trips EXACTLY, and fall back to an explicit
572
+ * millimetre token when it does not. So a US grid still reads `0'-0", 16'-6"` — the notation its author
573
+ * typed — while a metric level writes `3000mm` rather than being rounded into `9'-10 1/8"`.
574
+ *
575
+ * Injective, and provably so rather than by inspection: two values that both survive the ft-in round
576
+ * trip and share a string are the same value, a millimetre token names its value uniquely, and the two
577
+ * forms cannot be confused for one another because one always ends in `mm`.
578
+ *
579
+ * UNIT-NEUTRAL. This is persistence, not display: what it writes must read back identically whatever
580
+ * the reader's display preference is, which is exactly why it does not consult one.
581
+ */
297
582
  export function formatLevels(levels) {
298
- return (levels || []).map(fmtLen).join(', ');
583
+ // EQUALITY, not the tolerance `spacingToken` uses, and the divergence is argued there: a level is an
584
+ // authored absolute that must persist exactly, where a bay is a difference that must stay spelled
585
+ // like its neighbours. What this no longer does is trust `toFixed` never to go exponential - that
586
+ // fallback is shared, because an unparseable token breaks the whole string either way.
587
+ return (levels || []).map((mm) => {
588
+ finiteMm(mm);
589
+ const architectural = fmtLen(mm);
590
+ if (parseLen(architectural) === mm) return architectural;
591
+ return millimetreToken(mm) ?? architectural;
592
+ }).join(', ');
593
+ }
594
+
595
+ /**
596
+ * One `dir:'z'` axis row per parsed level — the reconciliation a `grid.z` write has to carry with it.
597
+ *
598
+ * WHY THIS HAS TO EXIST. `steel.model/v2` requires the z-axis count to EQUAL the parsed level count
599
+ * (`server/steel-model-v2.ts`, code `grid-axis-count`). Nothing enforced that on the write side: the
600
+ * client validator does not check it and `patchGrid` copies its patch verbatim, so adding a level
601
+ * produced a document the editor accepted and the SERVER refused — the edit looked like it worked and
602
+ * then failed to persist. Verified by executing it, not by reading.
603
+ *
604
+ * EXISTING ROWS ARE MATCHED BY ELEVATION when the caller can say what the rows meant, and positionally
605
+ * only when it cannot. An axis row carries no elevation of its own, so the elevation has to come from
606
+ * OUTSIDE: `priorLevels` is the parse of the `grid.z` these rows were last written for, zipped onto them
607
+ * in order. That is what turns "row 2" into "the row for 3048 mm", and it is the whole difference
608
+ * between inserting a level and renaming every level below it.
609
+ *
610
+ * Insert 3000 between 0 and 6000 with no `priorLevels` and the Roof row lands on 3000 while 6000 gets a
611
+ * brand-new id — a level was added and two existing ones silently changed identity. With `priorLevels`,
612
+ * 0 and 6000 keep their rows and ids and 3000 alone is minted.
613
+ *
614
+ * `gridLevelKey` is deliberately the identity used here, so this cannot disagree with `hidden_z` and
615
+ * label reconciliation about which row belongs to which level. A level with no prior row gets a fresh
616
+ * id; a row whose level is gone is dropped with it.
617
+ *
618
+ * WHEN `priorLevels` IS OMITTED the match falls back to position, which is right for the caller that has
619
+ * no prior string to parse (a wholesale `setGrid` replacing the document's grid outright) and wrong for
620
+ * an edit. Both behaviours are pinned by tests, including the middle-insertion case that separates them.
621
+ *
622
+ * `mintId` is INJECTED rather than generated here: ids are the caller's policy, and the editor's
623
+ * characterization harness pins them.
624
+ */
625
+ export function reconcileGridZAxes(grid, levels, mintId, priorLevels) {
626
+ const rows = Array.isArray(grid && grid.axes) ? grid.axes : [];
627
+ const priorZ = rows.filter((r) => r && r.dir === 'z');
628
+ // The rows' elevations, supplied by the caller as the parse of the string they were written for. A
629
+ // row's own `mm` is honoured first if a future schema ever gives it one — then this stops needing the
630
+ // caller at all — but nothing writes it today, so `priorLevels` is where the elevations come from.
631
+ const byKey = new Map();
632
+ const prior = Array.isArray(priorLevels) ? priorLevels : null;
633
+ if (prior) {
634
+ priorZ.forEach((row, index) => {
635
+ const mm = row && row.mm != null ? row.mm : (prior[index] && prior[index].mm);
636
+ const key = gridLevelKey(mm);
637
+ if (key != null && !byKey.has(key)) byKey.set(key, row);
638
+ });
639
+ }
640
+ const used = new Set();
641
+ const next = (levels || []).map((level, index) => {
642
+ const matched = byKey.get(gridLevelKey(level && level.mm)) || (prior ? null : priorZ[index]);
643
+ // A row is claimed by at most one level. Two levels inside one `gridLevelKey` cannot both take the
644
+ // same row and hand the document two axes with one id — which `grid-axis-id-unique` would refuse.
645
+ if (matched && !used.has(matched)) { used.add(matched); return { ...matched }; }
646
+ return { id: mintId(), dir: 'z' };
647
+ });
648
+ const others = rows.filter((r) => !r || r.dir !== 'z');
649
+ // Order preserved: non-z rows keep their places, z rows follow the level order the parse produced.
650
+ return [...others.filter(Boolean), ...next];
299
651
  }
300
652
 
301
653
  /** Auto labels: style 'num' → 1,2,3… ; 'alpha' → A…Z, AA, AB… */
@@ -420,9 +772,51 @@ export function axisLabelText(g, dir, style, n) {
420
772
  return labels.some((l) => /\s/.test(l)) ? null : labels.join(' ');
421
773
  }
422
774
 
423
- /** A fresh default grid (display-space origin px). 4×4 30' bays, ground level only. */
424
- export function defaultGrid(origin) {
425
- return { on: true, origin: (origin || [0, 0]).slice(0, 2), x: "0'-0\", 3*30'-0\"", y: "0'-0\", 3*30'-0\"", z: "0'-0\"", labels_x: '', labels_y: '', labels_z: [], ext: 5 * FT_MM };
775
+ /**
776
+ * The datum a proposed grid starts from, in the project's own units.
777
+ *
778
+ * ONE definition, used by `defaultGrid` and by all three inferring builders. They used to spell it
779
+ * four times and three of them spelled it in feet regardless of the job (#1205): a metric plan got a
780
+ * 1524 mm extension and a level called `0'-0"` sitting next to spacings #1148 had already made
781
+ * metric. A shared seed is what stops that happening a second time.
782
+ */
783
+ export function gridDatumFor(units) {
784
+ // VALIDATED here, not only in `defaultGrid`. This is exported, so leaving it to treat every value
785
+ // but 'mm' as imperial would keep a public route back to the exact silent-imperial failure this
786
+ // change removes — `undefined`, `'metric'` and `'MM'` would all quietly seed a US grid. The check
787
+ // itself moved to `requireMetric` when #1238 gave three more writers the same requirement; the
788
+ // policy and the message are this function's, unchanged.
789
+ return requireMetric('gridDatumFor', units)
790
+ ? { z: '0mm', ext: 2000 }
791
+ : { z: "0'-0\"", ext: 5 * FT_MM };
792
+ }
793
+
794
+ /**
795
+ * A fresh default grid (display-space origin px) — the "Start blank" seeds, in the project's own
796
+ * units. 4×4 bays, ground level only.
797
+ *
798
+ * A metric project used to get 30-foot bays shown in millimetres, which is an imperial grid wearing a
799
+ * metric hat — 9144 mm bays nobody would ever draw. `mm` seeds 6 m bays with a 2 m extension, which
800
+ * is what a UK frame actually looks like. (Ruled by the owner, 2026-09-05.)
801
+ *
802
+ * SCOPED TO A NEW GRID, and nothing else. The absent-`ext` fallback in `gridGeometry` stays 5 ft on
803
+ * purpose: that one applies to grids ALREADY AUTHORED, so changing it would silently move existing
804
+ * geometry rather than choose a starting point.
805
+ *
806
+ * `units` is REQUIRED. This paragraph used to say a default argument kept every existing caller on
807
+ * the imperial grid they were written against — that is no longer true and was the point of #1205
808
+ * item 4: the omission it protected was the silent imperial read.
809
+ */
810
+ export function defaultGrid(origin, units) {
811
+ // REQUIRED, and an unknown value throws — through `gridDatumFor`, so there is ONE gate rather than
812
+ // two that can disagree. Same policy as `snapQuantumMm`, for the reason it gives: a
813
+ // `units = 'ft-in'` default is how the previous attempt at this shipped as a no-op, with every
814
+ // call site still compiling and nothing passing the option. A grid seeded in the wrong system is
815
+ // silent and permanent. (#1205 item 4.)
816
+ const datum = gridDatumFor(units);
817
+ const metric = units === 'mm';
818
+ const span = metric ? '0mm, 3*6000mm' : "0'-0\", 3*30'-0\"";
819
+ return { on: true, origin: (origin || [0, 0]).slice(0, 2), x: span, y: span, z: datum.z, labels_x: '', labels_y: '', labels_z: [], ext: datum.ext };
426
820
  }
427
821
 
428
822
  /** True when g is structurally usable (parseable origin — the spacing strings report their own errors). */
@@ -458,16 +852,16 @@ export function gridLines(g) {
458
852
  *
459
853
  * `opts.yUp` selects coordinate space. Default false is a projected sheet grid, where Y grows DOWN the
460
854
  * page and spacings run UP it (`oy - off`). True is the native model grid, already in world mm with Y
461
- * up, so the spacings run along +Y and `ptPerFt` should be FT_MM (k = 1, the identity). Passing a native grid
855
+ * up, so the spacings run along +Y and the scale should be 1 mm/px (the identity). Passing a native grid
462
856
  * without this does not throw — it draws the whole grid mirrored about the origin's Y, plausibly, which is
463
857
  * the silent-wrong-space failure this epic exists to prevent.
464
858
  *
465
859
  * It also selects which per-line extent vocabulary is read: projected index-keyed `ends_x`/`ends_y` in
466
860
  * display px, or the native `ends` map keyed by stable axis id in world mm.
467
861
  */
468
- export function gridGeometry(g, ptPerFt, opts = {}) {
862
+ export function gridGeometry(g, mmPerPx, opts = {}) {
469
863
  const yUp = !!opts.yUp;
470
- const k = mmPerPx(ptPerFt);
864
+ const k = sheetScaleMm(mmPerPx);
471
865
  const px = (mm) => mm / k;
472
866
  const X = parseSpacings(g && g.x), Y = parseSpacings(g && g.y);
473
867
  const ok = sane(g);
@@ -530,12 +924,12 @@ export function gridGeometry(g, ptPerFt, opts = {}) {
530
924
  * position, or null when there's no such line.
531
925
  * ponytail: overrides are keyed by line INDEX — editing the spacing string re-maps them positionally.
532
926
  */
533
- export function moveGridLineEnd(g, ptPerFt, axis, i, end, np) {
534
- const geo = gridGeometry(g, ptPerFt);
927
+ export function moveGridLineEnd(g, mmPerPx, axis, i, end, np) {
928
+ const geo = gridGeometry(g, mmPerPx);
535
929
  const line = (axis === 'v' ? geo.v : geo.h)[i];
536
930
  if (!line) return null;
537
931
  const auto = axis === 'v' ? [geo.y0, geo.y1] : [geo.x0, geo.x1];
538
- const k = mmPerPx(ptPerFt);
932
+ const k = sheetScaleMm(mmPerPx);
539
933
  const MINLEN = 12 * IN_MM / k; // 12" minimum line length in px
540
934
  const other = end === 0 ? line.hi : line.lo;
541
935
  np = end === 0 ? Math.min(np, other - MINLEN) : Math.max(np, other + MINLEN);
@@ -575,10 +969,10 @@ export function gridSnapGeom(geo) {
575
969
  * Emitted PLAN-ONLY on purpose: 'grid-line' / 'grid-int' snap X/Y and keep the dragged Z, so a grid
576
970
  * can never yank a member off its elevation (candidatePoint in steel-3d-core honors that).
577
971
  */
578
- export function gridCandidates3d(g, ptPerFt, opts = {}) {
972
+ export function gridCandidates3d(g, mmPerPx, opts = {}) {
579
973
  if (!g || !g.on) return [];
580
- const geo = gridGeometry(g, ptPerFt, opts);
581
- const k = mmPerPx(ptPerFt);
974
+ const geo = gridGeometry(g, mmPerPx, opts);
975
+ const k = sheetScaleMm(mmPerPx);
582
976
  // The SAME reflection the 3D view applies to the drawn grid, and it must stay the same one or the snap
583
977
  // targets sit mirrored away from the lines the user is aiming at. `yUp` (v2, world mm) means none.
584
978
  const sy = opts.yUp ? k : -k;
@@ -597,31 +991,38 @@ export function gridCandidates3d(g, ptPerFt, opts = {}) {
597
991
  * axis 'v' = a vertical line (position = display x), 'h' = horizontal (display y). Mutates g:
598
992
  * clamps between neighbours (1" minimum bay — a drag can never reorder lines or scramble labels),
599
993
  * rebases the origin when the FIRST line moves (the other lines keep their world positions), and
600
- * rewrites the spacing string with offsets snapped to 1/16". Returns the clamped position (px),
994
+ * rewrites the spacing string with offsets snapped to the project's fine authoring quantum
995
+ * (1/16" in a US job, 1 mm in a metric one - `snapQuantumMm`; `units` is REQUIRED and throws). Returns the clamped position (px),
601
996
  * or null when the grid/axis has no such line.
997
+ * `units` comes BEFORE the optional `base` because it is REQUIRED: a required argument sitting after
998
+ * an optional one is how a caller ends up passing the units where the drag baseline goes.
602
999
  * `base` (optional) = the axis's line positions captured at DRAG START — pass it on every move of
603
1000
  * one continuous drag so the string is quantized ONCE from the originals; re-deriving from the
604
- * just-written string each mousemove lets 1/16" rounding creep onto lines that never moved.
1001
+ * just-written string each mousemove lets that rounding creep onto lines that never moved.
605
1002
  */
606
- export function moveGridLine(g, ptPerFt, axis, i, np, base) {
607
- const geo = gridGeometry(g, ptPerFt);
608
- const k = mmPerPx(ptPerFt);
609
- const snap16 = (mm) => Math.round(mm / (IN_MM / 16)) * (IN_MM / 16);
610
- const MIN = IN_MM / k; // 1" in display px
1003
+ export function moveGridLine(g, mmPerPx, axis, i, np, units, base) {
1004
+ const geo = gridGeometry(g, mmPerPx);
1005
+ const k = sheetScaleMm(mmPerPx);
1006
+ const snap16 = (mm) => snapToQuantum(mm, 'fine', units);
1007
+ // PHYSICAL, like the extension bounds above, and unchanged for a metric job (#1205 item 3): the
1008
+ // smallest bay a drag may produce is ~25 mm in any unit system, because a bay thinner than that is
1009
+ // a mis-drag rather than a decision. A clamp is not a quantum — #1148 left it alone for that
1010
+ // reason and this keeps it, respelled so the number stops reading as an imperial assumption.
1011
+ const MIN = GRID_MIN_BAY_MM / k;
611
1012
  if (axis === 'v') {
612
1013
  if (!geo.v[i] && !(base && base[i] != null)) return null;
613
1014
  const xs = base ? base.slice() : geo.v.map((l) => l.x); // ascending
614
1015
  np = Math.max(i > 0 ? xs[i - 1] + MIN : -Infinity, Math.min(i < xs.length - 1 ? xs[i + 1] - MIN : Infinity, np));
615
1016
  xs[i] = np;
616
1017
  g.origin[0] = xs[0];
617
- g.x = formatSpacings(xs.map((x) => snap16((x - xs[0]) * k)));
1018
+ g.x = formatSpacings(xs.map((x) => snap16((x - xs[0]) * k)), units);
618
1019
  } else {
619
1020
  if (!geo.h[i] && !(base && base[i] != null)) return null;
620
1021
  const ys = base ? base.slice() : geo.h.map((l) => l.y); // bottom→up: DESCENDING display y (h[0] = the origin line)
621
1022
  np = Math.max(i < ys.length - 1 ? ys[i + 1] + MIN : -Infinity, Math.min(i > 0 ? ys[i - 1] - MIN : Infinity, np));
622
1023
  ys[i] = np;
623
1024
  g.origin[1] = ys[0];
624
- g.y = formatSpacings(ys.map((y) => snap16((ys[0] - y) * k)));
1025
+ g.y = formatSpacings(ys.map((y) => snap16((ys[0] - y) * k)), units);
625
1026
  }
626
1027
  return np;
627
1028
  }
@@ -651,8 +1052,8 @@ export function gridLabelLike(t) {
651
1052
  * elements: filter-style [{kind:'line', d|x1..y2}, {kind:'circle', cx,cy,r}, {kind:'text', text,bbox}].
652
1053
  * Returns { grid, info:{ v, h, anchored:'circles'|'text'|'geometry', labeled } } or null.
653
1054
  */
654
- export function gridFromDrawing(elements, ptPerFt) {
655
- const k = mmPerPx(ptPerFt);
1055
+ export function gridFromDrawing(elements, mmPerPx, units) {
1056
+ const k = sheetScaleMm(mmPerPx);
656
1057
  const circles = [], texts = [];
657
1058
  const vb = new Map(), hb = new Map(); // rounded pos -> { lo, hi, ink, n, sum }
658
1059
  let bx0 = Infinity, by0 = Infinity, bx1 = -Infinity, by1 = -Infinity;
@@ -750,18 +1151,19 @@ export function gridFromDrawing(elements, ptPerFt) {
750
1151
  };
751
1152
  const v = harvest(vb, true), h = harvest(hb, false);
752
1153
  if ((v.length < 2 && h.length < 2) || v.length > 40 || h.length > 40) return null; // nothing grid-like, or garbage-in
753
- const snap16 = (mm) => Math.round(mm / (IN_MM / 16)) * (IN_MM / 16);
1154
+ const snap16 = (mm) => snapToQuantum(mm, 'fine', units);
754
1155
  const origin = [v.length ? v[0].pos : bx0, h.length ? h[h.length - 1].pos : by1]; // left-most × bottom-most
755
1156
  const xOff = v.map((l) => snap16((l.pos - origin[0]) * k));
756
1157
  const yOff = h.map((l) => snap16((origin[1] - l.pos) * k)).reverse(); // up the sheet, ascending
757
1158
  const labeled = [...v, ...h].length > 0 && [...v, ...h].every((l) => l.label);
1159
+ const datum = gridDatumFor(units);
758
1160
  const grid = {
759
1161
  on: true, origin,
760
- x: formatSpacings(xOff), y: formatSpacings(yOff), z: "0'-0\"",
1162
+ x: formatSpacings(xOff, units), y: formatSpacings(yOff, units), z: datum.z,
761
1163
  labels_x: labeled ? v.map((l) => l.label).join(' ') : '',
762
1164
  labels_y: labeled ? h.map((l) => l.label).reverse().join(' ') : '',
763
1165
  labels_z: [],
764
- ext: 5 * FT_MM,
1166
+ ext: datum.ext,
765
1167
  };
766
1168
  // extension: how far lines overhang the perpendicular family (to reach their bubbles)
767
1169
  const overhang = [];
@@ -770,17 +1172,29 @@ export function gridFromDrawing(elements, ptPerFt) {
770
1172
  for (const l of v) { overhang.push(Math.max(0, hTop - l.lo)); overhang.push(Math.max(0, l.hi - hBot)); }
771
1173
  }
772
1174
  const ov = overhang.filter((o) => o > 0).sort((a, b) => a - b);
773
- if (ov.length) grid.ext = Math.min(Math.max(snap16(ov[Math.floor(ov.length / 2)] * k), 2 * FT_MM), 20 * FT_MM);
1175
+ // KEPT for a metric job (#1205 item 2), and the honest argument is narrower than "these are
1176
+ // physical": 609.6 and 6096 are round FEET, picked by someone thinking in feet. What is true is
1177
+ // that this is an OUTLIER GUARD whose endpoints are arbitrary within an order of magnitude, so
1178
+ // re-rounding them to 600/6000 would change behaviour for cosmetics, against no evidence — which
1179
+ // this epic has a rule about. What was wrong was the SPELLING, so they are named in mm.
1180
+ //
1181
+ // That consequence — a metric job whose overhang fell under the floor stored `ext` = 609.6, a
1182
+ // fractional millimetre in a contract whose every other length is whole — was filed as #1238 and is
1183
+ // closed by `gridExtBoundsMm`, which spells the SAME window to the precision the job writes. The
1184
+ // measured value needs no rounding of its own: `snap16` is the 1 mm quantum in a metric job, so only
1185
+ // the clamp could ever introduce a fraction.
1186
+ const bounds = gridExtBoundsMm(units);
1187
+ if (ov.length) grid.ext = Math.min(Math.max(snap16(ov[Math.floor(ov.length / 2)] * k), bounds.min), bounds.max);
774
1188
  return { grid, info: { v: v.length, h: h.length, anchored: circles.length ? 'circles' : (texts.length ? 'text' : 'geometry'), labeled } };
775
1189
  }
776
1190
 
777
1191
  /**
778
1192
  * Propose a grid from the columns on a plan (display space): cluster distinct column Xs and Ys
779
- * (150 mm tolerance), origin = the bottom-left intersection, spacings snapped to the nearest 1/2"
780
- * so the strings read clean. Falls back to null when there are no columns (caller uses defaultGrid).
1193
+ * (150 mm tolerance), origin = the bottom-left intersection, spacings snapped to the project's coarse
1194
+ * authoring quantum (1/2" in a US job, 10 mm in a metric one) so the strings read clean. Falls back to null when there are no columns (caller uses defaultGrid).
781
1195
  */
782
- export function inferGrid(members, ptPerFt) {
783
- const k = mmPerPx(ptPerFt), tolPx = 150 / k;
1196
+ export function inferGrid(members, mmPerPx, units) {
1197
+ const k = sheetScaleMm(mmPerPx), tolPx = 150 / k;
784
1198
  const xs = [], ys = [];
785
1199
  for (const m of members || []) {
786
1200
  if (!m || m.role !== 'column' || !Array.isArray(m.wp) || !m.wp[0]) continue;
@@ -797,12 +1211,13 @@ export function inferGrid(members, ptPerFt) {
797
1211
  out.push(bucket.reduce((s, v) => s + v, 0) / bucket.length);
798
1212
  return out;
799
1213
  };
800
- const snapHalfIn = (mm) => Math.round(mm / (IN_MM / 2)) * (IN_MM / 2);
1214
+ const snapHalfIn = (mm) => snapToQuantum(mm, 'coarse', units);
801
1215
  const cx = cluster(xs), cy = cluster(ys);
802
1216
  const origin = [cx[0], cy[cy.length - 1]]; // left-most line × bottom-most (display y-down) line
803
1217
  const xOff = cx.map((x) => snapHalfIn((x - origin[0]) * k));
804
1218
  const yOff = cy.map((y) => snapHalfIn((origin[1] - y) * k)).reverse(); // up the sheet, ascending
805
- return { on: true, origin, x: formatSpacings(xOff), y: formatSpacings(yOff), z: "0'-0\"", labels_x: '', labels_y: '', labels_z: [], ext: 5 * FT_MM };
1219
+ const datum = gridDatumFor(units);
1220
+ return { on: true, origin, x: formatSpacings(xOff, units), y: formatSpacings(yOff, units), z: datum.z, labels_x: '', labels_y: '', labels_z: [], ext: datum.ext };
806
1221
  }
807
1222
 
808
1223
  /**
@@ -817,7 +1232,7 @@ export function inferGrid(members, ptPerFt) {
817
1232
  *
818
1233
  * THE THREE DIFFERENCES, all consequences of the display→world change:
819
1234
  *
820
- * 1. NO `ptPerFt`. v2 work points are already mm, so the 150 mm tolerance is applied directly instead
1235
+ * 1. NO scale. v2 work points are already mm, so the 150 mm tolerance is applied directly instead
821
1236
  * of being divided back into pixels. It is an ADJACENCY tolerance, not a cluster width — the walk
822
1237
  * compares each column to the LAST one admitted, so a run of columns 100 mm apart chains into a
823
1238
  * single line of unbounded span. The projected `150/k` px test is the same predicate
@@ -838,7 +1253,7 @@ export function inferGrid(members, ptPerFt) {
838
1253
  * line inferred at 1020 mm from an origin at 3 mm is authored as 1016 and reads back at 1019. That is
839
1254
  * the authoring notation doing its job — a proposal is a starting point the user edits, not a survey.
840
1255
  */
841
- export function inferGridMm(members) {
1256
+ export function inferGridMm(members, units) {
842
1257
  const tolMm = 150;
843
1258
  const xs = [], ys = [];
844
1259
  for (const m of members || []) {
@@ -857,10 +1272,11 @@ export function inferGridMm(members) {
857
1272
  out.push(bucket.reduce((s, v) => s + v, 0) / bucket.length);
858
1273
  return out;
859
1274
  };
860
- const snapHalfIn = (mm) => Math.round(mm / (IN_MM / 2)) * (IN_MM / 2);
1275
+ const snapHalfIn = (mm) => snapToQuantum(mm, 'coarse', units);
861
1276
  const cx = cluster(xs), cy = cluster(ys);
862
1277
  const origin = [cx[0], cy[0]]; // left-most line × lowest (world +Y is up) line
863
1278
  const xOff = cx.map((x) => snapHalfIn(x - origin[0]));
864
1279
  const yOff = cy.map((y) => snapHalfIn(y - origin[1]));
865
- return { on: true, origin, x: formatSpacings(xOff), y: formatSpacings(yOff), z: "0'-0\"", labels_x: '', labels_y: '', labels_z: [], ext: 5 * FT_MM };
1280
+ const datum = gridDatumFor(units);
1281
+ return { on: true, origin, x: formatSpacings(xOff, units), y: formatSpacings(yOff, units), z: datum.z, labels_x: '', labels_y: '', labels_z: [], ext: datum.ext };
866
1282
  }