@floless/app 0.137.4 → 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 +47618 -26808
  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 +470 -56
  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 +124 -140
  31. package/dist/web/steel-3d-view.js +352 -100
  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 +6458 -915
  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 +71 -64
  38. package/dist/web/steel-model-v2-client-validation.js +10 -3
  39. package/dist/web/steel-model-v2-commands.js +268 -76
  40. package/dist/web/steel-model-v2-projection.js +18 -17
  41. package/dist/web/steel-plan-transform.js +13 -13
  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 +17 -3
  45. package/dist/web/steel-view-generation.js +21 -7
  46. package/dist/web/workspaces.js +2178 -497
  47. package/package.json +4 -1
@@ -22,6 +22,103 @@
22
22
  import { FT_TO_MM as FT_MM, IN_TO_MM as IN_MM } from './steel-units.js';
23
23
  export { FT_MM, IN_MM };
24
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
+ }
121
+
25
122
  const gcd = (a, b) => { while (b) { const t = a % b; a = b; b = t; } return a; };
26
123
  export const truncateText = (value, maxLength = 40) => Array.from(String(value == null ? '' : value)).slice(0, maxLength).join('');
27
124
 
@@ -42,17 +139,29 @@ const parseInches = (raw) => {
42
139
  };
43
140
 
44
141
  /**
45
- * 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.
46
143
  *
47
- * It lives in this leaf module because five copies of `FT_MM / (ptPerFt > 0 ? ptPerFt : 1)` had grown
48
- * (here, steel-3d-core's `kOf`, steel-model-adapter's and steel-model-commands' `scaleOf`, and inline
49
- * in steel-plan-transform and server/contract-to-scene), each carrying a comment telling the next
50
- * 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.
51
148
  *
52
- * A missing, zero or negative `pt_per_ft` reads as 1 pt/ft rather than dividing by it, so an
53
- * 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.
54
163
  */
55
- export const mmPerPx = (ptPerFt) => FT_MM / (ptPerFt > 0 ? ptPerFt : 1);
164
+ export const sheetScaleMm = (mmPerPx) => (mmPerPx > 0 ? mmPerPx : FT_MM);
56
165
 
57
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. */
58
167
  export function parseLen(tok) {
@@ -133,11 +242,127 @@ export function parseSpacings(str) {
133
242
  return { offsets, err: null };
134
243
  }
135
244
 
136
- /** Cumulative offsets (mm) → a canonical comma-separated string; equal runs compress to n*d. */
137
- 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);
138
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);
139
362
  const diffs = offsets.map((v, i) => v - (i ? offsets[i - 1] : 0));
140
- 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));
141
366
  const out = [];
142
367
  for (let i = 0; i < tokens.length;) {
143
368
  let j = i + 1;
@@ -159,14 +384,26 @@ export function parseLevels(str, labelsZ = []) {
159
384
  const token = split.tokens[sourceIndex];
160
385
  const rawMm = parseLen(token);
161
386
  if (!isFinite(rawMm)) return { levels: [], err: 'can’t read “' + token + '”', warnings, tokens: split.tokens };
162
- 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;
163
394
  const authored = truncateText(String(labels[sourceIndex] == null ? '' : labels[sourceIndex]).trim());
164
- 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);
165
396
  if (duplicate) {
166
397
  warnings.push({ kind: authored && authored !== duplicate.label ? 'duplicate-label' : 'duplicate-level', sourceIndex, keptSourceIndex: duplicate.sourceIndex });
167
398
  continue;
168
399
  }
169
- 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 });
170
407
  }
171
408
  for (let i = split.tokens.length; i < labels.length; i++) {
172
409
  if (String(labels[i] == null ? '' : labels[i]).trim()) warnings.push({ kind: 'orphan-label', sourceIndex: i });
@@ -175,8 +412,32 @@ export function parseLevels(str, labelsZ = []) {
175
412
  return { levels, err: null, warnings, tokens: split.tokens };
176
413
  }
177
414
 
178
- /** Stable identity for a canonical level elevation: integer sixteenths of an inch. */
179
- 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;
180
441
 
181
442
  /**
182
443
  * Keep only hidden elevations that still exist in the authored level list, returning the authored
@@ -280,10 +541,13 @@ export function reconcileLevelLabels(previousParsed, normalizedLabels = [], next
280
541
  ? normalizedLabels.map((label) => truncateText(String(label == null ? '' : label).trim()))
281
542
  : [];
282
543
  const byElevation = new Map();
283
- 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] || '' }));
284
548
  const used = new Set();
285
549
  const matched = next.map((level) => {
286
- const prior = byElevation.get(fmtLen(level.mm));
550
+ const prior = byElevation.get(gridLevelKey(level.mm));
287
551
  if (!prior) return '';
288
552
  used.add(prior.index);
289
553
  return prior.label;
@@ -296,8 +560,94 @@ export function reconcileLevelLabels(previousParsed, normalizedLabels = [], next
296
560
  return { labels: [...matched, ...extras], extraCount: extras.length };
297
561
  }
298
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
+ */
299
582
  export function formatLevels(levels) {
300
- 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];
301
651
  }
