@floless/app 0.104.2 → 0.106.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.
@@ -154,6 +154,10 @@
154
154
  .aithumb{position:relative;display:inline-flex} .aithumb img{height:60px;border-radius:4px;border:1px solid var(--line);background:#fff;display:block}
155
155
  .aithumb button{position:absolute;top:-5px;right:-5px;width:16px;height:16px;padding:0;border-radius:8px;font-size:10px;line-height:16px;text-align:center;background:#7f1d1d;border-color:#991b1b;color:#fecaca}
156
156
  #saveStat.dirty{color:#fbbf24} #saveStat.ok{color:#86efac} #saveStat.err{color:#fca5a5}
157
+ /* Save conflict — someone else wrote here since we loaded. NOT the same as .err: the user's document
158
+ is fine, so it gets the existing cyan 'non-default, click to act' chip (same recipe as #csStat.local
159
+ and #snapStat) rather than the red failure colour. */
160
+ #saveStat.conflict{color:#22d3ee;border:1px solid #22d3ee;background:rgba(34,211,238,.10);border-radius:4px;padding:1px 6px;cursor:pointer}
157
161
  #csStat.local{border:1px solid #22d3ee;background:rgba(34,211,238,.10);border-radius:4px;padding:1px 6px;cursor:pointer} /* lift the chip out of the muted row when a local frame/plane is active (reuses the dim/accent cyan — no new colour); clickable → reset to global */
158
162
  #snapStat{cursor:pointer;border:1px solid #22d3ee;background:rgba(34,211,238,.10);border-radius:4px;padding:1px 6px} /* snap-override chip — same cyan treatment as #csStat.local; the cyan IS the snap-marker colour it restricts */
159
163
  #snapStat:hover b{color:#fff}
@@ -285,6 +289,27 @@
285
289
  .ftab-inp{background:#0f172a;color:var(--text);border:1px solid #475569;border-radius:4px;padding:4px 6px;width:100%;font:13px system-ui}
286
290
  .ftab-inp:focus{outline:none;border-color:var(--brand)}
287
291
  .ftab .cdel{padding:3px 7px;font-size:11px} .ftab .csrc{white-space:nowrap}
292
+ /* What a bound detail will BUILD — the line under a Connection detail field that turns a recorded
293
+ callout into an action. Existing tokens only (var(--mut)/--text/--brand/--line); no new palette. */
294
+ .drow{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin:5px 0 2px}
295
+ .dmsg{flex:1 1 100%;min-width:0;font-size:11px;line-height:1.45;color:var(--mut)}
296
+ .dmsg b{color:var(--text);font-weight:600}
297
+ .dmsg.warn{color:#fcd34d}
298
+ .drow button{flex:none}
299
+ .dnotes{margin:2px 0 0;padding:6px 8px;background:var(--bg);border:1px solid var(--line);border-radius:6px;
300
+ max-height:140px;overflow:auto;scrollbar-width:thin;scrollbar-color:#475569 transparent}
301
+ .dnotes::-webkit-scrollbar{width:8px;height:8px}
302
+ .dnotes::-webkit-scrollbar-thumb{background:#475569;border-radius:4px}
303
+ .dnotes::-webkit-scrollbar-track{background:transparent}
304
+ .dnotes li{font-size:11px;line-height:1.5;color:var(--mut);margin:0 0 3px 14px}
305
+ .dnotes li:last-child{margin-bottom:0}
306
+ .cbuilds{font-size:11px;line-height:1.4;color:var(--mut);margin-top:3px}
307
+ .cbuilds b{color:var(--text);font-weight:600}
308
+ .cbuilds .cundef{font-style:italic}
309
+ /* An authoring mistake the row itself can see — unreachable, not "waiting on you". Reuses the existing
310
+ .chip.fail tones rather than introducing a colour. */
311
+ .cbuilds .cwarn{display:inline-block;margin-left:6px;padding:0 5px;border-radius:4px;font-size:10px;
312
+ border:1px solid #7f1d1d;color:#fca5a5;cursor:default}
288
313
  .connset{opacity:.55} .rfichip{display:inline-block;min-width:18px;height:18px;line-height:18px;text-align:center;background:#7f1d1d;color:#fecaca;border-radius:9px;font-size:11px;padding:0 5px}
289
314
  .mbackdrop{position:absolute;inset:0;background:rgba(2,8,23,.62)}
290
315
  .mpanel{position:relative;background:var(--panel);border:1px solid var(--line);border-radius:10px;width:min(880px,92vw);max-height:86vh;display:flex;flex-direction:column;box-shadow:0 20px 60px rgba(0,0,0,.6)}
@@ -355,8 +380,15 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
355
380
  #moreMenu hr{border:0;border-top:1px solid var(--line);margin:4px 0}
356
381
  #moreMenu button{display:block;width:100%;text-align:left;background:transparent;border:0;border-radius:0;padding:7px 12px;color:var(--text);white-space:nowrap}
357
382
  #moreMenu button:hover{background:#334155}
358
- #moreMenu button.mdanger{color:#fca5a5}
359
- #moreMenu button.mdanger:hover{background:#7f1d1d;color:#fecaca}
383
+ /* "Revert to an earlier version…" is a POINTER into the workspaces shell's History step, so it
384
+ exists only when we're embedded there with a project open (boot adds body.in-workspace). Hidden
385
+ by default: Workflows mode has no version history to point at. The #moreMenu prefix is required
386
+ to beat "#moreMenu button{display:block}" above — the [hidden] attribute would lose to it. */
387
+ #moreMenu #revertB,#moreMenu #revertSep{display:none}
388
+ body.in-workspace #moreMenu #revertB,body.in-workspace #moreMenu #revertSep{display:block}
389
+ /* Same trap: "Send selection to Tekla" is hidden with an empty selection, and plain [hidden] loses
390
+ to the #moreMenu rule above — without this it ships as a visible row that only scolds you. */
391
+ #moreMenu #sendTeklaB[hidden]{display:none}
360
392
  #moreMenu button:disabled{opacity:.4;cursor:default;background:transparent}
361
393
  #moreMenu button.on{color:var(--brand)}
362
394
  button:focus-visible{outline:2px solid var(--brand);outline-offset:2px}
@@ -506,6 +538,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
506
538
  #m3dBar>button{font-size:12px;padding:5px 9px}
507
539
  #m3dBar .m3dwrap{position:relative;display:inline-flex}
508
540
  #m3dBar .m3dwrap>button{font-size:12px;padding:5px 9px;box-shadow:0 4px 14px rgba(0,0,0,.45)}
541
+ #m3dModeBtn{min-width:8.2em;text-align:center} /* same reason as #m3dDimAxis above: reflectMode() rewrites this label live, and "Realistic ▾" is far wider than "Solid ▾" — without a min-width every mode switch shoves Isolate/Views/Clip sideways. Scoped to this button; the sibling dropdowns have no such label variance. */
509
542
  .m3dmenu{position:absolute;left:0;top:calc(100% + 6px);min-width:172px;background:var(--panel);border:1px solid #475569;border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,.5);padding:4px 0;z-index:30;display:none}
510
543
  .m3dmenu.open{display:block}
511
544
  .m3dmenu button{display:block;width:100%;text-align:left;background:transparent;border:0;border-radius:0;padding:7px 12px;color:var(--text);white-space:nowrap;font-size:12px;box-shadow:none}
@@ -690,6 +723,12 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
690
723
  #m3dLegend .lrow:hover .drag-handle{opacity:1}
691
724
  #m3dLegend .lrow.flash{background:rgba(59,130,246,.12)}
692
725
  .leg-drag-ghost{position:fixed;pointer-events:none;z-index:70;background:var(--panel);border:1px solid var(--brand);border-radius:5px;padding:3px 8px;display:flex;align-items:center;gap:7px;font:12px system-ui;color:var(--text);width:200px;opacity:.88;box-shadow:0 4px 16px rgba(0,0,0,.6)}
726
+ /* The Ctrl+Shift drag-out badge. Same recipe as .leg-drag-ghost but sized to its text (a fixed width
727
+ would leave dead space beside "3 members → Tekla"). We position it ourselves on every pointer move;
728
+ the off-screen left is only where it waits between being created and that first move, so it never
729
+ flashes at the origin. It clips at the window edge — nothing can draw outside the browser. */
730
+ .tekla-drag-ghost{position:fixed;left:-9999px;top:0;pointer-events:none;z-index:70;background:var(--panel);border:1px solid var(--brand);border-radius:5px;padding:5px 10px;display:flex;align-items:center;gap:7px;font:12px system-ui;color:var(--text);white-space:nowrap;opacity:.95;box-shadow:0 4px 16px rgba(0,0,0,.6)}
731
+ .tekla-drag-ghost svg{color:var(--brand);flex:none}
693
732
  #m3dLegend .ldiv{height:1px;background:var(--line);margin:5px 2px}
694
733
  /* Objects-list SEARCH — narrows the member/connection rows as you type; never the 3D scene, never Dims/Grid/Clip.
695
734
  Built from the same tokens as #propPop .ppsearch (no new vocabulary); sits between the mode toggle and the hint. */
@@ -842,6 +881,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
842
881
  <div id=m3dInsertMenu class=m3dmenu role=menu></div>
843
882
  <input id=insFile type=file accept="image/*" style="display:none">
844
883
  </div>
884
+ <button id=dApplyBtn data-tip="Build the connection each detail callout describes, everywhere that callout appears. Ends someone confirmed, tuned by hand, or imported are left alone and listed.">Build from details</button>
845
885
  <button id=bpBtn data-tip="Auto-detail base plates on every column (a plate + anchor kit + weld, shown in 3D). Tune sizes per the schedule via the AI or per-column params.">Base plates</button>
846
886
  <button id=spBtn data-tip="Auto-detail bolted shear (fin) plates on eligible beam ends (a fin plate + bolt group + weld, shown in 3D). Tune sizes per the schedule via the AI or per-end params.">Shear plates</button>
847
887
  <button id=framesBtn>Frames</button>
@@ -867,10 +907,11 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
867
907
  <button class=msec-hdr data-sec=session aria-expanded=false data-tip="Reload from the server, or export the data">Session<span class=chev aria-hidden=true>▸</span></button>
868
908
  <div class=msec-body>
869
909
  <button id=reloadB data-tip="Reloads this page and pulls in any changes your terminal AI made since you last opened it.">↻ Reload from server</button>
910
+ <button id=sendTeklaB data-tip="Creates the selected members as native parts in the open Tekla model, at their real model coordinates. Same as Ctrl+Shift-dragging the selection out of the 3D view onto the Tekla window.">Send selection to Tekla</button>
870
911
  <button id=exp>Export contract…</button>
871
912
  </div>
872
- <hr>
873
- <button id=revertB class=mdanger data-tip="Throws away every change you've made in this browser and reloads the original AI-read model. This can't be undone.">Revert all edits…</button>
913
+ <hr id=revertSep>
914
+ <button id=revertB data-tip="Opens this project's version history, where you can restore an earlier version of the model.">Version history…</button>
874
915
  </div>
875
916
  </div>
876
917
  </header>
@@ -893,11 +934,13 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
893
934
  <span class=tb-sep></span>
894
935
  <!-- Display mode — dropdown; the button shows the current mode -->
895
936
  <div class=m3dwrap>
896
- <button id=m3dModeBtn data-tip="Display mode — solid, wireframe, or see-through (X-ray)">Solid ▾</button>
937
+ <button id=m3dModeBtn data-tip="Display mode — solid, wireframe, see-through (X-ray) or realistic materials">Solid ▾</button>
897
938
  <div id=m3dMode class=m3dmenu role=menu>
898
939
  <button data-mode=solid class=on data-tip="Solid shaded model">Solid</button>
899
940
  <button data-mode=wire data-tip="Wireframe — edges only">Wire</button>
900
941
  <button data-mode=xray data-tip="See-through — reveal hidden parts">X-ray</button>
942
+ <button data-mode=realistic data-tip="Realistic — real material finishes (steel, concrete, timber…)">Realistic</button>
943
+ <button data-mode=shadowed data-tip="Realistic with cast shadows — more depth, at a cost to frame rate">Shadowed</button>
901
944
  </div>
902
945
  </div>
903
946
  <button id=m3dIso data-tip="Isolate selected — hide everything else (Esc to exit)" style="display:none">Isolate</button>
@@ -1119,16 +1162,174 @@ const APP_ID = new URLSearchParams(location.search).get('app') || '';
1119
1162
  // /api/contract call; the contract-request (Ask AI) bodies carry `project` for slice-4 context.
1120
1163
  const PROJECT = new URLSearchParams(location.search).get('project') || '';
1121
1164
  const PROJECT_QS = PROJECT ? ('?project=' + encodeURIComponent(PROJECT)) : '';
1165
+ // ── The browser draft's identity, and the contract type this page can render (unit 5, P1c-3) ──
1166
+ // The one contract type this editor renders. A contract with NO `type` is legacy steel v1 — the server's
1167
+ // own validator says so and falls back to exactly this (contract-schema.ts, validateContract), so
1168
+ // diverging here would refuse documents this app itself wrote.
1169
+ const EDITOR_TYPE = 'steel.takeoff/v1';
1170
+ // The type the draft key is built from. Captured ONCE, right after boot() validates it, and never re-read
1171
+ // from `C` afterwards: `C` is mutable, and a key that can change identity mid-session would orphan the
1172
+ // draft it was writing (persist and restoreSaved would address different rows).
1173
+ let DRAFT_TYPE = EDITOR_TYPE;
1174
+ /**
1175
+ * Where this browser's unsaved edits live.
1176
+ *
1177
+ * Keyed by app AND project AND type. The old key was app-only, so two PROJECTS of the same app shared one
1178
+ * draft and silently overwrote each other's edits — reachable today, no v2 required. Type is in the key
1179
+ * because a store's type can change under a fixed app+project (that is exactly what P7's migration does),
1180
+ * and a v1 draft must never overlay a document of another type.
1181
+ *
1182
+ * Each component is encodeURIComponent'd so the separator cannot be forged: without it, app `a|b` +
1183
+ * project `c` and app `a` + project `b|c` are the same string.
1184
+ *
1185
+ * The prefix is `v2` because the stored SHAPE changed too (it now carries `baseEtag`). A `v1` payload has
1186
+ * no base, and restoreSaved must be able to tell those apart. Old `v1` keys are deliberately NOT migrated:
1187
+ * one belongs to an unknown project, so adopting it would attribute one project's edits to another — the
1188
+ * very bug this fixes.
1189
+ */
1190
+ function draftKey() {
1191
+ return 'steeltakeoff:edits:v2:' + encodeURIComponent(APP_ID) + '|' + encodeURIComponent(PROJECT) + '|' + encodeURIComponent(DRAFT_TYPE);
1192
+ }
1193
+ /**
1194
+ * Where a draft goes once it has been REFUSED as stale and offered back to the user.
1195
+ *
1196
+ * A separate row, because the main one is live: the moment the user makes one edit on the current
1197
+ * version, `persist()` overwrites it — and `edit()` retires the offer bar first, so they would never
1198
+ * see it go. The banner tells them their earlier edits are still saved on this computer; that has to be
1199
+ * true, so the offered copy is parked somewhere nothing else writes.
1200
+ */
1201
+ function offeredKey() { return draftKey() + '|offered'; }
1202
+ /**
1203
+ * Drop draft rows for THIS app+project that no longer belong to the type it now holds.
1204
+ *
1205
+ * Two ways they accumulate: the deliberately unmigrated `…:v1:` rows, and — once P7's migration changes
1206
+ * a store's type under a fixed app+project — the rows keyed by the previous type. Neither is ever read
1207
+ * again, and each holds a whole contract body against a per-origin storage quota, so leaving them is a
1208
+ * slow leak that would eventually break saving for a reason nobody could see.
1209
+ *
1210
+ * Scoped to this app+project on purpose: another project's rows are not ours to delete.
1211
+ */
1212
+ function sweepOrphanDrafts() {
1213
+ try {
1214
+ const mine = draftKey(), offered = offeredKey();
1215
+ const prefix = 'steeltakeoff:edits:', scope = encodeURIComponent(APP_ID) + '|' + encodeURIComponent(PROJECT) + '|';
1216
+ for (const k of Object.keys(localStorage)) {
1217
+ if (!k.startsWith(prefix) || k === mine || k === offered) continue;
1218
+ // A v1 key has no scope segment at all; a v2 key for this store carries exactly this prefix.
1219
+ // EXACT for v1 — a prefix test also matched a DIFFERENT app whose id merely starts with ours
1220
+ // (`…v1:harness` vs `…v1:harness-tower`), and another app's row is not ours to delete.
1221
+ if (k === 'steeltakeoff:edits:v1:' + APP_ID || k.includes(':v2:' + scope)) localStorage.removeItem(k);
1222
+ }
1223
+ } catch (_) { /* housekeeping only — never block the load */ }
1224
+ }
1225
+ /**
1226
+ * Re-point the stored draft at the server version it is now a delta from.
1227
+ *
1228
+ * WHY IT EXISTS. `scheduleSave` runs `persist(); persistServer();` in that order, so the draft records
1229
+ * the tag from BEFORE the write that advances it. Without this, storage holds the pre-write tag while
1230
+ * the server holds the post-write one, and the next reload reports "someone else changed this model"
1231
+ * about the tab's own save — every time. (connModifyRequest and the detail-placement request order the
1232
+ * pair the other way round; Ctrl+S orders it like scheduleSave. Re-stamping on the result covers all.)
1233
+ *
1234
+ * WHY IT TAKES `prev`, which is the part review had to find. Re-stamping unconditionally assumes the row
1235
+ * in storage is a delta from the version we just replaced — and there is a reachable state where it is
1236
+ * not: after `restoreSaved()` refuses a stale draft, the row belongs to an OLDER base while the tab
1237
+ * edits the current document. A `flushContract()` with no preceding `persist()` — Ask AI Send, the
1238
+ * History revert, the shell's Approve, the non-project Tekla send: all four exist — would then stamp
1239
+ * the current tag onto those old edits, and the NEXT reload would find the bases equal and silently
1240
+ * overlay them on top of the newer work. That is the masking bug this whole item exists to close,
1241
+ * re-entered through its own fix.
1242
+ *
1243
+ * So the rewrite is conditional on the row actually being the one we wrote: its base must be the tag we
1244
+ * just replaced. Under `scheduleSave` that is exactly what `persist()` stored a moment earlier, so the
1245
+ * intended path is untouched; any row belonging to some other base is left alone.
1246
+ *
1247
+ * Best-effort: a storage failure here costs a false conflict prompt on the next reload, never data.
1248
+ */
1249
+ function restampDraftBase(prev, next) {
1250
+ if (!next) return;
1251
+ try {
1252
+ const raw = localStorage.getItem(draftKey());
1253
+ if (!raw) return;
1254
+ const d = JSON.parse(raw);
1255
+ if (!d || typeof d !== 'object') return;
1256
+ // `== null` covers a v1-era row with no base: it predates this field, so it is not a delta from
1257
+ // `prev` in any checkable sense and must not inherit a tag it never earned.
1258
+ if (d.baseEtag !== prev) return;
1259
+ d.baseEtag = next;
1260
+ localStorage.setItem(draftKey(), JSON.stringify(d));
1261
+ } catch (_) { /* the draft stays on its old base — a false "changed elsewhere" prompt, not a loss */ }
1262
+ }
1263
+ // ── Own-write identity, replacing the 2.5 s SSE echo clock (unit 5, P1c-3) ──
1264
+ // Every PUT names itself; the server echoes that name in the contract-changed broadcast. A clock could not
1265
+ // tell "my echo" from "someone else's write inside the window", so a genuine external write landing in
1266
+ // those 2.5 s was silently swallowed — and once the conflict latch tripped, persistServer returned BEFORE
1267
+ // stamping the clock, so the window expired and stayed expired precisely when a wrong reload cost most.
1268
+ const ownWrites = [];
1269
+ // A pure backstop, not a working limit. queueWrite SERIALIZES this tab's writes, and an id is dropped on
1270
+ // success AND on every failure, so in steady state this holds at most one entry. The cap only matters if
1271
+ // some future path mints an id and never resolves it.
1272
+ const OWN_WRITES_MAX = 32;
1273
+ // Three tiers, because only the FIRST needs a secure context and this page is served over plain http in
1274
+ // some dev setups. `crypto.getRandomValues` is NOT secure-context-gated, so tier 2 is a real CSPRNG and
1275
+ // the Math.random tier is close to unreachable — it exists so a missing `crypto` cannot break saving.
1276
+ //
1277
+ // Entropy matters here, and an earlier comment overstated it (review): a held id is released on match
1278
+ // and on every failure, but an id whose echo never arrives lingers until the FIFO evicts it, and while
1279
+ // it lingers an event carrying the SAME id would be read as our own and suppressed. 122 bits (UUIDv4)
1280
+ // or 128 bits (tier 2) makes that unreachable; two `Math.random()` slices would not, since Math.random
1281
+ // is neither uniform over that space nor unguessable.
1282
+ function newMutationId() {
1283
+ try {
1284
+ const c = self.crypto;
1285
+ if (c && typeof c.randomUUID === 'function') return c.randomUUID();
1286
+ if (c && typeof c.getRandomValues === 'function') {
1287
+ const b = c.getRandomValues(new Uint8Array(16));
1288
+ return 'm-' + Array.from(b, n => n.toString(16).padStart(2, '0')).join('');
1289
+ }
1290
+ } catch (_) { /* fall through to the last resort */ }
1291
+ // Last resort only. Weaker, and deliberately not described as anything else.
1292
+ return 'm-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 12) + Math.random().toString(36).slice(2, 12);
1293
+ }
1294
+ function claimMutation(id) { ownWrites.push(id); while (ownWrites.length > OWN_WRITES_MAX) ownWrites.shift(); }
1295
+ /** Drop an id we are done with. Called on success (the echo arrived, or will be recognised by then) and on
1296
+ * EVERY failure — a refused write produces no broadcast at all, so its id would otherwise sit in the list
1297
+ * forever, where the only thing it can do is wrongly suppress somebody else's event. */
1298
+ function releaseMutation(id) { const i = ownWrites.indexOf(id); if (i >= 0) ownWrites.splice(i, 1); }
1122
1299
  let C, PAL, WT;
1123
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
1124
1301
  let ViewGen = null; // steel-view-generation.js pure F11 helpers — loaded before saved views are sanitised
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
1125
1303
  let TARGET_CONF = null; // the app's target_confidence input default (%), or null when undeclared — drives the chip's "· target N%" goal
1126
1304
  let view3d = false, view3dReady = false; // 2D|3D toggle state; view3dReady once Steel3DView.init has run
1127
1305
  // Fallback palette (colorFor indexes this array by profile order) when a contract ships no `palette`
1128
1306
  // — e.g. a contract shared/committed with raster_b64 + palette stripped for confidentiality.
1129
1307
  const DEFAULT_PAL=['#60a5fa','#94a3b8','#f59e0b','#34d399','#f472b6','#a78bfa','#fb7185','#22d3ee','#facc15','#4ade80'];
1130
- let lastLocalPut = 0; // timestamp of our own PUT — used to suppress the SSE echo
1131
- function showEmpty(icon, headline, bodyText, appIdText) {
1308
+ // (P1c-3 removed `lastLocalPut`: own-write echoes are now recognised by id — see ownWrites above. Leaving
1309
+ // the timestamp in place would have left a second, wrong answer to the same question.)
1310
+ // The server's tag for the contract this tab loaded, and whether a write has already lost a race.
1311
+ // `conflicted` LATCHES: once a save is refused, firing the identical PUT every 500 ms debounce tick is
1312
+ // wasted traffic and makes the pill flicker in a way that reads as broken rather than informative.
1313
+ let serverEtag = null;
1314
+ let conflicted = false;
1315
+ // Serialize THIS tab's writes. Without it the editor conflicts with ITSELF: a slow autosave still in
1316
+ // flight when the next one (or flushContract, which Approve awaits) fires means two requests carrying
1317
+ // the SAME tag — one wins, the other comes back 412 and shows the user a conflict caused by nobody but
1318
+ // themselves, potentially aborting Approve. `saveSeq` only decides which response owns the pill; it
1319
+ // never stopped the overlap. vector-editor already queues; this brings the steel editor in line.
1320
+ let writeQueue = Promise.resolve();
1321
+ const queueWrite = (fn) => (writeQueue = writeQueue.then(fn, fn));
1322
+ /**
1323
+ * The full-screen "there is nothing to show" state.
1324
+ *
1325
+ * `opts.detail` (P1c-3) is a whispered technical footer — today, the contract type this editor declined.
1326
+ * Two different readers exist for that refusal: the engineer, who must never need a schema string and gets
1327
+ * prose; and whoever triages their screenshot, for whom the exact string is the single fastest diagnostic
1328
+ * fact there is. Present-but-secondary serves both. Deliberately NOT monospace: no monospace family is
1329
+ * established on this surface, and introducing one would be a new font against a locked visual baseline —
1330
+ * size and colour de-emphasise it just as well.
1331
+ */
1332
+ function showEmpty(icon, headline, bodyText, appIdText, opts) {
1132
1333
  const wrap = document.createElement('div');
1133
1334
  wrap.style.cssText = 'display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;text-align:center;color:#e7ecf3;font:13px system-ui,sans-serif;gap:10px;padding:24px;background:#070a0f';
1134
1335
  const ic = document.createElement('div'); ic.style.cssText = 'font-size:28px;opacity:.5'; ic.textContent = icon;
@@ -1137,11 +1338,17 @@ function showEmpty(icon, headline, bodyText, appIdText) {
1137
1338
  else { h.textContent = headline; }
1138
1339
  const body = document.createElement('div'); body.style.cssText = 'font-size:12.5px;color:#9aa5b6;max-width:340px;line-height:1.55'; body.textContent = bodyText;
1139
1340
  wrap.append(ic, h, body);
1341
+ if (opts && opts.detail) {
1342
+ const det = document.createElement('div');
1343
+ det.style.cssText = 'font-size:10.5px;color:#9aa5b6;opacity:.65;margin-top:-2px';
1344
+ det.textContent = opts.detail; // textContent, not innerHTML: this string comes from the stored document
1345
+ wrap.append(det);
1346
+ }
1140
1347
  document.body.replaceChildren(wrap);
1141
1348
  }
1142
1349
  async function boot() {
1143
1350
  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; }
1144
- [SteelCore, ViewGen] = await Promise.all([import('./steel-3d-core.js'), import('./steel-view-generation.js')]); // await BEFORE main()/restoreSaved(): both draft-state sanitisers must exist at the load boundary
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
1145
1352
  const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS);
1146
1353
  if (!res.ok) {
1147
1354
  if (res.status === 404) {
@@ -1151,7 +1358,46 @@ async function boot() {
1151
1358
  }
1152
1359
  return;
1153
1360
  }
1154
- C = await res.json();
1361
+ // Parse into a LOCAL first (unit 5, P1c-3). `C` is the global everything else in this page reads, so
1362
+ // assigning before the type is validated would publish a document this editor cannot render — briefly
1363
+ // live, and observable to anything that runs in between. Validate, then publish.
1364
+ const loaded = await res.json();
1365
+ // Shape first, then type. A body that is null, an array or a scalar has no `type` to test, so a
1366
+ // type-only gate waved it through and the failure surfaced as a raw red `boot().catch` — "Cannot read
1367
+ // properties of null (reading 'palette')" — instead of the styled state this item introduces. `plans`
1368
+ // is what every path below indexes, so its absence is the honest floor.
1369
+ if (!loaded || typeof loaded !== 'object' || Array.isArray(loaded) || !Array.isArray(loaded.plans)) {
1370
+ showEmpty('⚠', 'Couldn’t read this model',
1371
+ 'The saved model is missing or in a shape this editor doesn’t recognise. Re-run the workflow to rebuild it, or restore an earlier version from History.',
1372
+ APP_ID);
1373
+ return;
1374
+ }
1375
+ const loadedType = loaded.type;
1376
+ // A missing type is legacy steel v1 (see EDITOR_TYPE). Anything else declared is refused HERE, before
1377
+ // the normalisation below starts mutating the document and before main() runs restoreSaved() — which
1378
+ // would otherwise overlay a steel draft onto a document of a different type entirely.
1379
+ if (loadedType != null && loadedType !== EDITOR_TYPE) {
1380
+ // Two different situations, and one message for both would be false in one of them. A steel.model/v2
1381
+ // IS a Steel Model — just a newer format this build cannot draw yet — so telling that user "this is
1382
+ // not a Steel Model" would be plainly wrong. Anything else means they opened the wrong workflow.
1383
+ const newerSteel = /^steel\.model\//.test(String(loadedType));
1384
+ showEmpty('⊞',
1385
+ newerSteel ? 'This Steel Model isn’t supported yet —' : 'Not a Steel Model —',
1386
+ newerSteel
1387
+ ? 'This workflow’s Steel Model uses a newer format this editor doesn’t open yet. Nothing’s wrong with the model — this editor just needs to catch up.'
1388
+ : 'This screen only opens Steel Model workflows — the plans and 3D model built from a steel take-off. This workflow’s output is something else.',
1389
+ APP_ID,
1390
+ { detail: 'type: ' + String(loadedType) });
1391
+ return;
1392
+ }
1393
+ // Pin the draft identity for the rest of the session. Read once, from the validated value, never from
1394
+ // the mutable `C` — see draftKey().
1395
+ DRAFT_TYPE = loadedType == null ? EDITOR_TYPE : loadedType;
1396
+ sweepOrphanDrafts(); // now that the identity is pinned, retire rows keyed by an older one
1397
+ C = loaded;
1398
+ // The server's tag for the contract we just read. Every write echoes it back, so a write that would
1399
+ // land on top of someone else's is refused instead of silently winning.
1400
+ serverEtag = res.headers.get('ETag');
1155
1401
  // The confidence target is a workflow INPUT (target_confidence), not contract data — read its
1156
1402
  // declared default off the app def so the chip can show the goal. Best-effort: on any failure the
1157
1403
  // chip just omits the "· target N%" suffix (no fabricated goal).
@@ -1188,17 +1434,45 @@ async function boot() {
1188
1434
  if (!m || typeof m !== 'object') return;
1189
1435
  if (m.type !== 'contract-changed') return;
1190
1436
  if (m.appId !== APP_ID) return;
1191
- // Suppress our own PUT echo (debounce: 2.5 s window)
1192
- if (Date.now() - lastLocalPut < 2500) return;
1193
- // External writeback (the AI wrote a new contract to the server) — the local
1194
- // localStorage draft is now STALE and would mask the server's version on reload
1195
- // (restoreSaved() overlays it). Drop it so any reload shows the AI's contract.
1196
- try { localStorage.removeItem('steeltakeoff:edits:v1:' + APP_ID); } catch (_) { /* ignore */ }
1437
+ // …and the same PROJECT. Two projects of one app share an appId, so without this a write to one
1438
+ // reloads the other's tab and (before the removal below was dropped) destroyed its draft — item
1439
+ // A's own bug class, left half-fixed: the key became project-scoped while the invalidation did
1440
+ // not. `|| ''` on both sides because an app-scoped write carries no `project` at all.
1441
+ if ((m.project || '') !== PROJECT) return;
1442
+ // OUR OWN echo, recognised by NAME rather than by clock (unit 5, P1c-3).
1443
+ const own = m.mutationId ? ownWrites.indexOf(m.mutationId) : -1;
1444
+ if (own >= 0) {
1445
+ // Everything OLDER than the match is superseded: SSE preserves order on a connection, so an
1446
+ // echo we have not seen by the time a later one arrives is never coming.
1447
+ const newest = own === ownWrites.length - 1;
1448
+ ownWrites.splice(0, own + 1);
1449
+ // Adopt the tag the server produced for our write — but ONLY from the newest echo. This is the
1450
+ // case the old clock could never cover (a PUT that succeeds while its response is lost leaves
1451
+ // `serverEtag` stale, so the tab's own next save is refused against its own change) — and
1452
+ // review found the mirror image: a LATE echo carries an OLDER tag, and adopting that rolls
1453
+ // `serverEtag` backwards, guaranteeing a 412 on the user's next write.
1454
+ if (newest && typeof m.etag === 'string' && m.etag) { const prev = serverEtag; serverEtag = m.etag; restampDraftBase(prev, m.etag); }
1455
+ return;
1456
+ }
1457
+ // An external write. The draft is deliberately NOT dropped here any more: with a server-issued
1458
+ // base recorded, a reload now compares bases and OFFERS a stale draft back instead of masking
1459
+ // the newer version with it — which is the only thing the removal was ever protecting against.
1460
+ // Removing it first was actively harmful, because it ran BEFORE the `hasUnsaved` check below:
1461
+ // in exactly the case where work was at risk, the durable copy was destroyed and only in-memory
1462
+ // `C` survived, so the banner's own Reload button lost it.
1197
1463
  // Auto-reload straight into the AI's version so the user never has to hit refresh — EXCEPT
1198
1464
  // when they have unsaved in-browser edits (saveStat 'dirty'/'err'), where a silent reload
1199
1465
  // would discard their work; there we fall back to the choose-to-reload banner.
1200
1466
  const sv = document.getElementById('saveStat');
1201
- const hasUnsaved = !!sv && (sv.classList.contains('dirty') || sv.classList.contains('err'));
1467
+ // 'conflict' counts as unsaved, and omitting it lost data: after a refused save the edits are
1468
+ // unsaved BY DEFINITION, so a silent reload here would drop the localStorage draft (above) and
1469
+ // discard exactly the work the conflict banner had just promised was "still here".
1470
+ // (Historically this also had to compensate for the 2.5 s echo suppressor, which stopped working
1471
+ // the moment the conflict latch tripped — persistServer returned before stamping its timestamp,
1472
+ // so the window expired and stayed expired. Identity has no such state, but this check is load
1473
+ // bearing on its own merits and stays.)
1474
+ const hasUnsaved = !!sv && (sv.classList.contains('dirty') || sv.classList.contains('err')
1475
+ || sv.classList.contains('conflict'));
1202
1476
  if (hasUnsaved) showAiUpdateBanner('The AI updated this model — reload to see it (you have unsaved edits).');
1203
1477
  else location.reload();
1204
1478
  };
@@ -1207,6 +1481,10 @@ async function boot() {
1207
1481
  // terminal: live writeback detection is dead, so surface it (the banner's Reload re-opens
1208
1482
  // the editor and its EventSource) instead of leaving the user on a silently-stale view.
1209
1483
  if (es.readyState === EventSource.CLOSED) {
1484
+ // Every id we are still holding is now DEAD: the channel that would have carried its echo is
1485
+ // gone, so none can ever be matched. Holding them serves nothing and is the only way the list
1486
+ // grows without bound — the one case review raised against retaining an id past its response.
1487
+ ownWrites.length = 0;
1210
1488
  console.warn('steel-editor: SSE channel closed — live updates paused');
1211
1489
  showAiUpdateBanner('Live updates disconnected — reload to resume change detection.');
1212
1490
  }
@@ -1217,13 +1495,25 @@ async function boot() {
1217
1495
  }
1218
1496
  }
1219
1497
 
1220
- function showAiUpdateBanner(message) {
1498
+ /**
1499
+ * The bottom bar for "this model changed underneath you".
1500
+ *
1501
+ * `opts` extends it for the save-conflict case without forking the component — same bar, same tokens, so
1502
+ * a user who has learned "blue bar at the bottom = something else changed" does not relearn it per cause.
1503
+ * onReload — override the reload action (the conflict path must drop the local draft first)
1504
+ * onOverwrite — adds the secondary "Save mine anyway" button; omitted, no such button appears
1505
+ */
1506
+ function showAiUpdateBanner(message, opts) {
1221
1507
  // Remove any existing banner before adding a new one (idempotent)
1222
1508
  const existing = document.getElementById('aiUpdateBanner');
1223
1509
  if (existing) existing.remove();
1224
1510
 
1225
1511
  const bar = document.createElement('div');
1226
1512
  bar.id = 'aiUpdateBanner';
1513
+ // Which cause raised this bar. Only the stale-draft caller sets it, so that one can be auto-dismissed
1514
+ // when it stops being true (see edit()) without touching the AI-update and conflict banners, which must
1515
+ // survive edits — persisting through them is the whole point of the conflict banner.
1516
+ if (opts && opts.kind) bar.dataset.kind = opts.kind;
1227
1517
  bar.style.cssText = [
1228
1518
  'position:fixed', 'bottom:0', 'left:0', 'right:0', 'z-index:50',
1229
1519
  'display:flex', 'align-items:center', 'gap:10px',
@@ -1239,8 +1529,12 @@ function showAiUpdateBanner(message) {
1239
1529
 
1240
1530
  const reloadBtn = document.createElement('button');
1241
1531
  reloadBtn.style.cssText = 'background:#3b82f6;color:#fff;border:1px solid #60a5fa;border-radius:6px;padding:5px 12px;cursor:pointer;font:13px system-ui';
1242
- reloadBtn.textContent = '↻ Reload';
1243
- reloadBtn.onclick = () => location.reload();
1532
+ // The LABEL is overridable as well as the handler. The two existing callers pass neither and render
1533
+ // byte-identically; the stale-draft caller does not reload at all, so a button reading "↻ Reload"
1534
+ // would have named an action it does not perform.
1535
+ reloadBtn.textContent = (opts && opts.reloadLabel) || '↻ Reload';
1536
+ if (opts && opts.reloadTip) reloadBtn.dataset.tip = opts.reloadTip; // data-tip, never title= — the themed tooltip is CI-enforced
1537
+ reloadBtn.onclick = (opts && opts.onReload) ? opts.onReload : () => location.reload();
1244
1538
 
1245
1539
  const dismissBtn = document.createElement('button');
1246
1540
  dismissBtn.style.cssText = 'background:transparent;color:#93c5fd;border:1px solid #3b82f6;border-radius:6px;padding:5px 10px;cursor:pointer;font:13px system-ui';
@@ -1250,6 +1544,15 @@ function showAiUpdateBanner(message) {
1250
1544
 
1251
1545
  bar.appendChild(msg);
1252
1546
  bar.appendChild(reloadBtn);
1547
+ if (opts && opts.onOverwrite) {
1548
+ // Visually subordinate to Reload — it is the destructive option, and it still has to pass a confirm.
1549
+ const over = document.createElement('button');
1550
+ over.style.cssText = 'background:transparent;color:#93c5fd;border:1px solid #3b82f6;border-radius:6px;padding:5px 10px;cursor:pointer;font:13px system-ui';
1551
+ over.textContent = 'Save mine anyway';
1552
+ over.dataset.tip = 'Replace the version someone else saved with what you have here';
1553
+ over.onclick = opts.onOverwrite;
1554
+ bar.appendChild(over);
1555
+ }
1253
1556
  bar.appendChild(dismissBtn);
1254
1557
  document.body.appendChild(bar);
1255
1558
  }
@@ -1306,9 +1609,7 @@ function fmtFtIn(v){if(v==null||isNaN(v))return '';const neg=v<0;let sx=Math.rou
1306
1609
  let num=fr,den=16;while(num>0&&num%2===0){num/=2;den/=2;}const fs=num>0?(' '+num+'/'+den):'';
1307
1610
  const body=ft>0?(ft+"'-"+inch+fs+'"'):(inch+fs+'"');return (neg?'-':'')+body;}
1308
1611
  const fmtDecIn=v=>(v==null||isNaN(v))?'—':((Math.round(v*100)/100)+'"');
1309
- function ensureMeta(m){if(!m.role)m.role='beam';
1310
- if(!m.ends){const c=/(^|[^A-Z])MF/i.test(m.profile||'')?'moment':'';m.ends=[{tos:null,note:c,tosDef:true,detail:''},{tos:null,note:c,tosDef:true,detail:''}];}
1311
- if(!m.col)m.col={bos:null,tos:null,note:(/(^|[^A-Z])MF/i.test(m.profile||'')?'moment':''),tosDef:true,detail:''};return m;}
1612
+ function ensureMeta(m){return ModelCmd.ensureMeta(m);} // unit 5 P3a: the model boundary owns member normalisation now
1312
1613
  // Effective profile position on the reference line (the work-line between the end dots), à la Tekla.
1313
1614
  // Explicit m.position wins; else a flat beam → top (top-of-steel), a steep beam (brace) / column → middle.
1314
1615
  // A VERTICAL brace is always centred: its work-points sit on the column ℄, and the slope heuristic alone
@@ -1335,9 +1636,9 @@ function swapMemberEnds(m){
1335
1636
  let braceOld=null;
1336
1637
  if(isBrace(m)){normBrace(m); // a brace reached here without m.brace (reader payload / direct call) would NPE below
1337
1638
  const t0=effEndTos(m.ends&&m.ends[0]),t1=effEndTos(m.ends&&m.ends[1]);braceOld={old:braceLowerEnd(m),tie:(t0===t1)};}
1338
- if(Array.isArray(m.wp)&&m.wp.length>=2)m.wp=[m.wp[1].slice(),m.wp[0].slice()];
1339
- if(Array.isArray(m.ends)&&m.ends.length>=2)m.ends=[m.ends[1],m.ends[0]];
1340
- if(m.col){const b=(m.col.bos!=null?m.col.bos:0),t=(m.col.tos!=null?m.col.tos:defaultTOS);m.col.bos=t;m.col.tos=b;m.col.tosDef=false;}
1639
+ if(Array.isArray(m.wp)&&m.wp.length>=2)MC().replaceEndpoints(m,[m.wp[1].slice(),m.wp[0].slice()]); // both args are evaluated before the assignment, so the swap still reads the pre-swap points; the wp-shape guard stays OUTSIDE the primitive
1640
+ if(Array.isArray(m.ends)&&m.ends.length>=2)ModelCmd.reverseEnds(m); // the length guard stays OUTSIDE the primitive: a one-ended member is broken, and swallowing that inside would hide it at every call site
1641
+ if(m.col)ModelCmd.swapColElevation(m.col,defaultTOS); // materialises BOTH sides first (bos null->0, tos null->defaultTOS), then swaps; a beam's vestigial col is swapped too, as it always was
1341
1642
  if(braceOld){
1342
1643
  if(braceOld.tie||(m.brace.lowerEnd===0||m.brace.lowerEnd===1))m.brace.lowerEnd=(1-braceOld.old);
1343
1644
  // braceDisplayLine takes its perpendicular from the a→b direction, so reversing wp flips which SIDE the
@@ -1470,14 +1771,15 @@ function braceSymbol(m,c,glow){
1470
1771
  for(const pts of braceHeadPoints(m)) s+=`<polygon class=bracehead fill="${c}" points="${pts}"/>`;
1471
1772
  return s+`</g>`;}
1472
1773
  // --- Move/Copy transform core (spec §4.1): offsets are [dx,dy,dzIn] — dx/dy plan px, dz inches. ---
1473
- let cmSeq=0;
1474
- function cloneMember(m){const c=JSON.parse(JSON.stringify(m));c.id='m'+Date.now()+'_c'+(cmSeq++);return c;}
1475
- // Rigid translate: wp shift; dz materializes the level default first then shifts both ends together
1476
- // (same contract as the 3D vertical-drag path) — a slope is preserved, tosDef flips off only when dz≠0.
1477
- function translateMembers(ms,off){const dz=off[2]||0;for(const m of ms){ensureMeta(m);
1478
- m.wp[0]=[m.wp[0][0]+off[0],m.wp[0][1]+off[1]];m.wp[1]=[m.wp[1][0]+off[0],m.wp[1][1]+off[1]];
1479
- if(dz){if(m.role==='column'){m.col.tos=(m.col.tos!=null?m.col.tos:defaultTOS)+dz;m.col.bos=(m.col.bos!=null?m.col.bos:0)+dz;m.col.tosDef=false;}
1480
- else m.ends.forEach(en=>{en.tos=(en.tos!=null?en.tos:defaultTOS)+dz;en.tosDef=false;});}}}
1774
+ let cmSeq=0; // still live: MC()'s mintId below is the '_c' id policy every clone but doDup's uses
1775
+ // unit 5 P3b-1: cloneMember, translateMembers and retargetTos are GONE from this file — the move/copy
1776
+ // family is now entirely behind the model boundary, so none of the three had a caller left. Their six
1777
+ // ?selftest=1 assertions moved with them to server/steel-model-commands.test.ts, where the primitives
1778
+ // that replaced them live (clone / translate / retargetTos).
1779
+ // The model boundary's write half, rebuilt per call so it always sees the CURRENT active plan and default
1780
+ // T.O.S. `mintId` stays here because id policy is the editor's: the characterization harness pins
1781
+ // Date.now() inside this realm. doDup passes its OWN minter to clone() — its ids are '_'+i, not '_c'+seq.
1782
+ function MC(){return ModelCmd.createModelCommands(C,{activePlan:P,defaultTosIn:defaultTOS,mintId:()=>'m'+Date.now()+'_c'+(cmSeq++)});}
1481
1783
  function linearOffsets(v,n){const o=[];for(let k=1;k<=n;k++)o.push([v[0]*k,v[1]*k,(v[2]||0)*k]);return o;}
1482
1784
  // Rectangular array: counts INCLUDE the original position; (0,0) is skipped so the grid adds n*m-1 copies.
1483
1785
  function arrayOffsets(vA,nA,vB,nB){const o=[];for(let i=0;i<nA;i++)for(let j=0;j<nB;j++){if(!i&&!j)continue;
@@ -1494,11 +1796,6 @@ function parseVec(s){s=String(s==null?'':s).trim();if(!s)return null;
1494
1796
  const d=parseLen(s);return d==null?null:{dist:d};}
1495
1797
  // To-level TOS mapping (spec §4.5): default-follow ends land on the target level automatically;
1496
1798
  // explicit overrides shift by Δ so relative offsets survive. Columns keep their height (bos shifts by Δ).
1497
- function retargetTos(m,srcDef,dstDef){const d=dstDef-srcDef;ensureMeta(m);
1498
- if(m.role==='column'){if(m.col.tosDef!==false)m.col.tos=dstDef;else if(m.col.tos!=null)m.col.tos+=d;
1499
- if(m.col.bos!=null)m.col.bos+=d;}
1500
- else for(const en of m.ends){if(en.tosDef!==false)en.tos=dstDef;else if(en.tos!=null)en.tos+=d;}
1501
- return m;}
1502
1799
  // best-effort: framing plans carry TOS at the level UNO — assume the L2 datum +16'-6" (198"); each end's
1503
1800
  // 'default' checkbox links it to this value (auto-updates when changed); uncheck to override.
1504
1801
  let defaultTOS=198, addProfile='', addType='beam'; // addType = the member type new members are drawn with (Add-member panel)
@@ -1512,9 +1809,7 @@ function armBaseTrim(colId){
1512
1809
  window.Steel3DView.setBasePickMode(colId);
1513
1810
  toast('Click a point along '+colId+' — the base snaps to framing levels · Esc cancels');
1514
1811
  }
1515
- function syncDefaults(){for(const m of P.members){ensureMeta(m);
1516
- if(m.role==='column'){if(m.col.tosDef!==false&&defaultTOS!=null)m.col.tos=defaultTOS;if(m.col.bos==null)m.col.bos=0;}
1517
- else for(const en of m.ends)if(en.tosDef!==false&&defaultTOS!=null)en.tos=defaultTOS;}}
1812
+ function syncDefaults(){for(const m of P.members)ModelCmd.syncToDefault(m,defaultTOS);} // re-datums only ends still FOLLOWING the default (an override survives) - that is the whole difference from #applyTos below
1518
1813
  const autofillTOS=syncDefaults;
1519
1814
  // profs is per-plan — computed in setPlan()
1520
1815
  // Undo snapshot — WHOLE-MODEL on a SINGLE GLOBAL stack. Captures every plane's members AND each plane's
@@ -1527,7 +1822,7 @@ const autofillTOS=syncDefaults;
1527
1822
  // select/delete/undo — a reader-side id-uniqueness hardening. dims3d rides its own persistence.
1528
1823
  // dim_style (the model-global dimension-style defaults) rides every entry like details/member_types: one
1529
1824
  // chronological stack means an undo simply walks the whole model back, so there is no cross-sheet clobber.
1530
- function snapshot(){return JSON.stringify({planes:C.plans.map(p=>({sheet:p.sheet,members:p.members,dims:p.dims||[],frame:p.frame||null,grid:p.grid||null})),joints:C.joints||[],clips:(window.Steel3DView&&window.Steel3DView.clipState)?window.Steel3DView.clipState():null,details:(C.detail_placements||[]),member_types:C.member_types||[],dim_style:C.dim_style||null,member_styles:C.member_styles||{}});} // members/dims/frame/grid are all PER-SHEET → captured per sheet so a cross-sheet undo restores each sheet's OWN dims/frame/grid, never the active sheet's over another's. clips/work area are view-state riding the undo stack; details/dim_style = model-global, captured whole.
1825
+ function snapshot(){return JSON.stringify({planes:C.plans.map(p=>({sheet:p.sheet,members:p.members,dims:p.dims||[],frame:p.frame||null,grid:p.grid||null})),joints:C.joints||[],connections:Array.isArray(C.connections)?C.connections:null,clips:(window.Steel3DView&&window.Steel3DView.clipState)?window.Steel3DView.clipState():null,details:(C.detail_placements||[]),member_types:C.member_types||[],dim_style:C.dim_style||null,member_styles:C.member_styles||{}});} // members/dims/frame/grid are all PER-SHEET → captured per sheet so a cross-sheet undo restores each sheet's OWN dims/frame/grid, never the active sheet's over another's. clips/work area are view-state riding the undo stack; details/dim_style/connections = model-global, captured whole. connections is NOT per-plan sliced (unlike joints, keyed by a plan-local member id): the library is genuinely model-wide, referenced identically from every sheet.
1531
1826
  // Undo/redo is a SINGLE GLOBAL stack (not per-plane): snapshot() above captures EVERY plane's
1532
1827
  // members, so one whole-model stack is coherent — undo restores all planes at once, and a cross-
1533
1828
  // sheet edit/delete/to-level round-trips fully. (Earlier this was per-plane — `undo=P.undo` swapped
@@ -1548,6 +1843,20 @@ function apply(json){const d=JSON.parse(json);
1548
1843
  if(tp&&tp!==P)tp.members=(o.members||[]).map(ensureMeta);
1549
1844
  else if(!tp){console.error('undo: sheet '+o.sheet+' not found — cross-plan slice skipped');toast('Undo couldn’t restore sheet '+o.sheet);}}} // restore THIS plan's joint slice: drop joints owned by this plan (old ∪ restored member ids), re-add the snapshot's — OTHER sheets' joints stay untouched. grid is per-plan (restored above); 'others' = the cross-plan slice a to-level commit captured. dims3d rides its own path.
1550
1845
  if('details' in d)C.detail_placements=Array.isArray(d.details)?d.details:[]; // restore the model-global placed details (Slice 4)
1846
+ // The connection library rides the undo stack too — it holds each detail's RECIPE (what it builds, its
1847
+ // schedule, its notes), so "remember this as 5-S504" must undo as ONE action with the joint it created.
1848
+ // Before this it was mutated through edit() but never captured, so deleting a row restored every
1849
+ // ends[].conn while the row itself stayed deleted — dangling references, silently.
1850
+ // null means "there was no library at all": restore ABSENCE rather than materialising an empty array,
1851
+ // so an undo never adds a key the contract did not have. (The characterization baseline caught exactly
1852
+ // that — `$.connections` appearing at step "19 undo" — which is what these tests are for.)
1853
+ if('connections' in d){if(Array.isArray(d.connections))C.connections=d.connections;else delete C.connections;
1854
+ // The restored rows are FRESH objects from JSON.parse, so an open Connections table is still showing —
1855
+ // and its cell handlers are still closed over — the discarded ones. Without this, undo under the open
1856
+ // library looks like it did nothing, and the next cell edit writes to an orphan: the field updates, the
1857
+ // save does not, and the change vanishes on the next re-render. Only possible now that `connections`
1858
+ // rides the undo stack, so it is this change's regression to close.
1859
+ if(typeof connLibOpen==='function'&&connLibOpen())renderConnTable();}
1551
1860
  if('dim_style' in d){C.dim_style=d.dim_style||{};sanitizeDimStyle();} // model-global dimension-style defaults ride the undo stack too (changing them repaints every non-overriding dim)
1552
1861
  updCS();
1553
1862
  selIds=new Set([...selIds].filter(id=>byId(id)||/^det:/.test(id))); // keep a selected placed-detail id (det:…) — it isn't a member
@@ -1564,15 +1873,29 @@ function apply(json){const d=JSON.parse(json);
1564
1873
  scheduleSave();render();sync3D();}
1565
1874
  function doUndo(){if(!undo.length)return;redo.push(snapshotLike());apply(undo.pop());}
1566
1875
  function doRedo(){if(!redo.length)return;undo.push(snapshotLike());apply(redo.pop());}
1567
- function edit(fn){const pv=snapshot();fn();pushUndo(pv);render();sync3D();}
1876
+ function edit(fn){
1877
+ // The stale-draft offer stops being safe the moment they build on the CURRENT version instead: clicking
1878
+ // "View my edits instead" afterwards would overlay the old edits on top of this new work and discard it
1879
+ // silently. Only that banner is dismissed — the AI-update and conflict bars MUST survive edits, which is
1880
+ // the entire reason the conflict bar exists. (unit 5, P1c-3)
1881
+ const _b=document.getElementById('aiUpdateBanner'); if(_b&&_b.dataset.kind==='staleBase')_b.remove();
1882
+ const pv=snapshot();fn();pushUndo(pv);render();sync3D();}
1568
1883
  // --- auto-save: edits persist to this browser (localStorage). Raster stays embedded; only members + TOS are stored. ---
1569
- const LSKEY = 'steeltakeoff:edits:v1:' + APP_ID;
1884
+ const LSKEY = draftKey(); // app + project + type — see draftKey() in the outer scope, which boot()'s SSE handler shares (it cannot see this closure, which is why the key used to be spelled out twice)
1885
+ // A structural guard, NOT a base identity — it only knows sheet names and segment counts, so two genuinely
1886
+ // different server contracts routinely produce the same string (members change; segment counts do not).
1887
+ // `baseEtag` is what decides whether the server moved; this decides whether the per-sheet overlay below is
1888
+ // even meaningful.
1570
1889
  function dataSig(){return C.plans.map(p=>p.sheet+':'+((p.segments||[]).length)).join('|');} // ignore stored edits if the dataset changed
1571
1890
  let saveT=null, saveSeq=0; // saveSeq: monotonic id per server save. Only the LATEST save's response may set the pill — an older in-flight PUT that resolves late must not overwrite a newer verdict (e.g. a stale 'ok' clobbering a fresh 'err').
1572
- function setSaved(state,msg){const el=document.getElementById('saveStat');if(!el)return;el.classList.remove('dirty','ok','err');
1891
+ function setSaved(state,msg){const el=document.getElementById('saveStat');if(!el)return;el.classList.remove('dirty','ok','err','conflict');
1892
+ el.removeAttribute('data-tip'); el.onclick=null;
1573
1893
  if(state==='ok'){el.classList.add('ok');el.textContent=msg||'Saved ✓';}
1574
1894
  else if(state==='dirty'){el.classList.add('dirty');el.textContent='Saving…';}
1575
1895
  else if(state==='err'){el.classList.add('err');el.textContent='Save failed';}
1896
+ else if(state==='conflict'){el.classList.add('conflict');el.textContent='Save conflict';
1897
+ el.dataset.tip='Someone else saved changes to this model since you opened it. Your edits are still here — click to choose what to do.';
1898
+ el.onclick=()=>showConflictBanner();} // the chip never acts on its own; it re-opens the banner
1576
1899
  else el.textContent=msg||'Auto-save on';}
1577
1900
  // Saved views (Views Organizer) — normalise an incoming array to clean, known-key entries. Robust to a
1578
1901
  // partial/stale server or localStorage draft (same discipline as dim_overlays): drops non-objects, mints a
@@ -1584,46 +1907,249 @@ function sanitizeViews(arr){return ViewGen.sanitizeViews(arr);}
1584
1907
  // async persistServer() PUT (or flushContract()), which resolves later and OWNS the 'ok'/'err' transition — so
1585
1908
  // green means the server truly has it. Every persist() caller is paired with such a server write (before or
1586
1909
  // after), so the pill always resolves. A localStorage write failure is still logged + flagged 'err' here.
1587
- function persist(){try{localStorage.setItem(LSKEY,JSON.stringify({sig:dataSig(),ts:Date.now(),active:C.active,
1588
- 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, detail_placements:C.detail_placements, views:C.views,
1910
+ // `baseEtag` — the SERVER-ISSUED tag of the version these edits are a delta from, stored BESIDE the body
1911
+ // rather than derived from it. Derived-from-`C` was the bug: `dataSig()` is blind to everything except
1912
+ // sheet names and segment counts, so a newer server contract with the same shape (the ordinary case — an
1913
+ // AI revision changes members, not segments) compared EQUAL, and restoreSaved silently overlaid a stale
1914
+ // draft on top of it, masking the other write. See restampDraftBase() for why reading the CURRENT
1915
+ // serverEtag here is right, and why it must be re-stamped when a write lands.
1916
+ function persist(){try{localStorage.setItem(LSKEY,JSON.stringify({sig:dataSig(),baseEtag:serverEtag,ts:Date.now(),active:C.active,
1917
+ 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,
1589
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);}}
1590
1919
  // --- server-side draft save: PUT the FULL contract C — this is the copy Approve bakes.
1591
1920
  // localStorage (persist) stays the instant per-browser draft cache; this is the durable one.
1592
1921
  // fetch does NOT reject on HTTP 400 (schema rejection), so treat !res.ok as 'err' (not a false 'Saved ✓'). ---
1593
- async function persistServer(){const seq=saveSeq;try{ // capture THIS intent's id (scheduleSave already bumped saveSeq for the edit) — a newer edit/flush bumps it again and invalidates this PUT's late response
1594
- lastLocalPut = Date.now();
1595
- const res=await fetch('/api/contract/'+encodeURIComponent(APP_ID)+PROJECT_QS,{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(C)});
1922
+ /**
1923
+ * A save was refused because someone else wrote to this model after we loaded it.
1924
+ *
1925
+ * INSIDE main() deliberately — this editor is one big closure, and `toast`, `persistServer` and the
1926
+ * conflict latch all live here. Declared outside, these would reference nothing.
1927
+ *
1928
+ * A pill alone is not enough, and that is the whole reason the banner exists: autosave means nobody is
1929
+ * watching the pill, so a conflict the user never notices means they keep editing a base that will never
1930
+ * save. Assertive but non-blocking — a modal here would rip focus mid-drag, and "keep editing" is a
1931
+ * legitimate choice.
1932
+ *
1933
+ * Deliberately actor-agnostic. A refused write tells us the model moved, not WHO moved it (another tab,
1934
+ * the AI, a workflow run), so the copy says "somewhere else" rather than claiming the AI did it — that
1935
+ * specific wording stays reserved for the SSE path, which actually knows.
1936
+ */
1937
+ /**
1938
+ * The 428 case: the server refused the save because the request carried no precondition.
1939
+ *
1940
+ * UNREACHABLE FROM THIS FILE, and the copy says so honestly rather than guessing a cause. Every write
1941
+ * path here sends one, so a 428 means a first-party writer has regressed — a bug in our code, not
1942
+ * something the user did or can diagnose. The first draft of this blamed "a tab left open across a
1943
+ * server upgrade"; review killed that, correctly: a page old enough to send no precondition is also
1944
+ * old enough to lack this branch, so it would never reach this banner. Telling the user their editor is
1945
+ * out of date would therefore be wrong every time it appeared.
1946
+ *
1947
+ * Kept anyway as a net: if a future writer regresses, this is a clear message plus a console error
1948
+ * instead of a bare "Save failed". Deliberately NOT the conflict copy (nothing else wrote), and
1949
+ * deliberately no "Save mine anyway" — there is nothing to overwrite, so the button would be a lie.
1950
+ * No auto-retry: an unchanged request would be refused identically.
1951
+ */
1952
+ function showSaveRefusedBanner(){
1953
+ showAiUpdateBanner('FloLess couldn’t save that change. Reload and try again — if it keeps happening, please report it.');
1954
+ }
1955
+ function showConflictBanner(){
1956
+ showAiUpdateBanner(
1957
+ 'This model was changed somewhere else while you were editing — your changes here didn’t save.',
1958
+ {
1959
+ // This used to delete the draft first, because restoreSaved() re-overlaid it whenever dataSig()
1960
+ // still matched — so a plain reload silently restored the very edits that had just conflicted. A
1961
+ // server-issued base retires that: the reload now finds the bases differ and OFFERS the edits back
1962
+ // instead of re-applying them, so the reason for throwing away the user's only copy is gone.
1963
+ onReload: () => { location.reload(); },
1964
+ onOverwrite: confirmOverwrite,
1965
+ });
1966
+ }
1967
+
1968
+ /**
1969
+ * The one destructive choice, so it is the one thing that blocks.
1970
+ *
1971
+ * Kept secondary and confirm-gated on purpose: the AI writing a revision is a first-class product action
1972
+ * here, so a stale tab must not clobber it with one stray click. The copy says what actually happens to
1973
+ * the other person's work rather than a soft "try again". Built from the existing .mbackdrop/.mpanel/
1974
+ * .danger tokens — no native confirm(), per the styled-modal rule.
1975
+ */
1976
+ function confirmOverwrite(){
1977
+ const back=document.createElement('div');
1978
+ back.className='modal'; back.style.cssText='position:fixed;inset:0;z-index:60;display:flex;align-items:center;justify-content:center';
1979
+ back.innerHTML='<div class=mbackdrop></div>'
1980
+ +'<div class=mpanel style="width:min(520px,92vw)">'
1981
+ +'<div class=mhead style="padding:14px 16px;border-bottom:1px solid var(--line);font-weight:600">Overwrite the other changes?</div>'
1982
+ +'<div style="padding:14px 16px;line-height:1.5">Someone else saved a version of this model after you opened yours. '
1983
+ +'Saving now replaces their version with what you see here — their changes will be gone for good.</div>'
1984
+ +'<div style="padding:12px 16px;display:flex;gap:8px;justify-content:flex-end;border-top:1px solid var(--line)">'
1985
+ +'<button id=cfCancel>Cancel</button><button id=cfGo class=danger>Overwrite and save</button></div></div>';
1986
+ document.body.appendChild(back);
1987
+ const close=()=>back.remove();
1988
+ back.querySelector('.mbackdrop').onclick=close;
1989
+ back.querySelector('#cfCancel').onclick=close;
1990
+ back.querySelector('#cfGo').onclick=async()=>{
1991
+ close();
1992
+ conflicted=false;
1993
+ await persistServer(true); // force: If-Match:* — deliberate, but still a precondition
1994
+ // Only claim success if the store actually took it. The first cut cleared the banner and toasted
1995
+ // unconditionally, so a force that itself failed told the user their work was saved when it was not
1996
+ // — the worst possible thing to be wrong about here.
1997
+ const el=document.getElementById('saveStat');
1998
+ if(el&&el.classList.contains('ok')){
1999
+ const bar=document.getElementById('aiUpdateBanner'); if(bar)bar.remove();
2000
+ toast('Saved — the other version was replaced.');
2001
+ } else {
2002
+ toast('Still not saved — nothing was overwritten.');
2003
+ }
2004
+ };
2005
+ }
2006
+
2007
+ /**
2008
+ * A styled destructive confirm — same tokens as confirmOverwrite() above, per the no-native-confirm rule.
2009
+ * Resolves true only if the user takes the destructive action; Esc / backdrop / Cancel all resolve false.
2010
+ *
2011
+ * Built with createElement rather than an HTML string: every caller passes MODEL data (a detail number, a
2012
+ * row's own label, a count), and a contract string must never reach a markup position.
2013
+ */
2014
+ function confirmDanger({title,body,confirmLabel}){
2015
+ return new Promise(resolve=>{
2016
+ const el=(tag,css,text)=>{const n=document.createElement(tag);if(css)n.style.cssText=css;if(text!=null)n.textContent=text;return n;};
2017
+ const back=el('div','position:fixed;inset:0;z-index:60;display:flex;align-items:center;justify-content:center');
2018
+ back.className='modal';
2019
+ const bd=el('div');bd.className='mbackdrop';
2020
+ // Same pinned-head/footer, scrolling-body construction as detailModalShell — a long confirm body
2021
+ // would otherwise push the destructive button out of the viewport where it cannot be reached.
2022
+ const panel=el('div','width:min(520px,92vw);display:flex;flex-direction:column;max-height:86vh');panel.className='mpanel';
2023
+ const head=el('div','padding:14px 16px;border-bottom:1px solid var(--line);font-weight:600;flex:none',title);head.className='mhead';
2024
+ const foot=el('div','padding:12px 16px;display:flex;gap:8px;justify-content:flex-end;border-top:1px solid var(--line);flex:none');
2025
+ const cancel=el('button',null,'Cancel'), go=el('button',null,confirmLabel);go.className='danger';
2026
+ foot.append(cancel,go);
2027
+ panel.append(head,el('div','padding:14px 16px;line-height:1.5;white-space:pre-line;flex:1 1 auto;overflow-y:auto;min-height:0',body),foot);
2028
+ back.append(bd,panel);
2029
+ document.body.appendChild(back);
2030
+ const done=v=>{document.removeEventListener('keydown',onKey,true);back.remove();resolve(v);};
2031
+ const onKey=e=>{if(e.key==='Escape'){e.stopPropagation();done(false);}};
2032
+ document.addEventListener('keydown',onKey,true); // capture: the editor's global Esc handlers must not win over an open modal
2033
+ bd.onclick=()=>done(false);cancel.onclick=()=>done(false);go.onclick=()=>done(true);
2034
+ go.focus();
2035
+ });
2036
+ }
2037
+
2038
+ // `force` REPLACES the precondition rather than skipping it — `If-Match: *` ("must exist") instead of the
2039
+ // exact tag, so a deliberate overwrite still cannot create a store out of nothing. Only the explicit
2040
+ // "Overwrite and save" confirm passes it. (This said "skips the precondition" until P1c made a write
2041
+ // without one a 428; it was already inaccurate, and would now describe an impossible request.)
2042
+ async function persistServer(force){const seq=saveSeq;
2043
+ // Once conflicted, stop firing doomed PUTs; re-surface the explanation instead of hammering the
2044
+ // network every debounce tick. Cleared only by a reload or a confirmed overwrite.
2045
+ if(conflicted&&!force){showConflictBanner();return;}
2046
+ return queueWrite(async()=>{
2047
+ // Name this write so its own SSE echo is recognised by identity, not by a 2.5 s clock (unit 5, P1c-3).
2048
+ // Minted BEFORE the request, deliberately: the broadcast can reach us before the response does, and an
2049
+ // id we do not yet know would read as somebody else's write and reload the page mid-edit.
2050
+ const mid=newMutationId();claimMutation(mid);
2051
+ try{ // capture THIS intent's id (scheduleSave already bumped saveSeq for the edit) — a newer edit/flush bumps it again and invalidates this PUT's late response
2052
+ const headers={'content-type':'application/json','x-floless-mutation-id':mid};
2053
+ // TOTAL, as of P1c: a write with no precondition is refused (428), so every branch must send one.
2054
+ // `*` on force = "must exist", a deliberate overwrite. No tag at all means we read through the BAKED
2055
+ // fallback (the GET tags only store-backed documents), i.e. this app has no draft yet — so the honest
2056
+ // precondition is `If-None-Match: *`, "I believe this store is empty". It also wins us a real check:
2057
+ // two editors both seeing no tag used to both create, last one silently winning.
2058
+ if(force)headers['if-match']='*';
2059
+ else if(serverEtag)headers['if-match']=serverEtag;
2060
+ else headers['if-none-match']='*';
2061
+ const res=await fetch('/api/contract/'+encodeURIComponent(APP_ID)+PROJECT_QS,{method:'PUT',headers,body:JSON.stringify(C)});
2062
+ // A REFUSED write produces no broadcast, so its id would sit in ownWrites forever — where the only
2063
+ // thing it can still do is wrongly suppress somebody else's event. Released on every leg below.
2064
+ if(res.status===428){ // a writer here sent no precondition — a bug in our code; see showSaveRefusedBanner
2065
+ releaseMutation(mid);
2066
+ console.error('save refused 428 — a first-party writer sent no precondition; this is a FloLess bug');
2067
+ if(seq===saveSeq)setSaved('err');
2068
+ showSaveRefusedBanner();
2069
+ return;
2070
+ }
2071
+ if(res.status===412){ // NOT a failure of the user's document — someone else wrote here since we loaded
2072
+ releaseMutation(mid);
2073
+ conflicted=true;
2074
+ if(seq===saveSeq)setSaved('conflict');
2075
+ showConflictBanner();
2076
+ return;
2077
+ }
2078
+ // NOTE the asymmetry, which is deliberate: success does NOT release the id. The echo for this very
2079
+ // write is usually still in flight — the server broadcasts before it replies — so releasing here would
2080
+ // make the tab read its OWN echo as external and reload itself mid-edit. The id is released when the
2081
+ // echo consumes it, when the write fails, or when the SSE channel closes (nothing can echo after that).
2082
+ if(res.ok){const t=res.headers.get('ETag');if(t){const pv=serverEtag;serverEtag=t;restampDraftBase(pv,t);}conflicted=false;} // chain the next edit off the new tag, and re-point the stored draft at the version it is now a delta from (see restampDraftBase)
2083
+ else releaseMutation(mid); // 400/500: nothing was written, so nothing will echo
1596
2084
  if(seq===saveSeq)setSaved(res.ok?'ok':'err'); // only the latest save owns the pill (a stale late response must not clobber a newer verdict)
1597
2085
  if(!res.ok)console.error('server save rejected ('+res.status+')',await res.text().catch(()=>'')); // 400 = schema reject: edits won't be what Approve bakes
1598
- }catch(e){if(seq===saveSeq)setSaved('err');console.error('server save failed',e);}}
1599
- function scheduleSave(){setSaved('dirty');++saveSeq;clearTimeout(saveT);saveT=setTimeout(()=>{persist();persistServer();},500);} // ++saveSeq: a fresh edit is a new save intent — it invalidates any still-in-flight PUT so that PUT's late response can't flip the pill to a stale 'Saved ✓' while this edit is still unsaved (persistServer below captures this same intent id)
2086
+ }catch(e){releaseMutation(mid);if(seq===saveSeq)setSaved('err');console.error('server save failed',e);}
2087
+ });}
2088
+ function scheduleSave(){setSaved('dirty');++saveSeq;clearTimeout(saveT);saveT=setTimeout(()=>{saveT=null;persist();persistServer();},500);} // clear the handle as it fires: `saveT !== null` is read as "a write is still pending" (the project send refuses on it), and a spent timer id would read as pending forever // ++saveSeq: a fresh edit is a new save intent — it invalidates any still-in-flight PUT so that PUT's late response can't flip the pill to a stale 'Saved ✓' while this edit is still unsaved (persistServer below captures this same intent id)
1600
2089
  // Flush: cancel the pending debounce and PUT the current in-memory contract to the
1601
2090
  // server right now. The parent (aware.js #contract-editor-approve) awaits this before
1602
2091
  // POSTing approve, so Approve always bakes the latest edits — not a stale debounce
1603
2092
  // snapshot. Throws on a non-2xx response so the parent can abort and show the warn toast.
1604
2093
  window.flushContract = async () => {
1605
- clearTimeout(saveT);
1606
- lastLocalPut = Date.now();
2094
+ clearTimeout(saveT); saveT = null; // the debounced write is being taken over by this flush, so it is no longer pending
2095
+ // Behind the SAME queue as autosave — Approve awaits this, and a flush racing an in-flight autosave
2096
+ // was the self-conflict path that could abort Approve for no reason.
2097
+ return queueWrite(async () => {
2098
+ const mid = newMutationId(); claimMutation(mid); // same own-echo identity as persistServer — see there
1607
2099
  const seq = ++saveSeq;
1608
2100
  let res;
1609
2101
  try {
2102
+ // Conditional like every other write, and it MUST refresh the tag on success. Getting this wrong is
2103
+ // not theoretical — the first cut omitted both, so an Approve-time flush bypassed the precondition
2104
+ // AND left `serverEtag` stale, which made the very next autosave fail against a change the user had
2105
+ // just made themselves. A conflict banner for your own edit is worse than no banner.
2106
+ const headers = { 'content-type': 'application/json', 'x-floless-mutation-id': mid };
2107
+ // Same total rule as persistServer — see the comment there for why "no tag" means If-None-Match: *.
2108
+ if (serverEtag) headers['if-match'] = serverEtag; else headers['if-none-match'] = '*';
1610
2109
  res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS, {
1611
- method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(C),
2110
+ method: 'PUT', headers, body: JSON.stringify(C),
1612
2111
  });
1613
2112
  } catch (e) {
2113
+ releaseMutation(mid); // nothing was written, so no broadcast will ever carry this id
1614
2114
  if (seq === saveSeq) setSaved('err'); // B9: a network rejection must show "Save failed", not leave the pill stuck on "Saving…" (this fn cancels the debounced persistServer that would otherwise flag it)
1615
2115
  throw e; // still reject so the parent (Approve) aborts — regardless of seq
1616
2116
  }
2117
+ if (res.status === 428) { // same cause as persistServer's 428 branch — a writer sent no precondition
2118
+ releaseMutation(mid);
2119
+ console.error('flush refused 428 — a first-party writer sent no precondition; this is a FloLess bug');
2120
+ if (seq === saveSeq) setSaved('err');
2121
+ showSaveRefusedBanner();
2122
+ throw new Error('save refused: no precondition sent');
2123
+ }
2124
+ if (res.status === 412) {
2125
+ // Approve must abort (the throw below), and the user needs to know WHY — a bare "save failed" toast
2126
+ // would send them looking for a problem in their own model.
2127
+ releaseMutation(mid);
2128
+ conflicted = true;
2129
+ if (seq === saveSeq) setSaved('conflict');
2130
+ showConflictBanner();
2131
+ throw new Error('save conflict');
2132
+ }
2133
+ if (res.ok) { const t = res.headers.get('ETag'); if (t) { const pv = serverEtag; serverEtag = t; restampDraftBase(pv, t); } conflicted = false; }
2134
+ else releaseMutation(mid);
1617
2135
  if (seq === saveSeq) setSaved(res.ok ? 'ok' : 'err'); // only the latest save owns the pill
1618
2136
  if (!res.ok) throw new Error('save failed (' + res.status + ')');
2137
+ });
1619
2138
  };
1620
- function restoreSaved(){try{const raw=localStorage.getItem(LSKEY);if(!raw)return false;const d=JSON.parse(raw);
1621
- if(d.sig!==dataSig())return false;const by={};(d.plans||[]).forEach(p=>by[p.sheet]=p);
2139
+ /**
2140
+ * Overlay a stored draft's fields onto C.
2141
+ *
2142
+ * Extracted from restoreSaved() (unit 5, P1c-3) so the AUTOMATIC restore and the user-initiated "View my
2143
+ * edits instead" apply exactly the same fields. Two copies of this list would drift, and the failure would
2144
+ * be silent: a field the button forgot would simply not come back, looking like it was never saved.
2145
+ */
2146
+ function applyDraftFields(d){const by={};(d.plans||[]).forEach(p=>by[p.sheet]=p);
1622
2147
  if(d.custom_details)C.custom_details=d.custom_details;
1623
2148
  if(d.profile_colors)C.profile_colors=d.profile_colors;
1624
2149
  if(d.member_styles)C.member_styles=sanitizeMemberStyles(d.member_styles); // F5: restore per-type line styles from the local draft (sanitised — the localStorage draft is unvalidated, unlike the server contract)
1625
2150
  if(Array.isArray(d.member_types))C.member_types=sanitizeMemberTypes(d.member_types);
1626
2151
  if(d.target_confidence!=null)C.target_confidence=d.target_confidence;
2152
+ 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.
1627
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;}});
1628
2154
  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)
1629
2155
  if(Array.isArray(d.detail_placements))C.detail_placements=d.detail_placements; // restore placed details
@@ -1632,7 +2158,111 @@ function restoreSaved(){try{const raw=localStorage.getItem(LSKEY);if(!raw)return
1632
2158
  if('prop_labels' in d)C.prop_labels=sanitizePropLabels(d.prop_labels); // restore canvas property-label display state (sanitised to known keys/placement)
1633
2159
  if(Array.isArray(d.joints))C.joints=d.joints; // restore model-global connection joints (base plates) from the local draft
1634
2160
  if(Array.isArray(d.views))C.views=sanitizeViews(d.views); // restore the unlimited saved-view library from the local draft; malformed generated provenance is dropped
1635
- if(d.active!=null)C.active=d.active;return true;}catch(e){console.warn('discarding corrupt local draft',e);return false;}}
2161
+ if(d.active!=null)C.active=d.active;}
2162
+ /**
2163
+ * The bar for "your unsaved edits are older than what the server now holds".
2164
+ *
2165
+ * Default is the SERVER's version — the one thing that can lose data here is silently showing the user
2166
+ * their own old edits while a colleague's or the AI's newer work sits unseen on the server, which is
2167
+ * exactly what the coarse dataSig() check used to allow. Their edits are not discarded; they stay in
2168
+ * storage and this offers them back.
2169
+ *
2170
+ * One click, no confirm: nothing server-side changes when they look. What DOES need care is what happens
2171
+ * on the next autosave — see the handler.
2172
+ */
2173
+ function showStaleDraftBanner(d){
2174
+ showAiUpdateBanner('This model has changed since you last edited it here — you’re viewing the current version. Your edits from before are still saved on this computer.',{
2175
+ kind:'staleBase',
2176
+ reloadLabel:'View my edits instead',
2177
+ reloadTip:'Switch to the changes you made before. The version on the server won’t change unless you edit and save again.',
2178
+ onReload:()=>{
2179
+ applyDraftFields(d);
2180
+ // REWIND the tag to the one those edits were built on. Without this the next autosave would carry
2181
+ // the CURRENT server tag, satisfy the precondition, and silently replace the newer version with
2182
+ // these older edits — no 412, no banner, no warning. With it, the next save is correctly refused
2183
+ // and drops into the conflict flow that already exists (banner → confirm → "Save mine anyway").
2184
+ // `|| null` because a v1-era draft carries no base: a null tag sends `If-None-Match: *`, which a
2185
+ // non-empty store also refuses. Same destination, same protection.
2186
+ serverEtag=d.baseEtag||null;
2187
+ // The offer has been taken; these edits are the live document again, so the parked copy is no
2188
+ // longer a separate thing to protect. persist() will write them back to the main row on the next
2189
+ // edit, now correctly based on the tag they were built from.
2190
+ try{localStorage.removeItem(offeredKey());localStorage.setItem(LSKEY,JSON.stringify(d));}catch(_){}
2191
+ const bar=document.getElementById('aiUpdateBanner'); if(bar)bar.remove();
2192
+ // Repaint in place rather than reload: the server tag has not moved, so a reload would re-detect the
2193
+ // same stale base and put the bar straight back up. Deliberately no scheduleSave() — merely LOOKING
2194
+ // at the old edits must not fire a write (and a conflict banner) on their behalf.
2195
+ render();sync3D();
2196
+ toast('Showing your earlier edits — not yet saved to the server.');
2197
+ },
2198
+ });
2199
+ }
2200
+ /**
2201
+ * Decide what this browser's stored edits do to the freshly-loaded contract.
2202
+ *
2203
+ * Wraps the real decision so a PARKED offer (see offeredKey) is re-made on every reload rather than
2204
+ * only on the load that first detected it — otherwise a user who reloads instead of answering the bar
2205
+ * loses track of edits the bar told them were still saved.
2206
+ */
2207
+ function restoreSaved(){
2208
+ const applied=restoreSavedInner();
2209
+ try{
2210
+ const oraw=localStorage.getItem(offeredKey());
2211
+ if(oraw){
2212
+ // A parked offer is not RE-OFFERED once fresh edits restore cleanly on top of the current version:
2213
+ // those are the user's latest work, and offering the older copy would walk them backwards. But it
2214
+ // is not deleted either — that reasoning argues against showing it, never against keeping it, and
2215
+ // deleting here made the banner's promise false after one edit and one reload, silently, because
2216
+ // edit() retires the bar first. One small row per store is the price of keeping the promise.
2217
+ if(!applied){
2218
+ const od=JSON.parse(oraw);
2219
+ // The SAME structural gate the live row gets, which review found this path had skipped.
2220
+ // applyDraftFields overlays per SHEET, so offering a draft built against a different dataset
2221
+ // would let the user apply edits that cannot fit — the very masking the live gate prevents,
2222
+ // reachable through the parked copy instead.
2223
+ if(od&&typeof od==='object'&&od.sig===dataSig())showStaleDraftBanner(od);
2224
+ // Deliberately NOT deleted when it does not fit. dataSig() is derived from the server document,
2225
+ // and a rollback can restore the dataset these edits were built against — at which point they
2226
+ // become offerable again. An unofferable row is one small row per store; discarding the user's
2227
+ // only copy to save it is the trade this whole item exists to refuse.
2228
+ else if(od)console.warn('steel-editor: parked edits do not match this drawing set — not offered');
2229
+ }
2230
+ }
2231
+ }catch(_){
2232
+ // Unreadable, therefore un-offerable, therefore pure leak — unlike a row that merely does not FIT
2233
+ // this dataset, which a rollback can make offerable again. Reclaim only the unparseable case.
2234
+ try{localStorage.removeItem(offeredKey());}catch(__){}
2235
+ }
2236
+ return applied;
2237
+ }
2238
+ function restoreSavedInner(){try{const raw=localStorage.getItem(LSKEY);if(!raw)return false;const d=JSON.parse(raw);
2239
+ // Structural first: the overlay below is per-sheet, so it is meaningless if the sheets moved.
2240
+ if(d.sig!==dataSig())return false;
2241
+ // Then the real base check. `serverEtag` is the tag boot() just read — main() is called synchronously
2242
+ // from boot() and nothing writes before this point, so it has not been advanced by a save yet. (If a
2243
+ // future change schedules a write earlier, this comparison silently starts meaning something else.)
2244
+ // Both sides must be present to compare: the baked-.flo fallback legitimately serves NO ETag, and a
2245
+ // v1-era draft carries no base, so "cannot compare" falls back to dataSig() alone — the weakest check
2246
+ // available, strictly no worse than before this PR, and stated rather than papered over.
2247
+ // A draft made against a store that served NO tag, where the store now serves one, is stale by
2248
+ // construction: only a write can make a store tag-bearing, so somebody wrote. `'baseEtag' in d`
2249
+ // separates that from a v1-era row, which has no such key at all and must keep the dataSig fallback.
2250
+ const bornTagless = ('baseEtag' in d) && d.baseEtag == null && !!serverEtag;
2251
+ if(bornTagless || (typeof d.baseEtag==='string'&&d.baseEtag&&serverEtag&&d.baseEtag!==serverEtag)){
2252
+ // PARK it, do not merely leave it: the main row is live, so the user's first edit on the current
2253
+ // version would overwrite these edits — and edit() retires the offer bar before that happens, so
2254
+ // they would never see them go. The banner promises they are still saved on this computer, and
2255
+ // that promise has to survive an ordinary next action.
2256
+ // ONE parked offer per store, and the FIRST one wins. A second refusal (park → ignore → edit → the
2257
+ // server moves again) must not overwrite it: that row is the one the banner already promised was
2258
+ // still saved, so it is the one thing here that must not be the casualty. The newer draft stays in
2259
+ // the live row, which is exactly where it sat before parking existed. An unbounded pile of offers
2260
+ // is the alternative, and one promise kept beats two promises half-kept.
2261
+ try{if(localStorage.getItem(offeredKey())==null){localStorage.setItem(offeredKey(),raw);localStorage.removeItem(LSKEY);}}catch(_){/* the offer is still made from memory below */}
2262
+ showStaleDraftBanner(d);
2263
+ return false;
2264
+ }
2265
+ applyDraftFields(d);return true;}catch(e){console.warn('discarding corrupt local draft',e);return false;}}
1636
2266
  function updUR(){document.getElementById('undoB').disabled=!undo.length;document.getElementById('redoB').disabled=!redo.length;}
1637
2267
  // Canonical, model-global palette rank (B2): EVERY plan's non-blank member profiles ∪ weight-table keys,
1638
2268
  // uppercased + sorted — the SAME basis contract-to-scene.ts uses, so a profile gets ONE hue in the 2D legend
@@ -1669,6 +2299,29 @@ function sanitizeMemberStyles(ms){if(!ms||typeof ms!=='object'||Array.isArray(ms
1669
2299
  const w=WOK[s.weight]?s.weight:'med',d=DOK[s.dash]?s.dash:'solid';
1670
2300
  if(w!=='med'||d!=='solid')out[key]={weight:w,dash:d};}
1671
2301
  return out;}
2302
+ // Sanitize a connection library restored from the localStorage DRAFT (unvalidated input, unlike the
2303
+ // server contract — same treatment as sanitizeMemberStyles / sanitizeDims3d). A row without a usable id is
2304
+ // dropped: every ends[].conn / joints[].conn reference resolves by id, so an id-less row is unreachable
2305
+ // anyway and keeping it would only let a later save write a contract the schema rejects (id is required).
2306
+ // The recipe/notes/image keys carry each detail's meaning, so they are preserved but shape-checked —
2307
+ // detail-recipes.ts already refuses a malformed recipe, and this keeps junk from reaching it at all.
2308
+ function sanitizeConnections(rows){if(!Array.isArray(rows))return [];
2309
+ const txt=(v,n)=>typeof v==='string'?v.slice(0,n):undefined;
2310
+ const obj=v=>(v&&typeof v==='object'&&!Array.isArray(v))?v:undefined;
2311
+ const out=[];
2312
+ for(const r of rows){if(!r||typeof r!=='object'||Array.isArray(r))continue;
2313
+ const id=txt(r.id,120);if(!id||!id.trim())continue;
2314
+ const row={...r,id};
2315
+ const rec=obj(r.recipe);
2316
+ if(rec){const kind=txt(rec.kind,64);
2317
+ row.recipe={...(kind?{kind}:{}),...(obj(rec.params)?{params:obj(rec.params)}:{}),
2318
+ ...(Array.isArray(rec.schedule)?{schedule:rec.schedule.filter(s=>s&&typeof s==='object'&&!Array.isArray(s)).slice(0,200)}:{})};
2319
+ }else if('recipe' in row)delete row.recipe;
2320
+ if(Array.isArray(r.notes))row.notes=r.notes.filter(n=>n&&typeof n==='object'&&typeof n.text==='string')
2321
+ .slice(0,200).map(n=>({text:n.text.slice(0,2000),...(typeof n.source==='string'?{source:n.source.slice(0,32)}:{})}));
2322
+ else if('notes' in row)delete row.notes;
2323
+ out.push(row);}
2324
+ return out;}
1672
2325
  function len(a,b){return Math.hypot(a[0]-b[0],a[1]-b[1]);}
1673
2326
  // ── Column profile sections ─────────────────────────────────────────────────────────────────────
1674
2327
  // A column is drawn on the plan as its profile-SECTION footprint (I/box/channel/angle/tube), not a
@@ -2078,7 +2731,7 @@ function deleteSelGrids(){
2078
2731
  const glLids=new Set([...selGridIds].filter(id=>id.startsWith('gl:')).map(id=>id.slice(3)));
2079
2732
  const freeToDelete=(P.grid&&Array.isArray(P.grid.lines))?P.grid.lines.filter(l=>glLids.has(String(l.id))):[];
2080
2733
  const hadReg=[...selGridIds].some(id=>id.startsWith('gv:')||id.startsWith('gh:'));
2081
- if(freeToDelete.length)edit(()=>{P.grid.lines=P.grid.lines.filter(l=>!glLids.has(String(l.id)));selGridIds.clear();});
2734
+ if(freeToDelete.length)edit(()=>{ModelCmd.removeGridLines(P.grid,glLids);selGridIds.clear();});
2082
2735
  else{selGridIds.clear();render();}
2083
2736
  if(hadReg)toast('Regular grid lines come from the grid spacing — remove them in “Grid lines…”. Only free grid lines are deletable here.');}
2084
2737
  // cursor-following distance readout for grid drags (same chrome as the 3D drag readout)
@@ -2107,10 +2760,10 @@ function gridRenameBubble(axis,gi,anchorEl){
2107
2760
  const nv=inp.value.trim();
2108
2761
  if(!nv||nv===cur)return;
2109
2762
  if(/\s/.test(nv)){toast('Labels can’t contain spaces');return;}
2110
- if(axis==='l'){edit(()=>{if(P.grid.lines&&P.grid.lines[gi])P.grid.lines[gi].label=nv;});return;}
2763
+ if(axis==='l'){edit(()=>{ModelCmd.setGridLineLabel(P.grid,gi,nv);});return;}
2111
2764
  const key=axis==='v'?'labels_x':'labels_y',style=axis==='v'?'num':'alpha';
2112
2765
  const toks=gc.labelsFor(P.grid[key],style,lines.length);toks[gi]=nv;
2113
- edit(()=>{P.grid[key]=toks.join(' ');});};
2766
+ edit(()=>{ModelCmd.patchGrid(P.grid,{[key]:toks.join(' ')});});};
2114
2767
  inp.addEventListener('keydown',ev=>{ev.stopPropagation();
2115
2768
  if(ev.key==='Enter'){ev.preventDefault();finish(true);}
2116
2769
  else if(ev.key==='Escape'){ev.preventDefault();finish(false);}});
@@ -2126,7 +2779,7 @@ function sanitizePlanGrid(pl){if(!pl||pl.grid==null)return;const g=pl.grid;
2126
2779
  sanitizeGridLines(g);}
2127
2780
  function gridLineId(){return 'gl'+Date.now().toString(36)+Math.floor(Math.random()*1000).toString(36);}
2128
2781
  function gridNextLineLabel(){const n=(P&&P.grid&&Array.isArray(P.grid.lines))?P.grid.lines.length+1:1;return 'L'+n;}
2129
- function gridEnsureForLine(a){const gc=GC();if(P.grid)return;P.grid={on:true,origin:a.slice(),x:'',y:'',z:"0'-0\"",labels_x:'',labels_y:'',labels_z:[],ext:gc?5*gc.FT_MM:1524,lines:[]};}
2782
+ function gridEnsureForLine(a){const gc=GC();ModelCmd.ensurePlanGrid(P,()=>({on:true,origin:a.slice(),x:'',y:'',z:"0'-0\"",labels_x:'',labels_y:'',labels_z:[],ext:gc?5*gc.FT_MM:1524,lines:[]}));}
2130
2783
  // The 3D pick's minimum line length, in display px — a fixed floor, since 3D has no 2D `zoom` to scale by. 6 px is
2131
2784
  // what the 2D tool enforces at 1:1; in real terms that is 6*mmPerPx (~2" at a typical 1/4"=1' sheet scale).
2132
2785
  const GRID_LINE_MIN_DISP=6;
@@ -2135,8 +2788,8 @@ const GRID_LINE_MIN_DISP=6;
2135
2788
  // meaningless while the user is in 3D, so inheriting it would make an identical 3D pick commit or get rejected
2136
2789
  // depending on a hidden viewport (fitted at zoom≈0.2 it would silently refuse lines under ~2.5 ft).
2137
2790
  function gridAddFreeLine(a,b,label,minDisp){const gc=GC();if(Math.hypot(b[0]-a[0],b[1]-a[1])<(minDisp>0?minDisp:6/zoom)){toast('Line is too short to create a grid line');return false;}
2138
- gridEnsureForLine(a);if(!Array.isArray(P.grid.lines))P.grid.lines=[];
2139
- P.grid.lines.push({id:gridLineId(),label:label||gridNextLineLabel(),a:a.slice(),b:b.slice()});return true;}
2791
+ gridEnsureForLine(a);
2792
+ ModelCmd.addGridLine(P.grid,{id:gridLineId(),label:label||gridNextLineLabel(),a:a.slice(),b:b.slice()});return true;}
2140
2793
  function gridSetPickClass(){document.body.classList.toggle('gridpick',!!gridPick||!!gridLinePick);
2141
2794
  // ONE choke point for the 3D side: every path that arms or tears down the pick (start, cancel, setGridMode,
2142
2795
  // Move/Copy arm, plan switch, view switch) already calls this, so the 3D pick can never outlive the 2D flag.
@@ -2166,7 +2819,7 @@ function gridReadFromDrawing(keep){
2166
2819
  if(keep.labels_y)g.labels_y=keep.labels_y;
2167
2820
  g.labels_z=Array.isArray(keep.labels_z)?keep.labels_z.slice():[];
2168
2821
  if(Array.isArray(keep.hidden_z)&&keep.hidden_z.length)g.hidden_z=keep.hidden_z.slice();}
2169
- edit(()=>{P.grid=g;});
2822
+ edit(()=>{ModelCmd.setPlanGrid(P,g);});
2170
2823
  toast('Grid read from the drawing — '+r.info.v+' × '+r.info.h+' lines'+(r.info.labeled?'':'. Labels are auto — Ask AI can read the printed marks.'));}
2171
2824
  // The bubble marks on most CAD sets are OUTLINED (not text), so the detector can't read them. The
2172
2825
  // sanctioned path for that gap is the Ask-AI relay (the UI never calls an LLM): pre-fill the existing
@@ -2189,7 +2842,7 @@ function updGridToggle(){const b=document.getElementById('gridToggleB');if(!b)re
2189
2842
  // and the ⋯ menu item — all call this. grid.on is contract data, so the flip is undoable like every
2190
2843
  // other grid operation.
2191
2844
  function gridSetVisible(on){if(!C||typeof P==='undefined'||!P||!P.grid||on===gridOn())return;
2192
- edit(()=>{P.grid.on=!!on;});updGridToggle();refresh3DGrid();if(view3d)build3DLegend();}
2845
+ edit(()=>{ModelCmd.patchGrid(P.grid,{on:!!on});});updGridToggle();refresh3DGrid();if(view3d)build3DLegend();}
2193
2846
  document.addEventListener('gridcore-ready',()=>{try{if(C)render();}catch(_){}}); // module shim finished after boot → paint the grid layer
2194
2847
  function setGridMode(on){if(!C)return;gridMode=!!on;
2195
2848
  if(!gridMode){const ae=document.activeElement,pn=document.getElementById('panel');if(ae&&pn&&pn.contains(ae))ae.blur(); // commit a focused field (change fires on blur) BEFORE the panel is torn down — a canvas click's pointerdown runs before the browser's own focus change
@@ -2240,8 +2893,8 @@ function renderGridPanel(p){
2240
2893
  <div class=hint style="margin-top:10px">Spacing uses <b>n*d</b> to repeat (e.g. <b>3*25'</b> = three 25' bays). Tokens: <b>25'-6"</b>, <b>6"</b>, <b>7.5m</b>, bare mm.</div>`;
2241
2894
  document.getElementById('gridLineB').onclick=gridStartLinePick;
2242
2895
  const rb=document.getElementById('gridReadB');if(rb)rb.onclick=()=>gridReadFromDrawing(null);
2243
- const ab=document.getElementById('gridAutoB');if(ab)ab.onclick=()=>{const g=gc.inferGrid(P.members,ppf);if(!g){toast('No columns to infer a grid from');return;}edit(()=>{P.grid=g;});};
2244
- const bb=document.getElementById('gridBlankB');if(bb)bb.onclick=()=>{const o=gridDefaultOrigin();edit(()=>{P.grid=gc.defaultGrid(o);});};
2896
+ const ab=document.getElementById('gridAutoB');if(ab)ab.onclick=()=>{const g=gc.inferGrid(P.members,ppf);if(!g){toast('No columns to infer a grid from');return;}edit(()=>{ModelCmd.setPlanGrid(P,g);});};
2897
+ const bb=document.getElementById('gridBlankB');if(bb)bb.onclick=()=>{const o=gridDefaultOrigin();edit(()=>{ModelCmd.setPlanGrid(P,gc.defaultGrid(o));});};
2245
2898
  return;}
2246
2899
  const g=P.grid,nCols=planColumnCount();
2247
2900
  const normSp=v=>{const r=gc.parseSpacings(v);return r.err?String(v||''):gc.formatSpacings(r.offsets);};
@@ -2311,27 +2964,27 @@ function renderGridPanel(p){
2311
2964
  else if(ev.key==='Escape'){ev.preventDefault();el.value=orig;fbAll();}});
2312
2965
  el.addEventListener('change',()=>commit(el.value.trim(),el));};
2313
2966
  wire('gX',(v,el)=>{const r=gc.parseSpacings(v);if(r.err)return;const next=gc.formatSpacings(r.offsets);if(el.value!==next){el.value=next;fbAll();}if(next!==(g.x||''))edit(()=>{ // a changed LINE COUNT invalidates the index-keyed per-line ends (they'd re-bind to the wrong lines)
2314
- if(P.grid.ends_x&&r.offsets.length!==gc.parseSpacings(P.grid.x).offsets.length)delete P.grid.ends_x;
2315
- P.grid.x=next;});});
2967
+ if(P.grid.ends_x&&r.offsets.length!==gc.parseSpacings(P.grid.x).offsets.length)ModelCmd.patchGrid(P.grid,{ends_x:undefined});
2968
+ ModelCmd.patchGrid(P.grid,{x:next});});});
2316
2969
  wire('gY',(v,el)=>{const r=gc.parseSpacings(v);if(r.err)return;const next=gc.formatSpacings(r.offsets);if(el.value!==next){el.value=next;fbAll();}if(next!==(g.y||''))edit(()=>{
2317
- if(P.grid.ends_y&&r.offsets.length!==gc.parseSpacings(P.grid.y).offsets.length)delete P.grid.ends_y;
2318
- P.grid.y=next;});});
2319
- wire('gZ',(v,el)=>{const r=gc.parseLevels(v);if(r.err)return;const next=gc.formatLevels(r.levels.map(l=>l.mm)),old=Array.isArray(g.labels_z)?g.labels_z:[],labels=gc.reconcileLevelLabels(zParsed,zNormalizedLabels.labels,r).labels,hidden=gc.normalizeHiddenLevels(g.hidden_z,r.levels),warning=levelWarningText(r);if(el.value!==next){el.value=next;fbAll();}if(next!==(g.z||'')||JSON.stringify(labels)!==JSON.stringify(old)||JSON.stringify(hidden)!==JSON.stringify(g.hidden_z||[]))edit(()=>{P.grid.z=next;P.grid.labels_z=labels;if(hidden.length)P.grid.hidden_z=hidden;else delete P.grid.hidden_z;});if(warning)toast(warning);});
2320
- wire('gLX',(v)=>{if(v!==(g.labels_x||''))edit(()=>{P.grid.labels_x=v;});});
2321
- wire('gLY',(v)=>{if(v!==(g.labels_y||''))edit(()=>{P.grid.labels_y=v;});});
2322
- document.querySelectorAll('[data-zlabel]').forEach(el=>{const orig=el.value;el.addEventListener('input',()=>{const limited=gc.truncateText(el.value,40);if(limited!==el.value)el.value=limited;});el.addEventListener('keydown',ev=>{ev.stopPropagation();if(ev.key==='Enter'){ev.preventDefault();el.blur();}else if(ev.key==='Escape'){ev.preventDefault();el.value=orig;}});el.addEventListener('change',()=>{const i=+el.dataset.zlabel,nv=gc.truncateText(el.value.trim(),40),labels=zNormalizedLabels.labels.slice();if(labels[i]===nv&&g.z===normZ)return;labels[i]=nv;edit(()=>{P.grid.z=normZ;P.grid.labels_z=labels;});});});
2323
- document.querySelectorAll('[data-zvisible]').forEach(el=>el.addEventListener('change',()=>{const lv=zParsed.levels[+el.dataset.zvisible];if(!lv)return;const key=gc.gridLevelKey(lv.mm),next=hiddenZ.filter(mm=>gc.gridLevelKey(mm)!==key);if(!el.checked)next.push(lv.mm);const hidden=gc.normalizeHiddenLevels(next,zParsed.levels);edit(()=>{if(hidden.length)P.grid.hidden_z=hidden;else delete P.grid.hidden_z;});}));
2324
- wire('gExt',(v,el)=>{const mm=gc.parseLen(v);if(!isFinite(mm)||mm<0){el.style.borderColor='#fca5a5';return;}el.style.borderColor='';if(Math.abs(mm-(isFinite(g.ext)?g.ext:1524))>0.5)edit(()=>{P.grid.ext=mm;});});
2970
+ if(P.grid.ends_y&&r.offsets.length!==gc.parseSpacings(P.grid.y).offsets.length)ModelCmd.patchGrid(P.grid,{ends_y:undefined});
2971
+ ModelCmd.patchGrid(P.grid,{y:next});});});
2972
+ wire('gZ',(v,el)=>{const r=gc.parseLevels(v);if(r.err)return;const next=gc.formatLevels(r.levels.map(l=>l.mm)),old=Array.isArray(g.labels_z)?g.labels_z:[],labels=gc.reconcileLevelLabels(zParsed,zNormalizedLabels.labels,r).labels,hidden=gc.normalizeHiddenLevels(g.hidden_z,r.levels),warning=levelWarningText(r);if(el.value!==next){el.value=next;fbAll();}if(next!==(g.z||'')||JSON.stringify(labels)!==JSON.stringify(old)||JSON.stringify(hidden)!==JSON.stringify(g.hidden_z||[]))edit(()=>{ModelCmd.patchGrid(P.grid,{z:next,labels_z:labels,hidden_z:hidden.length?hidden:undefined});});if(warning)toast(warning);});
2973
+ wire('gLX',(v)=>{if(v!==(g.labels_x||''))edit(()=>{ModelCmd.patchGrid(P.grid,{labels_x:v});});});
2974
+ wire('gLY',(v)=>{if(v!==(g.labels_y||''))edit(()=>{ModelCmd.patchGrid(P.grid,{labels_y:v});});});
2975
+ document.querySelectorAll('[data-zlabel]').forEach(el=>{const orig=el.value;el.addEventListener('input',()=>{const limited=gc.truncateText(el.value,40);if(limited!==el.value)el.value=limited;});el.addEventListener('keydown',ev=>{ev.stopPropagation();if(ev.key==='Enter'){ev.preventDefault();el.blur();}else if(ev.key==='Escape'){ev.preventDefault();el.value=orig;}});el.addEventListener('change',()=>{const i=+el.dataset.zlabel,nv=gc.truncateText(el.value.trim(),40),labels=zNormalizedLabels.labels.slice();if(labels[i]===nv&&g.z===normZ)return;labels[i]=nv;edit(()=>{ModelCmd.patchGrid(P.grid,{z:normZ,labels_z:labels});});});});
2976
+ document.querySelectorAll('[data-zvisible]').forEach(el=>el.addEventListener('change',()=>{const lv=zParsed.levels[+el.dataset.zvisible];if(!lv)return;const key=gc.gridLevelKey(lv.mm),next=hiddenZ.filter(mm=>gc.gridLevelKey(mm)!==key);if(!el.checked)next.push(lv.mm);const hidden=gc.normalizeHiddenLevels(next,zParsed.levels);edit(()=>{ModelCmd.patchGrid(P.grid,{hidden_z:hidden.length?hidden:undefined});});}));
2977
+ wire('gExt',(v,el)=>{const mm=gc.parseLen(v);if(!isFinite(mm)||mm<0){el.style.borderColor='#fca5a5';return;}el.style.borderColor='';if(Math.abs(mm-(isFinite(g.ext)?g.ext:1524))>0.5)edit(()=>{ModelCmd.patchGrid(P.grid,{ext:mm});});});
2325
2978
  const gsh=document.getElementById('gShow');if(gsh)gsh.addEventListener('change',()=>gridSetVisible(gsh.checked));
2326
- const grx=document.getElementById('gridResetExtB');if(grx)grx.onclick=()=>{edit(()=>{delete P.grid.ends_x;delete P.grid.ends_y;});}; // drop every per-line extent override → all lines follow the global Extension again
2327
- const gdz=document.getElementById('gridDropZLabels');if(gdz)gdz.onclick=()=>{const labels=zNormalizedLabels.labels.slice(0,zParsed.levels.length);edit(()=>{P.grid.z=normZ;P.grid.labels_z=labels;});toast(`${zExtraCount} extra Z label${zExtraCount===1?'':'s'} removed`);}; // labels are sorted by elevation, so canonicalize z in the same atomic edit (an imported unsorted z must not rebind them by source index)
2979
+ const grx=document.getElementById('gridResetExtB');if(grx)grx.onclick=()=>{edit(()=>{ModelCmd.patchGrid(P.grid,{ends_x:undefined,ends_y:undefined});});}; // drop every per-line extent override → all lines follow the global Extension again
2980
+ const gdz=document.getElementById('gridDropZLabels');if(gdz)gdz.onclick=()=>{const labels=zNormalizedLabels.labels.slice(0,zParsed.levels.length);edit(()=>{ModelCmd.patchGrid(P.grid,{z:normZ,labels_z:labels});});toast(`${zExtraCount} extra Z label${zExtraCount===1?'':'s'} removed`);}; // labels are sorted by elevation, so canonicalize z in the same atomic edit (an imported unsorted z must not rebind them by source index)
2328
2981
  document.getElementById('gridLineB').onclick=gridStartLinePick;
2329
- const gcl=document.getElementById('gridClearLinesB');if(gcl)gcl.onclick=()=>{edit(()=>{delete P.grid.lines;});};
2982
+ const gcl=document.getElementById('gridClearLinesB');if(gcl)gcl.onclick=()=>{edit(()=>{ModelCmd.clearGridLines(P.grid);});};
2330
2983
  document.getElementById('gridPickB').onclick=()=>{gridPick=!gridPick;gridLinePick=null;gridSetPickClass();panel();};
2331
2984
  const r2=document.getElementById('gridReadB2');if(r2)r2.onclick=()=>gridReadFromDrawing(P.grid);
2332
2985
  const lb=document.getElementById('gridLabelsAiB');if(lb)lb.onclick=gridAskAiLabels;
2333
- const a2=document.getElementById('gridAutoB2');if(a2)a2.onclick=()=>{const ng=gc.inferGrid(P.members,ppf);if(!ng){toast('No columns to infer a grid from');return;}ng.z=P.grid.z;ng.labels_x=P.grid.labels_x;ng.labels_y=P.grid.labels_y;ng.labels_z=Array.isArray(P.grid.labels_z)?P.grid.labels_z.slice():[];if(Array.isArray(P.grid.hidden_z)&&P.grid.hidden_z.length)ng.hidden_z=P.grid.hidden_z.slice();ng.ext=P.grid.ext;edit(()=>{P.grid=ng;});}; // re-infer geometry, keep the user's levels/labels/visibility/extension
2334
- document.getElementById('gridRemoveB').onclick=()=>{edit(()=>{P.grid=null;});};
2986
+ const a2=document.getElementById('gridAutoB2');if(a2)a2.onclick=()=>{const ng=gc.inferGrid(P.members,ppf);if(!ng){toast('No columns to infer a grid from');return;}ng.z=P.grid.z;ng.labels_x=P.grid.labels_x;ng.labels_y=P.grid.labels_y;ng.labels_z=Array.isArray(P.grid.labels_z)?P.grid.labels_z.slice():[];if(Array.isArray(P.grid.hidden_z)&&P.grid.hidden_z.length)ng.hidden_z=P.grid.hidden_z.slice();ng.ext=P.grid.ext;edit(()=>{ModelCmd.setPlanGrid(P,ng);});}; // re-infer geometry, keep the user's levels/labels/visibility/extension
2987
+ document.getElementById('gridRemoveB').onclick=()=>{edit(()=>{ModelCmd.setPlanGrid(P,null);});};
2335
2988
  document.getElementById('gridDoneB').onclick=()=>{setGridMode(false);render();};
2336
2989
  }
2337
2990
  function setGeo(){document.body.classList.toggle('geo',!!geoMode);document.body.classList.toggle('geoel',geoMode==='el');} // geoel = Extend/Trim armed; grid lines are a target ONLY then (not in Split), so their crosshair/highlight keys off geoel, not geo
@@ -2348,10 +3001,11 @@ function repeatLast(){if(lastCmd){lastCmd.run();if(typeof toast==='function')toa
2348
3001
  // Multi: trim/extend the nearest end of EVERY given member to the (tA,tB) target line; members
2349
3002
  // parallel to the target (no intersection) are skipped. One undo for the whole batch.
2350
3003
  function snapEndMulti(ms,tA,tB){const pv=snapshot();let n=0,skipped=0;
3004
+ const mc=MC(); // hoisted: ms is the whole selection, so building the commands object per member would be a batch-latency regression
2351
3005
  for(const m of ms){
2352
3006
  if(isBrace(m)){skipped++;continue;} // extend/trim never moves a brace work point (it must stay on the column ℄) — matches doSplit
2353
3007
  const I=lineX(m.wp[0],m.wp[1],tA,tB);if(!I)continue;
2354
- const h=len(m.wp[0],I)<=len(m.wp[1],I)?0:1;m.wp[h]=I;m.rfi=(_wt(m.profile)==null);n++;}
3008
+ const h=len(m.wp[0],I)<=len(m.wp[1],I)?0:1;mc.setEndpoint(m,h,I);m.rfi=(_wt(m.profile)==null);n++;} // h is DATA — the end nearer the intersection
2355
3009
  if(skipped)toast(n?(skipped+' brace'+(skipped>1?'s':'')+' skipped — braces can’t be extended/trimmed'):'Braces can’t be extended/trimmed — edit them from the inspector');
2356
3010
  if(n){pushUndo(pv);render();sync3D();}return n;}
2357
3011
  function doSplit(m,pt){if(isBrace(m)){toast('Braces can’t be split — edit them from the inspector');return;} // split/extend/trim disabled on braces (offset would create off-℄ WPs · Codex round-2)
@@ -2359,12 +3013,15 @@ function doSplit(m,pt){if(isBrace(m)){toast('Braces can’t be split — edit th
2359
3013
  // F9: split keeps m.id for the first half with CHANGED endpoints (the clone gets a fresh id), so a dim ref to m
2360
3014
  // would silently jump — detach every ref to m in its plan before geometry moves (safe-freeze; pv above still has
2361
3015
  // them so undo restores). The clone's new id carries no refs. (Codex R3 #2.)
2362
- {const own=planeOfMember(m);for(const d of (own&&own.dims||[]))for(const rk of ['aRef','bRef'])if(d[rk]&&d[rk].m===m.id)delete d[rk];}
3016
+ const own=planeOfMember(m);
3017
+ {for(const d of (own&&own.dims||[]))for(const rk of ['aRef','bRef'])if(d[rk]&&d[rk].m===m.id)delete d[rk];}
2363
3018
  const a=m.wp[0].slice(),b=m.wp[1].slice(),q=pt.slice(),mk=()=>({tos:null,note:'',tosDef:true,detail:''});
2364
- m.wp=[a,q];if(m.ends)m.ends=[m.ends[0],mk()]; // first half keeps its start end, fresh cut end
2365
- const c=JSON.parse(JSON.stringify(base));c.id='m'+Date.now();c.wp=[q.slice(),b];
3019
+ const mc=MC();
3020
+ mc.replaceEndpoints(m,[a,q]);if(m.ends)m.ends=[m.ends[0],mk()]; // first half keeps its start end, fresh cut end
3021
+ const c=mc.clone(base,()=>'m'+Date.now()); // from `base` (captured BEFORE the line above rewrote m.wp), and doSplit's OWN id policy: no suffix at all, unlike doDup's '_'+i and MC()'s '_c'+cmSeq
3022
+ mc.replaceEndpoints(c,[q.slice(),b]);
2366
3023
  if(c.ends)c.ends=[mk(),base.ends?base.ends[1]:mk()]; // second half keeps the original far end
2367
- c.rfi=(_wt(c.profile)==null);P.members.push(c);selIds=new Set([m.id,c.id]);selDimIds.clear();geoMode=null;setGeo();pushUndo(pv);render();}
3024
+ c.rfi=(_wt(c.profile)==null);mc.addMembers(own||P,[c]);selIds=new Set([m.id,c.id]);selDimIds.clear();geoMode=null;setGeo();pushUndo(pv);render();} // the second half lands on the sheet that OWNS the member, not the active one — 3D Split can target any sheet, and pushing to P would have split a member across two sheets (its wp is in the owner's display space, so the half would also be mis-scaled). The 2D caller is unaffected: its selection is necessarily on P.
2368
3025
  // --- duplicates: members with coincident geometry (same two work-points, order-independent, ~3px tol) ---
2369
3026
  function dupFoot(m){if(!m||!m.wp||m.wp.length<2)return null;const r=p=>Math.round(p[0]/3)+','+Math.round(p[1]/3);const a=r(m.wp[0]),b=r(m.wp[1]);return a<b?a+'|'+b:b+'|'+a;}
2370
3027
  // Elevation signature. Two members at the SAME footprint but a DIFFERENT explicit top-of-steel are different
@@ -2391,7 +3048,10 @@ function dedupeFootprintIds(members,rankFn){const byFoot={};for(const m of membe
2391
3048
  function redundantDups(){return dedupeFootprintIds(P.members,dupScore);}
2392
3049
  // --- merge collinear chords: same-profile, end-to-end, STRAIGHT beam runs → one member each.
2393
3050
  // The skew read breaks a chord into collinear sub-segments at every rung; this rejoins each run.
2394
- // MIRROR of server/steel-merge.ts (the tested source of truth) — keep the two in lock-step.
3051
+ // THE source of truth. There used to be a second copy at server/steel-merge.ts calling itself the
3052
+ // "tested source of truth"; it had zero production callers and had already drifted (it never gained the
3053
+ // affectedIds this one returns), so it was deleted — unit 5, P3c-3c. Its rules are pinned against THIS
3054
+ // copy in server/steel-editor-characterization.test.ts, "merge (live copy): …".
2395
3055
  const MRG_END=3, MRG_ANG=3*Math.PI/180, MRG_TOS=0.5;
2396
3056
  function _mUnit(a,b){const dx=b[0]-a[0],dy=b[1]-a[1],L=Math.hypot(dx,dy)||1;return [dx/L,dy/L];}
2397
3057
  function _mElig(m){return (m.role||'beam')==='beam'&&!isBrace(m)&&Array.isArray(m.wp)&&m.wp.length>=2&&typeof m.profile==='string'&&m.profile.trim()!=='';} // braces never merge with beams (Codex round-1)
@@ -2464,8 +3124,10 @@ function zoomCentered(z){const r=stage.getBoundingClientRect();applyZoom(z,r.lef
2464
3124
  function fitToWindow(){applyZoom(Math.min(stage.clientWidth/EXTX,stage.clientHeight/EXTY)*0.98);}
2465
3125
  // --- duplicate the selected member(s) in place (Ctrl+D) ---
2466
3126
  function doDup(){const arr=sel2d();if(!arr.length)return;const o=12,pv=snapshot(),ns=new Set();
2467
- let i=0;for(const s of arr){const id='m'+Date.now()+'_'+(i++);const c=JSON.parse(JSON.stringify(s));
2468
- c.id=id;c.wp=[[s.wp[0][0]+o,s.wp[0][1]+o],[s.wp[1][0]+o,s.wp[1][1]+o]];P.members.push(c);ns.add(id);}
3127
+ const mc=MC();let i=0;const mk=()=>'m'+Date.now()+'_'+(i++); // doDup's OWN id policy — NOT cmSeq's '_c' form; both land in the stored contract
3128
+ for(const s of arr){const id=mk();const c=mc.clone(s,()=>id); // mint BEFORE the deep copy: doDup always did, cloneMember always did the reverse, and one shared primitive can only pick one order. The characterization clock is constant within an operation, so the baseline cannot see this — hence pre-minting here rather than relying on it (Codex code review)
3129
+ mc.replaceEndpoints(c,[[s.wp[0][0]+o,s.wp[0][1]+o],[s.wp[1][0]+o,s.wp[1][1]+o]]); // replaces the wp array wholesale, as `c.wp=[[…],[…]]` did
3130
+ mc.addMembers(P,[c]);ns.add(c.id);}
2469
3131
  selIds=ns;selDimIds.clear();mode='sel';setMode();pushUndo(pv);render();}
2470
3132
  function esc(s){return String(s).replace(/[<>&"]/g,c=>({'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'}[c]));}
2471
3133
  function render(){
@@ -2927,8 +3589,8 @@ function panel(){
2927
3589
  '<div class=hint style="margin:0 0 6px;font-size:11px">Level <b>'+esc(fmtFtIn(defaultTOS))+'</b> ('+esc(P.sheet)+'). '+((P.tos_callouts&&P.tos_callouts.length)?'Per-zone T.O. STEEL callouts from the drawing applied to each member; ':'')+'ends ticked <b>default</b> follow the level.</div>'+
2928
3590
  '<div class=elab>Default TOS</div><input id=defTos inputmode=decimal placeholder="5 3/4&quot; · 1&#39;-0 1/4&quot;" value="'+esc(fmtFtIn(defaultTOS))+'"><span class=edec>'+esc(fmtDecIn(defaultTOS))+'</span>'+
2929
3591
  '<button class="ghostw f" id=applyTos>Reset all ends to default</button></div>';
2930
- document.getElementById('defTos').onchange=e=>{defaultTOS=parseLen(e.target.value);P.default_tos=defaultTOS;syncDefaults();scheduleSave();render();};
2931
- document.getElementById('applyTos').onclick=()=>edit(()=>{for(const m of P.members){ensureMeta(m);if(m.role==='column'){m.col.tosDef=true;m.col.tos=defaultTOS;}else for(const en of m.ends){en.tosDef=true;en.tos=defaultTOS;}}});
3592
+ document.getElementById('defTos').onchange=e=>{defaultTOS=parseLen(e.target.value);ModelCmd.setPlanDefaultTos(P,defaultTOS);syncDefaults();scheduleSave();render();sync3D();}; // sync3D: this moves every unset-elevation member on THIS sheet, so the 3D meshes and the per-sheet scale cache both have to follow — without it the 3D kept drawing them at the old datum
3593
+ document.getElementById('applyTos').onclick=()=>edit(()=>{for(const m of P.members)for(const o of ModelCmd.elevTargets(m))ModelCmd.setTosDefault(o,true,defaultTOS);}); // overwrites EVERY member, overrides included - unlike syncDefaults, which skips them
2932
3594
  document.querySelectorAll('.swc').forEach(c=>c.onchange=e=>{C.profile_colors[c.dataset.prof]=e.target.value;scheduleSave();render();sync3D();}); // recolour a profile (applies everywhere it's drawn; sync3D repaints a live 3D scene, no-op in 2D)
2933
3595
  const _rc=document.getElementById('resetCols');if(_rc)_rc.onclick=()=>{C.profile_colors={};scheduleSave();render();};
2934
3596
  return;}
@@ -3005,11 +3667,11 @@ function panel(){
3005
3667
  const chip=(id,val)=>{const b=document.getElementById(id);if(b)b.onclick=()=>setRot(val);};
3006
3668
  chip('rot0',0);chip('rot90',90);chip('rot180',180);chip('rot270',270);}
3007
3669
  // elevation wiring: a blank commit is skipped (Varies = unchanged); the "default" checkbox shows indeterminate when mixed.
3008
- const wMTos=(id,os)=>{const ck=document.getElementById(id+'_ck');if(ck){if(agg(os,o=>o.tosDef!==false)===VARIES)ck.indeterminate=true;ck.onchange=e=>edit(()=>{for(const o of os){o.tosDef=e.target.checked;if(o.tosDef)o.tos=defaultTOS;}});}
3009
- const inp=document.getElementById(id);if(inp)inp.onchange=e=>{const t=e.target.value.trim();if(!t)return;edit(()=>{const v=parseLen(t);for(const o of os){o.tos=v;o.tosDef=false;}});};};
3670
+ const wMTos=(id,os)=>{const ck=document.getElementById(id+'_ck');if(ck){if(agg(os,o=>o.tosDef!==false)===VARIES)ck.indeterminate=true;ck.onchange=e=>edit(()=>{for(const o of os)ModelCmd.setTosDefault(o,e.target.checked,defaultTOS);});}
3671
+ const inp=document.getElementById(id);if(inp)inp.onchange=e=>{const t=e.target.value.trim();if(!t)return;edit(()=>{const v=parseLen(t);for(const o of os)ModelCmd.setTosValue(o,v);});};};
3010
3672
  const wMText=(id,os,set)=>{const i=document.getElementById(id);if(i)i.onchange=e=>{const t=e.target.value.trim();if(!t)return;edit(()=>{for(const o of os)set(o,t);});};};
3011
3673
  if(allCol){const cs=cols.map(m=>m.col);
3012
- {const i=document.getElementById('bos');if(i)i.onchange=e=>{const t=e.target.value.trim();if(!t)return;edit(()=>{const v=parseLen(t);for(const o of cs)o.bos=v;});}}
3674
+ {const i=document.getElementById('bos');if(i)i.onchange=e=>{const t=e.target.value.trim();if(!t)return;edit(()=>{const v=parseLen(t);for(const o of cs)ModelCmd.setBos(o,v);});}}
3013
3675
  wMTos('tosC',cs);wMText('ntC',cs,(o,v)=>o.note=v);wMText('dtC',cs,(o,v)=>o.detail=v);}
3014
3676
  else if(allBeam){const s0=beams.map(m=>m.ends[0]),s1=beams.map(m=>m.ends[1]);
3015
3677
  wMTos('tosA',s0);wMText('ntA',s0,(o,v)=>o.note=v);wMText('dtA',s0,(o,v)=>o.detail=v);
@@ -3019,8 +3681,7 @@ function panel(){
3019
3681
  // edit() pushes undo unconditionally, so an all-brace selection must not enter it (Codex round-4).
3020
3682
  {const me=document.getElementById('matchEnds');if(me)me.onclick=()=>{
3021
3683
  const sel=selArr().filter(m=>m.role!=='column'), targets=sel.filter(m=>!isBrace(m)), sk=sel.length-targets.length;
3022
- if(targets.length)edit(()=>{for(const m of targets)
3023
- m.ends[1]={tos:m.ends[0].tos,note:m.ends[0].note,tosDef:m.ends[0].tosDef,detail:m.ends[0].detail,conn:m.ends[0].conn,connVerified:m.ends[0].connVerified};});
3684
+ if(targets.length)edit(()=>{for(const m of targets)ModelCmd.copyEndTo(m,0,1);});
3024
3685
  if(sk)toast(sk+' brace'+(sk>1?'s':'')+' skipped — matching ends would flatten the slope its arrows encode');};}}
3025
3686
  return;}
3026
3687
  const m=ensureMeta(arr[0]), wpf=_wt(m.profile), L=_lenFt(m).toFixed(1), col=(m.role==='column'), pos=posDefault(m);
@@ -3039,12 +3700,38 @@ function panel(){
3039
3700
  :(o.conn?'<span class=edec style="text-align:left;color:#fca5a5">references a missing row — re-pick</span>':'');
3040
3701
  return `<div class=elab>Connection</div><input id=${id} class=combo data-src=connrows readonly placeholder="— none — (pick from the library)" value="${esc(row?connLabel(row):'')}" autocomplete=off>${cap}`;};
3041
3702
  const fb=(o,html)=>`<div class="${o.conn?'connset':''}">${html}</div>`; // dim the note/detail fallback when a library row is referenced
3703
+ // What this end's detail will BUILD. Silent until there is a callout or a library reference to talk
3704
+ // about, so an un-annotated end gains no clutter. A refusal is never a dead end: it says what is missing
3705
+ // and offers the action that fixes it, because "Apply is greyed out and I don't know why" is the failure
3706
+ // this whole surface exists to avoid.
3707
+ const dStat=(id,o,which)=>{
3708
+ if(!o.detail&&!o.conn)return '';
3709
+ const r=resolveDetail(m,which), cap=captureEligible(m,which);
3710
+ const capBtn=cap?`<button id=${id}_cap class=ghost data-tip="Remember what this connection means, so every end with the same callout can be built from it">Remember as ${esc(o.detail)}</button>`:'';
3711
+ if(r.ok){
3712
+ // `built` also requires the joint to CITE this row: an identical-looking connection that came from a
3713
+ // different detail is not this detail's work, and saying "Built" for it would misreport provenance.
3714
+ const j=jointAtEnd(m.id,which), built=!!j&&j.kind===r.kind&&j.conn===r.rowId&&!recipeParamsDiffer(j.params,r.params);
3715
+ const row=connRowById(r.rowId), rec=row&&row.recipe;
3716
+ const why=(r.matched&&rec&&Array.isArray(rec.schedule))?(' · '+esc(schedRowLabel(rec.schedule[r.matched.index]))):'';
3717
+ const nn=(r.notes||[]).length;
3718
+ return `<div class=drow><div class=dmsg>${built?'Built':'Builds'} a <b>${esc(kindLabel(r.kind))}</b>${why}</div>`
3719
+ +`<button id=${id}_ap class=ghostw data-tip="${built?'Build it again from the detail, replacing what is here':'Build this connection from '+esc(o.detail||'the detail')}">${built?'Rebuild it':'Build it'}</button>${capBtn}</div>`
3720
+ +(nn?`<ul class=dnotes id=${id}_nl>${(r.notes||[]).map(n=>`<li>${esc(n.text)}</li>`).join('')}</ul>`:'');
3721
+ }
3722
+ if(r.reason==='no-detail')return ''; // nothing to say yet — the field itself is the prompt
3723
+ // The fixing action, per reason. 'fix' opens the chooser (a disagreement only the user can settle);
3724
+ // capture covers "nothing says what this builds" and "this size isn't in the schedule".
3725
+ const pick=(r.reason==='conflict'||r.reason==='ambiguous');
3726
+ const fixBtn=pick?`<button id=${id}_fx class=ghostw data-tip="Choose which connection this end really uses">Pick one</button>`:'';
3727
+ return `<div class=drow><div class="dmsg warn">${esc(r.message)}</div>${fixBtn}${capBtn}</div>`;
3728
+ };
3042
3729
  const dotS='<span class=epdot style="background:#facc15"></span>',dotE='<span class=epdot style="background:#f472b6"></span>'; // start=yellow, end=magenta — matches the canvas end markers
3043
3730
  const elev = col
3044
- ? `<div class="sect f">Elevation</div>${ftFld('bos',dotS+'Bottom (BOS)',m.col.bos)}${tosFld('tosC',dotE+'Top (TOS)',m.col)}${cFld('cnC',m.col)}${fb(m.col,nin('ntC',m.col.note)+dFld('dtC',m.col))}`
3045
- : `<div class="sect f">${dotS}Start</div>${tosFld('tosA','TOS',m.ends[0])}${cFld('cnA',m.ends[0])}${fb(m.ends[0],nin('ntA',m.ends[0].note)+dFld('dtA',m.ends[0]))}
3731
+ ? `<div class="sect f">Elevation</div>${ftFld('bos',dotS+'Bottom (BOS)',m.col.bos)}${tosFld('tosC',dotE+'Top (TOS)',m.col)}${cFld('cnC',m.col)}${fb(m.col,nin('ntC',m.col.note)+dFld('dtC',m.col))}${dStat('dtC',m.col,'col')}`
3732
+ : `<div class="sect f">${dotS}Start</div>${tosFld('tosA','TOS',m.ends[0])}${cFld('cnA',m.ends[0])}${fb(m.ends[0],nin('ntA',m.ends[0].note)+dFld('dtA',m.ends[0]))}${dStat('dtA',m.ends[0],0)}
3046
3733
  ${isBrace(m)?'':`<div class=divrow><hr><button class=ghost id=matchEnds>Match → both ends</button><hr></div>`}
3047
- <div class=sect>${dotE}End</div>${tosFld('tosB','TOS',m.ends[1])}${cFld('cnB',m.ends[1])}${fb(m.ends[1],nin('ntB',m.ends[1].note)+dFld('dtB',m.ends[1]))}`;
3734
+ <div class=sect>${dotE}End</div>${tosFld('tosB','TOS',m.ends[1])}${cFld('cnB',m.ends[1])}${fb(m.ends[1],nin('ntB',m.ends[1].note)+dFld('dtB',m.ends[1]))}${dStat('dtB',m.ends[1],1)}`;
3048
3735
  const bpj=col?(C.joints||[]).find(j=>j&&j.kind==='base-plate'&&j.main===m.id):null; // this column's base-plate joint, if detailed
3049
3736
  const pFld=(key,label,ph,unit)=>{const raw=bpj&&bpj.params&&bpj.params[key]!=null?bpj.params[key]:null;const val=raw==null?'':(unit==='mm'?esc(fmtFtIn(Number(raw)/25.4)):esc(String(raw)));return `<div class=elab>${label}</div><input id=bp_${key} inputmode=decimal placeholder="${esc(ph)}" value="${val}" autocomplete=off>${unit&&unit!=='mm'?`<span class=edec>${unit}</span>`:''}`;}; // mm params shown/entered in ft-in
3050
3737
  const bpSect=bpj?`<div class=divrow><hr><span class=sect style="margin:0">Base plate</span><hr></div>
@@ -3124,9 +3811,10 @@ function panel(){
3124
3811
  // plain X/Y move keeps a default-following Top on the sheet default (a tilted-frame local edit that really moves
3125
3812
  // Z still clears it). Same per-end TOS rule for a beam.
3126
3813
  const _dpCommit=(i,Pt)=>edit(()=>{const nx=Pt[0]*_dpPpf/12,ny=-Pt[1]*_dpPpf/12,zChg=Math.abs(Pt[2]-_dpZin(i))>1e-6;
3127
- if(col){m.wp[0]=[nx,ny];m.wp[1]=[nx,ny];
3128
- if(zChg){if(i===0)m.col.bos=Pt[2];else{m.col.tos=Pt[2];m.col.tosDef=false;}}}
3129
- else{m.wp[i]=[nx,ny];if(zChg){m.ends[i].tos=Pt[2];m.ends[i].tosDef=false;}}});
3814
+ const mc=MC();
3815
+ if(col){mc.setEndpointsInPlace(m,[nx,ny],[nx,ny]); // TWO literals, not one variable: the original wrote two distinct arrays, and sharing one would alias wp[0] and wp[1]
3816
+ if(zChg){if(i===0)ModelCmd.setBos(m.col,Pt[2]);else ModelCmd.setTosValue(m.col,Pt[2]);}} // Bottom writes bos ONLY; Top writes tos AND clears the default link
3817
+ else{mc.setEndpoint(m,i,[nx,ny]);if(zChg)ModelCmd.setTosValue(m.ends[i],Pt[2]);}});
3130
3818
  const _dpAxes=['X','Y','Z'];
3131
3819
  const _dpPH='5 3/4&quot; · 1&#39;-0 1/4&quot;';
3132
3820
  const _dpIn=(id,lbl,vin)=>{const v=Math.abs(vin)<1e-6?0:vin;return `<label class=detf><span>${lbl}</span><input id=${id} inputmode=decimal placeholder="${_dpPH}" value="${esc(fmtFtIn(v))}" autocomplete=off></label>`;}; // snap float-noise to 0 (no "-0"" from a local round-trip)
@@ -3203,17 +3891,39 @@ function panel(){
3203
3891
  const _ri=document.getElementById('detRotZ');if(_ri)_ri.onchange=e=>setRot(e.target.value);
3204
3892
  const chip=(id,val)=>{const b=document.getElementById(id);if(b)b.onclick=()=>setRot(val);};
3205
3893
  chip('rot0',0);chip('rot90',90);chip('rot180',180);chip('rot270',270);}
3206
- const wireTos=(id,o)=>{const ck=document.getElementById(id+'_ck');if(ck)ck.onchange=e=>edit(()=>{o.tosDef=e.target.checked;if(o.tosDef)o.tos=defaultTOS;});
3207
- const inp=document.getElementById(id);if(inp)inp.onchange=e=>edit(()=>{o.tos=parseLen(e.target.value);o.tosDef=false;});};
3894
+ const wireTos=(id,o)=>{const ck=document.getElementById(id+'_ck');if(ck)ck.onchange=e=>edit(()=>{ModelCmd.setTosDefault(o,e.target.checked,defaultTOS);});
3895
+ const inp=document.getElementById(id);if(inp)inp.onchange=e=>edit(()=>{ModelCmd.setTosValue(o,parseLen(e.target.value));});};
3208
3896
  const wireDet=(id,o)=>{const i=document.getElementById(id);if(i)i.onchange=e=>edit(()=>{o.detail=e.target.value.trim();});
3209
3897
  const pk=document.getElementById(id+'_pk');if(pk)pk.onclick=()=>{if(picking&&pickKind==='detail'&&pickEnd===o){picking=false;pickEnd=null;}else{picking=true;pickKind='detail';pickEnd=o;}render();};
3210
3898
  const op=document.getElementById(id+'_open');if(op)op.onclick=()=>openPreview(o.detail);};
3899
+ // The detail→connection actions under the field. `which` identifies the end so the resolver can reach
3900
+ // m.col vs m.ends[i]; the buttons only exist when dStat rendered them, so each lookup is guarded.
3901
+ const wireDetailBuild=(id,o,which)=>{
3902
+ const ap=document.getElementById(id+'_ap');
3903
+ if(ap)ap.onclick=()=>{
3904
+ const r=resolveDetail(m,which);
3905
+ if(!r.ok){toast(r.message);render();return;} // the model can move under an open panel — re-resolve, never build a stale answer
3906
+ // Same guard the bulk sweep applies: joints are matched model-wide by main+at while v1 member ids are
3907
+ // plan-local, so on a model with a repeated id this would clobber the other sheet's joint — which the
3908
+ // bulk action already refuses to touch. One button must not be laxer than the other.
3909
+ if(duplicateMemberIds().has(m.id)){toast('More than one member is called '+m.id+', so this connection could land on the wrong one — rename one of them first.');return;}
3910
+ const blk=detailApplyBlocker(m,which,r,false);
3911
+ if(blk){toast('Not built — '+blk.text+'. Remove it first, or tune this one by hand.');return;}
3912
+ let jid=null;edit(()=>{jid=buildJointFromDetail(m,which,r);});
3913
+ pendingConnSel=jid; // its parts only exist after the 3D rebuild → select the whole connection there
3914
+ toast('Built a '+kindLabel(r.kind)+' on '+m.id+' '+whichLabel(which)+' from '+(o.detail||'its connection'));
3915
+ };
3916
+ const cap=document.getElementById(id+'_cap');
3917
+ if(cap)cap.onclick=()=>openCaptureModal(m,which);
3918
+ const fx=document.getElementById(id+'_fx');
3919
+ if(fx)fx.onclick=()=>openDetailPick(m,which);
3920
+ };
3211
3921
  const wireConn=(id,o)=>{const i=document.getElementById(id);if(!i)return;i.onchange=e=>edit(()=>{const v=(e.target.value||'').trim();o.conn=(!v||v==='— none —')?'':v.split(' · ')[0];});};
3212
3922
  if(col){
3213
- document.getElementById('bos').onchange=e=>edit(()=>{m.col.bos=parseLen(e.target.value);});
3923
+ document.getElementById('bos').onchange=e=>edit(()=>{ModelCmd.setBos(m.col,parseLen(e.target.value));});
3214
3924
  wireTos('tosC',m.col);
3215
3925
  document.getElementById('ntC').onchange=e=>edit(()=>{m.col.note=e.target.value;});
3216
- wireDet('dtC',m.col);wireConn('cnC',m.col);
3926
+ wireDet('dtC',m.col);wireConn('cnC',m.col);wireDetailBuild('dtC',m.col,'col');
3217
3927
  if(bpj){const MAXCOUNT=20, MAXDIM=100000; // bolt grid is capped (scene parts = rows×cols, so a mistyped 1e5 can't explode the renderer); dims sanity-bounded
3218
3928
  const wireBp=(key,isInt)=>{const i=document.getElementById('bp_'+key);if(!i)return;i.onchange=e=>{
3219
3929
  const raw=e.target.value.trim();
@@ -3228,14 +3938,14 @@ function panel(){
3228
3938
  }else{
3229
3939
  wireTos('tosA',m.ends[0]);
3230
3940
  document.getElementById('ntA').onchange=e=>edit(()=>{m.ends[0].note=e.target.value;});
3231
- wireDet('dtA',m.ends[0]);wireConn('cnA',m.ends[0]);
3941
+ wireDet('dtA',m.ends[0]);wireConn('cnA',m.ends[0]);wireDetailBuild('dtA',m.ends[0],0);
3232
3942
  wireTos('tosB',m.ends[1]);
3233
3943
  document.getElementById('ntB').onchange=e=>edit(()=>{m.ends[1].note=e.target.value;});
3234
- wireDet('dtB',m.ends[1]);wireConn('cnB',m.ends[1]);
3944
+ wireDet('dtB',m.ends[1]);wireConn('cnB',m.ends[1]);wireDetailBuild('dtB',m.ends[1],1);
3235
3945
  // Not rendered for a brace — matching ends would FLATTEN the slope its arrowheads encode. Null-guarded
3236
3946
  // (the element is absent) plus a defensive isBrace check. (Codex round-4)
3237
3947
  {const me=document.getElementById('matchEnds');
3238
- if(me)me.onclick=()=>{if(isBrace(m))return;edit(()=>{m.ends[1]={tos:m.ends[0].tos,note:m.ends[0].note,tosDef:m.ends[0].tosDef,detail:m.ends[0].detail,conn:m.ends[0].conn,connVerified:m.ends[0].connVerified};});};}
3948
+ if(me)me.onclick=()=>{if(isBrace(m))return;edit(()=>{ModelCmd.copyEndTo(m,0,1);});};}
3239
3949
  // shear-plate inspector wiring (per detailed end) — every mutation rides edit() → undoable; editing
3240
3950
  // makes the plate user-owned (survives the auto-detail "Clear"). Bolt grid capped (rows×cols = parts).
3241
3951
  for(const {e,j} of spjs){const jid=j.id,MAXC=20,MAXD=100000; // jid is a JS closure var (the find key), never placed in the DOM
@@ -3280,7 +3990,7 @@ function panel(){
3280
3990
  }
3281
3991
  function addFromSeg(sid){const sg=P.segments.find(s=>s.id===sid);if(!sg)return;const prof=addProfile;const id='m'+Date.now();const pv=snapshot();
3282
3992
  const nm=ensureMeta({id,profile:prof,wp:[sg.a.slice(),sg.b.slice()],angle:sg.o,rfi:(_wt(prof)==null)});
3283
- applyMemberType([nm],addType);P.members.push(nm);
3993
+ applyMemberType([nm],addType);MC().addMembers(P,[nm]); // applyMemberType writes role/memberType, not geometry — it stays here
3284
3994
  if(prof&&!profs.includes(prof)){profs.push(prof);profs.sort();}pushUndo(pv);render();sync3D();}
3285
3995
  // --- marquee hit-test (crossing selection): does segment ab touch rect [x0,y0,x1,y1]? ---
3286
3996
  function inRect(p,r){return p[0]>=r[0]&&p[0]<=r[2]&&p[1]>=r[1]&&p[1]<=r[3];}
@@ -3837,7 +4547,7 @@ function drawClick(e){const s=dimSnapAt(e,drawDraft);const p=[s.x,s.y]; // dim
3837
4547
  if(len(a,b)<=6){drawPrev(e);return;} // sub-6px 2nd pick (double-click / near-miss) → KEEP the start, don't commit (mirrors dimClick's zero-length guard)
3838
4548
  const dx=Math.abs(b[0]-a[0]),dy=Math.abs(b[1]-a[1]),o=dx>3*dy?'H':(dy>3*dx?'V':'D'); // classify H/V/diagonal like the old drag-commit
3839
4549
  const id='m'+Date.now(),pv=snapshot();const nm=ensureMeta({id,profile:addProfile,wp:[a,b],angle:o,rfi:(_wt(addProfile)==null)});
3840
- applyMemberType([nm],addType);P.members.push(nm); // the Add-member panel's type owns role + legend category
4550
+ applyMemberType([nm],addType);MC().addMembers(P,[nm]); // the Add-member panel's type owns role + legend category
3841
4551
  if(addProfile&&!profs.includes(addProfile)){profs.push(addProfile);profs.sort();}pushUndo(pv);
3842
4552
  drawDraft=null;render();drawPrev(e);} // commit → clear the draft, keep the tool armed for the next member
3843
4553
  function drawPrevClear(){const g=document.getElementById('drawPrevLine');if(g)g.remove();snapClear();}
@@ -4042,10 +4752,11 @@ function dimEditCommit(){
4042
4752
  const mem=id=>(P.members||[]).find(x=>x&&x.id===id),addv=(p,v)=>[p[0]+v[0],p[1]+v[1]];
4043
4753
  edit(()=>{
4044
4754
  if(aRef||bRef){if(dimEdit.pin)delete d.pin;else d.pin=false;} // the popup's pin state commits onto the dim. Unpinned keeps the refs DORMANT (reanchor skips d.pin===false), so the typed value sticks AND the link can be re-pinned later — supersedes the old detach-both (Codex R1 #12) now that magnetism itself is pin-gated.
4755
+ const mcD=MC(); // safe to hoist because setEndpointsInPlace/setEndpoint read NOTHING from the command object's closure — only their member argument. MC() also snapshots defaultTOS BY VALUE, so anything that reads defaultTosIn (translate) must NOT be hoisted past a datum change.
4045
4756
  const doEnd=(driven,ref,mv,rawKey)=>{if(!driven)return;
4046
4757
  if(dimEdit.pin&&ref){const m=mem(ref.m);if(m&&Array.isArray(m.wp)&&m.wp.length>=2){
4047
- if(ref.pt==='mid'||m.role==='column'){m.wp[0]=addv(m.wp[0],mv);m.wp[1]=addv(m.wp[1],mv);} // mid = rigid; a COLUMN always moves rigidly (one plumb plan point — both wp stay coincident)
4048
- else if(ref.pt==='a')m.wp[0]=addv(m.wp[0],mv);else m.wp[1]=addv(m.wp[1],mv);}}
4758
+ if(ref.pt==='mid'||m.role==='column'){mcD.setEndpointsInPlace(m,addv(m.wp[0],mv),addv(m.wp[1],mv));} // mid = rigid; a COLUMN always moves rigidly (one plumb plan point — both wp stay coincident). Both args evaluate before either assignment, and neither reads the other's target.
4759
+ else{const k=ref.pt==='a'?0:1;mcD.setEndpoint(m,k,addv(m.wp[k],mv));}}} // same endpoint the inline pair addressed: 'a' -> wp[0], anything else -> wp[1]
4049
4760
  else{d[rawKey]=addv(d[rawKey],mv);}}; // pin OFF, or an unref'd end → move the dim's own coord
4050
4761
  doEnd(effA>0,aRef,mvA,'a');doEnd(effB>0,bRef,mvB,'b');
4051
4762
  });
@@ -4165,11 +4876,8 @@ function cmClick(e){
4165
4876
  function cmApplyOffsets(offs){const sel=sel2d();if(!sel.length){toast('Selection is empty — '+(cmTool==='move'?'Move':'Copy')+' ended');disarmCm();render();return;}
4166
4877
  if(cmArrayMode&&cmCountA*cmCountB>100){toast('Array capped at 100 instances — lower the counts (two passes reach further)');return;}
4167
4878
  if(!offs.length){toast(cmArrayMode?'A 1 × 1 array places no copies — raise a count':'Nothing to place');return;} // empty offset list (e.g. array 1×1) → no-op, never deref offs[0]
4168
- edit(()=>{
4169
- if(cmTool==='move'){translateMembers(sel,offs[0]);}
4170
- else{const ns=new Set();
4171
- for(const off of offs)for(const m of sel){const c=cloneMember(m);translateMembers([c],off);P.members.push(c);ns.add(c.id);}
4172
- selIds=ns;}}); // copy selects the new set (numbered badges)
4879
+ edit(()=>{const ns=MC().applyOffsets(sel,offs,{copy:cmTool!=='move'}); // unit 5 P3a: the model mutation is the boundary's; every UI concern below stays here
4880
+ if(cmTool!=='move')selIds=new Set(ns);}); // copy selects the new set (numbered badges); a move leaves the selection alone
4173
4881
  const L=Math.hypot(offs[0][0],offs[0][1],((offs[0][2]||0)*FT/12)); // dz shown in the same ft-in scale
4174
4882
  toast((cmTool==='move'?'Moved ':'Copied ')+sel.length+' member'+(sel.length===1?'':'s')+(offs.length>1?' ×'+offs.length:'')+' · '+fmtFtIn(L/FT*12));
4175
4883
  cmHudClose();cmDraft=null;cmPrevClear();panel();} // tool stays armed for the next pick pair; Esc finishes
@@ -4277,19 +4985,19 @@ function openLevelModal(tool){ // works from 2D and 3D — the commit is plan-
4277
4985
  const cancel=document.createElement('button');cancel.textContent='Cancel';cancel.onclick=closeLevelModal;
4278
4986
  go.onclick=()=>{if(pick>=0){toLevelCommit(tool,pick);closeLevelModal();}};
4279
4987
  ft.append(cancel,go);pn.append(hd,body,note,ft);lvModal.append(bd,pn);document.body.appendChild(lvModal);}
4280
- function toLevelCommit(tool,ti){const sel=selArr();const T=C.plans[ti]; // model-wide: a cross-sheet selection all moves/copies to the target level (counts match the modal, which reads selIds)
4988
+ function toLevelCommit(tool,ti){const sel=selArr();const T=C.plans[ti];const mc=MC(); // model-wide: a cross-sheet selection all moves/copies to the target level (counts match the modal, which reads selIds)
4281
4989
  if(!sel.length){toast('Selection is empty — nothing to '+(tool==='move'?'move':'copy'));return;}
4282
4990
  if(!T)return;
4283
- if(!Array.isArray(T.members))T.members=[];
4991
+ if(!Array.isArray(T.members))T.members=[]; // stays BEFORE snapshot(): a non-array captured into the undo entry breaks restore code that maps over it. mc.addMembers deliberately does not do this.
4284
4992
  const dstDef=(T.default_tos!=null?T.default_tos:198);
4285
4993
  const pv=snapshot(); // whole-model pre-mutation → one global-stack entry undoes the source removals AND the target adds
4286
4994
  const moved=[];
4287
4995
  for(const m of sel){const srcPl=planeOf(m.id);if(srcPl===T)continue; // already on the target level → no-op for this member
4288
4996
  const srcDef=(srcPl&&srcPl.default_tos!=null?srcPl.default_tos:defaultTOS); // retarget TOS from EACH source plane's own default (sources may span sheets)
4289
- const c=(tool==='copy')?cloneMember(m):m;retargetTos(c,srcDef,dstDef);moved.push(c);}
4997
+ const c=(tool==='copy')?mc.clone(m):m;mc.retargetTos(c,srcDef,dstDef);moved.push(c);}
4290
4998
  if(!moved.length){toast('Selection is already on '+T.sheet);return;}
4291
- if(tool==='move'){const mv=new Set(moved.map(m=>m.id));for(const pl of C.plans)pl.members=(pl.members||[]).filter(m=>!mv.has(m.id));selIds=new Set();} // remove moved members from EVERY source plane, not just the active one
4292
- T.members.push(...moved);T.members.forEach(ensureMeta);
4999
+ if(tool==='move'){mc.removeMembers(new Set(moved.map(m=>m.id)));selIds=new Set();} // remove moved members from EVERY source plane, not just the active one — and BEFORE the push below, which would otherwise delete what it just added
5000
+ mc.addMembers(T,moved);T.members.forEach(ensureMeta); // forEach normalizes the WHOLE target sheet, not just `moved` — addMembers must not absorb it
4293
5001
  pushUndo(pv);disarmCm();render();sync3D(); // one global-stack entry; disarm BEFORE render so the panel never advertises a dead tool
4294
5002
  toast((tool==='move'?'Moved ':'Copied ')+moved.length+' member'+(moved.length===1?'':'s')+' to '+T.sheet);}
4295
5003
  // --- Local coordinate system "set axes" tool: two snapped clicks (origin, then X-direction) define
@@ -4349,9 +5057,11 @@ function updCS(){const s=document.getElementById('csStat');const r=document.getE
4349
5057
  if(s){s.innerHTML='Axes <b>'+(f?(Math.round(Math.atan2(f.u[1],f.u[0])*180/Math.PI)+'° local'):'Global')+'</b>';s.classList.toggle('local',!!f);s.dataset.tip=f?'Local axes active — ortho draw & X/Y dimensions follow them. Click to reset to global.':'Global axes (default). Set local axes from the ⋯ menu for skewed framing.';}
4350
5058
  if(r)r.disabled=!(P&&P.frame);}
4351
5059
  // themed transient toast (baseline tokens — never a native alert)
4352
- function toast(msg){let t=document.getElementById('toast');
5060
+ // `sticky` holds the toast up with no timer — for an operation whose result the user must see land
5061
+ // (the Tekla send takes seconds); the next plain toast() replaces the text and re-arms the timer.
5062
+ function toast(msg,sticky){let t=document.getElementById('toast');
4353
5063
  if(!t){t=document.createElement('div');t.id='toast';t.style.cssText='position:fixed;left:50%;bottom:18px;transform:translateX(-50%);background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:8px;padding:8px 14px;box-shadow:0 6px 20px rgba(0,0,0,.5);z-index:60;font:13px system-ui;opacity:0;transition:opacity .2s;pointer-events:none';document.body.appendChild(t);}
4354
- t.textContent=msg;t.style.opacity='1';clearTimeout(t._h);t._h=setTimeout(()=>{t.style.opacity='0';},2600);}
5064
+ t.textContent=msg;t.style.opacity='1';clearTimeout(t._h);if(!sticky)t._h=setTimeout(()=>{t.style.opacity='0';},2600);}
4355
5065
  // --- pointer: select(+ctrl toggle / box) + group-move + endpoint (Shift = ortho) ---
4356
5066
  svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
4357
5067
  if(csaxisMode){csClick(e);e.preventDefault();return;} // set-local-axes armed → clicks define origin then X-direction
@@ -4362,7 +5072,7 @@ svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
4362
5072
  else{const a=gridLinePick.a.slice(),b=[x,y],pv=snapshot();if(gridAddFreeLine(a,b)){pushUndo(pv);gridCancelLinePick();render();refresh3DGrid();}else panel();}
4363
5073
  e.preventDefault();return;}
4364
5074
  if(gridPick){let q=toSvg(e),x=q.x,y=q.y;if(!e.altKey){buildSnap(null);const sn=snap(x,y);x=sn.x;y=sn.y;}snapClear(); // armed pick-origin → one snapped click sets the grid's 1-A corner (undoable)
4365
- gridPick=false;gridSetPickClass();if(P.grid)edit(()=>{P.grid.origin=[x,y];});else panel();e.preventDefault();return;}
5075
+ gridPick=false;gridSetPickClass();if(P.grid)edit(()=>{ModelCmd.patchGrid(P.grid,{origin:[x,y]});});else panel();e.preventDefault();return;}
4366
5076
  if(qdPick&&(view3d||mode!=='sel'||dimMode||csaxisMode||geoMode||cmTool||picking||dimSplitMode)){qdPick=null;setQdPickCls();} // a stale F7 station pick must never fire while/after ANOTHER tool runs — the first click under that tool disarms it instead (Codex final-review #3)
4367
5077
  if(qdPick){let q=toSvg(e),x=q.x,y=q.y;if(!e.altKey){buildSnap(null);const sn=snap(x,y);x=sn.x;y=sn.y;}snapClear();const pp=qdPick;qdPick=null;setQdPickCls();quickDimSpacing(pp.pt,[x,y]);e.preventDefault();return;} // F7 grid quick-dim: the armed one-shot station pick consumes this click BEFORE the grid-line hit test — the picked station often lies ON a grid line, which must not start a grid drag instead (Codex final-review #6)
4368
5078
  {const gb=t.closest&&t.closest('g.gridbubg'),ghit=(t.classList&&t.classList.contains('gridhit'))?t:null; // grid line body OR label bubble → drag slides the line; a no-move click selects it (bubble double-click still renames)
@@ -4406,7 +5116,9 @@ svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
4406
5116
  else if(tm)tgt=[tm.wp[0],tm.wp[1]];}
4407
5117
  else if(t.classList.contains('seg')){const sg=P.segments.find(s=>s.id===t.dataset.seg);if(sg)tgt=[sg.a,sg.b];}
4408
5118
  else if(t.classList.contains('gridhit')){const gp=gridLineEndpoints(t);if(gp)tgt=gp;} // a grid line is a valid target — its two endpoints define the line to meet
4409
- if(tgt){geoMode=null;setGeo();if(!snapEndMulti(sel2d(),tgt[0],tgt[1]))render();} // miss (empty/own line) keeps the mode armed; a 0-result target (all parallel / all braces) still needs a render() to un-arm the panel + grid affordance (snapEndMulti only renders when it moved something)
5119
+ if(tgt){const off2=selArr().filter(mm=>!P.members.includes(mm)); // selection is MODEL-WIDE, so a 2D trim can carry off-sheet members too — snapEndMulti is plan-local and would silently drop them
5120
+ if(off2.length){geoMode=null;setGeo();toast('Trim/Extend needs every selected member on the open sheet — '+off2.length+' '+(off2.length===1?'is':'are')+' on another sheet. Deselect them or switch sheets.');render();return;}
5121
+ geoMode=null;setGeo();if(!snapEndMulti(sel2d(),tgt[0],tgt[1]))render();} // miss (empty/own line) keeps the mode armed; a 0-result target (all parallel / all braces) still needs a render() to un-arm the panel + grid affordance (snapEndMulti only renders when it moved something)
4410
5122
  return;}
4411
5123
  if(t.classList.contains('handle')){const id=t.dataset.mid||[...selIds][0],m=byId(id),h=+t.dataset.h;if(!m)return;buildSnap(id);
4412
5124
  drag={type:'end',h,id,anchor:m.wp[1-h].slice(),orig:m.wp[h].slice(),pre:snapshot()};svg.setPointerCapture(e.pointerId);e.preventDefault();return;} // anchor = the fixed end (length ref); orig = where this end started (moved ref)
@@ -4473,7 +5185,7 @@ svg.addEventListener('pointermove',e=>{
4473
5185
  else{a=[drag.origA[0]+dxc,drag.origA[1]+dyc];b=[drag.origB[0]+dxc,drag.origB[1]+dyc];snapClear();}
4474
5186
  gridReadout(e,gridDelta(Math.hypot(a[0]-drag.origA[0],a[1]-drag.origA[1])),'');
4475
5187
  }
4476
- line.a=a;line.b=b;refreshGridLayer();refreshMagneticDims2D();const dl=svg.querySelector(`line.gridln[data-gl="${drag.gi}"]`);if(dl)dl.classList.add('gdrag');return;} // free-line drag mutates P.grid.lines LIVE → gl:-anchored dims track it (Codex final-review #2)
5188
+ ModelCmd.setGridLineEnds(line,a,b);refreshGridLayer();refreshMagneticDims2D();const dl=svg.querySelector(`line.gridln[data-gl="${drag.gi}"]`);if(dl)dl.classList.add('gdrag');return;} // free-line drag mutates P.grid.lines LIVE → gl:-anchored dims track it (Codex final-review #2)
4477
5189
  if(drag.type==='gridline'){const dxc=p.x-drag.startPt[0],dyc=p.y-drag.startPt[1];
4478
5190
  if(!drag.moved){if(Math.hypot(dxc,dyc)<=4/zoom)return;drag.moved=true; // past the tolerance = a drag, not a click
4479
5191
  const along=drag.axis==='v'?Math.abs(dyc):Math.abs(dxc),perp=drag.axis==='v'?Math.abs(dxc):Math.abs(dyc);
@@ -4485,7 +5197,7 @@ svg.addEventListener('pointermove',e=>{
4485
5197
  for(const q of snapPts){const c=drag.axis==='v'?q[0]:q[1];const d=Math.abs(c-np);if(d<bd){bd=d;bp=c;}}
4486
5198
  if(bp!=null){np=bp;snapMark(drag.axis==='v'?np:p.x,drag.axis==='v'?p.y:np,'line');}else snapClear();}
4487
5199
  else snapClear();
4488
- const applied=gc.moveGridLine(P.grid,ppf,drag.axis,drag.gi,np,drag.base); // clamps between neighbours, rebases origin on line 1/A
5200
+ const applied=ModelCmd.moveGridLine(gc,P.grid,ppf,drag.axis,drag.gi,np,drag.base); // clamps between neighbours, rebases origin on line 1/A
4489
5201
  const geo=gridGeo(),lines=geo?geo[drag.axis]:null; // live readout: how far it moved + the bay it resizes
4490
5202
  let sub='';
4491
5203
  if(lines&&lines.length>1){const pos=(l)=>drag.axis==='v'?l.x:l.y;const bay=drag.gi>0?Math.abs(pos(lines[drag.gi])-pos(lines[drag.gi-1])):Math.abs(pos(lines[1])-pos(lines[0]));sub=' · bay '+dimValueText(bay);}
@@ -4496,7 +5208,7 @@ svg.addEventListener('pointermove',e=>{
4496
5208
  for(const q of snapPts){const c=drag.axis==='v'?q[1]:q[0];const d=Math.abs(c-np);if(d<bd){bd=d;bp=c;}}
4497
5209
  if(bp!=null){np=bp;snapMark(drag.axis==='v'?drag.orig:np,drag.axis==='v'?np:drag.orig,'end');}else snapClear();}
4498
5210
  else snapClear();
4499
- const applied=gc.moveGridLineEnd(P.grid,ppf,drag.axis,drag.gi,drag.end,np); // 12" min length; near the full span → back to auto
5211
+ const applied=ModelCmd.moveGridLineEnd(gc,P.grid,ppf,drag.axis,drag.gi,drag.end,np); // 12" min length; near the full span → back to auto
4500
5212
  gridReadout(e,gridDelta((applied!=null?applied:np)-drag.origEnd),'');
4501
5213
  }
4502
5214
  refreshGridLayer();refreshMagneticDims2D(); // moveGridLine mutates P.grid LIVE — grid-anchored dims must track the drag, not jump at pointer-up (Codex final-review #2)
@@ -4505,8 +5217,9 @@ svg.addEventListener('pointermove',e=>{
4505
5217
  if(drag.type==='dimend'){const d=P.dims.find(x=>x.id===drag.id);if(d){let x=p.x,y=p.y;if(!e.altKey){const sn=snap(x,y);x=sn.x;y=sn.y;sn.hit?snapMark(x,y):snapClear();}else snapClear();
4506
5218
  if(drag.grip){const gp=drag.grip,m=(P.members||[]).find(mm=>mm&&mm.id===gp.mid); // pinned grip: the handle DRIVES the member — end wp follows the pointer; mid/column translate rigidly (delta from the grabbed anchor), so the anchor still lands exactly at [x,y]
4507
5219
  if(m&&Array.isArray(m.wp)&&m.wp.length>=2){
4508
- if(gp.rigid){const dx=x-gp.oa[0],dy=y-gp.oa[1];m.wp[0]=[gp.ow[0][0]+dx,gp.ow[0][1]+dy];m.wp[1]=[gp.ow[1][0]+dx,gp.ow[1][1]+dy];}
4509
- else if(gp.pt==='a')m.wp[0]=[x,y];else m.wp[1]=[x,y];}}
5220
+ const mcG=MC(); // built inside the grip branch, so the far more common ungripped dim drag pays nothing
5221
+ if(gp.rigid){const dx=x-gp.oa[0],dy=y-gp.oa[1];mcG.setEndpointsInPlace(m,[gp.ow[0][0]+dx,gp.ow[0][1]+dy],[gp.ow[1][0]+dx,gp.ow[1][1]+dy]);} // ABSOLUTE from the grab-time origin gp.ow, as the inline pair was
5222
+ else mcG.setEndpoint(m,gp.pt==='a'?0:1,[x,y]);}}
4510
5223
  if(drag.end===0)d.a=[x,y];else d.b=[x,y];render();}return;} // dragging a dim anchor → snap + re-measure live (render() reanchors every OTHER magnetic dim off the grip-moved member too)
4511
5224
  if(drag.type==='dim'){if(!drag.moved){if(Math.hypot(e.clientX-drag.cx0,e.clientY-drag.cy0)<4)return;drag.moved=true;} // below the threshold it's a click/double-click, not an offset slide — don't touch off or write an undo entry (Codex code-review #4)
4512
5225
  const d=P.dims.find(x=>x.id===drag.id);if(d){d.off=dimOffFromPointer(d.a,d.b,d.axis,[p.x,p.y],d.rot);render();}return;}
@@ -4520,8 +5233,8 @@ svg.addEventListener('pointermove',e=>{
4520
5233
  drag.moved=true;
4521
5234
  if(!drag.armed)return; // drag-move OFF, plain grab → never translate (the up-handler teaches the toggle)
4522
5235
  if(drag.copy){ // materialize clones once; from here it's a normal move of the clones
4523
- const ns=new Set(),ci=[];
4524
- for(const it of drag.items){const src=byId(it.id);if(!src)continue;const c=cloneMember(src);P.members.push(c);ns.add(c.id);ci.push({id:c.id,o0:c.wp[0].slice(),o1:c.wp[1].slice()});}
5236
+ const ns=new Set(),ci=[],mcD=MC();
5237
+ for(const it of drag.items){const src=byId(it.id);if(!src)continue;const c=mcD.clone(src);mcD.addMembers(P,[c]);ns.add(c.id);ci.push({id:c.id,o0:c.wp[0].slice(),o1:c.wp[1].slice()});}
4525
5238
  selIds=ns;drag.items=ci;buildSnap(ns);render();} // select the clones + snap them to the sources/others; render shows them (drag continues via updateLine)
4526
5239
  else if(drag.add&&!selIds.has(drag.clickId)){selIds=new Set([drag.clickId]);render();}} // Shift/Ctrl-drag on an unselected member → move just it (select so state matches the gesture)
4527
5240
  if(!drag.armed)return;
@@ -4536,14 +5249,15 @@ svg.addEventListener('pointermove',e=>{
4536
5249
  if(snapAllowed('ext')){const ex=nearestOnExtension(nx,ny,bd);if(ex){bd=Math.hypot(ex.x-nx,ex.y-ny);best={q:[ex.x,ex.y],cx:ex.x-nx,cy:ex.y-ny,kind:'ext',from:ex.from};}}} // ...and onto a line's extension (parity with the single-endpoint drag / draw / dim paths)
4537
5250
  if(best){dx+=best.cx;dy+=best.cy;if(best.kind==='ext')snapExtFrom=best.from;snapMark(best.q[0],best.q[1],best.kind);}else snapClear();}
4538
5251
  else snapClear();
5252
+ const mcM=MC(); // hoisted: this block runs on EVERY pointermove, so rebuilding the commands per member per mouse event would be a drag-latency regression
4539
5253
  for(const it of drag.items){const m=byId(it.id);if(!m)continue;
4540
- m.wp[0]=[it.o0[0]+dx,it.o0[1]+dy];m.wp[1]=[it.o1[0]+dx,it.o1[1]+dy];updateLine(m);}
5254
+ mcM.setEndpointsInPlace(m,[it.o0[0]+dx,it.o0[1]+dy],[it.o1[0]+dx,it.o1[1]+dy]);updateLine(m);} // ABSOLUTE from the grab origin (not a relative translate, which would accumulate per event); keeps the outer wp array, as the inline writes did
4541
5255
  if(selIds.size<=2)for(const m of sel2d())updateHandles(m);refreshMagneticDims2D();return;} // F9: magnetic dims track the moving members live
4542
5256
  // endpoint
4543
5257
  const m=byId(drag.id);if(!m)return;let x=p.x,y=p.y;
4544
5258
  if(e.shiftKey){[x,y]=orthoLock(drag.anchor[0],drag.anchor[1],x,y);snapClear();} // ortho endpoint — local frame when set, else screen H/V
4545
5259
  else if(!e.altKey){const sn=snap(x,y,drag.anchor);x=sn.x;y=sn.y;sn.hit?snapMark(x,y):snapClear();}else snapClear(); // anchor = the member's fixed end → ⟂/∥ to a target line
4546
- m.wp[drag.h]=[x,y];updateLine(m);updateHandles(m);refreshMagneticDims2D(); // F9: magnetic dims track the moving endpoint live
5260
+ MC().setEndpoint(m,drag.h,[x,y]);updateLine(m);updateHandles(m);refreshMagneticDims2D(); // ABSOLUTE (this fires once per pointermove with a snapped point, so a relative primitive would accumulate); updateLine/updateHandles are DOM and stay here. F9: magnetic dims track the moving endpoint live
4547
5261
  {let g=document.getElementById('epPrevG');if(!g){g=document.createElementNS(SVGNS,'g');g.id='epPrevG';g.setAttribute('pointer-events','none');svg.appendChild(g);}epPrevDraw(g,drag.orig,drag.anchor,[x,y],m);}}); // live moved + length readout
4548
5262
  svg.addEventListener('pointerup',()=>{if(!drag)return;snapClear();epPrevClear();
4549
5263
  if(drag.type==='gridfree'){const moved=drag.moved,pre=drag.pre,add=drag.add,geo=gridGeo(),line=geo&&(geo.lines||[])[drag.gi],gid='gl:'+(line&&line.id!=null?line.id:drag.gi);drag=null;gridReadoutHide();snapOnlyClear2d();
@@ -4658,8 +5372,8 @@ document.getElementById('revB').onclick=()=>{const ids=reversedBeams(); // bea
4658
5372
  toast(ids.length+' reversed beam'+(ids.length>1?'s':'')+' selected — press P to swap direction');}; // select reversed → review → P swaps them
4659
5373
  document.getElementById('mrgB').onclick=()=>{const r=mergeCollinearJS(P.members); // conservative; result is undoable (Ctrl+Z)
4660
5374
  if(!r.mergedAway){toast('Nothing to merge');return;}
4661
- edit(()=>{const aff=new Set(r.affectedIds);for(const d of (P.dims||[]))for(const rk of ['aRef','bRef'])if(d[rk]&&aff.has(d[rk].m))delete d[rk]; // F9: detach dim refs to every merged member before replacing P.members (safe-freeze; Codex R3 #3)
4662
- P.members=r.members;selIds=new Set();selDimIds.clear();});
5375
+ edit(()=>{ModelCmd.detachDimRefs(P,r.affectedIds); // F9: detach dim refs to every merged member (safe-freeze; Codex R3 #3). What matters is that this lands before the next render() — reanchorAllPlans() runs there, and the survivor keeps its id, so a ref left attached would silently re-anchor to the merged end. edit() renders after the callback, so this and the line below are order-independent; the original's order is kept regardless.
5376
+ ModelCmd.setPlanMembers(P,r.members);selIds=new Set();selDimIds.clear();});
4663
5377
  toast('Merged '+r.mergedAway+' segment'+(r.mergedAway===1?'':'s')+' into '+r.runs+' member'+(r.runs===1?'':'s'));};
4664
5378
  document.getElementById('undoB').onclick=doUndo;
4665
5379
  document.getElementById('redoB').onclick=doRedo;
@@ -4668,6 +5382,10 @@ setDragMove(dragMoveOn); // reflect the persisted state on load (body class +
4668
5382
  addEventListener('keydown',e=>{
4669
5383
  const inForm=/^(INPUT|SELECT|TEXTAREA)$/.test((document.activeElement||{}).tagName);
4670
5384
  if(dimEdit){if(e.key==='Escape'){e.preventDefault();closeDimEdit();}return;} // F8 popup is modal — suppress every editor/tool shortcut (incl. Ctrl+Z under the popup). Its own input/buttons handle their keys and stopPropagation, so they never reach here (Codex R2 #8).
5385
+ // A live drag-out to Tekla owns Escape: the 3D view cancels the gesture on its own handler (this one
5386
+ // runs first). Without this, Escape would fall through to the deselect below and clear the very
5387
+ // selection the gesture is still carrying.
5388
+ if(e.key==='Escape'&&window.Steel3DView&&window.Steel3DView.teklaDragging&&window.Steel3DView.teklaDragging())return;
4671
5389
  if(e.key==='Escape'&&moreOpen()){closeMore();moreBtn.focus();return;}
4672
5390
  if(e.key==='Escape'&&xfMenuC.isOpen()){xfMenuC.close();return;}
4673
5391
  if(lvOpen()){if(e.key==='Escape')closeLevelModal();return;} // the level modal is modal: no Delete/undo/tool keys mutate state underneath it
@@ -4721,7 +5439,7 @@ addEventListener('keydown',e=>{
4721
5439
  if(selDimIds.size){P.dims=P.dims.filter(d=>!selDimIds.has(d.id));selDimIds.clear();}
4722
5440
  if(selIds.size){const jids=selJointIds();if(jids.size)C.joints=(C.joints||[]).filter(j=>!(j&&jids.has(j.id))); // any selected connection parts → remove their joints too (a mixed member+connection or connection+grid Delete)
4723
5441
  for(const pl of C.plans)pl.members=(pl.members||[]).filter(m=>!selIds.has(m.id));selIds.clear();} // selection spans sheets → remove from every plane, not just the active one
4724
- if(freeToDelete.length&&P.grid&&Array.isArray(P.grid.lines))P.grid.lines=P.grid.lines.filter(l=>!glLids.has(String(l.id)));
5442
+ if(freeToDelete.length)ModelCmd.removeGridLines(P.grid,glLids);
4725
5443
  selGridIds.clear();});
4726
5444
  else{selGridIds.clear();render();} // only regular grid lines were selected → nothing to delete (no phantom undo step); repaint to drop the highlight
4727
5445
  if(hadReg)toast('Regular grid lines come from the grid spacing — remove them in “Grid lines…”. Only free grid lines are deletable here.');
@@ -4774,7 +5492,12 @@ const moreBtn=document.getElementById('moreBtn'),moreMenu=document.getElementByI
4774
5492
  function moreOpen(){return moreMenu.classList.contains('open');}
4775
5493
  function moreOutside(e){if(!moreMenu.contains(e.target)&&e.target!==moreBtn)closeMore();}
4776
5494
  function closeMore(){moreMenu.classList.remove('open');moreBtn.setAttribute('aria-expanded','false');document.removeEventListener('mousedown',moreOutside,true);}
4777
- moreBtn.onclick=e=>{e.stopPropagation();if(moreOpen())closeMore();else{moreMenu.classList.add('open');moreBtn.setAttribute('aria-expanded','true');document.addEventListener('mousedown',moreOutside,true);}};
5495
+ moreBtn.onclick=e=>{e.stopPropagation();if(moreOpen())closeMore();else{
5496
+ // "Send selection to Tekla" is hidden, not disabled, with nothing selected — there is no action to
5497
+ // offer yet, and a greyed row would read as a broken feature rather than an empty state.
5498
+ document.getElementById('sendTeklaB').hidden=!selArr().length;
5499
+ moreMenu.classList.add('open');moreBtn.setAttribute('aria-expanded','true');document.addEventListener('mousedown',moreOutside,true);}};
5500
+ document.getElementById('sendTeklaB').onclick=()=>{closeMore();sendSelectionToTekla(teklaSelectionIds());};
4778
5501
  moreMenu.addEventListener('click',e=>{if(e.target.closest('button')&&!e.target.closest('.msnap')&&!e.target.closest('.dtog')&&!e.target.closest('.msec-hdr')&&!e.target.closest('.ins-in-menu'))closeMore();}); // an item's own handler runs (bubble) before this closes the menu; the snap toggles, section headers, and the Insert picker keep the menu open (settings, not one-shot actions)
4779
5502
  // "Snapping" is collapsible to save menu space — the header expands the running-snap switches below it
4780
5503
  // Every ⋯ section is a collapse/expand accordion (Snapping + Display + Detailing + …); state persists in localStorage.
@@ -4899,6 +5622,53 @@ document.getElementById('cpLevelB').onclick=()=>openLevelModal('copy');
4899
5622
  // Coped beams (auto, clash-driven) — cache the cut labels per member as the scene is fetched so the
4900
5623
  // member Inspector can show a read-only "Cope (auto)" note (a coped beam otherwise looks like an error).
4901
5624
  let copesByMember={}, partsById={};
5625
+
5626
+ // --- Send the selection to Tekla (Ctrl+Shift-drag it out of the 3D view, or ⋯ → Session). The
5627
+ // server bakes just these members as native parts in the OPEN model, at their real model
5628
+ // coordinates — where you released the mouse is a gesture, not a location. Each send is its own
5629
+ // insert, so sending the same members twice puts them in twice (undo/delete in Tekla). ---
5630
+ let teklaSendBusy=false;
5631
+ const teklaSelectionIds=()=>selArr().map(m=>m.id); // members only: grid lines, dimensions and connection parts are never sent (selArr matches against real members)
5632
+ async function sendSelectionToTekla(ids){
5633
+ if(teklaSendBusy)return;
5634
+ const list=[...new Set((Array.isArray(ids)?ids:[]).filter(Boolean))];
5635
+ if(!list.length){toast('Select the members you want to send first.');return;}
5636
+ const n=list.length,noun=n===1?'member':'members';
5637
+ teklaSendBusy=true;toast('Sending '+n+' '+noun+' to Tekla…',true);
5638
+ try{
5639
+ // Push the on-screen edits first, or a just-moved beam lands at its old place. NOT in a project:
5640
+ // there the server exports the APPROVED snapshot (not this draft), while every contract PUT clears
5641
+ // that approval — so flushing would only un-approve the project and make the export refuse itself.
5642
+ // Which leaves a project with unsent edits in a bind we must not paper over: inside the autosave
5643
+ // window the project is still approved, so the send would SUCCEED against the approved snapshot and
5644
+ // bake stale geometry — a beam you just moved landing where it used to be, reported as a success.
5645
+ // Refuse instead, and name the step that fixes it.
5646
+ if(PROJECT){
5647
+ if(saveT!==null){toast('Approve this version before sending — your latest edits aren’t in the approved model yet.');return;}
5648
+ } else await window.flushContract();
5649
+ const res=await fetch('/api/contract/'+encodeURIComponent(APP_ID)+'/export-tekla'+PROJECT_QS,
5650
+ {method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({memberIds:list})});
5651
+ const j=await res.json().catch(()=>({}));
5652
+ if(!res.ok||!j.ok)throw new Error(j.error||('send failed ('+res.status+')'));
5653
+ // Report what TEKLA received, never what we asked for: the server legitimately drops members it
5654
+ // can't resolve (an RFI with no AISC size) and still succeeds, so the requested count would
5655
+ // overstate a partial send. Mirrors the whole-model export's "sent with gaps" wording.
5656
+ // Count MEMBERS specifically — `counts.native` includes the plates, bolts and welds a connection
5657
+ // brings with it, so one member with a base plate would otherwise be reported as two "members".
5658
+ const em=(j.receipt&&Array.isArray(j.receipt.emitted))?j.receipt.emitted:null;
5659
+ const got=em?em.filter(r=>r&&r.kind==='member').length:n;
5660
+ const gotNoun=got===1?'member':'members',missed=n-got;
5661
+ toast(missed>0
5662
+ ?'Inserted '+got+' of '+n+' '+noun+' into Tekla — '+missed+' had no size to build yet.'
5663
+ :'Inserted '+got+' '+gotNoun+' into Tekla.');
5664
+ }catch(e){
5665
+ console.error('send to Tekla failed',e);
5666
+ // The server's own messages are plain English; a transport failure ("Failed to fetch") is not.
5667
+ const msg=e&&e.message?e.message:'';
5668
+ toast(/failed to fetch|networkerror|load failed/i.test(msg)?'Couldn’t reach the app to send — is it still running?':(msg||'Couldn’t insert into Tekla.'));
5669
+ }finally{teklaSendBusy=false;}
5670
+ }
5671
+
4902
5672
  const view3dApi={
4903
5673
  onFrame3dChange:()=>{updCS();if(typeof csSyncF3d==='function')csSyncF3d();
4904
5674
  // F14: the Definition-points local (X′/Y′/Z′) row reads the 3D frame — refresh the inspector when the
@@ -4946,20 +5716,30 @@ const view3dApi={
4946
5716
  ptPerFt:()=>(P&&P.pt_per_ft>0?P.pt_per_ft:1),
4947
5717
  defaultTosMm:()=>(defaultTOS!=null?defaultTOS*25.4:0), // editor stores default T.O.S in inches
4948
5718
  geoMode:()=>geoMode, // 'el' | 'split' | null — armed Trim/Extend/Split state
4949
- onMoveMember:(id,newWp)=>{edit(()=>{const m=byId(id);if(m)m.wp=newWp;});}, // 3D drag → write wp (undoable, autosaves, syncs 2D/chip/BOM). NOTE: the Select filter gates SELECTION (pick/marquee/Ctrl+A), NOT direct 3D drag-manipulation — gating here would strand the renderer's live preview (the mesh is already moved), so a filtered member is still directly draggable in 3D by design.
5719
+ onMoveMember:(id,newWp)=>{edit(()=>{const m=byId(id);if(m)MC().replaceEndpoints(m,newWp);});}, // 3D drag → write wp (undoable, autosaves, syncs 2D/chip/BOM). NOTE: the Select filter gates SELECTION (pick/marquee/Ctrl+A), NOT direct 3D drag-manipulation — gating here would strand the renderer's live preview (the mesh is already moved), so a filtered member is still directly draggable in 3D by design.
4950
5720
  dragMoveEnabled:()=>dragMoveOn, // the 3D view gates its plain member-drag on this
4951
5721
  dragMoveHint:()=>{if(dragHintShown)return;dragHintShown=true;try{localStorage.setItem('steel:dragmovehint:v1','1');}catch(_){}toast('Drag to move/copy is off — turn it on in the Move / Copy menu, or use the Move (M) / Copy (C) tools');},
4952
- onCopyDrag3d:(ids,dxMm,dyMm)=>{const r6=n=>Math.round(n*1e6)/1e6; // Ctrl+drag copy: mm delta → plan px (Y FLIPPED), clone + translate + select (direct manipulation, not gated by the Select filter — see onMoveMember)
4953
- edit(()=>{const ns=new Set();for(const id of (ids||[])){const src=byId(id);if(!src)continue;const pl=planeOf(id);const k=304.8/((pl&&pl.pt_per_ft>0)?pl.pt_per_ft:1); // mm→px in the SOURCE plane's own scale (sheets may differ)
4954
- const c=cloneMember(src);translateMembers([c],[r6(dxMm/k),r6(-dyMm/k),0]);pl.members=pl.members||[];pl.members.push(c);ns.add(c.id);}selIds=ns;}); // clone lands on the SOURCE's plane (a cross-sheet selection copies each member onto its own sheet, not the active one)
5722
+ onCopyDrag3d:(ids,dxMm,dyMm)=>{ // Ctrl+drag copy: WORLD MM straight across the boundary now — it owns the per-plane mm→px conversion (direct manipulation, not gated by the Select filter — see onMoveMember)
5723
+ edit(()=>{selIds=new Set(MC().copyDragMm(ids,[dxMm,dyMm],planeOf));}); // each clone lands on its SOURCE's plane at THAT plane's scale (a cross-sheet selection copies each member onto its own sheet, not the active one)
4955
5724
  toast('Copied '+(ids?ids.length:0)+' member'+((ids&&ids.length===1)?'':'s'));},
4956
- onMoveEndpoint:(id,end,wp)=>{edit(()=>{const m=byId(id);if(m&&Array.isArray(m.wp)&&m.wp.length>=2)m.wp[end]=wp;});}, // 3D end-node drag → write just that endpoint (direct manipulation, not gated by the Select filter — see onMoveMember)
4957
- onElevateMember:(id,dIn)=>{edit(()=>{const m=byId(id);if(!m)return;ensureMeta(m); // 3D Alt-drag → raise/lower T.O.S by dIn inches (direct manipulation, not gated by the Select filter — see onMoveMember)
4958
- if(m.role==='column'){m.col.tos=(m.col.tos!=null?m.col.tos:defaultTOS)+dIn;m.col.bos=(m.col.bos!=null?m.col.bos:0)+dIn;m.col.tosDef=false;} // rigid raise (bos null→0, both shift) so the column isn't stretched
4959
- else m.ends.forEach(e=>{e.tos=(e.tos!=null?e.tos:defaultTOS)+dIn;e.tosDef=false;});});},
5725
+ onMoveEndpoint:(id,end,wp)=>{edit(()=>{const m=byId(id);if(m&&Array.isArray(m.wp)&&m.wp.length>=2)MC().setEndpoint(m,end,wp);});}, // 3D end-node drag → write just that endpoint. The wp-shape guard stays HERE, not inside the primitive: setEndpoint's other two callers should throw on a broken member rather than be silently skipped (direct manipulation, not gated by the Select filter — see onMoveMember)
5726
+ onElevateMember:(id,dIn)=>{edit(()=>{const m=byId(id);if(!m)return; // 3D Alt-drag → raise/lower T.O.S by dIn inches (direct manipulation, not gated by the Select filter — see onMoveMember). elevateBy calls ensureMeta itself, as translate and retargetTos do, so the call site no longer duplicates it; planeOfMember below needs no normalisation (it matches by object identity)
5727
+ const pl=planeOfMember(m),base=(pl?(pl.default_tos!=null?pl.default_tos:0):defaultTOS); // OWNING sheet by OBJECT identity (ids are only sheet-unique — planeOf(id) would hit the first sheet carrying that id, not necessarily this member's). Materialize an unset elevation from that sheet's datum — the 3D measures dz from that sheet's geometry, so adding it to the ACTIVE sheet's default would land the member off by the difference between the two defaults
5728
+ ModelCmd.elevateBy(m,dIn,base);});}, // `base` is passed IN, never resolved inside: it is the OWNING sheet's datum, and the boundary's own defaultTosIn is the editor GLOBAL. Unifying them here would erase a pre-existing difference this refactor must preserve
4960
5729
  onTrimExtend:(targetId)=>{const tm=byId(targetId);
4961
- if(tm&&isBrace(tm)){toast('A brace can’t be an extend/trim target');return;} // same rule as 2D: never target a brace's invisible baseline
4962
- if(tm){geoMode=null;setGeo();snapEndMulti(sel2d(),tm.wp[0],tm.wp[1]);}}, // 3D Trim/Extend → every selected member's nearest end to the target line (snapEndMulti skips braces)
5730
+ if(tm&&isBrace(tm)){geoMode=null;setGeo();toast('A brace can’t be an extend/trim target');return;} // same rule as 2D: never target a brace's invisible baseline
5731
+ // ponytail: PLAN-LOCAL. snapEndMulti works in one sheet's display px, so this is exact only while the
5732
+ // target and every selected member live on the ACTIVE sheet. Cross-sheet it degrades twice: an
5733
+ // off-sheet target's wp is read in the active sheet's scale, and sel2d() silently drops off-sheet
5734
+ // members (3D selection is model-wide, so the user can select them). Guarded below rather than
5735
+ // silently doing the wrong thing. Upgrade path: intersect in scene mm, then invert each result with
5736
+ // that member's own plan scale (scaleFor/planScaleOf) — i.e. the same seam, once members are
5737
+ // model-level and no longer carry per-sheet display coordinates.
5738
+ if(!tm)return;
5739
+ const own=planeOfMember(tm),sel=sel2d(),off=selArr().filter(m=>!P.members.includes(m)); // off-sheet by OBJECT identity — a length comparison would false-refuse whenever two sheets share a bare member id
5740
+ if(own&&own!==P){geoMode=null;setGeo();toast('Trim/Extend needs the target on the open sheet — switch to '+(own.sheet||'its sheet')+' first');return;}
5741
+ if(off.length){geoMode=null;setGeo();toast('Trim/Extend needs every selected member on the open sheet — '+off.length+' '+(off.length===1?'is':'are')+' on another sheet. Deselect them or switch sheets.');return;}
5742
+ geoMode=null;setGeo();snapEndMulti(sel,tm.wp[0],tm.wp[1]);}, // 3D Trim/Extend → every selected member's nearest end to the target line (snapEndMulti skips braces)
4963
5743
  onSplit:(id,wp)=>{const m=byId(id);if(m){doSplit(m,wp);sync3D();}}, // 3D Split → cut at the clicked point on the member
4964
5744
  getDims3d:()=>C.dims3d||[],
4965
5745
  getGrid:()=>(P&&P.grid)||null, // the ACTIVE plan's structural grid for the 3D render + plan-locked snapping (per-plan, display-space)
@@ -4989,10 +5769,15 @@ const view3dApi={
4989
5769
  newDim3dId:()=>'d3'+Date.now()+'_'+(dimSeq++), // same scheme as 2D dim ids (Date.now + dimSeq tie-breaker)
4990
5770
  fmtLen:(mm)=>fmtFtIn(mm/304.8*12),
4991
5771
  toast:(m)=>toast(m),
5772
+ teklaSelectionIds, // Ctrl+Shift drag-out: the sendable member ids (the badge count and the payload are the same list)
5773
+ teklaSendBusy:()=>teklaSendBusy, // one drop at a time — the view refuses to start a second drag mid-send
5774
+ onSendToTekla:(ids)=>sendSelectionToTekla(ids),
4992
5775
  // 3D Move/Copy: the 3D view reads the armed tool + counts, and hands commit offsets back in scene mm.
4993
5776
  cmState:()=>cmTool?{tool:cmTool,array:cmArrayMode,count:cmCount,countA:cmCountA,countB:cmCountB}:null,
4994
- onTransform3d:(offsMm)=>{const k=304.8/((P&&P.pt_per_ft>0)?P.pt_per_ft:1),r6=(n)=>Math.round(n*1e6)/1e6; // mm → plan px (Y FLIPPED, matching dispToMm) + inches for dz; r6 kills float-noise before it persists into wp
4995
- cmApplyOffsets(offsMm.map(o=>[r6(o[0]/k),r6(-o[1]/k),r6((o[2]||0)/25.4)]));},
5777
+ // mm → plan px (Y FLIPPED) + inches for dz, now owned by the model boundary. toDisplayOffsets MUTATES
5778
+ // NOTHING on purpose: cmApplyOffsets below is what moves the members, and it also owns the empty-selection
5779
+ // toast, the 100-copy cap and the distance toast — which measures from these same ROUNDED offsets.
5780
+ onTransform3d:(offsMm)=>{cmApplyOffsets(MC().toDisplayOffsets(offsMm));},
4996
5781
  disarmTransform:()=>{if(cmTool){disarmCm();render();}}, // the 3D dim tool arming kicks Move/Copy off the left-click
4997
5782
  // 3D draw-on-plane (spec §7): the editor's add-member mode + profile drive it; two plane picks (scene mm) come back here.
4998
5783
  addModeActive:()=>mode==='add',
@@ -5012,7 +5797,7 @@ const view3dApi={
5012
5797
  const mfNote=/(^|[^A-Z])MF/i.test(addProfile||'')?'moment':''; // a moment-frame profile keeps the auto note ensureMeta gives 2D-drawn members
5013
5798
  m.ends=[{tos:near(zA)?null:zA,note:mfNote,tosDef:near(zA),detail:''},{tos:near(zB)?null:zB,note:mfNote,tosDef:near(zB),detail:''}];}
5014
5799
  if((addType==='column')===(m.role==='column'))m.memberType=addType; // 3D geometry decides column-vs-beam; only stamp the panel's type when it agrees with that role
5015
- m.rfi=(_wt(addProfile)==null);P.members.push(m);
5800
+ m.rfi=(_wt(addProfile)==null);MC().addMembers(P,[m]);
5016
5801
  if(addProfile&&!profs.includes(addProfile)){profs.push(addProfile);profs.sort();}
5017
5802
  selIds=new Set([id]);});
5018
5803
  const asCol=hIn<6&&dzIn>6;
@@ -5032,7 +5817,7 @@ const view3dApi={
5032
5817
  const cur=(m.col.bos!=null?m.col.bos:0);
5033
5818
  if(Math.abs(bosIn-cur)<0.02){toast('Column base already at that level');return;}
5034
5819
  const dir=bosIn<cur?'extended':'trimmed'; // lower base = longer column = extended; higher = trimmed
5035
- edit(()=>{m.col.bos=bosIn;}); // set BOS only (leave tosDef — the top isn't edited); the base plate re-seats at the new base via expandBasePlate, same undo
5820
+ edit(()=>{ModelCmd.setBos(m.col,bosIn);}); // set BOS only (leave tosDef — the top isn't edited); the base plate re-seats at the new base via expandBasePlate, same undo
5036
5821
  // Report the ACTUAL result: a snapped level when honored, else the ft-in elevation; call out the clamp so a
5037
5822
  // pick above the min stub isn't misreported as landing on the snapped level.
5038
5823
  const where=clamped?(fmtFtIn(bosIn)+' (clamped to a 1′ minimum stub)'):(p.snapped?(p.label||'a level'):fmtFtIn(bosIn));
@@ -6110,7 +6895,7 @@ let bar3dWired=false;
6110
6895
  function seg3dActive(sel,attr,val){document.querySelectorAll(sel+' button').forEach(b=>b.classList.toggle('on',b.getAttribute(attr)===val));}
6111
6896
  // Reflect the live projection / display mode into the Camera + Display dropdowns: tick the active menu item AND label the trigger button, so the current mode shows without opening the menu.
6112
6897
  function reflectProj(){const V=window.Steel3DView;if(!V)return;const p=V.projection();seg3dActive('#m3dProj','data-proj',p);const b=document.getElementById('m3dProjBtn');if(b)b.textContent=(p==='ortho'?'Ortho':'Persp')+' ▾';}
6113
- function reflectMode(){const V=window.Steel3DView;if(!V)return;const m=V.mode();seg3dActive('#m3dMode','data-mode',m);const b=document.getElementById('m3dModeBtn');if(b)b.textContent=(m==='wire'?'Wire':m==='xray'?'X-ray':'Solid')+' ▾';}
6898
+ function reflectMode(){const V=window.Steel3DView;if(!V)return;const m=V.mode();seg3dActive('#m3dMode','data-mode',m);const b=document.getElementById('m3dModeBtn');if(b)b.textContent=(m==='wire'?'Wire':m==='xray'?'X-ray':m==='realistic'?'Realistic':m==='shadowed'?'Shadowed':'Solid')+' ▾';}
6114
6899
  function wire3DBar(){if(bar3dWired||!window.Steel3DView)return;bar3dWired=true;
6115
6900
  // Camera + Display dropdowns — open/close like Clip/Work/Plane; picking an item sets the mode, ticks it, and relabels the trigger (reflectProj/reflectMode).
6116
6901
  const projBtn=document.getElementById('m3dProjBtn'),projMenu=document.getElementById('m3dProj');
@@ -6390,6 +7175,11 @@ function applyDetailRename(old,nw){nw=(nw||'').trim();if(!nw||nw===old)return fa
6390
7175
  if(pl.details)for(const d of pl.details)if(d.text===old)d.text=nw;
6391
7176
  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;}}
6392
7177
  if(C.custom_details[old]!=null){C.custom_details[nw]=C.custom_details[old];delete C.custom_details[old];}
7178
+ // The connection library is keyed to the callout TEXT, so a rename that skipped it would leave every row
7179
+ // pointing at a name nothing uses any more — each end would silently stop resolving ("nothing says what
7180
+ // this builds") with no visible cause. Harmless when `detail` was only a display string; not any more,
7181
+ // now that the row carries what the detail BUILDS.
7182
+ for(const r of (C.connections||[]))if(r&&r.detail===old)r.detail=nw;
6393
7183
  scheduleSave();return true;}
6394
7184
  function detTexts(){const seen=new Set(),out=[];
6395
7185
  for(const d of (P.details||[])) if(!seen.has(d.text)){seen.add(d.text);out.push(d.text);}
@@ -6507,23 +7297,102 @@ function toggleShearPlates(){
6507
7297
  }
6508
7298
  }
6509
7299
  {const _s=document.getElementById('spBtn');if(_s)_s.onclick=toggleShearPlates;}
7300
+ // --- Build from details: turn every resolvable detail callout into real connection geometry, model-wide.
7301
+ // The skips are the important half of the result, so they get a modal rather than a toast that scrolls
7302
+ // past — with an explicit second action for the ones that were protected rather than broken. ---
7303
+ const DSKIP_LABEL={'no-row':'Nothing says what the callout means','row-has-no-recipe':'Nothing says what the detail builds',
7304
+ 'kind-mismatch':'The detail builds the wrong kind for that end','conflict':'The callout and the connection reference disagree',
7305
+ 'ambiguous':'The callout matches more than one connection','no-schedule-match':'That size is not in the detail’s schedule',
7306
+ 'verified':'Someone confirmed it','custom':'An imported connection is there','tuned':'Tuned by hand','no-detail':'No detail on that end',
7307
+ 'duplicate-id':'More than one member has that name, so the connection could land on the wrong one'};
7308
+ const DSKIP_PROTECTED={verified:1,custom:1,tuned:1}; // skipped to protect existing work — the only ones an overwrite could take
7309
+ function describeSkip(s){return (s.m&&s.m.id?s.m.id:'?')+' '+whichLabel(s.which);}
7310
+ function runApplyAllDetails(force){
7311
+ const res=applyAllDetails({force:force});
7312
+ if(!res.applied&&!res.already&&!res.skipped.length){toast('No detail callouts are bound to member ends yet — bind one with the ⌖ button on a member’s Connection detail.');return;}
7313
+ if(res.applied){pendingConnSel=res.lastId;render();}
7314
+ const groups={};for(const s of res.skipped)(groups[s.reason]=groups[s.reason]||[]).push(s);
7315
+ const order=Object.keys(groups).sort((a,b)=>groups[b].length-groups[a].length);
7316
+ const protectedN=order.filter(k=>DSKIP_PROTECTED[k]).reduce((n,k)=>n+groups[k].length,0);
7317
+ const S=detailModalShell(res.applied?('Built '+res.applied+' connection'+(res.applied===1?'':'s')):'Nothing new to build');
7318
+ const {el,body,foot,close}=S;
7319
+ const head=[];
7320
+ if(res.applied)head.push('Built '+res.applied+' from their detail callouts.');
7321
+ if(res.already)head.push(res.already+' '+(res.already===1?'was':'were')+' already exactly right.');
7322
+ if(!res.applied&&!res.already)head.push('None of the bound callouts could be built yet.');
7323
+ body.append(el('div','font-size:12px;line-height:1.5;color:var(--mut);margin-bottom:'+(order.length?'10px':'0'),head.join(' ')));
7324
+ if(order.length){
7325
+ const lab=el('div',null,'Left alone — '+res.skipped.length);lab.className='elab';body.append(lab);
7326
+ const list=el('div','max-height:220px;overflow:auto;scrollbar-width:thin;scrollbar-color:#475569 transparent;border:1px solid var(--line);border-radius:6px;padding:6px 8px');
7327
+ list.className='dnotes';
7328
+ for(const k of order){
7329
+ const g=groups[k];
7330
+ const line=el('div','margin:0 0 6px');
7331
+ line.append(el('div','font-size:12px;color:var(--text)',(DSKIP_LABEL[k]||k)+' — '+g.length));
7332
+ line.append(el('div','font-size:11px;color:var(--mut);line-height:1.45',
7333
+ g.slice(0,8).map(describeSkip).join(', ')+(g.length>8?(' and '+(g.length-8)+' more'):'')));
7334
+ list.append(line);}
7335
+ body.append(list);}
7336
+ const done=el('button',null,'Done');done.onclick=close;
7337
+ if(protectedN&&!force){
7338
+ const over=el('button',null,'Replace the '+protectedN+' protected one'+(protectedN===1?'':'s'));
7339
+ over.className='danger';
7340
+ over.onclick=async()=>{close();
7341
+ if(await confirmDanger({title:'Replace work that was protected?',
7342
+ body:protectedN+' end'+(protectedN===1?' was':'s were')+' left alone because someone confirmed '+(protectedN===1?'it':'them')+', tuned '+(protectedN===1?'it':'them')+' by hand, or imported the geometry.\n\nReplacing rebuilds '+(protectedN===1?'it':'them')+' from the detail, and imported geometry cannot be recovered by rebuilding. This can be undone with Ctrl+Z.',
7343
+ confirmLabel:'Replace them'}))runApplyAllDetails(true);};
7344
+ foot.append(over);}
7345
+ foot.append(done);done.focus();}
7346
+ {const _d=document.getElementById('dApplyBtn');if(_d)_d.onclick=()=>runApplyAllDetails(false);}
6510
7347
  function renderConnTable(){const tb=document.getElementById('connBody');if(!tb)return;
6511
7348
  document.getElementById('connCompHead').textContent=(PLAT_LABEL[connPlat]||connPlat)+' id';
6512
7349
  const rows=C.connections||[];
6513
7350
  if(!rows.length){tb.innerHTML='<tr><td colspan=5 style="text-align:center;padding:32px;color:var(--mut);font-size:12px">No connections defined — click + New row to add the first.</td></tr>';updConnBtn();return;}
7351
+ const dupKeys=new Set(dupDetailKeys()); // detail numbers that two or more rows share, once for the whole table
6514
7352
  const srcChip=s=>s==='drawing'?'<span class="chip assumed">drawing</span>':s==='company-rules'?'<span class=chip>company-rules</span>':'<span class=chip style="border-color:#1d4ed8;color:#93c5fd">user</span>';
6515
7353
  tb.innerHTML=rows.map(r=>`<tr data-id="${esc(r.id)}">`
6516
7354
  +`<td><input class="combo ftab-inp" data-src=conntypes data-f=type value="${esc(r.type||'')}" placeholder="moment" autocomplete=off></td>`
6517
- +`<td><input class="combo ftab-inp" data-src=details data-f=detail value="${esc(r.detail||'')}" placeholder="e.g. 50S504" autocomplete=off></td>`
7355
+ +`<td><input class="combo ftab-inp" data-src=details data-f=detail value="${esc(r.detail||'')}" placeholder="e.g. 50S504" autocomplete=off>`
7356
+ // What this detail BUILDS, under its number — the row is now a definition, not only a mapping, and a
7357
+ // row nobody has defined must say so rather than look identical to one that is ready to use.
7358
+ // Two authoring faults only this table can see, so this is where they get said. A COLLIDING detail
7359
+ // number makes every end carrying that callout un-buildable (the resolver refuses to guess between the
7360
+ // rows) while both rows look perfectly healthy here; a SHADOWED schedule row is one the author wrote
7361
+ // that can never win. Both were computed and documented as warnings but wired to nothing until now.
7362
+ +`<div class=cbuilds>${r.recipe&&r.recipe.kind
7363
+ ? `Builds a <b>${esc(recipeSummary(r.recipe))}</b>${(r.notes||[]).length?` · ${(r.notes||[]).length} note${(r.notes||[]).length>1?'s':''}`:''}`
7364
+ : `<span class=cundef>Nothing says what this builds</span>`}`
7365
+ +(dupKeys.has(normDetailKey(r.detail))?`<span class=cwarn data-tip="Another row uses the same detail number, so no member end can be built from either — give them distinct numbers.">shares this number with another row</span>`:'')
7366
+ +((r.recipe&&shadowedSchedRows(r.recipe.schedule).length)?`<span class=cwarn data-tip="A size row here is already covered by an earlier, broader row, so it can never apply.">${shadowedSchedRows(r.recipe.schedule).length} size row${shadowedSchedRows(r.recipe.schedule).length>1?'s':''} can never apply</span>`:'')
7367
+ +`</div></td>`
6518
7368
  +`<td><input class=ftab-inp data-f=target value="${esc((r.targets&&r.targets[connPlat])||'')}" placeholder="e.g. 146" autocomplete=off></td>`
6519
7369
  +`<td class=csrc>${srcChip(r.source||'user')}</td>`
6520
7370
  +`<td><button class="danger cdel" data-tip="Remove this row">✕</button></td></tr>`).join('');
6521
7371
  tb.querySelectorAll('tr[data-id]').forEach(tr=>{const id=tr.dataset.id;const row=connRowById(id);if(!row)return;
6522
7372
  tr.querySelector('[data-f=type]').onchange=e=>edit(()=>{row.type=e.target.value.trim();});
6523
- tr.querySelector('[data-f=detail]').onchange=e=>edit(()=>{row.detail=e.target.value.trim();});
7373
+ // Re-render after a DETAIL edit: this is the field the duplicate-number warning keys on, and the row it
7374
+ // collides with is a different row, so the table cannot update itself in place. Without this the warning
7375
+ // only appeared the next time the library was opened — i.e. never, at the moment you create the clash.
7376
+ tr.querySelector('[data-f=detail]').onchange=e=>{edit(()=>{row.detail=e.target.value.trim();});renderConnTable();};
6524
7377
  tr.querySelector('[data-f=target]').onchange=e=>edit(()=>{if(!row.targets)row.targets={};const v=e.target.value.trim();if(v)row.targets[connPlat]=v;else delete row.targets[connPlat];});
6525
- tr.querySelector('.cdel').onclick=()=>{edit(()=>{C.connections=C.connections.filter(x=>x.id!==id);
6526
- for(const pl of (C.plans||[]))for(const m of (pl.members||[])){if(m.col&&m.col.conn===id)m.col.conn='';for(const en of (m.ends||[]))if(en&&en.conn===id)en.conn='';}});renderConnTable();};});
7378
+ // Deleting a row now costs more than a mapping: it also destroys the detail's RECIPE, schedule and
7379
+ // notes. So warn when anything is actually using it, and clear joints[].conn as well as ends[].conn —
7380
+ // that reference already existed in the schema and was never cleared here, so it dangled silently.
7381
+ // The joints themselves are KEPT: the geometry is real work, only its provenance link goes.
7382
+ tr.querySelector('.cdel').onclick=async()=>{
7383
+ const ends=connEndUsage(id), joints=(C.joints||[]).filter(j=>j&&j.conn===id).length, hasRecipe=!!(row.recipe&&row.recipe.kind);
7384
+ if(hasRecipe||ends||joints){
7385
+ const label=row.detail?('Detail '+row.detail):('Connection '+id);
7386
+ const lines=[label+' still has work pointing at it:'];
7387
+ if(hasRecipe)lines.push('• what it builds ('+row.recipe.kind+(Array.isArray(row.recipe.schedule)&&row.recipe.schedule.length?', plus a '+row.recipe.schedule.length+'-row schedule':'')+')'+((row.notes||[]).length?' and '+row.notes.length+' note'+(row.notes.length>1?'s':''):''));
7388
+ if(ends)lines.push('• '+ends+' member end'+(ends>1?'s':'')+' referencing it');
7389
+ if(joints)lines.push('• '+joints+' placed connection'+(joints>1?'s':'')+' citing it');
7390
+ lines.push('','The connections already built stay in the model — they just stop saying which detail they came from. This can be undone with Ctrl+Z.');
7391
+ if(!await confirmDanger({title:'Delete '+label+'?',body:lines.join('\n'),confirmLabel:'Delete it'}))return;
7392
+ }
7393
+ edit(()=>{C.connections=C.connections.filter(x=>x.id!==id);
7394
+ for(const pl of (C.plans||[]))for(const m of (pl.members||[])){if(m.col&&m.col.conn===id)m.col.conn='';for(const en of (m.ends||[]))if(en&&en.conn===id)en.conn='';}
7395
+ for(const j of (C.joints||[]))if(j&&j.conn===id)delete j.conn;});renderConnTable();};});
6527
7396
  updConnBtn();}
6528
7397
  document.getElementById('connBtn').onclick=openConnLib;
6529
7398
  document.getElementById('connClose').onclick=closeConnLib;
@@ -6839,6 +7708,412 @@ const COMBO_SRC={
6839
7708
  // back on select); type/detail follow for the human. Kept here so COMBO_SRC + cFld + wireConn agree.
6840
7709
  function connLabel(r){return r.id+' · '+(r.type||'?')+(r.detail?' · '+r.detail:'');}
6841
7710
  function connRowById(id){return (C.connections||[]).find(r=>r&&r.id===id)||null;}
7711
+ // How many member ends reference this library row — model-wide (a column base counts as one end). Used to
7712
+ // tell the user what a row deletion would cut loose before it happens.
7713
+ function connEndUsage(id){let n=0;
7714
+ for(const pl of (C.plans||[]))for(const m of (pl.members||[])){if(!m)continue;
7715
+ if(m.col&&m.col.conn===id)n++;
7716
+ for(const en of (m.ends||[]))if(en&&en.conn===id)n++;}
7717
+ return n;}
7718
+
7719
+ // ── detail → connection recipe ──────────────────────────────────────────────────────────────────
7720
+ // >>> BEGIN detail-recipes mirror >>> (the markers are load-bearing: detail-recipes-parity.test.ts
7721
+ // slices exactly this block out of the page and runs it against server/detail-recipes.ts over a shared
7722
+ // fixture table, so the two cannot drift. Move a marker and that test fails by name.)
7723
+ // MIRRORS server/detail-recipes.ts (this file is an import-less standalone doc, exactly as it already
7724
+ // mirrors scoreContract / rfiList / redundantDups). The TS module is the TESTED SOURCE OF TRUTH — keep
7725
+ // the two in sync; detail-recipes.test.ts is where the rules are pinned.
7726
+ //
7727
+ // A drawing detail ("5-S504") is a TYPICAL arrangement + a SCHEDULE that varies the numbers by member
7728
+ // size + the NOTES that come with it. All of that lives on the connections[] row, so binding a callout to
7729
+ // an end can now BUILD the connection instead of only recording intent.
7730
+ //
7731
+ // Everything here REFUSES rather than guesses: an ambiguous callout, a stale conn disagreeing with the
7732
+ // visible callout, or a size the schedule does not cover returns a reason and the candidates to choose
7733
+ // between. That is what makes "apply to every end" safe to offer.
7734
+
7735
+ // A matching aid, NEVER an identity: -/ are the same separator, but . _ and zero-padding are left alone
7736
+ // (squashing those merges A.01-S501 with A-1-S501, which can be two different details).
7737
+ function normDetailKey(t){return String(t==null?'':t).trim().toUpperCase().replace(/\s+/g,' ').replace(/\s*[-/]\s*/g,'/');}
7738
+ function connRowsForDetail(text){const k=normDetailKey(text);if(!k)return [];return (C.connections||[]).filter(r=>r&&normDetailKey(r.detail)===k);}
7739
+ function dupDetailKeys(){const seen={},out=[];for(const r of (C.connections||[])){const k=normDetailKey(r&&r.detail);if(k)seen[k]=(seen[k]||0)+1;}
7740
+ for(const k in seen)if(seen[k]>1)out.push(k);return out;}
7741
+ // Specificity rank, most specific first. A row carrying several matchers ranks by its MOST specific one —
7742
+ // without that the rank is undefined and the winner depends on evaluation accident.
7743
+ function schedRank(mt){const m=mt||{};return m.profile?1:m.profilePrefix?2:m.depth?3:m.role?4:5;}
7744
+ function _secDepthIn(profile){const row=(window.__AISC_SECTIONS||{})[canonProfile(profile).replace(/\s+/g,'')];return (row&&isFinite(row[0]))?row[0]:null;}
7745
+ function schedMatches(mt,m){const q=mt||{};
7746
+ if(q.profile&&canonProfile(m&&m.profile)!==canonProfile(q.profile))return false;
7747
+ if(q.profilePrefix&&canonProfile(m&&m.profile).indexOf(canonProfile(q.profilePrefix))!==0)return false;
7748
+ if(q.role&&((m&&m.role==='column')?'column':'beam')!==q.role)return false;
7749
+ if(q.depth){const inch=_secDepthIn(m&&m.profile);
7750
+ if(inch==null)return false; // an untabulated designation FAILS a depth matcher rather than being assigned one — that is why profilePrefix exists beside it
7751
+ const d=q.depth.unit==='mm'?inch*25.4:inch;
7752
+ if(q.depth.min!=null&&d<q.depth.min)return false;
7753
+ if(q.depth.max!=null&&d>q.depth.max)return false;}
7754
+ return true;}
7755
+ function pickSchedRow(sched,m){if(!Array.isArray(sched)||!sched.length)return null;let best=null;
7756
+ sched.forEach((row,index)=>{if(!row||!schedMatches(row.match,m))return;const rank=schedRank(row.match);
7757
+ if(!best||rank<best.rank)best={row,index,rank};}); // strictly < → the FIRST row at a rank wins (document order breaks a tie, deterministically)
7758
+ return best;}
7759
+ function shadowedSchedRows(sched){if(!Array.isArray(sched))return [];const out=[],seen={};let sawCatchAll=false;
7760
+ sched.forEach((row,i)=>{if(!row)return;
7761
+ const mt=row.match||{},sig=JSON.stringify([canonProfile(mt.profile),canonProfile(mt.profilePrefix),mt.depth||null,mt.role||null]);
7762
+ if(seen[sig]){out.push(i);return;}
7763
+ if(sawCatchAll){out.push(i);return;} // nothing after a catch-all is reachable — it matches every member
7764
+ seen[sig]=1;if(schedRank(mt)===5)sawCatchAll=true;});
7765
+ return out;}
7766
+ function mergeRecipeParams(typical,row){return Object.assign({},typical||{},row||{});}
7767
+ // Conservative on purpose: a key on one side only counts as DIFFERENT, because the absent side rides an
7768
+ // engine default that may or may not equal the explicit value. A false "differs" costs one named skip; a
7769
+ // false "same" silently overwrites someone's tuning.
7770
+ function recipeParamsDiffer(a,b){const x=a||{},y=b||{},ks={};for(const k in x)ks[k]=1;for(const k in y)ks[k]=1;
7771
+ for(const k in ks){if(!(k in x)||!(k in y))return true;if(!Object.is(x[k],y[k]))return true;}
7772
+ return false;}
7773
+ function jointAtFor(which){return which==='col'?'base':'end'+which;}
7774
+ const RECIPE_KIND_TARGET={'base-plate':'col','shear-plate':'end'};
7775
+ function endObjFor(m,which){if(!m)return {};return which==='col'?(m.col||{}):((m.ends||[])[which]||{});}
7776
+ // Resolve one member end to {ok:true,kind,params,notes,rowId,matched} or a NAMED refusal carrying the
7777
+ // candidates the user can pick between — a refusal must never be a dead end.
7778
+ function resolveDetail(m,which){
7779
+ const rows=(C.connections||[]).filter(r=>r&&typeof r.id==='string');
7780
+ const end=endObjFor(m,which);
7781
+ const byId=end.conn?rows.find(r=>r.id===end.conn):null;
7782
+ const byText=connRowsForDetail(end.detail);
7783
+ let row=null;
7784
+ if(byId){
7785
+ // The editor writes conn and detail through INDEPENDENT fields, so an end really can carry a stale row
7786
+ // reference beside a newer callout. Building the referenced row while the drawing shows another detail
7787
+ // is the "wrong connection rather than no connection" failure — refuse and name both.
7788
+ if(byText.length&&!byText.some(r=>r.id===byId.id))
7789
+ return {ok:false,reason:'conflict',message:'This end points at connection “'+byId.id+'” but its callout reads “'+(end.detail||'')+'”. Pick which one is right.',candidates:[byId.id].concat(byText.map(r=>r.id))};
7790
+ row=byId;
7791
+ }else if(byText.length>1){
7792
+ return {ok:false,reason:'ambiguous',message:'“'+(end.detail||'')+'” matches '+byText.length+' connections. Pick which one it means.',candidates:byText.map(r=>r.id)};
7793
+ }else if(byText.length===1)row=byText[0];
7794
+ if(!row){
7795
+ if(end.conn)return {ok:false,reason:'no-row',message:'This end points at a connection that no longer exists.'};
7796
+ return normDetailKey(end.detail)
7797
+ ? {ok:false,reason:'no-row',message:'Nothing says what “'+end.detail+'” builds yet.'}
7798
+ : {ok:false,reason:'no-detail',message:'No connection detail on this end yet.'};
7799
+ }
7800
+ const rec=row.recipe,kind=(rec&&typeof rec.kind==='string')?rec.kind.trim():'';
7801
+ if(!kind)return {ok:false,reason:'row-has-no-recipe',message:'Nothing says what “'+(row.detail||row.id)+'” builds yet.',candidates:[row.id]};
7802
+ const want=RECIPE_KIND_TARGET[kind];
7803
+ // A brace carries role 'beam', so a shear-plate recipe LOOKS applicable — but expandJoints refuses it
7804
+ // (beam.isBrace → skipped), and auto-detail and the Favourites bake already exclude braces. Without this
7805
+ // the panel would say "built a shear plate" for geometry the engine then silently drops. The rule is
7806
+ // memberType, not role — matched to steel-confidence's isBraceMember so the mirror and module agree.
7807
+ if(want&&typeof m.memberType==='string'&&m.memberType.trim().toLowerCase()==='brace')
7808
+ return {ok:false,reason:'brace-unsupported',message:'A brace can’t carry a '+String(kind).replace(/-/g,' ')+' — building it would produce nothing.',candidates:[row.id]}; // spelled out inline, NOT via kindLabel(): this block is sliced out and run standalone by the parity test, so it must not reach for a helper defined elsewhere on the page
7809
+ if(want&&((want==='col')!==(which==='col')))
7810
+ return {ok:false,reason:'kind-mismatch',message:'“'+(row.detail||row.id)+'” builds a '+kind+', which belongs on a '+(want==='col'?'column base, not a beam end':'beam end, not a column base')+'.',candidates:[row.id]};
7811
+ const hasSched=Array.isArray(rec.schedule)&&rec.schedule.length>0;
7812
+ const picked=hasSched?pickSchedRow(rec.schedule,m):null;
7813
+ // A schedule exists BECAUSE the numbers vary by size, so falling back to the typical for a size nobody
7814
+ // listed would be fabricating a value. Name it instead.
7815
+ if(hasSched&&!picked)
7816
+ return {ok:false,reason:'no-schedule-match',message:'“'+(row.detail||row.id)+'” has a size schedule that doesn’t cover '+((m&&m.profile)||'this member')+'.',candidates:[row.id]};
7817
+ return {ok:true,kind:kind,params:mergeRecipeParams(rec.params,picked&&picked.row.params),
7818
+ // Narrowed to {text, source?} exactly like the module's cleanNotes — returning the caller's own objects
7819
+ // would hand every other key on a contract-supplied note straight through to whatever renders it.
7820
+ notes:(Array.isArray(row.notes)?row.notes:[]).filter(n=>n&&typeof n.text==='string')
7821
+ .map(n=>typeof n.source==='string'?{text:n.text,source:n.source}:{text:n.text}),
7822
+ rowId:row.id,matched:picked?{index:picked.index,rank:picked.rank}:null};}
7823
+ // <<< END detail-recipes mirror <<<
7824
+
7825
+ // ── building a connection FROM a detail ─────────────────────────────────────────────────────────
7826
+ // The apply engine, kept free of DOM so the single-end button, the bulk action and any future caller
7827
+ // all go through one set of rules. Joint shape matches every other authoring path (auto-detail, the
7828
+ // Favourites apply at onInsertPlace, the IFC import): {id,kind,main,at,params,source} + conn.
7829
+
7830
+ // Unique vs ANY existing joint id, the same way bpJointId/spJointId are — NOT the single-shot
7831
+ // Date.now()+random() the favourite/import paths use. Those mint one id per user click; this one runs in a
7832
+ // synchronous sweep where Date.now() is constant for every end, leaving a 10k random space: a 200-end
7833
+ // model has an ~86% chance of at least one collision, and two joints sharing an id collide their part ids,
7834
+ // select the wrong connection, and make the params inspector edit whichever find() reaches first.
7835
+ function detailJointId(){const ids=new Set((C.joints||[]).map(j=>j&&j.id));
7836
+ let n=0,id='cx'+Date.now().toString(36)+Math.floor(Math.random()*1e4).toString(36);
7837
+ while(ids.has(id))id='cx'+Date.now().toString(36)+Math.floor(Math.random()*1e4).toString(36)+'-'+(++n);
7838
+ return id;}
7839
+ // A 'custom' (imported IFC) joint bound to this member. Custom joints carry `main` but never an `at` — the
7840
+ // favourite and import bakes both omit it — so jointAtEnd can never see one, which left the "an imported
7841
+ // connection is here" refusal permanently dead AND let a build drop a second, overlapping connection on
7842
+ // top of imported geometry. Matched by member alone, deliberately: without an `at` we cannot tell WHERE on
7843
+ // the member it sits, and refusing a whole member is the honest side of that ignorance.
7844
+ function customJointOn(memberId){return (C.joints||[]).find(j=>j&&j.kind==='custom'&&j.main===memberId)||null;}
7845
+ // Member ids that occur on more than one sheet. v1 ids are per-plan, so this really happens (two sheets
7846
+ // each reading a "B1"), and anything that matches joints by `main` alone cannot tell them apart.
7847
+ function duplicateMemberIds(){const seen={},dup=new Set();
7848
+ for(const pl of (C.plans||[]))for(const m of (pl.members||[])){if(!m||!m.id)continue;
7849
+ if(seen[m.id])dup.add(m.id);else seen[m.id]=1;}
7850
+ return dup;}
7851
+ // The joint already sitting at this end, if any — one connection per end, same rule the favourite/import
7852
+ // paths use (two overlapping joints would also make "edit on member" target the older one).
7853
+ function jointAtEnd(memberId,which){const at=jointAtFor(which);
7854
+ return (C.joints||[]).find(j=>j&&j.main===memberId&&(j.at===at||(which==='col'&&j.kind==='base-plate'&&!j.at)))||null;}
7855
+ // Every (member, end) in the MODEL that carries a callout or a library reference — the population the
7856
+ // bulk action walks. Model-wide, like joints and the selection.
7857
+ function detailEndTargets(){const out=[];
7858
+ for(const m of allMembers()){if(!m)continue;
7859
+ if(m.role==='column'){if(m.col&&(m.col.detail||m.col.conn))out.push({m,which:'col'});continue;}
7860
+ if(isBrace(m))continue; // a brace carries neither a shear plate nor a base plate — the engine skips the joint, so we must not claim to have applied one
7861
+ for(const w of [0,1]){const e=(m.ends||[])[w];if(e&&(e.detail||e.conn))out.push({m,which:w});}}
7862
+ return out;}
7863
+ /**
7864
+ * Why applying to this end would be REFUSED even though its detail resolves — the protection for work
7865
+ * that already exists. Returns null when it is safe to build.
7866
+ *
7867
+ * Bulk replacement across sheets is the most destructive thing in this feature, so it defaults to
7868
+ * skip-and-name for anything a human or an import put there. `force` is the explicit reviewed overwrite.
7869
+ */
7870
+ function detailApplyBlocker(m,which,res,force){
7871
+ const end=endObjFor(m,which),j=jointAtEnd(m.id,which);
7872
+ if(!force){
7873
+ if(end.connVerified===true)return {reason:'verified',text:'someone confirmed this end'};
7874
+ if(j&&j.verified===true)return {reason:'verified',text:'someone confirmed this connection'};
7875
+ if((j&&j.kind==='custom')||customJointOn(m.id))return {reason:'custom',text:'an imported connection is on this member — it cannot be rebuilt if replaced'};
7876
+ if(j&&j.source==='user'&&recipeParamsDiffer(j.params,res.params))return {reason:'tuned',text:'this one was tuned by hand'};
7877
+ }
7878
+ return null;}
7879
+ /**
7880
+ * Build the connection this end's detail describes. Caller owns the edit() wrapper so a bulk run is ONE
7881
+ * undo step; pass the resolution in so the caller can report without resolving twice.
7882
+ * Returns the new joint id.
7883
+ */
7884
+ function buildJointFromDetail(m,which,res){
7885
+ const at=jointAtFor(which),id=detailJointId();
7886
+ const joint={id,kind:res.kind,main:m.id,at,params:Object.assign({},res.params),source:'user',conn:res.rowId};
7887
+ // A fin plate wants its support recorded the same way auto-detail records it (geometry-inferred, and
7888
+ // optional — the engine places the plate off the beam end + axis either way).
7889
+ if(res.kind==='shear-plate'&&which!=='col'){const sup=spInferSupport(m,which);joint.secondaries=sup?[sup.id]:[];}
7890
+ if(!Array.isArray(C.joints))C.joints=[];
7891
+ C.joints=C.joints.filter(j=>!(j&&j.main===m.id&&(j.at===at||(which==='col'&&j.kind==='base-plate'&&!j.at))));
7892
+ C.joints.push(joint);
7893
+ // Point the end at the row it was built from, on BOTH sides: the end gains the library reference the
7894
+ // confidence report scores, and the joint cites the same row for its type/detail identity.
7895
+ const end=endObjFor(m,which);if(end)end.conn=res.rowId;
7896
+ return id;}
7897
+ /**
7898
+ * Resolve + build every end whose detail resolves. One edit() → one undo step for the whole sweep.
7899
+ * Returns {applied, already, skipped:[{m,which,reason,text}]} — the caller reports it; nothing is silent.
7900
+ */
7901
+ function applyAllDetails(opts){const force=!!(opts&&opts.force),only=opts&&opts.onlyRowId;
7902
+ const targets=detailEndTargets(),skipped=[];let applied=0,already=0,lastId=null;
7903
+ // v1 member ids are PLAN-LOCAL, and joints are matched model-wide by main+at — so two sheets each
7904
+ // holding a "B1" would have the second build silently replace the first one's joint. Every other
7905
+ // authoring path has the same exposure (it is the tracked reader id-uniqueness gap), but this action
7906
+ // sweeps every sheet in one click, which is what turns a latent edge into an easy one. Refuse those
7907
+ // ends by name rather than quietly losing a connection.
7908
+ const dupIds=duplicateMemberIds();
7909
+ const work=[];
7910
+ for(const t of targets){
7911
+ if(dupIds.has(t.m.id)){skipped.push({m:t.m,which:t.which,reason:'duplicate-id',text:'more than one member is called '+t.m.id});continue;}
7912
+ const res=resolveDetail(t.m,t.which);
7913
+ if(!res.ok){skipped.push({m:t.m,which:t.which,reason:res.reason,text:res.message});continue;}
7914
+ if(only&&res.rowId!==only)continue;
7915
+ const blk=detailApplyBlocker(t.m,t.which,res,force);
7916
+ if(blk){skipped.push({m:t.m,which:t.which,reason:blk.reason,text:blk.text});continue;}
7917
+ // Already exactly what the detail says → not work, and not a failure either. Counted separately so
7918
+ // "applied 0" never reads as "nothing happened" when the model is simply already correct.
7919
+ const j=jointAtEnd(t.m.id,t.which);
7920
+ if(j&&j.kind===res.kind&&!recipeParamsDiffer(j.params,res.params)&&j.conn===res.rowId&&endObjFor(t.m,t.which).conn===res.rowId){already++;continue;}
7921
+ work.push({t,res});}
7922
+ if(work.length)edit(()=>{for(const w of work){lastId=buildJointFromDetail(w.t.m,w.t.which,w.res);applied++;}});
7923
+ return {applied,already,skipped,lastId};}
7924
+
7925
+ // ── the two detail modals ───────────────────────────────────────────────────────────────────────
7926
+ // Both are built with createElement rather than an HTML string: every value shown here is MODEL data
7927
+ // (a detail number, a profile, a row's own label), and a contract string must never reach a markup
7928
+ // position. Same tokens as the other modals — .modal/.mbackdrop/.mpanel/.mhead/.elab/.hint/.danger.
7929
+
7930
+ /** Shell shared by the two: backdrop + panel + head + a footer, Esc/backdrop closing. */
7931
+ function detailModalShell(title){
7932
+ const el=(t,css,txt)=>{const n=document.createElement(t);if(css)n.style.cssText=css;if(txt!=null)n.textContent=txt;return n;};
7933
+ const back=el('div','position:fixed;inset:0;z-index:60;display:flex;align-items:center;justify-content:center');
7934
+ back.className='modal';
7935
+ const bd=el('div');bd.className='mbackdrop';
7936
+ // .mpanel is max-height:86vh with overflow:visible, so taller content spills OUTSIDE its own box — the
7937
+ // footer then renders below the fold and the primary button cannot be clicked at all. Measured in the
7938
+ // browser: a 4-option capture dialog put "Remember it" at y=1147 in a 950px viewport. So the panel is a
7939
+ // flex column with a pinned head/footer and only the BODY scrolls. The global `*` rule themes that
7940
+ // scrollbar, so no native white bar appears.
7941
+ const panel=el('div','width:min(520px,92vw);display:flex;flex-direction:column;max-height:86vh');panel.className='mpanel';
7942
+ const head=el('div','padding:14px 16px;border-bottom:1px solid var(--line);font-weight:600;flex:none',title);head.className='mhead';
7943
+ const body=el('div','padding:14px 16px;flex:1 1 auto;overflow-y:auto;min-height:0');
7944
+ const foot=el('div','padding:12px 16px;display:flex;gap:8px;justify-content:flex-end;border-top:1px solid var(--line);flex:none');
7945
+ panel.append(head,body,foot);back.append(bd,panel);document.body.appendChild(back);
7946
+ const close=()=>{document.removeEventListener('keydown',onKey,true);back.remove();};
7947
+ const onKey=e=>{if(e.key==='Escape'){e.stopPropagation();close();}};
7948
+ document.addEventListener('keydown',onKey,true); // capture, so the editor's global Esc handlers do not win over an open modal
7949
+ bd.onclick=close;
7950
+ return {el,back,body,foot,close};}
7951
+
7952
+ /**
7953
+ * "Remember this as 5-S504" — teach the library what a detail means, from an end already built.
7954
+ *
7955
+ * The SCOPE is the whole point of the dialog. Recording what the user did is what builds a schedule
7956
+ * without ever parsing a schedule table, but done silently it turns one tuned end into a project-wide
7957
+ * rule. So each option shows how many ends it would govern, and the default is the narrowest.
7958
+ */
7959
+ function openCaptureModal(m,which){
7960
+ const e=endObjFor(m,which),j=jointAtEnd(m.id,which);
7961
+ if(!e||!j){toast('Build a connection on this end first, then you can remember what it means');return;}
7962
+ const text=String(e.detail||'').trim();
7963
+ const opts=captureScopeOptions(m,which,text);
7964
+ const existing=connRowsForDetail(text)[0]||(e.conn?connRowById(e.conn):null);
7965
+ const S=detailModalShell('Remember detail '+text);
7966
+ const {el,body,foot,close}=S;
7967
+ body.append(el('div','font-size:12px;line-height:1.5;color:var(--mut);margin-bottom:10px',
7968
+ 'This '+whichLabel(which)+' of '+m.id+' has a '+kindLabel(j.kind)+'. Save it as what “'+text+'” means, and any end with the same callout can be built from it.'));
7969
+ const typeLab=el('div',null,'Connection type');typeLab.className='elab';body.append(typeLab);
7970
+ const type=el('input');type.placeholder='shear · moment · pinned — the drawing’s word';type.autocomplete='off';
7971
+ type.value=(existing&&existing.type)||'';
7972
+ body.append(type);
7973
+ const typeHint=el('div','margin-top:4px','Without this the confidence report can never rate these ends highly — it is one word off the drawing.');
7974
+ typeHint.className='hint';body.append(typeHint);
7975
+ const scopeLab=el('div',null,'Use these numbers for');scopeLab.className='elab';body.append(scopeLab);
7976
+ const group=el('div','display:flex;flex-direction:column;gap:2px');
7977
+ opts.forEach((o,i)=>{
7978
+ const row=el('label','display:flex;align-items:baseline;gap:8px;padding:5px 6px;border-radius:6px;cursor:pointer');
7979
+ const rb=el('input');rb.type='radio';rb.name='dcapscope';rb.value=o.scope;rb.checked=i===0;rb.style.cssText='flex:none;margin:0';
7980
+ const txt=el('div','flex:1;min-width:0');
7981
+ txt.append(el('div','font-size:12px;color:var(--text)',o.label));
7982
+ txt.append(el('div','font-size:11px;color:var(--mut);line-height:1.4',o.hint+' — '+o.n+' end'+(o.n===1?'':'s')));
7983
+ row.append(rb,txt);group.append(row);});
7984
+ body.append(group);
7985
+ const cancel=el('button',null,'Cancel'),save=el('button',null,'Remember it');
7986
+ cancel.className='ghost';cancel.onclick=close;
7987
+ save.onclick=()=>{
7988
+ const picked=opts.find(o=>o.scope===(group.querySelector('input[name=dcapscope]:checked')||{}).value)||opts[0];
7989
+ close();
7990
+ const out=captureDetailRecipe(m,which,picked,type.value.trim());
7991
+ if(out&&out.error==='ambiguous'){
7992
+ // Two rows share this callout — settle which one this end means first, then capture onto it.
7993
+ toast('“'+text+'” matches more than one connection — choose which one it means, then remember it');
7994
+ openDetailPick(m,which);return;
7995
+ }
7996
+ if(!out||!out.rowId){toast('Could not save that — the end needs a detail callout and a built connection');return;}
7997
+ toast((picked.scope==='end'
7998
+ ? ('“'+text+'” now points at this connection — nothing else changed')
7999
+ : ('“'+text+'” now means a '+kindLabel(j.kind)+' for “'+picked.label+'” — build the other ends from the ⋯ menu')) // NOT lowercased: the label carries a profile designation (W18), and "all w18" reads as a typo
8000
+ +(out.droppedSchedule?' · its old size schedule was dropped — it sized a different connection':''));
8001
+ render();};
8002
+ foot.append(cancel,save);save.focus();}
8003
+
8004
+ /**
8005
+ * The way OUT of a conflict / ambiguity. The resolver refuses to pick between two rows because guessing
8006
+ * would bake a connection the drawing does not show — but a refusal with no next step is just a wall, so
8007
+ * this is that step. Choosing writes end.conn, which settles the end permanently.
8008
+ */
8009
+ function openDetailPick(m,which){
8010
+ const r=resolveDetail(m,which);
8011
+ if(r.ok||!r.candidates||!r.candidates.length){render();return;}
8012
+ const rows=r.candidates.map(id=>connRowById(id)).filter(Boolean);
8013
+ if(!rows.length){toast('Those connections no longer exist');render();return;}
8014
+ const S=detailModalShell('Which connection does this end use?');
8015
+ const {el,body,foot,close}=S;
8016
+ body.append(el('div','font-size:12px;line-height:1.5;color:var(--mut);margin-bottom:10px',r.message));
8017
+ const group=el('div','display:flex;flex-direction:column;gap:2px');
8018
+ rows.forEach((row,i)=>{
8019
+ const lab=el('label','display:flex;align-items:baseline;gap:8px;padding:5px 6px;border-radius:6px;cursor:pointer');
8020
+ const rb=el('input');rb.type='radio';rb.name='dpick';rb.value=row.id;rb.checked=i===0;rb.style.cssText='flex:none;margin:0';
8021
+ const txt=el('div','flex:1;min-width:0');
8022
+ txt.append(el('div','font-size:12px;color:var(--text)',(row.detail||row.id)+(row.type?(' · '+row.type):'')));
8023
+ txt.append(el('div','font-size:11px;color:var(--mut);line-height:1.4',
8024
+ row.recipe&&row.recipe.kind?('builds a '+recipeSummary(row.recipe)):'nothing says what this one builds yet'));
8025
+ lab.append(rb,txt);group.append(lab);});
8026
+ body.append(group);
8027
+ const cancel=el('button',null,'Cancel'),use=el('button',null,'Use this one');
8028
+ cancel.className='ghost';cancel.onclick=close;
8029
+ use.onclick=()=>{const id=(group.querySelector('input[name=dpick]:checked')||{}).value;close();
8030
+ if(!id)return;
8031
+ const end=endObjFor(m,which);edit(()=>{end.conn=id;});
8032
+ toast('This '+whichLabel(which)+' now uses '+((connRowById(id)||{}).detail||id));};
8033
+ foot.append(cancel,use);use.focus();}
8034
+
8035
+ // ── plain-English labels for the detail UI ──────────────────────────────────────────────────────
8036
+ // Everything a detailer reads. No jargon, no ids where a name will do.
8037
+ function kindLabel(k){return k==='base-plate'?'base plate':k==='shear-plate'?'shear plate':String(k||'connection').replace(/-/g,' ');}
8038
+ function whichLabel(w){return w==='col'?'base':w===1?'end':'start';}
8039
+ // Describe WHICH members a schedule row covers, in the words a schedule uses.
8040
+ function schedRowLabel(row){const q=(row&&row.match)||{};
8041
+ if(q.profile)return q.profile;
8042
+ if(q.profilePrefix)return q.profilePrefix+' sizes';
8043
+ if(q.depth){const u=q.depth.unit==='mm'?'mm':'"';const lo=q.depth.min,hi=q.depth.max;
8044
+ return (lo!=null&&hi!=null)?(lo+'–'+hi+u+' deep'):(lo!=null?('over '+lo+u+' deep'):('up to '+hi+u+' deep'));}
8045
+ if(q.role)return q.role==='column'?'columns':'beams';
8046
+ return 'every size';}
8047
+ function recipeSummary(rec){if(!rec||!rec.kind)return '';
8048
+ const n=Array.isArray(rec.schedule)?rec.schedule.length:0;
8049
+ return kindLabel(rec.kind)+(n?(' · '+n+' size'+(n>1?'s':'')):'');}
8050
+ // A capture is offered only when there is something real to remember: a built connection AND a callout
8051
+ // to remember it under.
8052
+ function captureEligible(m,which){const e=endObjFor(m,which);
8053
+ return !!(e&&normDetailKey(e.detail)&&jointAtEnd(m.id,which));}
8054
+ /**
8055
+ * How many ends each capture SCOPE would govern — the blast radius, shown before anything is written.
8056
+ * A recipe silently becoming a project-wide rule is the main risk in this feature, so the count is part
8057
+ * of the choice rather than a detail discovered later.
8058
+ */
8059
+ function captureScopeOptions(m,which,detailText){
8060
+ const key=normDetailKey(detailText),prof=canonProfile(m&&m.profile);
8061
+ const series=prof.match(/^([A-Z]+\d+)/); // the leading size family, e.g. W18X35 → W18. Absent for a designation with no digits — that scope is simply not offered.
8062
+ const pool=detailEndTargets().filter(t=>normDetailKey(endObjFor(t.m,t.which).detail)===key);
8063
+ const count=f=>pool.filter(f).length;
8064
+ const opts=[{scope:'end',label:'This end only',hint:'No rule — just these numbers, here',n:1}];
8065
+ if(prof)opts.push({scope:'profile',label:'All '+prof,hint:'A schedule row for this exact size',n:count(t=>canonProfile(t.m.profile)===prof),match:{profile:prof}});
8066
+ if(series&&series[1]!==prof)opts.push({scope:'series',label:'All '+series[1],hint:'A schedule row for this size family',n:count(t=>canonProfile(t.m.profile).indexOf(series[1])===0),match:{profilePrefix:series[1]}});
8067
+ opts.push({scope:'typical',label:'Every size',hint:'The typical — used wherever no size row matches',n:pool.length});
8068
+ return opts;}
8069
+ /**
8070
+ * Write what this end's connection means onto the library row for its callout, creating the row if the
8071
+ * callout names nothing yet. `scope` decides whether it becomes the typical, a schedule row, or nothing
8072
+ * at all (end-only, which just leaves the joint as it is).
8073
+ */
8074
+ function captureDetailRecipe(m,which,opt,type){
8075
+ const e=endObjFor(m,which),j=jointAtEnd(m.id,which);
8076
+ if(!e||!j)return null;
8077
+ const text=String(e.detail||'').trim(),key=normDetailKey(text);
8078
+ if(!key)return null;
8079
+ const params=Object.assign({},j.params||{});
8080
+ // AMBIGUITY IS REFUSED HERE TOO. resolveDetail refuses to choose between two rows that normalise to the
8081
+ // same callout; capture has to hold the same line. Taking the first hit would write this recipe onto
8082
+ // whichever row happened to be first and corrupt a typical that other ends still resolve against —
8083
+ // silently, since those ends would go on refusing as ambiguous.
8084
+ const hits=connRowsForDetail(text);
8085
+ const bound=e.conn?connRowById(e.conn):null;
8086
+ const boundHere=!!(bound&&normDetailKey(bound.detail)===key); // a stale reference must not be the thing we teach
8087
+ if(hits.length>1&&!boundHere)return {error:'ambiguous'};
8088
+ let rowId=null,droppedSchedule=false;
8089
+ edit(()=>{
8090
+ if(!Array.isArray(C.connections))C.connections=[];
8091
+ let row=boundHere?bound:(hits[0]||null);
8092
+ if(!row){row={id:'cx'+Date.now().toString(36)+Math.floor(Math.random()*1e4).toString(36),type:type||'',detail:text,targets:{},source:'user'};C.connections.push(row);}
8093
+ else if(type&&!row.type)row.type=type; // never overwrite a type the user already set
8094
+ rowId=row.id;
8095
+ // A row that USED to mean a different kind cannot keep its schedule: those rows size a base plate, and
8096
+ // re-teaching the detail as a shear plate would leave them sizing something that no longer exists, then
8097
+ // silently merge base-plate numbers into a fin plate. Drop the schedule and tell the user.
8098
+ const prevKind=row.recipe&&row.recipe.kind;
8099
+ const kindChanged=!!(prevKind&&prevKind!==j.kind);
8100
+ if(kindChanged&&Array.isArray(row.recipe.schedule)&&row.recipe.schedule.length)droppedSchedule=true;
8101
+ const rec=(row.recipe&&!kindChanged)?row.recipe:{};
8102
+ rec.kind=j.kind; // ALWAYS the kind actually being captured, never a leftover from what it used to mean
8103
+ row.recipe=rec;
8104
+ if(opt.scope==='typical'){rec.params=params;}
8105
+ else if(opt.scope!=='end'){
8106
+ const sched=Array.isArray(rec.schedule)?rec.schedule.slice():[];
8107
+ const sig=JSON.stringify(opt.match);
8108
+ const at=sched.findIndex(r=>r&&JSON.stringify(r.match||{})===sig);
8109
+ if(at>=0)sched[at]={match:opt.match,params:params};else sched.push({match:opt.match,params:params});
8110
+ // Keep the catch-all last so it cannot shadow a size row. The resolver ranks by specificity anyway,
8111
+ // so this is for the reader, not for correctness.
8112
+ sched.sort((a,b)=>schedRank(a&&a.match)-schedRank(b&&b.match));
8113
+ rec.schedule=sched;}
8114
+ e.conn=rowId;j.conn=rowId; // the end and the joint both cite the row, so the confidence report sees the reference
8115
+ });
8116
+ return {rowId:rowId,droppedSchedule:droppedSchedule};}
6842
8117
  const comboPop=document.createElement('div');comboPop.id='comboPop';document.body.appendChild(comboPop);
6843
8118
  let comboInput=null,comboIdx=-1;
6844
8119
  function showCombo(inp){const src=COMBO_SRC[inp.dataset.src];if(!src)return;comboInput=inp;
@@ -6903,7 +8178,7 @@ function setPlan(i){C.active=i;P=C.plans[i];
6903
8178
  snapOnlyClear2d();closeSnapMenu(); // a snap override never outlives its plan (different geometry)
6904
8179
  disarmCm(); // Move/Copy resets per plan too (its counts persist — they're session prefs, not plan data)
6905
8180
  defaultTOS=(P.default_tos!=null?P.default_tos:198);
6906
- P.default_tos=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)
8181
+ 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)
6907
8182
  if(!P.autofilled){autofillTOS();P.autofilled=true;}
6908
8183
  const ds=new Set([...(P.details||[]).map(d=>d.text),...Object.keys(C.custom_details)]);document.getElementById('detailsBtn').textContent='Details ('+ds.size+')';
6909
8184
  setMode();render();fitToWindow();
@@ -6912,7 +8187,26 @@ function setPlan(i){C.active=i;P=C.plans[i];
6912
8187
  const planSel=document.getElementById('planSel');
6913
8188
  planSel.innerHTML=C.plans.map((p,i)=>`<option value="${i}">${esc(p.sheet)} · ${esc(p.title)}</option>`).join('');
6914
8189
  planSel.onchange=e=>setPlan(+e.target.value);
6915
- document.getElementById('revertB').onclick=()=>{if(confirm('Discard ALL saved edits and reload the originally detected contract? This cannot be undone.')){localStorage.removeItem(LSKEY);location.reload();}};
8190
+ // "Revert to an earlier version…" — a POINTER into the workspaces shell's History step, never a
8191
+ // revert of its own. The project version ledger already restores any version as a NEW version
8192
+ // (audited, itself undoable, and it re-locks exports); this item only makes it reachable from
8193
+ // inside the editor. It therefore exists ONLY when we're embedded in that shell with a project
8194
+ // open — Workflows mode has no history to point at, and a standalone project tab has no shell to
8195
+ // switch. See docs/superpowers/specs/2026-07-21-steel-editor-revert-signpost-design.md.
8196
+ function wsShell(){ // the parent shell's bridge, or null when we aren't embedded in it
8197
+ try{const p=window.parent;if(!p||p===window)return null;
8198
+ const b=p.flolessWorkspaces;return b&&typeof b.openHistory==='function'?b:null;}
8199
+ catch(_){return null;}} // cross-origin or torn-down parent — treat as not embedded, never throw
8200
+ if(PROJECT&&wsShell()){
8201
+ document.body.classList.add('in-workspace'); // the CSS above reveals #revertB + #revertSep
8202
+ document.getElementById('revertB').onclick=async()=>{const b=wsShell();if(!b)return; // re-read the bridge at click time: the shell may have been torn down since boot
8203
+ // Flush the debounced autosave BEFORE navigating. History renders server state derived from this
8204
+ // contract (the version list and the sign-off), so a still-pending PUT would have it paint a stale
8205
+ // approvedAt — and the moment the shell hides this iframe the save pill goes with it, so a failed
8206
+ // save would never be seen. Same order, same reason, as the shell's pre-Approve flush. A rejected
8207
+ // save keeps us here, where the red pill is visible, rather than navigating away from the problem.
8208
+ try{await flushContract();}catch(_){return;}
8209
+ b.openHistory();};}
6916
8210
  const _restored=restoreSaved(); // bring back this browser's saved edits before first paint
6917
8211
  // B4: normalize brace sub-objects across ALL plans — seed defaults on a brace, strip a stale m.brace off a
6918
8212
  // non-brace, clamp bad values. Covers reader-emitted, partial and localStorage-restored payloads, so it runs
@@ -7127,21 +8421,12 @@ if(new URLSearchParams(location.search).get('selftest')==='1'){(function(){
7127
8421
  // 7) Move/Copy transform core (spec §4.1)
7128
8422
  ok((()=>{const o=linearOffsets([10,0,2],3);return o.length===3&&pnear([o[2][0],o[2][1]],[30,0])&&near(o[2][2],6);})(),'linearOffsets scales all 3 comps');
7129
8423
  ok((()=>{const o=arrayOffsets([10,0,0],2,[0,5,0],3);return o.length===5&&o.every(q=>!(q[0]===0&&q[1]===0))&&pnear([o[4][0],o[4][1]],[10,10]);})(),'arrayOffsets n*m-1, no zero, grid sum');
7130
- ok((()=>{const m={id:'t',role:'beam',wp:[[0,0],[10,0]],ends:[{tos:null,tosDef:true},{tos:100,tosDef:false}]};translateMembers([m],[5,-3,12]);
7131
- return pnear(m.wp[0],[5,-3])&&pnear(m.wp[1],[15,-3])&&near(m.ends[0].tos,defaultTOS+12)&&m.ends[0].tosDef===false&&near(m.ends[1].tos,112);})(),'translateMembers rigid dz');
7132
- ok((()=>{const m={id:'t2',role:'beam',wp:[[0,0],[10,0]],ends:[{tos:null,tosDef:true},{tos:null,tosDef:true}]};translateMembers([m],[5,0,0]);
7133
- return m.ends[0].tosDef===true&&pnear(m.wp[0],[5,0]);})(),'translateMembers dz=0 keeps default-follow');
7134
- ok((()=>{const m={id:'tc',role:'column',wp:[[0,0],[0,0]],ends:[{},{}],col:{bos:0,tos:198,tosDef:false}};translateMembers([m],[0,0,24]);
7135
- return near(m.col.bos,24)&&near(m.col.tos,222);})(),'translateMembers column rigid (bos+tos)');
7136
- ok((()=>{const src={id:'a',wp:[[1,2],[3,4]],ends:[{tos:1}]};const c=cloneMember(src);c.wp[0][0]=99;
7137
- return c.id!=='a'&&src.wp[0][0]===1;})(),'cloneMember new id, deep copy');
8424
+ // unit 5 P3b-1: the three translateMembers, one cloneMember and two retargetTos assertions that lived
8425
+ // here moved to server/steel-model-commands.test.ts when the functions themselves did. They tested the
8426
+ // translate / clone / retarget contracts directly, and those contracts are now the boundary's.
7138
8427
  ok((()=>{const v=parseVec("16'");return !!v&&near(v.dist,192);})(),'parseVec single ft → inches');
7139
8428
  ok((()=>{const v=parseVec("12,-6,3");return !!v&&near(v.comp[0],12)&&near(v.comp[1],-6)&&near(v.comp[2],3);})(),'parseVec components');
7140
8429
  ok(parseVec('abc')===null&&parseVec('1,x')===null&&parseVec('')===null&&parseVec('1,2,3,4')===null,'parseVec rejects garbage');
7141
- ok((()=>{const m={id:'c1',role:'column',wp:[[0,0],[0,0]],ends:[{},{}],col:{bos:0,tos:null,tosDef:true}};retargetTos(m,198,396);
7142
- return near(m.col.tos,396)&&near(m.col.bos,198);})(),'retargetTos column keeps height');
7143
- ok((()=>{const m={id:'b1',role:'beam',wp:[[0,0],[1,0]],ends:[{tos:null,tosDef:true},{tos:190,tosDef:false}]};retargetTos(m,198,396);
7144
- return m.ends[0].tosDef===true&&near(m.ends[0].tos,396)&&near(m.ends[1].tos,388);})(),'retargetTos beam: default follows, override Δ-shifts');
7145
8430
  // 8) GLOBAL undo stack (whole-model). The regression the per-plane stacks caused: editing sheet A,
7146
8431
  // then sheet B, then undoing must revert ONLY the last edit (B) and leave A's edit intact — with the
7147
8432
  // old per-plane design a whole-model snapshot on A's stack silently reverted B. Also: a cross-plane
@@ -7367,6 +8652,54 @@ if(new URLSearchParams(location.search).get('selftest')==='1'){(function(){
7367
8652
  {const br=normBrace(mk({id:'brD',wp:[[0,0],[100,0]]}));P.members=[br];
7368
8653
  doSplit(br,[50,0]);ok(P.members.length===1,'doSplit refuses to cut a brace');}
7369
8654
 
8655
+ // --- cross-sheet coordinate seam: the 3D reaches members on ANY sheet, so these editor callbacks
8656
+ // must resolve the OWNING plane, never the active one. Ids are only sheet-unique, so resolution is
8657
+ // by object identity throughout. ---
8658
+
8659
+ // doSplit puts the second half on the sheet that OWNS the member, not the active one
8660
+ {const savedPlans=C.plans,savedP=P;
8661
+ const off={sheet:'S-OFF',pt_per_ft:36,default_tos:348,members:[],dims:[]};
8662
+ const bm={id:'sp1',role:'beam',profile:'W16X26',wp:[[0,0],[100,0]],ends:[{},{}]};
8663
+ off.members=[bm];P.members=[];C.plans=[savedP,off];
8664
+ doSplit(bm,[50,0]);
8665
+ ok(off.members.length===2&&P.members.length===0,'doSplit lands the second half on the OWNING sheet, not the active one');
8666
+ C.plans=savedPlans;P=savedP;}
8667
+
8668
+ // onElevateMember materialises an unset T.O.S from the OWNING sheet's datum (and from 0, like the
8669
+ // bake, when that sheet has none) — never from the active sheet's defaultTOS
8670
+ {const savedPlans=C.plans,savedP=P,savedTos=defaultTOS;defaultTOS=198;
8671
+ const off={sheet:'S-OFF2',pt_per_ft:36,default_tos:348,members:[],dims:[]};
8672
+ const bm={id:'el1',role:'beam',profile:'W16X26',wp:[[0,0],[100,0]],ends:[{},{}]};
8673
+ const noDef={sheet:'S-NODEF',pt_per_ft:12,members:[],dims:[]};
8674
+ const bm2={id:'el2',role:'beam',profile:'W16X26',wp:[[0,0],[100,0]],ends:[{},{}]};
8675
+ off.members=[bm];noDef.members=[bm2];C.plans=[savedP,off,noDef];
8676
+ view3dApi.onElevateMember('el1',12);
8677
+ ok(Math.abs(bm.ends[0].tos-360)<1e-6,'onElevateMember materialises from the OWNING sheet datum (348+12), not the active one (198+12)');
8678
+ view3dApi.onElevateMember('el2',12);
8679
+ ok(Math.abs(bm2.ends[0].tos-12)<1e-6,'a sheet with no default_tos resolves to 0 like the bake, not to the active sheet');
8680
+ C.plans=savedPlans;P=savedP;defaultTOS=savedTos;}
8681
+
8682
+ // The Trim/Extend off-sheet guard. It filters by OBJECT identity, so it reports exactly the members
8683
+ // that are not on the open sheet — no count arithmetic that a duplicate id could skew.
8684
+ {const savedPlans=C.plans,savedP=P,savedSel=selIds;
8685
+ const mine={id:'t1',role:'beam',profile:'W16X26',wp:[[0,0],[100,0]],ends:[{},{}]};
8686
+ const other={id:'t2',role:'beam',profile:'W16X26',wp:[[0,50],[100,50]],ends:[{},{}]};
8687
+ const off={sheet:'S-OFF3',pt_per_ft:36,default_tos:348,members:[other],dims:[]};
8688
+ P.members=[mine];C.plans=[savedP,off];
8689
+ selIds=new Set(['t1']);
8690
+ ok(selArr().filter(m=>!P.members.includes(m)).length===0,'an all-active-sheet selection does not trip the off-sheet guard');
8691
+ selIds=new Set(['t1','t2']);
8692
+ ok(selArr().filter(m=>!P.members.includes(m)).length===1,'a selection reaching another sheet trips it, naming exactly the off-sheet member');
8693
+ // Known limitation, pinned so it is a decision and not a surprise: selIds keys by ID, and ids are
8694
+ // only SHEET-unique, so selecting a bare id shared by two sheets selects BOTH — the guard then
8695
+ // (correctly) reports the selection as cross-sheet and Trim/Extend refuses. Model-level member
8696
+ // identity removes the ambiguity; until then refusing beats silently trimming one of the two.
8697
+ const dupA={id:'dupT',role:'beam',profile:'W16X26',wp:[[0,0],[100,0]],ends:[{},{}]};
8698
+ const dupB={id:'dupT',role:'beam',profile:'W16X26',wp:[[0,50],[100,50]],ends:[{},{}]};
8699
+ P.members=[dupA];off.members=[dupB];selIds=new Set(['dupT']);
8700
+ ok(selArr().filter(m=>!P.members.includes(m)).length===1,'a bare id shared across sheets selects both, so the guard refuses (id-keyed selection, pre-existing)');
8701
+ C.plans=savedPlans;P=savedP;selIds=savedSel;}
8702
+
7370
8703
  // swapSelectionEnds skips braces (the bulk path that used to flip a brace's offset side)
7371
8704
  {const br=normBrace(mk({id:'brW',wp:[[0,0],[100,0]],brace:{type:'vertical',floor:'above',offset:24}}));
7372
8705
  P.members=[br];const si=selIds;selIds=new Set(['brW']);const u0=undo.length;