@floless/app 0.108.0 → 0.108.1

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.
@@ -53398,32 +53398,46 @@ function isSea() {
53398
53398
  return false;
53399
53399
  }
53400
53400
  }
53401
- function storeDir() {
53402
- if (process.env.FLOLESS_LICENSE_DIR) return process.env.FLOLESS_LICENSE_DIR;
53403
- if (isSea() && process.env.LOCALAPPDATA) return (0, import_node_path8.join)(process.env.LOCALAPPDATA, "FlolessApp-data");
53401
+ function resolveStoreDir(e = process.env) {
53402
+ if (e.FLOLESS_LICENSE_DIR) return e.FLOLESS_LICENSE_DIR;
53403
+ if (e.LOCALAPPDATA) return (0, import_node_path8.join)(e.LOCALAPPDATA, "FlolessApp-data");
53404
53404
  return (0, import_node_path8.join)((0, import_node_os8.homedir)(), ".aware");
53405
53405
  }
53406
+ function storeDir() {
53407
+ return resolveStoreDir(process.env);
53408
+ }
53406
53409
  var tokenPath = () => (0, import_node_path8.join)(storeDir(), "floless-license.json");
53407
53410
  var cachePath = () => (0, import_node_path8.join)(storeDir(), "floless-license-cache.json");
53411
+ function legacyStoreDirs(e = process.env, sea = isSea(), home = (0, import_node_os8.homedir)()) {
53412
+ const dirs = [];
53413
+ if (sea && e.LOCALAPPDATA) dirs.push((0, import_node_path8.join)(e.LOCALAPPDATA, "FlolessApp"));
53414
+ dirs.push((0, import_node_path8.join)(home, ".aware"));
53415
+ return dirs;
53416
+ }
53417
+ var STORE_FILES = ["floless-license.json", "floless-license-cache.json", "floless-install-id"];
53418
+ function adoptStore(oldDir, newDir) {
53419
+ try {
53420
+ if (oldDir === newDir) return false;
53421
+ if (!(0, import_node_fs9.existsSync)((0, import_node_path8.join)(oldDir, "floless-license.json"))) return false;
53422
+ if ((0, import_node_fs9.existsSync)((0, import_node_path8.join)(newDir, "floless-license.json"))) return false;
53423
+ (0, import_node_fs9.mkdirSync)(newDir, { recursive: true });
53424
+ for (const f of STORE_FILES) {
53425
+ const oldP = (0, import_node_path8.join)(oldDir, f);
53426
+ const newP = (0, import_node_path8.join)(newDir, f);
53427
+ if ((0, import_node_fs9.existsSync)(oldP) && !(0, import_node_fs9.existsSync)(newP)) (0, import_node_fs9.copyFileSync)(oldP, newP);
53428
+ }
53429
+ return true;
53430
+ } catch {
53431
+ return false;
53432
+ }
53433
+ }
53408
53434
  var _migrated = false;
53409
53435
  function migrateLegacyStore() {
53410
53436
  if (_migrated) return;
53411
53437
  _migrated = true;
53412
- if (process.env.FLOLESS_LICENSE_DIR || !(isSea() && process.env.LOCALAPPDATA)) return;
53413
- const oldDir = (0, import_node_path8.join)(process.env.LOCALAPPDATA, "FlolessApp");
53438
+ if (process.env.FLOLESS_LICENSE_DIR) return;
53414
53439
  const newDir = storeDir();
53415
- if (oldDir === newDir) return;
53416
- for (const f of ["floless-license.json", "floless-license-cache.json", "floless-install-id"]) {
53417
- try {
53418
- const oldP = (0, import_node_path8.join)(oldDir, f);
53419
- const newP = (0, import_node_path8.join)(newDir, f);
53420
- if ((0, import_node_fs9.existsSync)(oldP) && !(0, import_node_fs9.existsSync)(newP)) {
53421
- (0, import_node_fs9.mkdirSync)(newDir, { recursive: true });
53422
- (0, import_node_fs9.copyFileSync)(oldP, newP);
53423
- }
53424
- } catch {
53425
- }
53426
- }
53440
+ for (const oldDir of legacyStoreDirs()) if (adoptStore(oldDir, newDir)) return;
53427
53441
  }
53428
53442
  function readJson(path) {
53429
53443
  try {
@@ -53778,7 +53792,7 @@ function appVersion() {
53778
53792
  return resolveVersion({
53779
53793
  isSea: isSea2(),
53780
53794
  sqVersionXml: readSqVersionXml(),
53781
- define: true ? "0.108.0" : void 0,
53795
+ define: true ? "0.108.1" : void 0,
53782
53796
  pkgVersion: readPkgVersion()
53783
53797
  });
53784
53798
  }
@@ -53788,7 +53802,7 @@ function resolveChannel(s) {
53788
53802
  return "dev";
53789
53803
  }
53790
53804
  function appChannel() {
53791
- return resolveChannel({ isSea: isSea2(), define: true ? "0.108.0" : void 0 });
53805
+ return resolveChannel({ isSea: isSea2(), define: true ? "0.108.1" : void 0 });
53792
53806
  }
53793
53807
 
53794
53808
  // workflow-update.ts
@@ -11,18 +11,21 @@ on **port 4317** and drive it with Playwright (the standing real-E2E rule).
11
11
  script is `tsx watch …` (auto-reload) but the server is usually launched with **`start`
12
12
  (NO watch)** — so **server TS edits (`index.ts`, `aware-adapter.ts`, `app-reader.ts`) need a
13
13
  manual restart**; a 404 on a route you just added means the old process is still running.
14
- - **License env (the shared-dir trick) — REQUIRED:** the dev server's license dir
15
- (`licensing.ts storeDir()`) defaults to `~/.aware`, which has **no token**, so without an
16
- override the dev server is signed-out and the UI is gated. Start it with
17
- `FLOLESS_LICENSE_DIR=%LOCALAPPDATA%\FlolessApp-data` (git-bash: `"$LOCALAPPDATA/FlolessApp-data"`)
18
- so it shares the **installed SEA app's** token + `floless-install-id` (so no seat takeover —
19
- single-session/newest-login-wins). Token lives at
20
- `%LOCALAPPDATA%\FlolessApp-data\floless-license.json`.
14
+ - **License — no env var needed on Windows:** the dev server's license dir
15
+ (`licensing.ts storeDir()`) resolves to `%LOCALAPPDATA%\FlolessApp-data` for dev/npm *and* the
16
+ packaged app alike, so it shares the **installed app's** token + `floless-install-id` out of the
17
+ box (no seat takeover — single-session/newest-login-wins). Token lives at
18
+ `%LOCALAPPDATA%\FlolessApp-data\floless-license.json`. Non-Windows falls back to `~/.aware`.
19
+ Set `FLOLESS_LICENSE_DIR` only to point somewhere *else* (tests, an isolated/mock store).
20
+ - **Never hardcode a license path in `.claude/launch.json`:** it performs **no variable
21
+ expansion** — `${env:VAR}`, `${VAR}`, `$VAR`, `%VAR%` and `~` all reach the child process
22
+ verbatim (probe-verified), so any absolute path there is correct on exactly one machine and
23
+ 402s every `/api` route on every other one.
21
24
  - **`web/` is served fresh from disk per request** — edits to `web/*.js|css|html` need only a
22
25
  browser **reload**, no server restart. Only server TS needs a restart.
23
26
  - **Restart recipe (Windows):** find the listener (`netstat -ano | grep :4317`), get its tree
24
27
  (`Get-CimInstance Win32_Process`), `taskkill //PID <tsx-pid> //T //F`, then relaunch
25
- `FLOLESS_LICENSE_DIR="$LOCALAPPDATA/FlolessApp-data" npx tsx main.ts --serve` in the background.
28
+ `npx tsx main.ts --serve` in the background.
26
29
 
27
30
  ## The run trace (what `aware app run` emits)
28
31
 
@@ -620,3 +620,64 @@ export function inferGrid(members, ptPerFt) {
620
620
  const yOff = cy.map((y) => snapHalfIn((origin[1] - y) * k)).reverse(); // up the sheet, ascending
621
621
  return { on: true, origin, x: formatSpacings(xOff), y: formatSpacings(yOff), z: "0'-0\"", labels_x: '', labels_y: '', labels_z: [], ext: 5 * FT_MM };
622
622
  }
623
+
624
+ /**
625
+ * `inferGrid` for steel.model/v2 — propose THE model grid from the model's columns, in WORLD MM
626
+ * (unit 5, P5; INACTIVE — nothing loads a v2 model yet).
627
+ *
628
+ * The AUTHORING HALF OF THIS MODULE IS UNCHANGED and that is deliberate: `parseLen` / `parseSpacings` /
629
+ * `formatSpacings` / `fmtLen` are the notation, and the v2 schema keeps it — "Authoring notation is
630
+ * unchanged (relative X/Y spacing strings, absolute Z levels; web/grid-core.js is the parser source of
631
+ * truth), but every coordinate here is world mm" (`$defs.modelGrid`). Only the coordinate half is new,
632
+ * so this shares the clustering rule and the 1/2" spacing snap with its v1 sibling rather than restating
633
+ * them differently.
634
+ *
635
+ * THE THREE DIFFERENCES, all consequences of the display→world change:
636
+ *
637
+ * 1. NO `ptPerFt`. v2 work points are already mm, so the 150 mm tolerance is applied directly instead
638
+ * of being divided back into pixels. It is an ADJACENCY tolerance, not a cluster width — the walk
639
+ * compares each column to the LAST one admitted, so a run of columns 100 mm apart chains into a
640
+ * single line of unbounded span. Inherited verbatim (v1's `150/k` px test is the same predicate
641
+ * after the scale cancels), and named here because "150 mm tolerance" alone reads as a width.
642
+ * 2. THE Y AXIS IS NOT REVERSED. v1 reads display space, where Y grows DOWN — hence its bottom-most
643
+ * origin (`cy[cy.length-1]`) and its `.reverse()`. World +Y already runs up the plan, so the origin
644
+ * is the LOWEST Y and the offsets come out ascending on their own. Keeping v1's reversal here would
645
+ * produce a grid mirrored about its own origin, which parses cleanly and is silently upside-down.
646
+ * 3. `origin` IS RETURNED IN MM, matching `$defs.modelGrid.origin` — "The [1,A] corner in WORLD MM
647
+ * (v1's was display space)". v1 returns px there, and the two are not interchangeable.
648
+ *
649
+ * A column with an UNKNOWN elevation still counts. Its `z` is an RFI; its plan position is not, and
650
+ * dropping it would move the [1,A] corner because an unanswered question sits on the grid line.
651
+ * Returns null when the model has no columns — the caller falls back to `defaultGrid`, as in v1.
652
+ *
653
+ * ORIGIN + OFFSETS DO NOT EXACTLY RECONSTRUCT THE CLUSTER CENTRES, and that is inherited rather than
654
+ * new: the offsets are snapped to the 1/2" authoring quantum while the origin is the raw centre, so a
655
+ * line inferred at 1020 mm from an origin at 3 mm is authored as 1016 and reads back at 1019. That is
656
+ * the authoring notation doing its job — a proposal is a starting point the user edits, not a survey.
657
+ */
658
+ export function inferGridMm(members) {
659
+ const tolMm = 150;
660
+ const xs = [], ys = [];
661
+ for (const m of members || []) {
662
+ if (!m || m.role !== 'column' || !m.from || typeof m.from !== 'object') continue;
663
+ if (!Number.isFinite(m.from.x) || !Number.isFinite(m.from.y)) continue;
664
+ xs.push(m.from.x); ys.push(m.from.y);
665
+ }
666
+ if (!xs.length) return null;
667
+ const cluster = (vals) => {
668
+ const sorted = [...vals].sort((a, b) => a - b), out = [];
669
+ let bucket = [sorted[0]];
670
+ for (let i = 1; i < sorted.length; i++) {
671
+ if (sorted[i] - bucket[bucket.length - 1] <= tolMm) bucket.push(sorted[i]);
672
+ else { out.push(bucket.reduce((s, v) => s + v, 0) / bucket.length); bucket = [sorted[i]]; }
673
+ }
674
+ out.push(bucket.reduce((s, v) => s + v, 0) / bucket.length);
675
+ return out;
676
+ };
677
+ const snapHalfIn = (mm) => Math.round(mm / (IN_MM / 2)) * (IN_MM / 2);
678
+ const cx = cluster(xs), cy = cluster(ys);
679
+ const origin = [cx[0], cy[0]]; // left-most line × lowest (world +Y is up) line
680
+ const xOff = cx.map((x) => snapHalfIn(x - origin[0]));
681
+ const yOff = cy.map((y) => snapHalfIn(y - origin[1]));
682
+ return { on: true, origin, x: formatSpacings(xOff), y: formatSpacings(yOff), z: "0'-0\"", labels_x: '', labels_y: '', labels_z: [], ext: 5 * FT_MM };
683
+ }
@@ -611,12 +611,15 @@ export function dominantAxis3d(a, b, axesMap) {
611
611
  return best;
612
612
  }
613
613
 
614
- // ---- steel.model/v2 foundation (model-level epic, unit 2) — INACTIVE ------------------------------
615
- // Pure primitives for the model-level contract. Nothing below is wired into the editor or the 3D view:
616
- // unit 2 ships the v2 contract inactive, so these exist to be unit-tested and consumed by unit 3's
617
- // migration preview. Kept here because they are the same KIND of thing as the rest of this module
618
- // (framework-free scene-space math, node-tested from server/steel-3d-core.test.ts) and server code
619
- // already imports web/*-core.js (contract-to-scene.ts pulls in grid-core).
614
+ // ---- steel.model/v2 foundation (model-level epic, units 2 + 5) — INACTIVE -------------------------
615
+ // Pure primitives for the model-level contract. Nothing IN THIS SECTION is wired into the editor or the
616
+ // 3D view: unit 2 ships the v2 contract inactive, so these exist to be unit-tested and consumed by
617
+ // unit 3's migration preview and unit 5's read boundary. (The section is bounded — `dim3dGeom` below it
618
+ // was appended later and IS live in the 3D view; keep new v2 primitives above it.) Kept here because
619
+ // they are the same KIND of thing as the rest of this module (framework-free scene-space math,
620
+ // node-tested from server/steel-3d-core.test.ts) and server code already imports web/*-core.js —
621
+ // contract-to-scene.ts pulls in grid-core, and steel-model-read.ts pulls in knownZ/isUnknownElev from
622
+ // right here, which is why unit 5's v2 primitives are SHARED from this file rather than mirrored.
620
623
 
621
624
  /**
622
625
  * The pinned tolerances from epic §5.2b. These are CONTRACT SEMANTICS — they decide what displays,
@@ -781,6 +784,142 @@ export function registerSheet(input) {
781
784
  return { verdict, reasons, transform: { ...transform, extentMm, residualMm } };
782
785
  }
783
786
 
787
+ /**
788
+ * A steel.model/v2 member's centreline in WORLD MM — the v2 sibling of `memberGeometry`, and unit 5 P5's
789
+ * core primitive. Returns the SAME shape `{ kind, line:[[x,y,z],[x,y,z]] }`, so every consumer of the v1
790
+ * function (the snap picker, the elevation snapper, the 3D view's overlays) works unchanged.
791
+ *
792
+ * FOUR THINGS THE v1 SIBLING DOES THAT THIS MUST NOT — each one a silent wrong answer if copied:
793
+ *
794
+ * * NO px SCALE. v2 work points are world mm already (schema `$defs.workPoint`).
795
+ * * NO Y NEGATION. `contract-to-scene` flips display Y on the way in; v2 stores the flipped value.
796
+ * * NO `default_tos` FALLBACK. v2 has no such field: migration MATERIALIZES v1's defaults, which is the
797
+ * whole reason the `{known} | {unknown}` union exists (`$defs.elevation`).
798
+ * * NO PLUMB. v1's column is a POINT SYMBOL — one plan point plus `col.bos`/`col.tos` — so the v1
799
+ * function puts the top at the base's X/Y. A v2 column carries two REAL work points stored base→top,
800
+ * and `contract-to-scene`'s v2 path says why in as many words: "a battered column keeps its lean
801
+ * instead of being re-plumbed onto a single plan point the way v1's point-symbol column was". Copying
802
+ * v1's line here would snap a leaning column's top onto its base and report it confidently.
803
+ *
804
+ * `kind` follows the AUTHORED `role` and is never derived from geometry (epic §15.2: vertical braces and
805
+ * near-vertical members make "column = vertical" unsafe). An absent role is a beam, per the schema.
806
+ *
807
+ * Returns **null** — never a guessed point — when either endpoint elevation is `{unknown}`, or when the
808
+ * work points are malformed. That matches `knownZ` ("never returns 0 for unknown"), the read boundary's
809
+ * refusal to substitute an elevation the contract never stated, and `sceneFromModel`, which refuses to
810
+ * build a scene at all rather than default one member.
811
+ */
812
+ export function memberGeometryV2(m) {
813
+ if (!m || typeof m !== 'object') return null;
814
+ const a = m.from, b = m.to;
815
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return null;
816
+ if (!Number.isFinite(a.x) || !Number.isFinite(a.y) || !Number.isFinite(b.x) || !Number.isFinite(b.y)) return null;
817
+ const z0 = knownZ(a.z), z1 = knownZ(b.z);
818
+ if (z0 === null || z1 === null) return null;
819
+ return {
820
+ kind: m.role === 'column' ? 'column' : 'beam',
821
+ line: [[nz(a.x), nz(a.y), nz(z0)], [nz(b.x), nz(b.y), nz(z1)]],
822
+ };
823
+ }
824
+
825
+ /**
826
+ * Snap targets from v2 members — the v2 sibling of `snapCandidates`, emitting the identical record shapes
827
+ * so `snapPoint`'s precedence table and `candidatePoint` need no v2 case.
828
+ *
829
+ * WHY THIS IS NOT `snapCandidates(members, 304.8, 0, excludeId)`. That nearly works — `kOf(304.8)` is 1 —
830
+ * and is wrong twice: it would still negate Y (v2 coordinates are already world), and it would still read
831
+ * `m.wp`/`m.col`/`m.ends`, which a v2 member does not have. A v2 member routed through the v1 function
832
+ * does not throw; it yields NaN candidates that snap silently to nowhere. Silence is the failure mode.
833
+ *
834
+ * THE CANDIDATE TYPE takes TWO conjuncts, and both matter: a member gets a `vertical-axis` (which
835
+ * `candidatePoint` reads as "lock plan X/Y, keep the dragged Z") only when it is an authored COLUMN
836
+ * **and** its plan footprint is a point. Everything else is a line and gets `centerline` + `midpoint`.
837
+ * The role half is not redundant — a role-less member with a coincident footprint (a vertical brace, a
838
+ * degenerate beam) is NOT given an axis, exactly as in v1, whose `memberGeometry` likewise reports
839
+ * `kind:'column'` only for an authored `role === 'column'`. Stated because the first draft of this
840
+ * paragraph claimed footprint alone, and deleting the role conjunct left the whole file green.
841
+ *
842
+ * Equality of the footprint is exact rather than toleranced on purpose: the pinned `MODEL_V2_TOL` values
843
+ * are contract semantics with stated meanings (de-dup candidacy, cut-plane inclusion), and borrowing one
844
+ * here would be inventing a tolerance for a question neither answers. What makes exact equality SOUND is
845
+ * narrower than an earlier version of this comment claimed: migration transforms a column's two work
846
+ * points INDEPENDENTLY (`steel-model-migrate.ts` runs `toLocalMm` then `applySimilarity` on each of
847
+ * `wp[0]` and `wp[1]`), so the guarantee is only that COINCIDENT v1 work points — what the editor writes
848
+ * for an ordinary column — map to bitwise-equal v2 points, both functions being pure. A v1 column
849
+ * authored with a plan lean is a real thing (`steel-editor.html`'s `_lenFt` test pins that its length
850
+ * "includes the plan lean", and migration tolerances `coincidentXY` rather than assuming it), and it
851
+ * migrates battered and is treated as a line here — which is the intended v2 rule, not a failure of it.
852
+ *
853
+ * PAIRWISE INTERSECTIONS ARE A SEPARATE RULE, and it is keyed on the ROLE, not the footprint: no column
854
+ * ever joins the list, exactly as in v1. Review found the alternative to be a real defect. The inherited
855
+ * intersection elevation is `(A.p0.z + B.p0.z) / 2` — an approximation v1 only ever applies to two beams,
856
+ * whose ends sit near one level. A column's `p0` is its BASE, so a column based at 0 crossing a beam at
857
+ * 5000 in plan would emit a snap target at 2500: a point on NEITHER member, and off by half a storey.
858
+ * A battered column keeps its centreline, midpoint and vertices, which are real points on it; only the
859
+ * fabricated crossing is withheld. Interpolating the true crossing elevation would be better than both,
860
+ * and is deliberately not invented here — it would change v1's rule too, which P5 must not do.
861
+ *
862
+ * WHICH LEAVES A STEEP BRACE, and it is inherited rather than endorsed. A brace is `memberType:'brace'`
863
+ * with `role` absent or 'beam', so it reads as a beam here and joins the list — carrying exactly the
864
+ * approximation described above, for the same reason (a near-vertical brace's `p0` is its lower end).
865
+ * v1 does the identical thing, so tightening it here would be a v1 behaviour change wearing a v2 label,
866
+ * and it belongs with whoever owns that rule. Named so the next reader knows the column exclusion is the
867
+ * boundary of a fix, not a complete account of the hazard. Asserted, not just stated: the tests pin that
868
+ * a steep brace still intersects.
869
+ *
870
+ * `excludeId` IS MATCHED BY ID, and what makes that sound is the DOCUMENT, not this function: v2 ids are
871
+ * model-global and `checkModelReferences` refuses a duplicate, so the sheet-scoped collision that forces
872
+ * `elevationLevelsByPlan` to exclude by object cannot arrive through a validated path. This function runs
873
+ * no such check itself. Were a duplicate to reach it anyway, BOTH copies drop out — fewer snap targets,
874
+ * never a wrong position — while `memberById` would answer with the first. Conservative, and stated
875
+ * because the asymmetry is real rather than because it is reachable.
876
+ */
877
+ export function snapCandidatesV2(members, excludeId) {
878
+ const out = [];
879
+ const lines = []; // beam/brace centrelines, for pairwise plan intersections — never a column's
880
+ for (const m of members || []) {
881
+ if (!m || m.id === excludeId) continue;
882
+ const geo = memberGeometryV2(m);
883
+ if (!geo) continue; // unknown elevation / malformed: an RFI is not a target
884
+ const [p0, p1] = geo.line;
885
+ if (geo.kind === 'column' && p0[0] === p1[0] && p0[1] === p1[1]) {
886
+ out.push({ type: 'vertical-axis', p: p0, fromId: m.id });
887
+ } else {
888
+ out.push({ type: 'centerline', a: p0, b: p1, fromId: m.id });
889
+ out.push({ type: 'midpoint', p: [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2, (p0[2] + p1[2]) / 2], fromId: m.id });
890
+ if (geo.kind !== 'column') lines.push({ id: m.id, p0, p1 });
891
+ }
892
+ out.push({ type: 'vertex', p: p0, fromId: m.id });
893
+ out.push({ type: 'vertex', p: p1, fromId: m.id });
894
+ }
895
+ for (let i = 0; i < lines.length; i++) {
896
+ for (let j = i + 1; j < lines.length; j++) {
897
+ const x = segXY(lines[i].p0, lines[i].p1, lines[j].p0, lines[j].p1);
898
+ if (x) out.push({ type: 'intersection', p: [x[0], x[1], (lines[i].p0[2] + lines[j].p0[2]) / 2], fromIds: [lines[i].id, lines[j].id] });
899
+ }
900
+ }
901
+ return out;
902
+ }
903
+
904
+ /**
905
+ * Distinct endpoint elevation levels (mm, sorted) among v2 members — the v2 sibling of `elevationLevels`,
906
+ * feeding the same Alt-drag vertical snap.
907
+ *
908
+ * There is no `elevationLevelsByPlan` sibling and there should not be: that function exists ONLY because
909
+ * v1 resolves each sheet in its own `default_tos`, and v2 has neither per-sheet defaults nor per-sheet
910
+ * scales. One world model means one level set.
911
+ */
912
+ export function elevationLevelsV2(members, excludeId) {
913
+ const set = new Set();
914
+ for (const m of members || []) {
915
+ if (!m || m.id === excludeId) continue;
916
+ const geo = memberGeometryV2(m);
917
+ if (!geo) continue;
918
+ set.add(Math.round(geo.line[0][2])); set.add(Math.round(geo.line[1][2]));
919
+ }
920
+ return [...set].sort((a, b) => a - b);
921
+ }
922
+
784
923
  export function dim3dGeom(a, b, axis, axisDir) {
785
924
  const p1 = [a[0], a[1], a[2]];
786
925
  const u = (axis === 'x' || axis === 'y') ? unitOrNull(axisDir) : null; // z/free never project onto axisDir
@@ -0,0 +1,116 @@
1
+ /**
2
+ * What detail callouts a plan carries — the one place that answers it.
3
+ *
4
+ * A plan states its detail callouts TWO ways and both are legal:
5
+ * details[] {text, disp} — placements the reader recognised as details
6
+ * callouts[] {kind, text, disp, target:{sheet,number}} — the navigable callout bubbles
7
+ * A real drawing set commonly lands entirely in `callouts[]` with `details[]` empty. Anything that
8
+ * reads only one of the two is blind to half the drawing, which is exactly how issue #397 happened:
9
+ * the ⌖ pick tool, the Connection-detail combobox and the Details list read `details[]` alone, so on
10
+ * such a set there was nothing to pick and the dropdown was empty.
11
+ *
12
+ * TWO ANSWERS, because the callers want different things:
13
+ * planDetailRefs every PHYSICAL bubble, in source order, NOT deduplicated — one pick hot-zone each.
14
+ * A set may carry the same detail at many places (the demo set repeats one callout
15
+ * five times); you pick the bubble beside the end you are detailing, so collapsing
16
+ * them would make all but one of those ends unpickable.
17
+ * planDetailTexts the unique NAMES, sorted — for the dropdown and the Details list, where offering
18
+ * the same detail five times is just noise.
19
+ *
20
+ * PURE and framework-free (no DOM), node-tested from server/steel-detail-refs.test.ts — same shape as
21
+ * grid-core.js / steel-3d-core.js / steel-view-generation.js. Keeping it out of steel-editor.html is
22
+ * the point: the untested page closure is where #397 was able to hide.
23
+ *
24
+ * This does NOT normalise notation. `7/S-402` and `7-S-402` denote the same detail and normDetailKey
25
+ * (server/detail-recipes.ts, mirrored in the page) is what knows that — at RESOLUTION time, where it
26
+ * matters. Minting a third copy of that rule here would be one more thing to drift; listing a name
27
+ * exactly as the drawing prints it is also what lets a detailer match it against the sheet.
28
+ */
29
+
30
+ const finite = (n) => Number.isFinite(typeof n === 'number' ? n : Number(n));
31
+ /** A drawable position. The renderer coerces, so numeric strings are accepted — but not a NaN, which
32
+ * would put an un-clickable rect at an undefined coordinate. */
33
+ const point = (d) => Array.isArray(d) && d.length >= 2 && finite(d[0]) && finite(d[1]);
34
+ const text = (v) => String(v == null ? '' : v).trim();
35
+
36
+ /**
37
+ * The sheet a detail reference points at — `7/S-402` and `5-S504` both answer their sheet; null when the
38
+ * text names none. Unchanged behaviour, moved here so the two halves of a reference are parsed in one
39
+ * place and are actually covered by tests.
40
+ */
41
+ export function sheetOf(t) {
42
+ const m = String(t || '').replace(/^\w+-/, '').match(/(S-?\w+)/);
43
+ if (!m) return null;
44
+ const s = m[1].toUpperCase();
45
+ return s.startsWith('S-') ? s : 'S-' + s.slice(1);
46
+ }
47
+
48
+ /**
49
+ * The detail number — the leading token of a reference — or null.
50
+ *
51
+ * BOTH separators are accepted, because a drawing prints `7/S-402` at least as often as `5-S504` and
52
+ * normDetailKey already treats `-` and `/` as the same separator. While this was dash-only every
53
+ * slash-form callout answered null, which made the page's bubbleFor() bail and cost those details their
54
+ * cropped thumbnail and their "· detail N" label — invisible until callouts became pickable (#397).
55
+ */
56
+ export function numOf(t) {
57
+ const m = String(t || '').match(/^([0-9A-Za-z]+)[-/]/);
58
+ return m ? m[1].toUpperCase() : null;
59
+ }
60
+
61
+ /**
62
+ * The reference a callout names, or null if it names none.
63
+ *
64
+ * Prefers `text` — what is actually printed on the sheet, which is what a detailer cross-checks
65
+ * against. Falls back to rebuilding it from the structured target as `number-sheet`, the same form the
66
+ * navigable bubble already derives for its preview key. A target carrying only one half is not a
67
+ * reference and returns null rather than a half-name nothing can resolve.
68
+ */
69
+ export function calloutRefText(callout) {
70
+ if (!callout || typeof callout !== 'object') return null;
71
+ const printed = text(callout.text);
72
+ if (printed) return printed;
73
+ const target = callout.target;
74
+ if (!target || typeof target !== 'object') return null;
75
+ const number = text(target.number), sheet = text(target.sheet);
76
+ return (number && sheet) ? number + '-' + sheet : null;
77
+ }
78
+
79
+ /** Both callout lists a plan may carry, details first, each in source order. */
80
+ function entries(plan) {
81
+ if (!plan || typeof plan !== 'object') return [];
82
+ const out = [];
83
+ for (const list of [plan.details, plan.callouts]) if (Array.isArray(list)) out.push(...list);
84
+ return out;
85
+ }
86
+
87
+ /**
88
+ * Every placeable detail callout on the plan: `{text, disp, kind}`, in source order, NOT deduplicated.
89
+ *
90
+ * Requires a POSITION as well as a name — this is what gets drawn as a hot-zone, and one without a
91
+ * coordinate cannot be drawn. (planDetailTexts deliberately keeps those: a detail the drawing names
92
+ * but does not place is still a detail you should be able to select.)
93
+ */
94
+ export function planDetailRefs(plan) {
95
+ const out = [];
96
+ for (const entry of entries(plan)) {
97
+ if (!entry || typeof entry !== 'object') continue;
98
+ const name = calloutRefText(entry);
99
+ if (!name || !point(entry.disp)) continue;
100
+ out.push({ text: name, disp: [Number(entry.disp[0]), Number(entry.disp[1])], kind: text(entry.kind) || 'detail' });
101
+ }
102
+ return out;
103
+ }
104
+
105
+ /**
106
+ * Every detail this plan can bind to, unique and sorted — the plan's own callouts plus the model's
107
+ * custom details. Numeric-aware ordering, so detail 2 sorts before detail 10 the way a detailer reads
108
+ * them. A custom name that repeats a callout is listed once.
109
+ */
110
+ export function planDetailTexts(plan, customNames) {
111
+ const seen = new Set(), out = [];
112
+ const add = (name) => { if (name && !seen.has(name)) { seen.add(name); out.push(name); } };
113
+ for (const entry of entries(plan)) add(calloutRefText(entry));
114
+ if (customNames) for (const name of customNames) add(text(name));
115
+ return out.sort((a, b) => String(a).localeCompare(String(b), undefined, { numeric: true }));
116
+ }
@@ -1300,6 +1300,7 @@ let C, PAL, WT;
1300
1300
  let SteelCore = null; // steel-3d-core.js module namespace — boot() awaits its dynamic import before main() so the classic script can call its pure helpers (sanitizeDims3d) at load
1301
1301
  let ViewGen = null; // steel-view-generation.js pure F11 helpers — loaded before saved views are sanitised
1302
1302
  let ModelCmd = null; // steel-model-commands.js — the model boundary's WRITE half (unit 5, P3a); the read half is steel-model-adapter.js
1303
+ let DetailRefs = null; // steel-detail-refs.js — what detail callouts a plan carries (details[] ∪ callouts[]); the ⌖ pick tool, the Connection-detail combobox and the Details list must all read the SAME answer (#397)
1303
1304
  let TARGET_CONF = null; // the app's target_confidence input default (%), or null when undeclared — drives the chip's "· target N%" goal
1304
1305
  let view3d = false, view3dReady = false; // 2D|3D toggle state; view3dReady once Steel3DView.init has run
1305
1306
  // Fallback palette (colorFor indexes this array by profile order) when a contract ships no `palette`
@@ -1348,7 +1349,7 @@ function showEmpty(icon, headline, bodyText, appIdText, opts) {
1348
1349
  }
1349
1350
  async function boot() {
1350
1351
  if (!APP_ID) { showEmpty('⊞', 'No workflow selected', 'Open a workflow in the FloLess canvas, then open the contract editor from that workflow’s node.'); return; }
1351
- [SteelCore, ViewGen, ModelCmd] = await Promise.all([import('./steel-3d-core.js'), import('./steel-view-generation.js'), import('./steel-model-commands.js')]); // await BEFORE main()/restoreSaved(): both draft-state sanitisers must exist at the load boundary
1352
+ [SteelCore, ViewGen, ModelCmd, DetailRefs] = await Promise.all([import('./steel-3d-core.js'), import('./steel-view-generation.js'), import('./steel-model-commands.js'), import('./steel-detail-refs.js')]); // await BEFORE main()/restoreSaved(): both draft-state sanitisers must exist at the load boundary, and render() reads DetailRefs
1352
1353
  const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS);
1353
1354
  if (!res.ok) {
1354
1355
  if (res.status === 404) {
@@ -1915,7 +1916,7 @@ function sanitizeViews(arr){return ViewGen.sanitizeViews(arr);}
1915
1916
  // serverEtag here is right, and why it must be re-stamped when a write lands.
1916
1917
  function persist(){try{localStorage.setItem(LSKEY,JSON.stringify({sig:dataSig(),baseEtag:serverEtag,ts:Date.now(),active:C.active,
1917
1918
  custom_details:C.custom_details, profile_colors:C.profile_colors, member_styles:C.member_styles, member_types:C.member_types, target_confidence:C.target_confidence, dims3d:C.dims3d, dim_overlays:C.dim_overlays, dim_style:C.dim_style, prop_labels:C.prop_labels, joints:C.joints, connections:C.connections, detail_placements:C.detail_placements, views:C.views,
1918
- plans:C.plans.map(p=>({sheet:p.sheet,members:p.members,default_tos:p.default_tos,details:p.details,dims:p.dims,frame:p.frame||null,grid:p.grid||null}))}));}catch(e){setSaved('err');console.error('local autosave failed',e);}}
1919
+ plans:C.plans.map(p=>({sheet:p.sheet,members:p.members,default_tos:p.default_tos,details:p.details,callouts:p.callouts,dims:p.dims,frame:p.frame||null,grid:p.grid||null}))}));}catch(e){setSaved('err');console.error('local autosave failed',e);}}
1919
1920
  // --- server-side draft save: PUT the FULL contract C — this is the copy Approve bakes.