302
652
 
303
653
  /** Auto labels: style 'num' → 1,2,3… ; 'alpha' → A…Z, AA, AB… */
@@ -422,9 +772,51 @@ export function axisLabelText(g, dir, style, n) {
422
772
  return labels.some((l) => /\s/.test(l)) ? null : labels.join(' ');
423
773
  }
424
774
 
425
- /** A fresh default grid (display-space origin px). 4×4 30' bays, ground level only. */
426
- export function defaultGrid(origin) {
427
- 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 };
428
820
  }
429
821
 
430
822
  /** True when g is structurally usable (parseable origin — the spacing strings report their own errors). */
@@ -460,16 +852,16 @@ export function gridLines(g) {
460
852
  *
461
853
  * `opts.yUp` selects coordinate space. Default false is a projected sheet grid, where Y grows DOWN the
462
854
  * page and spacings run UP it (`oy - off`). True is the native model grid, already in world mm with Y
463
- * 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
464
856
  * without this does not throw — it draws the whole grid mirrored about the origin's Y, plausibly, which is
465
857
  * the silent-wrong-space failure this epic exists to prevent.
466
858
  *
467
859
  * It also selects which per-line extent vocabulary is read: projected index-keyed `ends_x`/`ends_y` in
468
860
  * display px, or the native `ends` map keyed by stable axis id in world mm.
469
861
  */
470
- export function gridGeometry(g, ptPerFt, opts = {}) {
862
+ export function gridGeometry(g, mmPerPx, opts = {}) {
471
863
  const yUp = !!opts.yUp;
472
- const k = mmPerPx(ptPerFt);
864
+ const k = sheetScaleMm(mmPerPx);
473
865
  const px = (mm) => mm / k;
474
866
  const X = parseSpacings(g && g.x), Y = parseSpacings(g && g.y);
475
867
  const ok = sane(g);
@@ -532,12 +924,12 @@ export function gridGeometry(g, ptPerFt, opts = {}) {
532
924
  * position, or null when there's no such line.
533
925
  * ponytail: overrides are keyed by line INDEX — editing the spacing string re-maps them positionally.
534
926
  */
535
- export function moveGridLineEnd(g, ptPerFt, axis, i, end, np) {
536
- const geo = gridGeometry(g, ptPerFt);
927
+ export function moveGridLineEnd(g, mmPerPx, axis, i, end, np) {
928
+ const geo = gridGeometry(g, mmPerPx);
537
929
  const line = (axis === 'v' ? geo.v : geo.h)[i];
538
930
  if (!line) return null;
539
931
  const auto = axis === 'v' ? [geo.y0, geo.y1] : [geo.x0, geo.x1];
540
- const k = mmPerPx(ptPerFt);
932
+ const k = sheetScaleMm(mmPerPx);
541
933
  const MINLEN = 12 * IN_MM / k; // 12" minimum line length in px
542
934
  const other = end === 0 ? line.hi : line.lo;
543
935
  np = end === 0 ? Math.min(np, other - MINLEN) : Math.max(np, other + MINLEN);
@@ -577,10 +969,10 @@ export function gridSnapGeom(geo) {
577
969
  * Emitted PLAN-ONLY on purpose: 'grid-line' / 'grid-int' snap X/Y and keep the dragged Z, so a grid
578
970
  * can never yank a member off its elevation (candidatePoint in steel-3d-core honors that).
579
971
  */
580
- export function gridCandidates3d(g, ptPerFt, opts = {}) {
972
+ export function gridCandidates3d(g, mmPerPx, opts = {}) {
581
973
  if (!g || !g.on) return [];
582
- const geo = gridGeometry(g, ptPerFt, opts);
583
- const k = mmPerPx(ptPerFt);
974
+ const geo = gridGeometry(g, mmPerPx, opts);
975
+ const k = sheetScaleMm(mmPerPx);
584
976
  // The SAME reflection the 3D view applies to the drawn grid, and it must stay the same one or the snap
585
977
  // targets sit mirrored away from the lines the user is aiming at. `yUp` (v2, world mm) means none.
586
978
  const sy = opts.yUp ? k : -k;
@@ -599,31 +991,38 @@ export function gridCandidates3d(g, ptPerFt, opts = {}) {
599
991
  * axis 'v' = a vertical line (position = display x), 'h' = horizontal (display y). Mutates g:
600
992
  * clamps between neighbours (1" minimum bay — a drag can never reorder lines or scramble labels),
601
993
  * rebases the origin when the FIRST line moves (the other lines keep their world positions), and
602
- * 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),
603
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.
604
999
  * `base` (optional) = the axis's line positions captured at DRAG START — pass it on every move of
605
1000
  * one continuous drag so the string is quantized ONCE from the originals; re-deriving from the
606
- * 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.
607
1002
  */
608
- export function moveGridLine(g, ptPerFt, axis, i, np, base) {
609
- const geo = gridGeometry(g, ptPerFt);
610
- const k = mmPerPx(ptPerFt);
611
- const snap16 = (mm) => Math.round(mm / (IN_MM / 16)) * (IN_MM / 16);
612
- 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;
613
1012
  if (axis === 'v') {
614
1013
  if (!geo.v[i] && !(base && base[i] != null)) return null;
615
1014
  const xs = base ? base.slice() : geo.v.map((l) => l.x); // ascending
616
1015
  np = Math.max(i > 0 ? xs[i - 1] + MIN : -Infinity, Math.min(i < xs.length - 1 ? xs[i + 1] - MIN : Infinity, np));
617
1016
  xs[i] = np;
618
1017
  g.origin[0] = xs[0];
619
- g.x = formatSpacings(xs.map((x) => snap16((x - xs[0]) * k)));
1018
+ g.x = formatSpacings(xs.map((x) => snap16((x - xs[0]) * k)), units);
620
1019
  } else {
621
1020
  if (!geo.h[i] && !(base && base[i] != null)) return null;
622
1021
  const ys = base ? base.slice() : geo.h.map((l) => l.y); // bottom→up: DESCENDING display y (h[0] = the origin line)
623
1022
  np = Math.max(i < ys.length - 1 ? ys[i + 1] + MIN : -Infinity, Math.min(i > 0 ? ys[i - 1] - MIN : Infinity, np));
624
1023
  ys[i] = np;
625
1024
  g.origin[1] = ys[0];
626
- g.y = formatSpacings(ys.map((y) => snap16((ys[0] - y) * k)));
1025
+ g.y = formatSpacings(ys.map((y) => snap16((ys[0] - y) * k)), units);
627
1026
  }
628
1027
  return np;
629
1028
  }
@@ -653,8 +1052,8 @@ export function gridLabelLike(t) {
653
1052
  * elements: filter-style [{kind:'line', d|x1..y2}, {kind:'circle', cx,cy,r}, {kind:'text', text,bbox}].
654
1053
  * Returns { grid, info:{ v, h, anchored:'circles'|'text'|'geometry', labeled } } or null.
655
1054
  */
656
- export function gridFromDrawing(elements, ptPerFt) {
657
- const k = mmPerPx(ptPerFt);
1055
+ export function gridFromDrawing(elements, mmPerPx, units) {
1056
+ const k = sheetScaleMm(mmPerPx);
658
1057
  const circles = [], texts = [];
659
1058
  const vb = new Map(), hb = new Map(); // rounded pos -> { lo, hi, ink, n, sum }
660
1059
  let bx0 = Infinity, by0 = Infinity, bx1 = -Infinity, by1 = -Infinity;
@@ -752,18 +1151,19 @@ export function gridFromDrawing(elements, ptPerFt) {
752
1151
  };
753
1152
  const v = harvest(vb, true), h = harvest(hb, false);
754
1153
  if ((v.length < 2 && h.length < 2) || v.length > 40 || h.length > 40) return null; // nothing grid-like, or garbage-in
755
- const snap16 = (mm) => Math.round(mm / (IN_MM / 16)) * (IN_MM / 16);
1154
+ const snap16 = (mm) => snapToQuantum(mm, 'fine', units);
756
1155
  const origin = [v.length ? v[0].pos : bx0, h.length ? h[h.length - 1].pos : by1]; // left-most × bottom-most
757
1156
  const xOff = v.map((l) => snap16((l.pos - origin[0]) * k));
758
1157
  const yOff = h.map((l) => snap16((origin[1] - l.pos) * k)).reverse(); // up the sheet, ascending
759
1158
  const labeled = [...v, ...h].length > 0 && [...v, ...h].every((l) => l.label);
1159
+ const datum = gridDatumFor(units);
760
1160
  const grid = {
761
1161
  on: true, origin,
762
- x: formatSpacings(xOff), y: formatSpacings(yOff), z: "0'-0\"",
1162
+ x: formatSpacings(xOff, units), y: formatSpacings(yOff, units), z: datum.z,
763
1163
  labels_x: labeled ? v.map((l) => l.label).join(' ') : '',
764
1164
  labels_y: labeled ? h.map((l) => l.label).reverse().join(' ') : '',
765
1165
  labels_z: [],
766
- ext: 5 * FT_MM,
1166
+ ext: datum.ext,
767
1167
  };
768
1168
  // extension: how far lines overhang the perpendicular family (to reach their bubbles)
769
1169
  const overhang = [];
@@ -772,17 +1172,29 @@ export function gridFromDrawing(elements, ptPerFt) {
772
1172
  for (const l of v) { overhang.push(Math.max(0, hTop - l.lo)); overhang.push(Math.max(0, l.hi - hBot)); }
773
1173
  }
774
1174
  const ov = overhang.filter((o) => o > 0).sort((a, b) => a - b);
775
- 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);
776
1188
  return { grid, info: { v: v.length, h: h.length, anchored: circles.length ? 'circles' : (texts.length ? 'text' : 'geometry'), labeled } };
777
1189
  }
778
1190
 
779
1191
  /**
780
1192
  * Propose a grid from the columns on a plan (display space): cluster distinct column Xs and Ys
781
- * (150 mm tolerance), origin = the bottom-left intersection, spacings snapped to the nearest 1/2"
782
- * 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).
783
1195
  */
784
- export function inferGrid(members, ptPerFt) {
785
- const k = mmPerPx(ptPerFt), tolPx = 150 / k;
1196
+ export function inferGrid(members, mmPerPx, units) {
1197
+ const k = sheetScaleMm(mmPerPx), tolPx = 150 / k;
786
1198
  const xs = [], ys = [];
787
1199
  for (const m of members || []) {
788
1200
  if (!m || m.role !== 'column' || !Array.isArray(m.wp) || !m.wp[0]) continue;
@@ -799,12 +1211,13 @@ export function inferGrid(members, ptPerFt) {
799
1211
  out.push(bucket.reduce((s, v) => s + v, 0) / bucket.length);
800
1212
  return out;
801
1213
  };
802
- const snapHalfIn = (mm) => Math.round(mm / (IN_MM / 2)) * (IN_MM / 2);
1214
+ const snapHalfIn = (mm) => snapToQuantum(mm, 'coarse', units);
803
1215
  const cx = cluster(xs), cy = cluster(ys);
804
1216
  const origin = [cx[0], cy[cy.length - 1]]; // left-most line × bottom-most (display y-down) line
805
1217
  const xOff = cx.map((x) => snapHalfIn((x - origin[0]) * k));
806
1218
  const yOff = cy.map((y) => snapHalfIn((origin[1] - y) * k)).reverse(); // up the sheet, ascending
807
- 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 };
808
1221
  }
809
1222
 
810
1223
  /**
@@ -819,7 +1232,7 @@ export function inferGrid(members, ptPerFt) {
819
1232
  *
820
1233
  * THE THREE DIFFERENCES, all consequences of the display→world change:
821
1234
  *
822
- * 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
823
1236
  * of being divided back into pixels. It is an ADJACENCY tolerance, not a cluster width — the walk
824
1237
  * compares each column to the LAST one admitted, so a run of columns 100 mm apart chains into a
825
1238
  * single line of unbounded span. The projected `150/k` px test is the same predicate
@@ -840,7 +1253,7 @@ export function inferGrid(members, ptPerFt) {
840
1253
  * line inferred at 1020 mm from an origin at 3 mm is authored as 1016 and reads back at 1019. That is
841
1254
  * the authoring notation doing its job — a proposal is a starting point the user edits, not a survey.
842
1255
  */
843
- export function inferGridMm(members) {
1256
+ export function inferGridMm(members, units) {
844
1257
  const tolMm = 150;
845
1258
  const xs = [], ys = [];
846
1259
  for (const m of members || []) {
@@ -859,10 +1272,11 @@ export function inferGridMm(members) {
859
1272
  out.push(bucket.reduce((s, v) => s + v, 0) / bucket.length);
860
1273
  return out;
861
1274
  };
862
- const snapHalfIn = (mm) => Math.round(mm / (IN_MM / 2)) * (IN_MM / 2);
1275
+ const snapHalfIn = (mm) => snapToQuantum(mm, 'coarse', units);
863
1276
  const cx = cluster(xs), cy = cluster(ys);
864
1277
  const origin = [cx[0], cy[0]]; // left-most line × lowest (world +Y is up) line
865
1278
  const xOff = cx.map((x) => snapHalfIn(x - origin[0]));
866
1279
  const yOff = cy.map((y) => snapHalfIn(y - origin[1]));
867
- 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 };
868
1282
  }