1920
1921
  // localStorage (persist) stays the instant per-browser draft cache; this is the durable one.
1921
1922
  // fetch does NOT reject on HTTP 400 (schema rejection), so treat !res.ok as 'err' (not a false 'Saved ✓'). ---
@@ -2150,7 +2151,10 @@ function applyDraftFields(d){const by={};(d.plans||[]).forEach(p=>by[p.sheet]=p)
2150
2151
  if(Array.isArray(d.member_types))C.member_types=sanitizeMemberTypes(d.member_types);
2151
2152
  if(d.target_confidence!=null)C.target_confidence=d.target_confidence;
2152
2153
  if(Array.isArray(d.connections))C.connections=sanitizeConnections(d.connections); // the connection library carries each detail's RECIPE, so a captured "5-S504 = this shear plate" must survive a reload that happens before the server draft lands. Sanitised because the localStorage draft is UNVALIDATED input (unlike the server contract) — same treatment as member_styles/dims3d.
2153
- C.plans.forEach(p=>{const s=by[p.sheet];if(s){if(Array.isArray(s.members))p.members=s.members;if(s.default_tos!=null)p.default_tos=s.default_tos;if(Array.isArray(s.details))p.details=s.details;if(Array.isArray(s.dims))p.dims=s.dims;if('frame' in s)p.frame=s.frame||null;if('grid' in s)p.grid=s.grid||null;p.autofilled=true;}});
2154
+ // callouts ride along with details: a detail RENAME rewrites both (applyDetailRename), so restoring one
2155
+ // without the other brings back renamed member ends pointing at a callout that still says the old name —
2156
+ // every one of those ends silently stops resolving, with the drawing showing the contradiction (#397).
2157
+ C.plans.forEach(p=>{const s=by[p.sheet];if(s){if(Array.isArray(s.members))p.members=s.members;if(s.default_tos!=null)p.default_tos=s.default_tos;if(Array.isArray(s.details))p.details=s.details;if(Array.isArray(s.callouts))p.callouts=s.callouts;if(Array.isArray(s.dims))p.dims=s.dims;if('frame' in s)p.frame=s.frame||null;if('grid' in s)p.grid=s.grid||null;p.autofilled=true;}});
2154
2158
  if(Array.isArray(d.dims3d))C.dims3d=SteelCore?SteelCore.sanitizeDims3d(d.dims3d):d.dims3d; // restore model-global 3D dims from the local draft — re-sanitise axisDir (a stale draft could carry junk that would wedge the next save)
2155
2159
  if(Array.isArray(d.detail_placements))C.detail_placements=d.detail_placements; // restore placed details
2156
2160
  if(d.dim_overlays&&typeof d.dim_overlays==='object'&&!Array.isArray(d.dim_overlays)){const o=d.dim_overlays;C.dim_overlays={bolt_pitch:o.bolt_pitch!==false,edge_clearance:o.edge_clearance!==false,cope_size:o.cope_size!==false,base_plate:o.base_plate!==false,anchor_depth:o.anchor_depth!==false};} // restore the legend DIMENSIONS toggles — sanitised to the known boolean keys (a corrupt/partial draft can't desync the legend from what's drawn; on unless explicitly false)
@@ -3149,8 +3153,13 @@ function render(){
3149
3153
  {const hsel=sel2d();if(hsel.length>=1){const HR=epR();for(const sm of hsel)for(let i=0;i<2;i++) s+=`<circle class="handle ${i===0?'ep-start':'ep-end'}" data-mid="${sm.id}" data-h="${i}" cx="${sm.wp[i][0]}" cy="${sm.wp[i][1]}" r="${HR}"/>`;}} // end 1 (start) yellow, end 2 (end) magenta · shown for every selected member · radius grows with zoom (epR) so it stays visible against the thick line
3150
3154
  if((mode==='add'||(picking&&pickKind==='profile'))&&P.labels) for(const lb of P.labels){const w=Math.max(40,lb.text.length*11);
3151
3155
  s+=`<rect class=lblhot data-prof="${esc(lb.text)}" x="${lb.disp[0]-w/2}" y="${lb.disp[1]-10}" width="${w}" height="20" rx="3"><title>${esc(lb.text)}</title></rect>`;}
3152
- if(picking&&pickKind==='detail'&&P.details) for(const d of P.details){const w=Math.max(34,d.text.length*8);
3153
- s+=`<rect class=dethot data-det="${esc(d.text)}" x="${d.disp[0]-w/2}" y="${d.disp[1]-9}" width="${w}" height="18" rx="3"><title>${esc(d.text)}</title></rect><text class=dettx x="${d.disp[0]}" y="${d.disp[1]+4}">${esc(d.text)}</text>`;}
3156
+ // One hot-zone per PHYSICAL callout bubble — details[] AND callouts[], undeduplicated, because you pick
3157
+ // the bubble beside the end you are detailing. Reading details[] alone left nothing to click on a set
3158
+ // whose reader landed everything in callouts[] (#397), which made binding a detail — and so everything
3159
+ // the detail BUILDS — unreachable. planDetailRefs drops any entry it cannot place, so disp is safe here.
3160
+ if(picking&&pickKind==='detail') for(const d of DetailRefs.planDetailRefs(P)){const w=Math.max(34,d.text.length*8);
3161
+ const tip=(d.kind==='section'?'Section ':d.kind==='elevation'?'Elevation ':'Detail ')+d.text; // sections are pickable too and look identical once armed — say which is which
3162
+ s+=`<rect class=dethot data-det="${esc(d.text)}" x="${d.disp[0]-w/2}" y="${d.disp[1]-9}" width="${w}" height="18" rx="3"><title>${esc(tip)}</title></rect><text class=dettx x="${d.disp[0]}" y="${d.disp[1]+4}">${esc(d.text)}</text>`;}
3154
3163
  // Workstream B: clickable callout bubbles in normal select mode — details[] + per-plan callouts[].
3155
3164
  // data-co-sheet drives the smart jump (loaded plan → switch; else data-co-prev → detail lightbox).
3156
3165
  // hidden while a sub-tool is armed (dim-split / geo extend-trim-split) so the bubbles never distract
@@ -3178,7 +3187,9 @@ function render(){
3178
3187
  s+=renderPropLabels(); // right-click property-label chips (2D); 3D labels ride the div-overlay pool
3179
3188
  s+=renderSelLenLabels(); // on-select member-length chips (2D), gated by the ⋯ Display "Show member length" toggle
3180
3189
  if(P.frame)s+=axisGlyphSvg(P.frame.o,P.frame.u,false); // local-axes glyph at the origin (only when a frame is set; removed on reset)
3181
- svg.innerHTML=s; document.getElementById('profiles').innerHTML=profs.map(p=>`<option value="${esc(p)}">`).join(''); document.getElementById('details').innerHTML=(P.details||[]).map(d=>`<option value="${esc(d.text)}">`).join(''); stats(); panel(); updUR(); updDup(); updConf(); updCS(); updConnBtn(); updBpBtn(); updSpBtn(); updGridToggle(); updLenToggle(); updDimToggle(); updCalloutToggle(); updPlToggle(); updRefToggle();
3190
+ // the detail datalist shows the SAME list as the combobox and the Details modal (#397), built as DOM
3191
+ // nodes rather than markup so a detail name coming off the drawing is never parsed as HTML
3192
+ svg.innerHTML=s; document.getElementById('profiles').innerHTML=profs.map(p=>`<option value="${esc(p)}">`).join(''); {const dl=document.getElementById('details');dl.replaceChildren(...detTexts().map(t=>{const o=document.createElement('option');o.value=t;return o;}));} stats(); panel(); updUR(); updDup(); updConf(); updCS(); updConnBtn(); updBpBtn(); updSpBtn(); updGridToggle(); updLenToggle(); updDimToggle(); updCalloutToggle(); updPlToggle(); updRefToggle();
3182
3193
  if(selFilterReady)reflectSelFilter(); // keep the Select-bar Members/Connections buttons in sync with the model — a new/removed connection kind (e.g. the first auto-detailed base plate) flips their on/off without a manual toggle. Gated on selFilterReady so it doesn't run until the deferred first reflect has armed it (that reflect needs BASE_MEMBER_TYPES, initialised later in main()).
3183
3194
  if(view3d&&window.Steel3DView){window.Steel3DView.setSelection(selIds);if(window.Steel3DView.setGridSelection)window.Steel3DView.setGridSelection(selGridIds);updateIsolateBtn();if((selIds.size||selGridIds.size)&&window.Steel3DView.selectedClips&&window.Steel3DView.selectedClips().length)window.Steel3DView.setSelectedClips([]);refreshLegendSel();} // keep the 3D member + grid highlight in sync; selecting geometry clears any clip selection (exclusive)
3184
3195
  try{updateConnCrumb();}catch(_){} // Connection Component breadcrumb follows the selection (3D-only; hidden at root)
@@ -7173,6 +7184,11 @@ function detThumb(text,imgEl){const key=(sheetOf(text)||'')+'|'+(numOf(text)||''
7173
7184
  function applyDetailRename(old,nw){nw=(nw||'').trim();if(!nw||nw===old)return false;
7174
7185
  for(const pl of C.plans){
7175
7186
  if(pl.details)for(const d of pl.details)if(d.text===old)d.text=nw;
7187
+ // callouts[] carries names too, and the Details list renames from BOTH (#397). Skipping these renamed
7188
+ // the ends but not the callout they point at, so the list snapped straight back to the old name while
7189
+ // every end silently stopped resolving — the same failure the connection-library note below describes.
7190
+ // Setting `text` also covers a callout that had none: it takes precedence over the target-derived name.
7191
+ if(pl.callouts)for(const co of pl.callouts)if(co&&DetailRefs.calloutRefText(co)===old)co.text=nw;
7176
7192
  for(const m of pl.members){if(m.ends)for(const en of m.ends)if(en.detail===old)en.detail=nw;if(m.col&&m.col.detail===old)m.col.detail=nw;}}
7177
7193
  if(C.custom_details[old]!=null){C.custom_details[nw]=C.custom_details[old];delete C.custom_details[old];}
7178
7194
  // The connection library is keyed to the callout TEXT, so a rename that skipped it would leave every row
@@ -7181,14 +7197,18 @@ function applyDetailRename(old,nw){nw=(nw||'').trim();if(!nw||nw===old)return fa
7181
7197
  // now that the row carries what the detail BUILDS.
7182
7198
  for(const r of (C.connections||[]))if(r&&r.detail===old)r.detail=nw;
7183
7199
  scheduleSave();return true;}
7184
- function detTexts(){const seen=new Set(),out=[];
7185
- for(const d of (P.details||[])) if(!seen.has(d.text)){seen.add(d.text);out.push(d.text);}
7186
- for(const n of Object.keys(C.custom_details)) if(!seen.has(n)){seen.add(n);out.push(n);}
7187
- return out.sort((a,b)=>String(a).localeCompare(String(b),undefined,{numeric:true}));}
7200
+ // Every detail name this plan can bind to — the plan's own callouts (details[] ∪ callouts[]) plus the
7201
+ // model's custom ones. THE single answer: the Details modal, the ⌖ field's combobox and the native
7202
+ // datalist all call this, so none of them can go blind on a shape the others handle (#397).
7203
+ function detTexts(){return DetailRefs.planDetailTexts(P,Object.keys(C.custom_details));}
7188
7204
  function openDetails(){const g=document.getElementById('detailsGrid');const uniq=detTexts();
7205
+ // What each name IS on the drawing, so a section is not labelled "detail" — the ⌖ pick tooltip already
7206
+ // makes that distinction and the card should agree. First bubble wins; anything unplaced reads as a detail.
7207
+ const kindOf={};for(const r of DetailRefs.planDetailRefs(P))if(!(r.text in kindOf))kindOf[r.text]=r.kind;
7189
7208
  g.innerHTML=uniq.length?uniq.map(t=>{const custom=C.custom_details[t]!=null;const sheet=custom?'':(sheetOf(t)||'');const pv=previewFor(t),b=custom?null:bubbleFor(t);
7190
7209
  const prev=pv?(b?`<img class=dthumb data-t="${esc(t)}" alt="${esc(t)}">`:`<img src="data:image/jpeg;base64,${pv}" alt="${esc(t)}">`):`<div class=dprev>Preview pending<br>from sheet ${esc(sheet)}</div>`;
7191
- const sub=custom?'Custom detail':('Sheet '+esc(sheet)+(b?' · detail '+esc(numOf(t)):''));
7210
+ const kind=kindOf[t]==='section'?'section':kindOf[t]==='elevation'?'elevation':'detail';
7211
+ const sub=custom?'Custom detail':('Sheet '+esc(sheet)+(b?' · '+kind+' '+esc(numOf(t)):''));
7192
7212
  return `<div class=dcard><div class=dprevwrap${pv?` data-det="${esc(t)}"`:''}>${prev}</div><div class=dmeta><input class=dname data-old="${esc(t)}" value="${esc(t)}" data-tip="Rename (updates every plan)" autocomplete=off><div class=ds>${sub}${custom?` · <a href="#" class=ddel data-del="${esc(t)}">delete</a>`:''}</div></div></div>`;}).join('')
7193
7213
  :'<div class=hint>No detail callouts detected. Use + New detail to add your own.</div>';
7194
7214
  g.querySelectorAll('img.dthumb').forEach(im=>detThumb(im.dataset.t,im));
@@ -7424,7 +7444,7 @@ document.addEventListener('paste',e=>{if(dnForm.style.display==='none')return;co
7424
7444
  for(const it of items){if(it.type&&it.type.indexOf('image')===0){const f=it.getAsFile();if(f){e.preventDefault();dnSetImage(f);return;}}}}); // paste a screenshot straight in
7425
7445
  document.getElementById('dnAdd').onclick=()=>{const name=document.getElementById('dnName').value.trim();
7426
7446
  if(!name){dnHint('Please enter a name.');return;}
7427
- if(C.custom_details[name]!=null||(P.details||[]).some(d=>d.text===name)){dnHint('That name already exists — pick another.');return;}
7447
+ if(detTexts().includes(name)){dnHint('That name already exists — pick another.');return;} // checks every name the Details list shows, callouts included — otherwise a new custom detail could duplicate a callout visible in that same list (#397)
7428
7448
  if(!dnPending){dnHint('Paste or choose an image first.');return;}
7429
7449
  C.custom_details[name]=dnPending;scheduleSave();showDnForm(false);render();openDetails();};
7430
7450
  // --- moment frame schedule (read from the Frame Elevations S-301/302/303) ---
@@ -7562,6 +7582,8 @@ function scoreContractJS(){const plans=C.plans||[];const byMember=[],byDetail=[]
7562
7582
  const known=new Set();for(const p of plans)if(p.sheet)known.add(p.sheet.toUpperCase());for(const s of Object.keys(C.detail_bubbles||{}))known.add(s.toUpperCase());
7563
7583
  plans.forEach((plan,pi)=>{segs+=(plan.segments||[]).length;const ms=plan.members||[];const dup=_confDupIds(ms);
7564
7584
  for(const m of ms){const r=_scoreMember(m,dup);byMember.push({id:m.id,planIdx:pi,sheet:plan.sheet||'',role:m.role==='column'?'column':'beam',isBrace:isBrace(m)||undefined,profile:m.profile||'',band:r.band,tons:r.band==='rfi'?0:_mTons(m,plan.pt_per_ft,plan.default_tos),factors:r.factors});} // isBrace mirrors the server MemberScore so the report can label it Brace
7585
+ // DELIBERATELY details[] only, for now — see #401 and the matching note in steel-confidence.ts, which
7586
+ // this mirrors (contract-score.test.ts holds the two in parity, so they move together or not at all).
7565
7587
  for(const d of (plan.details||[])){const sh=_detSheet(d.text);const ok=sh!=null&&known.has(sh.toUpperCase());byDetail.push({text:d.text||'',planIdx:pi,sheet:plan.sheet||'',band:ok?'high':'low',reason:ok?('references '+sh+' (in the set)'):sh?('references '+sh+' — not found in the set'):'no sheet reference parsed'});}});
7566
7588
  const roll=(arr,cw)=>{const c=_cnt0();let n=0,d=0,t=0;for(const m of arr){c[m.band]++;if(m.band==='rfi')continue;const w=cw?1:m.tons;n+=w*BANDW[m.band];d+=w;t+=m.tons;}return {score:d>0?Math.round(n/d*100):null,tons:t,counts:c};};
7567
7589
  const dRoll=arr=>{const c=_cnt0();let n=0,d=0;for(const x of arr){c[x.band]++;n+=BANDW[x.band];d++;}return {score:d>0?Math.round(n/d*100):null,tons:0,counts:c};};
@@ -7656,8 +7678,10 @@ document.getElementById('confClose').onclick=closeConf;
7656
7678
  document.getElementById('confBackdrop').onclick=closeConf;
7657
7679
  // --- detail preview lightbox (click a card / an end's ⤢ to enlarge) ---
7658
7680
  const SHEET_PREV=C.sheet_previews||{}, DBUB=C.detail_bubbles||{};
7659
- function sheetOf(text){const m=/(S-?\w+)/.exec(String(text||'').replace(/^\w+-/,''));if(!m)return null;const s=m[1].toUpperCase();return s.startsWith('S-')?s:'S-'+s.slice(1);}
7660
- function numOf(text){const m=/^([0-9A-Za-z]+)-/.exec(String(text||''));return m?m[1].toUpperCase():null;} // leading token = detail number
7681
+ // Both halves of a detail reference are parsed in steel-detail-refs.js, where they are covered by tests;
7682
+ // these keep the short names the ~13 call sites below already use.
7683
+ function sheetOf(text){return DetailRefs.sheetOf(text);}
7684
+ function numOf(text){return DetailRefs.numOf(text);} // now reads "7/S-402" as well as "5-S504" — see the module (#397)
7661
7685
  function previewFor(text){if(C.custom_details[text]!=null)return C.custom_details[text];const s=sheetOf(text);return s?SHEET_PREV[s]:null;}
7662
7686
  function bubbleFor(text){const s=sheetOf(text),n=numOf(text);if(!s||!n||!DBUB[s])return null;
7663
7687
  if(DBUB[s][n])return DBUB[s][n];const base=n.replace(/[A-Z]+$/,'');return (base&&DBUB[s][base])?DBUB[s][base]:null;} // 11A/11B → bubble 11
@@ -7701,7 +7725,7 @@ const COMBO_SRC={
7701
7725
  profiles:()=>profs,
7702
7726
  membertypes:()=>memberTypeRecords().map(t=>t.label),
7703
7727
  conntypes:()=>['moment','drag','shear','braced','pinned','fixed'],
7704
- details:()=>{const s=new Set();(P.details||[]).forEach(d=>s.add(d.text));Object.keys(C.custom_details).forEach(n=>s.add(n));return [...s].sort((a,b)=>String(a).localeCompare(String(b),undefined,{numeric:true}));},
7728
+ details:()=>detTexts(), // the SAME list the Details modal and the datalist show — see detTexts (#397)
7705
7729
  connrows:()=>['— none —',...(C.connections||[]).map(r=>connLabel(r))]
7706
7730
  };
7707
7731
  // A connection-library row's one-line label for the per-end picker. The id is the prefix (parsed
@@ -8180,7 +8204,7 @@ function setPlan(i){C.active=i;P=C.plans[i];
8180
8204
  defaultTOS=(P.default_tos!=null?P.default_tos:198);
8181
8205
  ModelCmd.setPlanDefaultTos(P,defaultTOS); // make the default explicit so the 3D scene + bake use the SAME TOS the editor/dots do (contractToScene falls back to 0, not 198 — keeping them in sync stops the end dots floating off the steel)
8182
8206
  if(!P.autofilled){autofillTOS();P.autofilled=true;}
8183
- const ds=new Set([...(P.details||[]).map(d=>d.text),...Object.keys(C.custom_details)]);document.getElementById('detailsBtn').textContent='Details ('+ds.size+')';
8207
+ document.getElementById('detailsBtn').textContent='Details ('+detTexts().length+')'; // counts what the modal LISTS — openDetails() sets the same label from the same list, and the two disagreed on a callouts-only sheet (#397)
8184
8208
  setMode();render();fitToWindow();
8185
8209
  refresh3DGrid(); // the grid is PER-PLAN, so a plan switch must re-render it in 3D too. The plan <select> is 2D-only, but the Confidence report's Locate buttons switch sheets from 3D — without this the 3D view keeps drawing the OLD sheet's grid while snapping reads the NEW sheet's (found by Codex on the grid-level review)
8186
8210
  const ps=document.getElementById('planSel');if(ps)ps.value=String(i);}
@@ -1,5 +1,5 @@
1
1
  /*
2
- * steel-model-adapter.js — the READ side of the steel editor's model boundary (unit 5, P2).
2
+ * steel-model-adapter.js — the READ side of the steel editor's model boundary (unit 5, P2 + P5).
3
3
  *
4
4
  * PURE and framework-free (no DOM, no Three.js), node-tested from server/steel-model-adapter.test.ts —
5
5
  * same shape as grid-core.js / steel-3d-core.js.
@@ -11,11 +11,16 @@
11
11
  * answers in WORLD MILLIMETRES regardless of how the contract underneath stores things, so P5 can add a v2
12
12
  * arm behind the same six methods and the editor never learns which one it is talking to.
13
13
  *
14
- * SCOPE — read only, and NOT YET WIRED IN.
15
- * P2 ships this tested and unconsumed on purpose. Rewiring the editor's read sites is P3's job, and doing
16
- * it here would invalidate the characterization baseline recorded in the same PR (that baseline is the only
17
- * evidence P3's refactor changes nothing). Nothing loads this module yet; P3 adds the <script> tag when it
18
- * consumes it. Writes are P3 as well — there are no mutators here by design.
14
+ * SCOPE — read only, and STILL NOT WIRED IN.
15
+ * P2 shipped this tested and unconsumed on purpose. Rewiring the editor's read sites would have invalidated
16
+ * the characterization baseline recorded in the same PR (that baseline is the only evidence a refactor
17
+ * changes nothing). P3 took the write half into `steel-model-commands.js` and left the read half here, so
18
+ * nothing loads this module yet: no `<script>` tag references it, and the sole non-test mention in `web/`
19
+ * is a signpost comment in `steel-editor.html`. P5 adds the v2 arm below on the same terms — the arm
20
+ * exists and is tested; nothing can reach it until P7 registers a v2 renderer.
21
+ *
22
+ * UNITS AND SIGNS BELOW DESCRIBE THE v1 ARM. The v2 arm needs none of them (world mm is already world mm);
23
+ * see `createModelAdapterV2`.
19
24
  *
20
25
  * UNITS AND SIGNS — the one thing to get right.
21
26
  * Contract geometry is per-sheet display pixels scaled by `plan.pt_per_ft`, with Y growing DOWNWARD, and
@@ -39,7 +44,7 @@
39
44
  * recorded here rather than asserted, since pinning a NaN as expected output would entrench a bug).
40
45
  */
41
46
 
42
- import { MODEL_V2_TOL } from './steel-3d-core.js';
47
+ import { MODEL_V2_TOL, memberGeometryV2 } from './steel-3d-core.js';
43
48
 
44
49
  const FT_MM = 304.8;
45
50
  const IN_MM = 25.4; // ← becomes 1 when the contract stores elevations in mm (metric canonicalization)
@@ -64,12 +69,27 @@ const num = (v) => {
64
69
  };
65
70
 
66
71
  /**
67
- * A read-only, world-mm view over a steel contract.
72
+ * A read-only, world-mm view over a steel contract — v1 or v2, and the caller cannot tell which.
68
73
  *
69
74
  * `activeSheet` selects which sheet `grid()` answers for; it defaults to the contract's own `active` index,
70
- * so a caller that does not care gets the sheet the editor has open.
75
+ * so a caller that does not care gets the sheet the editor has open. It is MEANINGLESS to a v2 model and
76
+ * documented as such on `createModelAdapterV2` — v2 has one model grid, not one per sheet.
77
+ *
78
+ * The dispatch is the type DISCRIMINATOR and nothing else, mirroring `isModelV2` (`steel-model-read.ts`)
79
+ * for the same reason it gives: it answers "does this document claim to be v2", never "is it usable".
80
+ * Validity is the server's to judge, and a read boundary that quietly fell back to the v1 arm for a
81
+ * malformed v2 document would answer with confident nonsense — a v2 member has no `wp`, so every method
82
+ * would report an absence rather than a problem. Mirrored rather than imported because that module is
83
+ * server TypeScript and this is a browser module; the same is true of the `dispToMm` mirror above.
71
84
  */
72
- export function createModelAdapter(contract, { activeSheet } = {}) {
85
+ export function createModelAdapter(contract, opts = {}) {
86
+ return (contract && typeof contract === 'object' && contract.type === 'steel.model/v2')
87
+ ? createModelAdapterV2(contract)
88
+ : createModelAdapterV1(contract, opts);
89
+ }
90
+
91
+ /** The steel.takeoff/v1 arm — per-sheet display pixels and inch elevations, converted here to world mm. */
92
+ function createModelAdapterV1(contract, { activeSheet } = {}) {
73
93
  const plans = (contract && Array.isArray(contract.plans)) ? contract.plans : [];
74
94
  const planFor = (m) => plans.find(p => Array.isArray(p.members) && p.members.includes(m)) || null;
75
95
 
@@ -208,3 +228,133 @@ export function createModelAdapter(contract, { activeSheet } = {}) {
208
228
  },
209
229
  };
210
230
  }
231
+
232
+ /**
233
+ * The steel.model/v2 arm (unit 5, P5) — INACTIVE. Same six methods, same world-mm contract, and no way
234
+ * for a caller to tell which arm it holds. That indistinguishability is the point: epic §15 answer 4
235
+ * chose "the inactive gate, at the ADAPTER BOUNDARY — not scattered `if (v2)` branches through the editor
236
+ * closure", so this file is where the version knowledge stops.
237
+ *
238
+ * NOTHING REACHES IT YET, and that is P5's premise rather than an oversight: no `<script>` loads this
239
+ * module, `renderers.js` has no `steel.model/v2` entry, and every steel route refuses a v2 document
240
+ * (`steel-model-gate.test.ts`). Opening a v2 contract is P7's registration act.
241
+ *
242
+ * `activeSheet` IS DELIBERATELY NOT ACCEPTED. In v1 it selects which sheet `grid()` answers for; v2 has
243
+ * ONE model grid in world mm ("v1 had one grid PER PLAN in that plan's display space, which is half of
244
+ * why sheets were never registered to a common frame" — `$defs.modelGrid`), so there is nothing for it to
245
+ * select. Taking the option and ignoring it would read as support.
246
+ *
247
+ * THE CONVERSIONS ALL DISAPPEAR HERE, which is the whole reason v2 exists: work points are stored in
248
+ * world mm, so there is no px scale, no Y negation, no inches, and no `default_tos`. What remains is the
249
+ * elevation union, and `memberGeometryV2` owns it — see that function for why a v2 column is not plumbed.
250
+ */
251
+ function createModelAdapterV2(contract) {
252
+ const members = (contract && Array.isArray(contract.members)) ? contract.members : [];
253
+ const memberById = (id) => members.find((m) => m && m.id === id);
254
+
255
+ /**
256
+ * The member's two world-mm work points as NAMED endpoints, or null when either elevation is unknown
257
+ * or the record is malformed.
258
+ *
259
+ * `memberGeometryV2` already answers this; what this adds is shape. It returns `line[0]`/`line[1]` to
260
+ * match the v1 `memberGeometry` its consumers expect, and reading an ARRAY position back out under
261
+ * `noUncheckedIndexedAccess` makes the result optional — which widened `createModelAdapter`'s inferred
262
+ * `geometry()` union until `g.from` read as possibly-undefined at every existing v1 call site. Naming
263
+ * the endpoints once, here, keeps both arms inferring the same return type.
264
+ *
265
+ * THE DESTRUCTURING DEFAULTS ARE UNREACHABLE, and are here for the type checker alone: a non-null
266
+ * `memberGeometryV2` always carries a two-point line of three finite numbers each, having already
267
+ * refused a malformed endpoint and an unknown elevation. Said plainly so the next reader does not
268
+ * infer a runtime possibility that the callee has already excluded — and so that removing them is
269
+ * understood to be a typechecking decision, not a safety one.
270
+ */
271
+ const ends = (m) => {
272
+ const g = memberGeometryV2(m);
273
+ if (!g) return null;
274
+ const [a = [], b = []] = g.line;
275
+ const [ax, ay, az] = a, [bx, by, bz] = b;
276
+ return { from: [ax, ay, az], to: [bx, by, bz], z0: Number(az), z1: Number(bz) };
277
+ };
278
+
279
+ return {
280
+ /**
281
+ * Every member in the model. v2 holds ONE root array — `members` is not a plan property at all — so
282
+ * this is the whole model by construction rather than by flattening.
283
+ *
284
+ * A FRESH array of LIVE member objects, exactly as the v1 arm returns: the elements are the contract's
285
+ * own records (P3's mutation commands operate on these), while the array is a copy so that a caller's
286
+ * `push`/`splice` cannot add or drop a member behind the write boundary's back.
287
+ */
288
+ members() {
289
+ return members.slice();
290
+ },
291
+
292
+ /** The member with this id, or undefined. Ids are model-global in v2, so "first match" is the match. */
293
+ memberById,
294
+
295
+ /**
296
+ * The member's WORK LINE in world mm — the two stored work points, verbatim.
297
+ *
298
+ * Null for an unknown id, malformed work points, or an endpoint whose elevation is `{unknown}`. An
299
+ * unknown elevation is an RFI, not a position, so it is never guessed — the same refusal the v1 arm
300
+ * makes for an unreadable `tos`, and the one `sceneFromModel` makes by declining to build at all.
301
+ *
302
+ * `frame` is a SPACE TAG naming the coordinate space, not a local UCS — as in the v1 arm.
303
+ */
304
+ geometry(id) {
305
+ const e = ends(memberById(id));
306
+ return e ? { from: e.from, to: e.to, frame: 'world-mm' } : null;
307
+ },
308
+
309
+ /**
310
+ * THE model grid, or null. Returned AS STORED — grid-core owns the notation, which v2 keeps unchanged;
311
+ * only its coordinates became world mm. `inferGridMm` is the sibling that proposes one.
312
+ *
313
+ * Unlike v1 this does not depend on which sheet is active, because there is nothing per-sheet left to
314
+ * depend on. A v2 plan has no `grid` property at all.
315
+ */
316
+ grid() {
317
+ return (contract && contract.grid) || null;
318
+ },
319
+
320
+ /**
321
+ * Always null for v2 — and this is an answer, not a gap.
322
+ *
323
+ * A v2 plan still carries `frame`, and it is still stored in that plan's DISPLAY space by design
324
+ * ("epic §10 keeps plan frame/dims local" — `$defs.frame`; migration copies it verbatim). The
325
+ * transform that would carry it into world mm is the SHEET REGISTRATION, and that is computed during
326
+ * migration and never persisted: `steel-model-migrate.ts` feeds each `registerSheet` result straight
327
+ * into `materializeMembers`, and the stored `migration` block keeps only id maps.
328
+ *
329
+ * So the only conversion available here — scale by `pt_per_ft` and flip Y, as the v1 arm does — would
330
+ * yield a SHEET-LOCAL mm frame published under a WORLD-mm contract. That is the same fabrication this
331
+ * boundary refuses when it reports null instead of substituting `default_tos` for an unreadable
332
+ * elevation, and it would be harder to notice: a plausible frame, silently in the wrong space.
333
+ *
334
+ * A real answer is derivable — resolve `datum_ref`/`control2_ref` against the model grid, pair them
335
+ * with `datum_at`/`control2_at`, and run the existing `registerSheet` — but that re-implements
336
+ * migration's `registerSheets` and is activation machinery, so it is recorded as P7's in the P5 design
337
+ * note rather than improvised here. Meanwhile null is this method's existing, tested vocabulary for
338
+ * "this sheet uses global axes", and every caller already handles it.
339
+ */
340
+ sheetFrame() {
341
+ return null;
342
+ },
343
+
344
+ /**
345
+ * The member's single top-of-steel elevation in mm, or null when it does not have one.
346
+ *
347
+ * Identical rule to v1, over a different storage: a column spans base→top by definition and so has no
348
+ * one level (read `geometry(id).to[2]` for its top), a member with an unknown endpoint has none to
349
+ * report, and two ends further apart than the pinned authoring quantum are a slope rather than a
350
+ * level. Null means "no one elevation", never zero.
351
+ */
352
+ elevationOf(id) {
353
+ const m = memberById(id);
354
+ if (!m || m.role === 'column') return null;
355
+ const e = ends(m);
356
+ if (!e) return null;
357
+ return Math.abs(e.z0 - e.z1) <= MODEL_V2_TOL.CUT_PLANE_MM ? e.z0 : null;
358
+ },
359
+ };
360
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floless/app",
3
- "version": "0.108.0",
3
+ "version": "0.108.1",
4
4
  "type": "module",
5
5
  "description": "Thin localhost host for floless.app — serves web/ and shells the aware CLI. No engine, no LLM.",
6
6
  "bin": {