@floless/app 0.104.2 → 0.105.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}
@@ -355,8 +359,15 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
355
359
  #moreMenu hr{border:0;border-top:1px solid var(--line);margin:4px 0}
356
360
  #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
361
  #moreMenu button:hover{background:#334155}
358
- #moreMenu button.mdanger{color:#fca5a5}
359
- #moreMenu button.mdanger:hover{background:#7f1d1d;color:#fecaca}
362
+ /* "Revert to an earlier version…" is a POINTER into the workspaces shell's History step, so it
363
+ exists only when we're embedded there with a project open (boot adds body.in-workspace). Hidden
364
+ by default: Workflows mode has no version history to point at. The #moreMenu prefix is required
365
+ to beat "#moreMenu button{display:block}" above — the [hidden] attribute would lose to it. */
366
+ #moreMenu #revertB,#moreMenu #revertSep{display:none}
367
+ body.in-workspace #moreMenu #revertB,body.in-workspace #moreMenu #revertSep{display:block}
368
+ /* Same trap: "Send selection to Tekla" is hidden with an empty selection, and plain [hidden] loses
369
+ to the #moreMenu rule above — without this it ships as a visible row that only scolds you. */
370
+ #moreMenu #sendTeklaB[hidden]{display:none}
360
371
  #moreMenu button:disabled{opacity:.4;cursor:default;background:transparent}
361
372
  #moreMenu button.on{color:var(--brand)}
362
373
  button:focus-visible{outline:2px solid var(--brand);outline-offset:2px}
@@ -506,6 +517,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
506
517
  #m3dBar>button{font-size:12px;padding:5px 9px}
507
518
  #m3dBar .m3dwrap{position:relative;display:inline-flex}
508
519
  #m3dBar .m3dwrap>button{font-size:12px;padding:5px 9px;box-shadow:0 4px 14px rgba(0,0,0,.45)}
520
+ #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
521
  .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
522
  .m3dmenu.open{display:block}
511
523
  .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 +702,12 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
690
702
  #m3dLegend .lrow:hover .drag-handle{opacity:1}
691
703
  #m3dLegend .lrow.flash{background:rgba(59,130,246,.12)}
692
704
  .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)}
705
+ /* The Ctrl+Shift drag-out badge. Same recipe as .leg-drag-ghost but sized to its text (a fixed width
706
+ would leave dead space beside "3 members → Tekla"). We position it ourselves on every pointer move;
707
+ the off-screen left is only where it waits between being created and that first move, so it never
708
+ flashes at the origin. It clips at the window edge — nothing can draw outside the browser. */
709
+ .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)}
710
+ .tekla-drag-ghost svg{color:var(--brand);flex:none}
693
711
  #m3dLegend .ldiv{height:1px;background:var(--line);margin:5px 2px}
694
712
  /* Objects-list SEARCH — narrows the member/connection rows as you type; never the 3D scene, never Dims/Grid/Clip.
695
713
  Built from the same tokens as #propPop .ppsearch (no new vocabulary); sits between the mode toggle and the hint. */
@@ -867,10 +885,11 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
867
885
  <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
886
  <div class=msec-body>
869
887
  <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>
888
+ <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
889
  <button id=exp>Export contract…</button>
871
890
  </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>
891
+ <hr id=revertSep>
892
+ <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
893
  </div>
875
894
  </div>
876
895
  </header>
@@ -893,11 +912,13 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
893
912
  <span class=tb-sep></span>
894
913
  <!-- Display mode — dropdown; the button shows the current mode -->
895
914
  <div class=m3dwrap>
896
- <button id=m3dModeBtn data-tip="Display mode — solid, wireframe, or see-through (X-ray)">Solid ▾</button>
915
+ <button id=m3dModeBtn data-tip="Display mode — solid, wireframe, see-through (X-ray) or realistic materials">Solid ▾</button>
897
916
  <div id=m3dMode class=m3dmenu role=menu>
898
917
  <button data-mode=solid class=on data-tip="Solid shaded model">Solid</button>
899
918
  <button data-mode=wire data-tip="Wireframe — edges only">Wire</button>
900
919
  <button data-mode=xray data-tip="See-through — reveal hidden parts">X-ray</button>
920
+ <button data-mode=realistic data-tip="Realistic — real material finishes (steel, concrete, timber…)">Realistic</button>
921
+ <button data-mode=shadowed data-tip="Realistic with cast shadows — more depth, at a cost to frame rate">Shadowed</button>
901
922
  </div>
902
923
  </div>
903
924
  <button id=m3dIso data-tip="Isolate selected — hide everything else (Esc to exit)" style="display:none">Isolate</button>
@@ -1119,16 +1140,174 @@ const APP_ID = new URLSearchParams(location.search).get('app') || '';
1119
1140
  // /api/contract call; the contract-request (Ask AI) bodies carry `project` for slice-4 context.
1120
1141
  const PROJECT = new URLSearchParams(location.search).get('project') || '';
1121
1142
  const PROJECT_QS = PROJECT ? ('?project=' + encodeURIComponent(PROJECT)) : '';
1143
+ // ── The browser draft's identity, and the contract type this page can render (unit 5, P1c-3) ──
1144
+ // The one contract type this editor renders. A contract with NO `type` is legacy steel v1 — the server's
1145
+ // own validator says so and falls back to exactly this (contract-schema.ts, validateContract), so
1146
+ // diverging here would refuse documents this app itself wrote.
1147
+ const EDITOR_TYPE = 'steel.takeoff/v1';
1148
+ // The type the draft key is built from. Captured ONCE, right after boot() validates it, and never re-read
1149
+ // from `C` afterwards: `C` is mutable, and a key that can change identity mid-session would orphan the
1150
+ // draft it was writing (persist and restoreSaved would address different rows).
1151
+ let DRAFT_TYPE = EDITOR_TYPE;
1152
+ /**
1153
+ * Where this browser's unsaved edits live.
1154
+ *
1155
+ * Keyed by app AND project AND type. The old key was app-only, so two PROJECTS of the same app shared one
1156
+ * draft and silently overwrote each other's edits — reachable today, no v2 required. Type is in the key
1157
+ * because a store's type can change under a fixed app+project (that is exactly what P7's migration does),
1158
+ * and a v1 draft must never overlay a document of another type.
1159
+ *
1160
+ * Each component is encodeURIComponent'd so the separator cannot be forged: without it, app `a|b` +
1161
+ * project `c` and app `a` + project `b|c` are the same string.
1162
+ *
1163
+ * The prefix is `v2` because the stored SHAPE changed too (it now carries `baseEtag`). A `v1` payload has
1164
+ * no base, and restoreSaved must be able to tell those apart. Old `v1` keys are deliberately NOT migrated:
1165
+ * one belongs to an unknown project, so adopting it would attribute one project's edits to another — the
1166
+ * very bug this fixes.
1167
+ */
1168
+ function draftKey() {
1169
+ return 'steeltakeoff:edits:v2:' + encodeURIComponent(APP_ID) + '|' + encodeURIComponent(PROJECT) + '|' + encodeURIComponent(DRAFT_TYPE);
1170
+ }
1171
+ /**
1172
+ * Where a draft goes once it has been REFUSED as stale and offered back to the user.
1173
+ *
1174
+ * A separate row, because the main one is live: the moment the user makes one edit on the current
1175
+ * version, `persist()` overwrites it — and `edit()` retires the offer bar first, so they would never
1176
+ * see it go. The banner tells them their earlier edits are still saved on this computer; that has to be
1177
+ * true, so the offered copy is parked somewhere nothing else writes.
1178
+ */
1179
+ function offeredKey() { return draftKey() + '|offered'; }
1180
+ /**
1181
+ * Drop draft rows for THIS app+project that no longer belong to the type it now holds.
1182
+ *
1183
+ * Two ways they accumulate: the deliberately unmigrated `…:v1:` rows, and — once P7's migration changes
1184
+ * a store's type under a fixed app+project — the rows keyed by the previous type. Neither is ever read
1185
+ * again, and each holds a whole contract body against a per-origin storage quota, so leaving them is a
1186
+ * slow leak that would eventually break saving for a reason nobody could see.
1187
+ *
1188
+ * Scoped to this app+project on purpose: another project's rows are not ours to delete.
1189
+ */
1190
+ function sweepOrphanDrafts() {
1191
+ try {
1192
+ const mine = draftKey(), offered = offeredKey();
1193
+ const prefix = 'steeltakeoff:edits:', scope = encodeURIComponent(APP_ID) + '|' + encodeURIComponent(PROJECT) + '|';
1194
+ for (const k of Object.keys(localStorage)) {
1195
+ if (!k.startsWith(prefix) || k === mine || k === offered) continue;
1196
+ // A v1 key has no scope segment at all; a v2 key for this store carries exactly this prefix.
1197
+ // EXACT for v1 — a prefix test also matched a DIFFERENT app whose id merely starts with ours
1198
+ // (`…v1:harness` vs `…v1:harness-tower`), and another app's row is not ours to delete.
1199
+ if (k === 'steeltakeoff:edits:v1:' + APP_ID || k.includes(':v2:' + scope)) localStorage.removeItem(k);
1200
+ }
1201
+ } catch (_) { /* housekeeping only — never block the load */ }
1202
+ }
1203
+ /**
1204
+ * Re-point the stored draft at the server version it is now a delta from.
1205
+ *
1206
+ * WHY IT EXISTS. `scheduleSave` runs `persist(); persistServer();` in that order, so the draft records
1207
+ * the tag from BEFORE the write that advances it. Without this, storage holds the pre-write tag while
1208
+ * the server holds the post-write one, and the next reload reports "someone else changed this model"
1209
+ * about the tab's own save — every time. (connModifyRequest and the detail-placement request order the
1210
+ * pair the other way round; Ctrl+S orders it like scheduleSave. Re-stamping on the result covers all.)
1211
+ *
1212
+ * WHY IT TAKES `prev`, which is the part review had to find. Re-stamping unconditionally assumes the row
1213
+ * in storage is a delta from the version we just replaced — and there is a reachable state where it is
1214
+ * not: after `restoreSaved()` refuses a stale draft, the row belongs to an OLDER base while the tab
1215
+ * edits the current document. A `flushContract()` with no preceding `persist()` — Ask AI Send, the
1216
+ * History revert, the shell's Approve, the non-project Tekla send: all four exist — would then stamp
1217
+ * the current tag onto those old edits, and the NEXT reload would find the bases equal and silently
1218
+ * overlay them on top of the newer work. That is the masking bug this whole item exists to close,
1219
+ * re-entered through its own fix.
1220
+ *
1221
+ * So the rewrite is conditional on the row actually being the one we wrote: its base must be the tag we
1222
+ * just replaced. Under `scheduleSave` that is exactly what `persist()` stored a moment earlier, so the
1223
+ * intended path is untouched; any row belonging to some other base is left alone.
1224
+ *
1225
+ * Best-effort: a storage failure here costs a false conflict prompt on the next reload, never data.
1226
+ */
1227
+ function restampDraftBase(prev, next) {
1228
+ if (!next) return;
1229
+ try {
1230
+ const raw = localStorage.getItem(draftKey());
1231
+ if (!raw) return;
1232
+ const d = JSON.parse(raw);
1233
+ if (!d || typeof d !== 'object') return;
1234
+ // `== null` covers a v1-era row with no base: it predates this field, so it is not a delta from
1235
+ // `prev` in any checkable sense and must not inherit a tag it never earned.
1236
+ if (d.baseEtag !== prev) return;
1237
+ d.baseEtag = next;
1238
+ localStorage.setItem(draftKey(), JSON.stringify(d));
1239
+ } catch (_) { /* the draft stays on its old base — a false "changed elsewhere" prompt, not a loss */ }
1240
+ }
1241
+ // ── Own-write identity, replacing the 2.5 s SSE echo clock (unit 5, P1c-3) ──
1242
+ // Every PUT names itself; the server echoes that name in the contract-changed broadcast. A clock could not
1243
+ // tell "my echo" from "someone else's write inside the window", so a genuine external write landing in
1244
+ // those 2.5 s was silently swallowed — and once the conflict latch tripped, persistServer returned BEFORE
1245
+ // stamping the clock, so the window expired and stayed expired precisely when a wrong reload cost most.
1246
+ const ownWrites = [];
1247
+ // A pure backstop, not a working limit. queueWrite SERIALIZES this tab's writes, and an id is dropped on
1248
+ // success AND on every failure, so in steady state this holds at most one entry. The cap only matters if
1249
+ // some future path mints an id and never resolves it.
1250
+ const OWN_WRITES_MAX = 32;
1251
+ // Three tiers, because only the FIRST needs a secure context and this page is served over plain http in
1252
+ // some dev setups. `crypto.getRandomValues` is NOT secure-context-gated, so tier 2 is a real CSPRNG and
1253
+ // the Math.random tier is close to unreachable — it exists so a missing `crypto` cannot break saving.
1254
+ //
1255
+ // Entropy matters here, and an earlier comment overstated it (review): a held id is released on match
1256
+ // and on every failure, but an id whose echo never arrives lingers until the FIFO evicts it, and while
1257
+ // it lingers an event carrying the SAME id would be read as our own and suppressed. 122 bits (UUIDv4)
1258
+ // or 128 bits (tier 2) makes that unreachable; two `Math.random()` slices would not, since Math.random
1259
+ // is neither uniform over that space nor unguessable.
1260
+ function newMutationId() {
1261
+ try {
1262
+ const c = self.crypto;
1263
+ if (c && typeof c.randomUUID === 'function') return c.randomUUID();
1264
+ if (c && typeof c.getRandomValues === 'function') {
1265
+ const b = c.getRandomValues(new Uint8Array(16));
1266
+ return 'm-' + Array.from(b, n => n.toString(16).padStart(2, '0')).join('');
1267
+ }
1268
+ } catch (_) { /* fall through to the last resort */ }
1269
+ // Last resort only. Weaker, and deliberately not described as anything else.
1270
+ return 'm-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 12) + Math.random().toString(36).slice(2, 12);
1271
+ }
1272
+ function claimMutation(id) { ownWrites.push(id); while (ownWrites.length > OWN_WRITES_MAX) ownWrites.shift(); }
1273
+ /** Drop an id we are done with. Called on success (the echo arrived, or will be recognised by then) and on
1274
+ * EVERY failure — a refused write produces no broadcast at all, so its id would otherwise sit in the list
1275
+ * forever, where the only thing it can do is wrongly suppress somebody else's event. */
1276
+ function releaseMutation(id) { const i = ownWrites.indexOf(id); if (i >= 0) ownWrites.splice(i, 1); }
1122
1277
  let C, PAL, WT;
1123
1278
  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
1279
  let ViewGen = null; // steel-view-generation.js pure F11 helpers — loaded before saved views are sanitised
1280
+ 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
1281
  let TARGET_CONF = null; // the app's target_confidence input default (%), or null when undeclared — drives the chip's "· target N%" goal
1126
1282
  let view3d = false, view3dReady = false; // 2D|3D toggle state; view3dReady once Steel3DView.init has run
1127
1283
  // Fallback palette (colorFor indexes this array by profile order) when a contract ships no `palette`
1128
1284
  // — e.g. a contract shared/committed with raster_b64 + palette stripped for confidentiality.
1129
1285
  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) {
1286
+ // (P1c-3 removed `lastLocalPut`: own-write echoes are now recognised by id — see ownWrites above. Leaving
1287
+ // the timestamp in place would have left a second, wrong answer to the same question.)
1288
+ // The server's tag for the contract this tab loaded, and whether a write has already lost a race.
1289
+ // `conflicted` LATCHES: once a save is refused, firing the identical PUT every 500 ms debounce tick is
1290
+ // wasted traffic and makes the pill flicker in a way that reads as broken rather than informative.
1291
+ let serverEtag = null;
1292
+ let conflicted = false;
1293
+ // Serialize THIS tab's writes. Without it the editor conflicts with ITSELF: a slow autosave still in
1294
+ // flight when the next one (or flushContract, which Approve awaits) fires means two requests carrying
1295
+ // the SAME tag — one wins, the other comes back 412 and shows the user a conflict caused by nobody but
1296
+ // themselves, potentially aborting Approve. `saveSeq` only decides which response owns the pill; it
1297
+ // never stopped the overlap. vector-editor already queues; this brings the steel editor in line.
1298
+ let writeQueue = Promise.resolve();
1299
+ const queueWrite = (fn) => (writeQueue = writeQueue.then(fn, fn));
1300
+ /**
1301
+ * The full-screen "there is nothing to show" state.
1302
+ *
1303
+ * `opts.detail` (P1c-3) is a whispered technical footer — today, the contract type this editor declined.
1304
+ * Two different readers exist for that refusal: the engineer, who must never need a schema string and gets
1305
+ * prose; and whoever triages their screenshot, for whom the exact string is the single fastest diagnostic
1306
+ * fact there is. Present-but-secondary serves both. Deliberately NOT monospace: no monospace family is
1307
+ * established on this surface, and introducing one would be a new font against a locked visual baseline —
1308
+ * size and colour de-emphasise it just as well.
1309
+ */
1310
+ function showEmpty(icon, headline, bodyText, appIdText, opts) {
1132
1311
  const wrap = document.createElement('div');
1133
1312
  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
1313
  const ic = document.createElement('div'); ic.style.cssText = 'font-size:28px;opacity:.5'; ic.textContent = icon;
@@ -1137,11 +1316,17 @@ function showEmpty(icon, headline, bodyText, appIdText) {
1137
1316
  else { h.textContent = headline; }
1138
1317
  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
1318
  wrap.append(ic, h, body);
1319
+ if (opts && opts.detail) {
1320
+ const det = document.createElement('div');
1321
+ det.style.cssText = 'font-size:10.5px;color:#9aa5b6;opacity:.65;margin-top:-2px';
1322
+ det.textContent = opts.detail; // textContent, not innerHTML: this string comes from the stored document
1323
+ wrap.append(det);
1324
+ }
1140
1325
  document.body.replaceChildren(wrap);
1141
1326
  }
1142
1327
  async function boot() {
1143
1328
  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
1329
+ [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
1330
  const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS);
1146
1331
  if (!res.ok) {
1147
1332
  if (res.status === 404) {
@@ -1151,7 +1336,46 @@ async function boot() {
1151
1336
  }
1152
1337
  return;
1153
1338
  }
1154
- C = await res.json();
1339
+ // Parse into a LOCAL first (unit 5, P1c-3). `C` is the global everything else in this page reads, so
1340
+ // assigning before the type is validated would publish a document this editor cannot render — briefly
1341
+ // live, and observable to anything that runs in between. Validate, then publish.
1342
+ const loaded = await res.json();
1343
+ // Shape first, then type. A body that is null, an array or a scalar has no `type` to test, so a
1344
+ // type-only gate waved it through and the failure surfaced as a raw red `boot().catch` — "Cannot read
1345
+ // properties of null (reading 'palette')" — instead of the styled state this item introduces. `plans`
1346
+ // is what every path below indexes, so its absence is the honest floor.
1347
+ if (!loaded || typeof loaded !== 'object' || Array.isArray(loaded) || !Array.isArray(loaded.plans)) {
1348
+ showEmpty('⚠', 'Couldn’t read this model',
1349
+ '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.',
1350
+ APP_ID);
1351
+ return;
1352
+ }
1353
+ const loadedType = loaded.type;
1354
+ // A missing type is legacy steel v1 (see EDITOR_TYPE). Anything else declared is refused HERE, before
1355
+ // the normalisation below starts mutating the document and before main() runs restoreSaved() — which
1356
+ // would otherwise overlay a steel draft onto a document of a different type entirely.
1357
+ if (loadedType != null && loadedType !== EDITOR_TYPE) {
1358
+ // Two different situations, and one message for both would be false in one of them. A steel.model/v2
1359
+ // IS a Steel Model — just a newer format this build cannot draw yet — so telling that user "this is
1360
+ // not a Steel Model" would be plainly wrong. Anything else means they opened the wrong workflow.
1361
+ const newerSteel = /^steel\.model\//.test(String(loadedType));
1362
+ showEmpty('⊞',
1363
+ newerSteel ? 'This Steel Model isn’t supported yet —' : 'Not a Steel Model —',
1364
+ newerSteel
1365
+ ? '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.'
1366
+ : '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.',
1367
+ APP_ID,
1368
+ { detail: 'type: ' + String(loadedType) });
1369
+ return;
1370
+ }
1371
+ // Pin the draft identity for the rest of the session. Read once, from the validated value, never from
1372
+ // the mutable `C` — see draftKey().
1373
+ DRAFT_TYPE = loadedType == null ? EDITOR_TYPE : loadedType;
1374
+ sweepOrphanDrafts(); // now that the identity is pinned, retire rows keyed by an older one
1375
+ C = loaded;
1376
+ // The server's tag for the contract we just read. Every write echoes it back, so a write that would
1377
+ // land on top of someone else's is refused instead of silently winning.
1378
+ serverEtag = res.headers.get('ETag');
1155
1379
  // The confidence target is a workflow INPUT (target_confidence), not contract data — read its
1156
1380
  // declared default off the app def so the chip can show the goal. Best-effort: on any failure the
1157
1381
  // chip just omits the "· target N%" suffix (no fabricated goal).
@@ -1188,17 +1412,45 @@ async function boot() {
1188
1412
  if (!m || typeof m !== 'object') return;
1189
1413
  if (m.type !== 'contract-changed') return;
1190
1414
  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 */ }
1415
+ // …and the same PROJECT. Two projects of one app share an appId, so without this a write to one
1416
+ // reloads the other's tab and (before the removal below was dropped) destroyed its draft — item
1417
+ // A's own bug class, left half-fixed: the key became project-scoped while the invalidation did
1418
+ // not. `|| ''` on both sides because an app-scoped write carries no `project` at all.
1419
+ if ((m.project || '') !== PROJECT) return;
1420
+ // OUR OWN echo, recognised by NAME rather than by clock (unit 5, P1c-3).
1421
+ const own = m.mutationId ? ownWrites.indexOf(m.mutationId) : -1;
1422
+ if (own >= 0) {
1423
+ // Everything OLDER than the match is superseded: SSE preserves order on a connection, so an
1424
+ // echo we have not seen by the time a later one arrives is never coming.
1425
+ const newest = own === ownWrites.length - 1;
1426
+ ownWrites.splice(0, own + 1);
1427
+ // Adopt the tag the server produced for our write — but ONLY from the newest echo. This is the
1428
+ // case the old clock could never cover (a PUT that succeeds while its response is lost leaves
1429
+ // `serverEtag` stale, so the tab's own next save is refused against its own change) — and
1430
+ // review found the mirror image: a LATE echo carries an OLDER tag, and adopting that rolls
1431
+ // `serverEtag` backwards, guaranteeing a 412 on the user's next write.
1432
+ if (newest && typeof m.etag === 'string' && m.etag) { const prev = serverEtag; serverEtag = m.etag; restampDraftBase(prev, m.etag); }
1433
+ return;
1434
+ }
1435
+ // An external write. The draft is deliberately NOT dropped here any more: with a server-issued
1436
+ // base recorded, a reload now compares bases and OFFERS a stale draft back instead of masking
1437
+ // the newer version with it — which is the only thing the removal was ever protecting against.
1438
+ // Removing it first was actively harmful, because it ran BEFORE the `hasUnsaved` check below:
1439
+ // in exactly the case where work was at risk, the durable copy was destroyed and only in-memory
1440
+ // `C` survived, so the banner's own Reload button lost it.
1197
1441
  // Auto-reload straight into the AI's version so the user never has to hit refresh — EXCEPT
1198
1442
  // when they have unsaved in-browser edits (saveStat 'dirty'/'err'), where a silent reload
1199
1443
  // would discard their work; there we fall back to the choose-to-reload banner.
1200
1444
  const sv = document.getElementById('saveStat');
1201
- const hasUnsaved = !!sv && (sv.classList.contains('dirty') || sv.classList.contains('err'));
1445
+ // 'conflict' counts as unsaved, and omitting it lost data: after a refused save the edits are
1446
+ // unsaved BY DEFINITION, so a silent reload here would drop the localStorage draft (above) and
1447
+ // discard exactly the work the conflict banner had just promised was "still here".
1448
+ // (Historically this also had to compensate for the 2.5 s echo suppressor, which stopped working
1449
+ // the moment the conflict latch tripped — persistServer returned before stamping its timestamp,
1450
+ // so the window expired and stayed expired. Identity has no such state, but this check is load
1451
+ // bearing on its own merits and stays.)
1452
+ const hasUnsaved = !!sv && (sv.classList.contains('dirty') || sv.classList.contains('err')
1453
+ || sv.classList.contains('conflict'));
1202
1454
  if (hasUnsaved) showAiUpdateBanner('The AI updated this model — reload to see it (you have unsaved edits).');
1203
1455
  else location.reload();
1204
1456
  };
@@ -1207,6 +1459,10 @@ async function boot() {
1207
1459
  // terminal: live writeback detection is dead, so surface it (the banner's Reload re-opens
1208
1460
  // the editor and its EventSource) instead of leaving the user on a silently-stale view.
1209
1461
  if (es.readyState === EventSource.CLOSED) {
1462
+ // Every id we are still holding is now DEAD: the channel that would have carried its echo is
1463
+ // gone, so none can ever be matched. Holding them serves nothing and is the only way the list
1464
+ // grows without bound — the one case review raised against retaining an id past its response.
1465
+ ownWrites.length = 0;
1210
1466
  console.warn('steel-editor: SSE channel closed — live updates paused');
1211
1467
  showAiUpdateBanner('Live updates disconnected — reload to resume change detection.');
1212
1468
  }
@@ -1217,13 +1473,25 @@ async function boot() {
1217
1473
  }
1218
1474
  }
1219
1475
 
1220
- function showAiUpdateBanner(message) {
1476
+ /**
1477
+ * The bottom bar for "this model changed underneath you".
1478
+ *
1479
+ * `opts` extends it for the save-conflict case without forking the component — same bar, same tokens, so
1480
+ * a user who has learned "blue bar at the bottom = something else changed" does not relearn it per cause.
1481
+ * onReload — override the reload action (the conflict path must drop the local draft first)
1482
+ * onOverwrite — adds the secondary "Save mine anyway" button; omitted, no such button appears
1483
+ */
1484
+ function showAiUpdateBanner(message, opts) {
1221
1485
  // Remove any existing banner before adding a new one (idempotent)
1222
1486
  const existing = document.getElementById('aiUpdateBanner');
1223
1487
  if (existing) existing.remove();
1224
1488
 
1225
1489
  const bar = document.createElement('div');
1226
1490
  bar.id = 'aiUpdateBanner';
1491
+ // Which cause raised this bar. Only the stale-draft caller sets it, so that one can be auto-dismissed
1492
+ // when it stops being true (see edit()) without touching the AI-update and conflict banners, which must
1493
+ // survive edits — persisting through them is the whole point of the conflict banner.
1494
+ if (opts && opts.kind) bar.dataset.kind = opts.kind;
1227
1495
  bar.style.cssText = [
1228
1496
  'position:fixed', 'bottom:0', 'left:0', 'right:0', 'z-index:50',
1229
1497
  'display:flex', 'align-items:center', 'gap:10px',
@@ -1239,8 +1507,12 @@ function showAiUpdateBanner(message) {
1239
1507
 
1240
1508
  const reloadBtn = document.createElement('button');
1241
1509
  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();
1510
+ // The LABEL is overridable as well as the handler. The two existing callers pass neither and render
1511
+ // byte-identically; the stale-draft caller does not reload at all, so a button reading "↻ Reload"
1512
+ // would have named an action it does not perform.
1513
+ reloadBtn.textContent = (opts && opts.reloadLabel) || '↻ Reload';
1514
+ if (opts && opts.reloadTip) reloadBtn.dataset.tip = opts.reloadTip; // data-tip, never title= — the themed tooltip is CI-enforced
1515
+ reloadBtn.onclick = (opts && opts.onReload) ? opts.onReload : () => location.reload();
1244
1516
 
1245
1517
  const dismissBtn = document.createElement('button');
1246
1518
  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 +1522,15 @@ function showAiUpdateBanner(message) {
1250
1522
 
1251
1523
  bar.appendChild(msg);
1252
1524
  bar.appendChild(reloadBtn);
1525
+ if (opts && opts.onOverwrite) {
1526
+ // Visually subordinate to Reload — it is the destructive option, and it still has to pass a confirm.
1527
+ const over = document.createElement('button');
1528
+ over.style.cssText = 'background:transparent;color:#93c5fd;border:1px solid #3b82f6;border-radius:6px;padding:5px 10px;cursor:pointer;font:13px system-ui';
1529
+ over.textContent = 'Save mine anyway';
1530
+ over.dataset.tip = 'Replace the version someone else saved with what you have here';
1531
+ over.onclick = opts.onOverwrite;
1532
+ bar.appendChild(over);
1533
+ }
1253
1534
  bar.appendChild(dismissBtn);
1254
1535
  document.body.appendChild(bar);
1255
1536
  }
@@ -1306,9 +1587,7 @@ function fmtFtIn(v){if(v==null||isNaN(v))return '';const neg=v<0;let sx=Math.rou
1306
1587
  let num=fr,den=16;while(num>0&&num%2===0){num/=2;den/=2;}const fs=num>0?(' '+num+'/'+den):'';
1307
1588
  const body=ft>0?(ft+"'-"+inch+fs+'"'):(inch+fs+'"');return (neg?'-':'')+body;}
1308
1589
  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;}
1590
+ function ensureMeta(m){return ModelCmd.ensureMeta(m);} // unit 5 P3a: the model boundary owns member normalisation now
1312
1591
  // Effective profile position on the reference line (the work-line between the end dots), à la Tekla.
1313
1592
  // Explicit m.position wins; else a flat beam → top (top-of-steel), a steep beam (brace) / column → middle.
1314
1593
  // A VERTICAL brace is always centred: its work-points sit on the column ℄, and the slope heuristic alone
@@ -1335,9 +1614,9 @@ function swapMemberEnds(m){
1335
1614
  let braceOld=null;
1336
1615
  if(isBrace(m)){normBrace(m); // a brace reached here without m.brace (reader payload / direct call) would NPE below
1337
1616
  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;}
1617
+ 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
1618
+ 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
1619
+ 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
1620
  if(braceOld){
1342
1621
  if(braceOld.tie||(m.brace.lowerEnd===0||m.brace.lowerEnd===1))m.brace.lowerEnd=(1-braceOld.old);
1343
1622
  // braceDisplayLine takes its perpendicular from the a→b direction, so reversing wp flips which SIDE the
@@ -1470,14 +1749,15 @@ function braceSymbol(m,c,glow){
1470
1749
  for(const pts of braceHeadPoints(m)) s+=`<polygon class=bracehead fill="${c}" points="${pts}"/>`;
1471
1750
  return s+`</g>`;}
1472
1751
  // --- 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;});}}}
1752
+ let cmSeq=0; // still live: MC()'s mintId below is the '_c' id policy every clone but doDup's uses
1753
+ // unit 5 P3b-1: cloneMember, translateMembers and retargetTos are GONE from this file — the move/copy
1754
+ // family is now entirely behind the model boundary, so none of the three had a caller left. Their six
1755
+ // ?selftest=1 assertions moved with them to server/steel-model-commands.test.ts, where the primitives
1756
+ // that replaced them live (clone / translate / retargetTos).
1757
+ // The model boundary's write half, rebuilt per call so it always sees the CURRENT active plan and default
1758
+ // T.O.S. `mintId` stays here because id policy is the editor's: the characterization harness pins
1759
+ // Date.now() inside this realm. doDup passes its OWN minter to clone() — its ids are '_'+i, not '_c'+seq.
1760
+ function MC(){return ModelCmd.createModelCommands(C,{activePlan:P,defaultTosIn:defaultTOS,mintId:()=>'m'+Date.now()+'_c'+(cmSeq++)});}
1481
1761
  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
1762
  // Rectangular array: counts INCLUDE the original position; (0,0) is skipped so the grid adds n*m-1 copies.
1483
1763
  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 +1774,6 @@ function parseVec(s){s=String(s==null?'':s).trim();if(!s)return null;
1494
1774
  const d=parseLen(s);return d==null?null:{dist:d};}
1495
1775
  // To-level TOS mapping (spec §4.5): default-follow ends land on the target level automatically;
1496
1776
  // 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
1777
  // best-effort: framing plans carry TOS at the level UNO — assume the L2 datum +16'-6" (198"); each end's
1503
1778
  // 'default' checkbox links it to this value (auto-updates when changed); uncheck to override.
1504
1779
  let defaultTOS=198, addProfile='', addType='beam'; // addType = the member type new members are drawn with (Add-member panel)
@@ -1512,9 +1787,7 @@ function armBaseTrim(colId){
1512
1787
  window.Steel3DView.setBasePickMode(colId);
1513
1788
  toast('Click a point along '+colId+' — the base snaps to framing levels · Esc cancels');
1514
1789
  }
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;}}
1790
+ 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
1791
  const autofillTOS=syncDefaults;
1519
1792
  // profs is per-plan — computed in setPlan()
1520
1793
  // Undo snapshot — WHOLE-MODEL on a SINGLE GLOBAL stack. Captures every plane's members AND each plane's
@@ -1564,15 +1837,29 @@ function apply(json){const d=JSON.parse(json);
1564
1837
  scheduleSave();render();sync3D();}
1565
1838
  function doUndo(){if(!undo.length)return;redo.push(snapshotLike());apply(undo.pop());}
1566
1839
  function doRedo(){if(!redo.length)return;undo.push(snapshotLike());apply(redo.pop());}
1567
- function edit(fn){const pv=snapshot();fn();pushUndo(pv);render();sync3D();}
1840
+ function edit(fn){
1841
+ // The stale-draft offer stops being safe the moment they build on the CURRENT version instead: clicking
1842
+ // "View my edits instead" afterwards would overlay the old edits on top of this new work and discard it
1843
+ // silently. Only that banner is dismissed — the AI-update and conflict bars MUST survive edits, which is
1844
+ // the entire reason the conflict bar exists. (unit 5, P1c-3)
1845
+ const _b=document.getElementById('aiUpdateBanner'); if(_b&&_b.dataset.kind==='staleBase')_b.remove();
1846
+ const pv=snapshot();fn();pushUndo(pv);render();sync3D();}
1568
1847
  // --- auto-save: edits persist to this browser (localStorage). Raster stays embedded; only members + TOS are stored. ---
1569
- const LSKEY = 'steeltakeoff:edits:v1:' + APP_ID;
1848
+ 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)
1849
+ // A structural guard, NOT a base identity — it only knows sheet names and segment counts, so two genuinely
1850
+ // different server contracts routinely produce the same string (members change; segment counts do not).
1851
+ // `baseEtag` is what decides whether the server moved; this decides whether the per-sheet overlay below is
1852
+ // even meaningful.
1570
1853
  function dataSig(){return C.plans.map(p=>p.sheet+':'+((p.segments||[]).length)).join('|');} // ignore stored edits if the dataset changed
1571
1854
  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');
1855
+ function setSaved(state,msg){const el=document.getElementById('saveStat');if(!el)return;el.classList.remove('dirty','ok','err','conflict');
1856
+ el.removeAttribute('data-tip'); el.onclick=null;
1573
1857
  if(state==='ok'){el.classList.add('ok');el.textContent=msg||'Saved ✓';}
1574
1858
  else if(state==='dirty'){el.classList.add('dirty');el.textContent='Saving…';}
1575
1859
  else if(state==='err'){el.classList.add('err');el.textContent='Save failed';}
1860
+ else if(state==='conflict'){el.classList.add('conflict');el.textContent='Save conflict';
1861
+ 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.';
1862
+ el.onclick=()=>showConflictBanner();} // the chip never acts on its own; it re-opens the banner
1576
1863
  else el.textContent=msg||'Auto-save on';}
1577
1864
  // Saved views (Views Organizer) — normalise an incoming array to clean, known-key entries. Robust to a
1578
1865
  // partial/stale server or localStorage draft (same discipline as dim_overlays): drops non-objects, mints a
@@ -1584,41 +1871,212 @@ function sanitizeViews(arr){return ViewGen.sanitizeViews(arr);}
1584
1871
  // async persistServer() PUT (or flushContract()), which resolves later and OWNS the 'ok'/'err' transition — so
1585
1872
  // green means the server truly has it. Every persist() caller is paired with such a server write (before or
1586
1873
  // 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,
1874
+ // `baseEtag` — the SERVER-ISSUED tag of the version these edits are a delta from, stored BESIDE the body
1875
+ // rather than derived from it. Derived-from-`C` was the bug: `dataSig()` is blind to everything except
1876
+ // sheet names and segment counts, so a newer server contract with the same shape (the ordinary case — an
1877
+ // AI revision changes members, not segments) compared EQUAL, and restoreSaved silently overlaid a stale
1878
+ // draft on top of it, masking the other write. See restampDraftBase() for why reading the CURRENT
1879
+ // serverEtag here is right, and why it must be re-stamped when a write lands.
1880
+ function persist(){try{localStorage.setItem(LSKEY,JSON.stringify({sig:dataSig(),baseEtag:serverEtag,ts:Date.now(),active:C.active,
1588
1881
  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,
1589
1882
  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
1883
  // --- server-side draft save: PUT the FULL contract C — this is the copy Approve bakes.
1591
1884
  // localStorage (persist) stays the instant per-browser draft cache; this is the durable one.
1592
1885
  // 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)});
1886
+ /**
1887
+ * A save was refused because someone else wrote to this model after we loaded it.
1888
+ *
1889
+ * INSIDE main() deliberately — this editor is one big closure, and `toast`, `persistServer` and the
1890
+ * conflict latch all live here. Declared outside, these would reference nothing.
1891
+ *
1892
+ * A pill alone is not enough, and that is the whole reason the banner exists: autosave means nobody is
1893
+ * watching the pill, so a conflict the user never notices means they keep editing a base that will never
1894
+ * save. Assertive but non-blocking — a modal here would rip focus mid-drag, and "keep editing" is a
1895
+ * legitimate choice.
1896
+ *
1897
+ * Deliberately actor-agnostic. A refused write tells us the model moved, not WHO moved it (another tab,
1898
+ * the AI, a workflow run), so the copy says "somewhere else" rather than claiming the AI did it — that
1899
+ * specific wording stays reserved for the SSE path, which actually knows.
1900
+ */
1901
+ /**
1902
+ * The 428 case: the server refused the save because the request carried no precondition.
1903
+ *
1904
+ * UNREACHABLE FROM THIS FILE, and the copy says so honestly rather than guessing a cause. Every write
1905
+ * path here sends one, so a 428 means a first-party writer has regressed — a bug in our code, not
1906
+ * something the user did or can diagnose. The first draft of this blamed "a tab left open across a
1907
+ * server upgrade"; review killed that, correctly: a page old enough to send no precondition is also
1908
+ * old enough to lack this branch, so it would never reach this banner. Telling the user their editor is
1909
+ * out of date would therefore be wrong every time it appeared.
1910
+ *
1911
+ * Kept anyway as a net: if a future writer regresses, this is a clear message plus a console error
1912
+ * instead of a bare "Save failed". Deliberately NOT the conflict copy (nothing else wrote), and
1913
+ * deliberately no "Save mine anyway" — there is nothing to overwrite, so the button would be a lie.
1914
+ * No auto-retry: an unchanged request would be refused identically.
1915
+ */
1916
+ function showSaveRefusedBanner(){
1917
+ showAiUpdateBanner('FloLess couldn’t save that change. Reload and try again — if it keeps happening, please report it.');
1918
+ }
1919
+ function showConflictBanner(){
1920
+ showAiUpdateBanner(
1921
+ 'This model was changed somewhere else while you were editing — your changes here didn’t save.',
1922
+ {
1923
+ // This used to delete the draft first, because restoreSaved() re-overlaid it whenever dataSig()
1924
+ // still matched — so a plain reload silently restored the very edits that had just conflicted. A
1925
+ // server-issued base retires that: the reload now finds the bases differ and OFFERS the edits back
1926
+ // instead of re-applying them, so the reason for throwing away the user's only copy is gone.
1927
+ onReload: () => { location.reload(); },
1928
+ onOverwrite: confirmOverwrite,
1929
+ });
1930
+ }
1931
+
1932
+ /**
1933
+ * The one destructive choice, so it is the one thing that blocks.
1934
+ *
1935
+ * Kept secondary and confirm-gated on purpose: the AI writing a revision is a first-class product action
1936
+ * here, so a stale tab must not clobber it with one stray click. The copy says what actually happens to
1937
+ * the other person's work rather than a soft "try again". Built from the existing .mbackdrop/.mpanel/
1938
+ * .danger tokens — no native confirm(), per the styled-modal rule.
1939
+ */
1940
+ function confirmOverwrite(){
1941
+ const back=document.createElement('div');
1942
+ back.className='modal'; back.style.cssText='position:fixed;inset:0;z-index:60;display:flex;align-items:center;justify-content:center';
1943
+ back.innerHTML='<div class=mbackdrop></div>'
1944
+ +'<div class=mpanel style="width:min(520px,92vw)">'
1945
+ +'<div class=mhead style="padding:14px 16px;border-bottom:1px solid var(--line);font-weight:600">Overwrite the other changes?</div>'
1946
+ +'<div style="padding:14px 16px;line-height:1.5">Someone else saved a version of this model after you opened yours. '
1947
+ +'Saving now replaces their version with what you see here — their changes will be gone for good.</div>'
1948
+ +'<div style="padding:12px 16px;display:flex;gap:8px;justify-content:flex-end;border-top:1px solid var(--line)">'
1949
+ +'<button id=cfCancel>Cancel</button><button id=cfGo class=danger>Overwrite and save</button></div></div>';
1950
+ document.body.appendChild(back);
1951
+ const close=()=>back.remove();
1952
+ back.querySelector('.mbackdrop').onclick=close;
1953
+ back.querySelector('#cfCancel').onclick=close;
1954
+ back.querySelector('#cfGo').onclick=async()=>{
1955
+ close();
1956
+ conflicted=false;
1957
+ await persistServer(true); // force: If-Match:* — deliberate, but still a precondition
1958
+ // Only claim success if the store actually took it. The first cut cleared the banner and toasted
1959
+ // unconditionally, so a force that itself failed told the user their work was saved when it was not
1960
+ // — the worst possible thing to be wrong about here.
1961
+ const el=document.getElementById('saveStat');
1962
+ if(el&&el.classList.contains('ok')){
1963
+ const bar=document.getElementById('aiUpdateBanner'); if(bar)bar.remove();
1964
+ toast('Saved — the other version was replaced.');
1965
+ } else {
1966
+ toast('Still not saved — nothing was overwritten.');
1967
+ }
1968
+ };
1969
+ }
1970
+
1971
+ // `force` REPLACES the precondition rather than skipping it — `If-Match: *` ("must exist") instead of the
1972
+ // exact tag, so a deliberate overwrite still cannot create a store out of nothing. Only the explicit
1973
+ // "Overwrite and save" confirm passes it. (This said "skips the precondition" until P1c made a write
1974
+ // without one a 428; it was already inaccurate, and would now describe an impossible request.)
1975
+ async function persistServer(force){const seq=saveSeq;
1976
+ // Once conflicted, stop firing doomed PUTs; re-surface the explanation instead of hammering the
1977
+ // network every debounce tick. Cleared only by a reload or a confirmed overwrite.
1978
+ if(conflicted&&!force){showConflictBanner();return;}
1979
+ return queueWrite(async()=>{
1980
+ // Name this write so its own SSE echo is recognised by identity, not by a 2.5 s clock (unit 5, P1c-3).
1981
+ // Minted BEFORE the request, deliberately: the broadcast can reach us before the response does, and an
1982
+ // id we do not yet know would read as somebody else's write and reload the page mid-edit.
1983
+ const mid=newMutationId();claimMutation(mid);
1984
+ 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
1985
+ const headers={'content-type':'application/json','x-floless-mutation-id':mid};
1986
+ // TOTAL, as of P1c: a write with no precondition is refused (428), so every branch must send one.
1987
+ // `*` on force = "must exist", a deliberate overwrite. No tag at all means we read through the BAKED
1988
+ // fallback (the GET tags only store-backed documents), i.e. this app has no draft yet — so the honest
1989
+ // precondition is `If-None-Match: *`, "I believe this store is empty". It also wins us a real check:
1990
+ // two editors both seeing no tag used to both create, last one silently winning.
1991
+ if(force)headers['if-match']='*';
1992
+ else if(serverEtag)headers['if-match']=serverEtag;
1993
+ else headers['if-none-match']='*';
1994
+ const res=await fetch('/api/contract/'+encodeURIComponent(APP_ID)+PROJECT_QS,{method:'PUT',headers,body:JSON.stringify(C)});
1995
+ // A REFUSED write produces no broadcast, so its id would sit in ownWrites forever — where the only
1996
+ // thing it can still do is wrongly suppress somebody else's event. Released on every leg below.
1997
+ if(res.status===428){ // a writer here sent no precondition — a bug in our code; see showSaveRefusedBanner
1998
+ releaseMutation(mid);
1999
+ console.error('save refused 428 — a first-party writer sent no precondition; this is a FloLess bug');
2000
+ if(seq===saveSeq)setSaved('err');
2001
+ showSaveRefusedBanner();
2002
+ return;
2003
+ }
2004
+ if(res.status===412){ // NOT a failure of the user's document — someone else wrote here since we loaded
2005
+ releaseMutation(mid);
2006
+ conflicted=true;
2007
+ if(seq===saveSeq)setSaved('conflict');
2008
+ showConflictBanner();
2009
+ return;
2010
+ }
2011
+ // NOTE the asymmetry, which is deliberate: success does NOT release the id. The echo for this very
2012
+ // write is usually still in flight — the server broadcasts before it replies — so releasing here would
2013
+ // make the tab read its OWN echo as external and reload itself mid-edit. The id is released when the
2014
+ // echo consumes it, when the write fails, or when the SSE channel closes (nothing can echo after that).
2015
+ 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)
2016
+ else releaseMutation(mid); // 400/500: nothing was written, so nothing will echo
1596
2017
  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
2018
  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)
2019
+ }catch(e){releaseMutation(mid);if(seq===saveSeq)setSaved('err');console.error('server save failed',e);}
2020
+ });}
2021
+ 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
2022
  // Flush: cancel the pending debounce and PUT the current in-memory contract to the
1601
2023
  // server right now. The parent (aware.js #contract-editor-approve) awaits this before
1602
2024
  // POSTing approve, so Approve always bakes the latest edits — not a stale debounce
1603
2025
  // snapshot. Throws on a non-2xx response so the parent can abort and show the warn toast.
1604
2026
  window.flushContract = async () => {
1605
- clearTimeout(saveT);
1606
- lastLocalPut = Date.now();
2027
+ clearTimeout(saveT); saveT = null; // the debounced write is being taken over by this flush, so it is no longer pending
2028
+ // Behind the SAME queue as autosave — Approve awaits this, and a flush racing an in-flight autosave
2029
+ // was the self-conflict path that could abort Approve for no reason.
2030
+ return queueWrite(async () => {
2031
+ const mid = newMutationId(); claimMutation(mid); // same own-echo identity as persistServer — see there
1607
2032
  const seq = ++saveSeq;
1608
2033
  let res;
1609
2034
  try {
2035
+ // Conditional like every other write, and it MUST refresh the tag on success. Getting this wrong is
2036
+ // not theoretical — the first cut omitted both, so an Approve-time flush bypassed the precondition
2037
+ // AND left `serverEtag` stale, which made the very next autosave fail against a change the user had
2038
+ // just made themselves. A conflict banner for your own edit is worse than no banner.
2039
+ const headers = { 'content-type': 'application/json', 'x-floless-mutation-id': mid };
2040
+ // Same total rule as persistServer — see the comment there for why "no tag" means If-None-Match: *.
2041
+ if (serverEtag) headers['if-match'] = serverEtag; else headers['if-none-match'] = '*';
1610
2042
  res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS, {
1611
- method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(C),
2043
+ method: 'PUT', headers, body: JSON.stringify(C),
1612
2044
  });
1613
2045
  } catch (e) {
2046
+ releaseMutation(mid); // nothing was written, so no broadcast will ever carry this id
1614
2047
  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
2048
  throw e; // still reject so the parent (Approve) aborts — regardless of seq
1616
2049
  }
2050
+ if (res.status === 428) { // same cause as persistServer's 428 branch — a writer sent no precondition
2051
+ releaseMutation(mid);
2052
+ console.error('flush refused 428 — a first-party writer sent no precondition; this is a FloLess bug');
2053
+ if (seq === saveSeq) setSaved('err');
2054
+ showSaveRefusedBanner();
2055
+ throw new Error('save refused: no precondition sent');
2056
+ }
2057
+ if (res.status === 412) {
2058
+ // Approve must abort (the throw below), and the user needs to know WHY — a bare "save failed" toast
2059
+ // would send them looking for a problem in their own model.
2060
+ releaseMutation(mid);
2061
+ conflicted = true;
2062
+ if (seq === saveSeq) setSaved('conflict');
2063
+ showConflictBanner();
2064
+ throw new Error('save conflict');
2065
+ }
2066
+ if (res.ok) { const t = res.headers.get('ETag'); if (t) { const pv = serverEtag; serverEtag = t; restampDraftBase(pv, t); } conflicted = false; }
2067
+ else releaseMutation(mid);
1617
2068
  if (seq === saveSeq) setSaved(res.ok ? 'ok' : 'err'); // only the latest save owns the pill
1618
2069
  if (!res.ok) throw new Error('save failed (' + res.status + ')');
2070
+ });
1619
2071
  };
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);
2072
+ /**
2073
+ * Overlay a stored draft's fields onto C.
2074
+ *
2075
+ * Extracted from restoreSaved() (unit 5, P1c-3) so the AUTOMATIC restore and the user-initiated "View my
2076
+ * edits instead" apply exactly the same fields. Two copies of this list would drift, and the failure would
2077
+ * be silent: a field the button forgot would simply not come back, looking like it was never saved.
2078
+ */
2079
+ function applyDraftFields(d){const by={};(d.plans||[]).forEach(p=>by[p.sheet]=p);
1622
2080
  if(d.custom_details)C.custom_details=d.custom_details;
1623
2081
  if(d.profile_colors)C.profile_colors=d.profile_colors;
1624
2082
  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)
@@ -1632,7 +2090,111 @@ function restoreSaved(){try{const raw=localStorage.getItem(LSKEY);if(!raw)return
1632
2090
  if('prop_labels' in d)C.prop_labels=sanitizePropLabels(d.prop_labels); // restore canvas property-label display state (sanitised to known keys/placement)
1633
2091
  if(Array.isArray(d.joints))C.joints=d.joints; // restore model-global connection joints (base plates) from the local draft
1634
2092
  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;}}
2093
+ if(d.active!=null)C.active=d.active;}
2094
+ /**
2095
+ * The bar for "your unsaved edits are older than what the server now holds".
2096
+ *
2097
+ * Default is the SERVER's version — the one thing that can lose data here is silently showing the user
2098
+ * their own old edits while a colleague's or the AI's newer work sits unseen on the server, which is
2099
+ * exactly what the coarse dataSig() check used to allow. Their edits are not discarded; they stay in
2100
+ * storage and this offers them back.
2101
+ *
2102
+ * One click, no confirm: nothing server-side changes when they look. What DOES need care is what happens
2103
+ * on the next autosave — see the handler.
2104
+ */
2105
+ function showStaleDraftBanner(d){
2106
+ 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.',{
2107
+ kind:'staleBase',
2108
+ reloadLabel:'View my edits instead',
2109
+ reloadTip:'Switch to the changes you made before. The version on the server won’t change unless you edit and save again.',
2110
+ onReload:()=>{
2111
+ applyDraftFields(d);
2112
+ // REWIND the tag to the one those edits were built on. Without this the next autosave would carry
2113
+ // the CURRENT server tag, satisfy the precondition, and silently replace the newer version with
2114
+ // these older edits — no 412, no banner, no warning. With it, the next save is correctly refused
2115
+ // and drops into the conflict flow that already exists (banner → confirm → "Save mine anyway").
2116
+ // `|| null` because a v1-era draft carries no base: a null tag sends `If-None-Match: *`, which a
2117
+ // non-empty store also refuses. Same destination, same protection.
2118
+ serverEtag=d.baseEtag||null;
2119
+ // The offer has been taken; these edits are the live document again, so the parked copy is no
2120
+ // longer a separate thing to protect. persist() will write them back to the main row on the next
2121
+ // edit, now correctly based on the tag they were built from.
2122
+ try{localStorage.removeItem(offeredKey());localStorage.setItem(LSKEY,JSON.stringify(d));}catch(_){}
2123
+ const bar=document.getElementById('aiUpdateBanner'); if(bar)bar.remove();
2124
+ // Repaint in place rather than reload: the server tag has not moved, so a reload would re-detect the
2125
+ // same stale base and put the bar straight back up. Deliberately no scheduleSave() — merely LOOKING
2126
+ // at the old edits must not fire a write (and a conflict banner) on their behalf.
2127
+ render();sync3D();
2128
+ toast('Showing your earlier edits — not yet saved to the server.');
2129
+ },
2130
+ });
2131
+ }
2132
+ /**
2133
+ * Decide what this browser's stored edits do to the freshly-loaded contract.
2134
+ *
2135
+ * Wraps the real decision so a PARKED offer (see offeredKey) is re-made on every reload rather than
2136
+ * only on the load that first detected it — otherwise a user who reloads instead of answering the bar
2137
+ * loses track of edits the bar told them were still saved.
2138
+ */
2139
+ function restoreSaved(){
2140
+ const applied=restoreSavedInner();
2141
+ try{
2142
+ const oraw=localStorage.getItem(offeredKey());
2143
+ if(oraw){
2144
+ // A parked offer is not RE-OFFERED once fresh edits restore cleanly on top of the current version:
2145
+ // those are the user's latest work, and offering the older copy would walk them backwards. But it
2146
+ // is not deleted either — that reasoning argues against showing it, never against keeping it, and
2147
+ // deleting here made the banner's promise false after one edit and one reload, silently, because
2148
+ // edit() retires the bar first. One small row per store is the price of keeping the promise.
2149
+ if(!applied){
2150
+ const od=JSON.parse(oraw);
2151
+ // The SAME structural gate the live row gets, which review found this path had skipped.
2152
+ // applyDraftFields overlays per SHEET, so offering a draft built against a different dataset
2153
+ // would let the user apply edits that cannot fit — the very masking the live gate prevents,
2154
+ // reachable through the parked copy instead.
2155
+ if(od&&typeof od==='object'&&od.sig===dataSig())showStaleDraftBanner(od);
2156
+ // Deliberately NOT deleted when it does not fit. dataSig() is derived from the server document,
2157
+ // and a rollback can restore the dataset these edits were built against — at which point they
2158
+ // become offerable again. An unofferable row is one small row per store; discarding the user's
2159
+ // only copy to save it is the trade this whole item exists to refuse.
2160
+ else if(od)console.warn('steel-editor: parked edits do not match this drawing set — not offered');
2161
+ }
2162
+ }
2163
+ }catch(_){
2164
+ // Unreadable, therefore un-offerable, therefore pure leak — unlike a row that merely does not FIT
2165
+ // this dataset, which a rollback can make offerable again. Reclaim only the unparseable case.
2166
+ try{localStorage.removeItem(offeredKey());}catch(__){}
2167
+ }
2168
+ return applied;
2169
+ }
2170
+ function restoreSavedInner(){try{const raw=localStorage.getItem(LSKEY);if(!raw)return false;const d=JSON.parse(raw);
2171
+ // Structural first: the overlay below is per-sheet, so it is meaningless if the sheets moved.
2172
+ if(d.sig!==dataSig())return false;
2173
+ // Then the real base check. `serverEtag` is the tag boot() just read — main() is called synchronously
2174
+ // from boot() and nothing writes before this point, so it has not been advanced by a save yet. (If a
2175
+ // future change schedules a write earlier, this comparison silently starts meaning something else.)
2176
+ // Both sides must be present to compare: the baked-.flo fallback legitimately serves NO ETag, and a
2177
+ // v1-era draft carries no base, so "cannot compare" falls back to dataSig() alone — the weakest check
2178
+ // available, strictly no worse than before this PR, and stated rather than papered over.
2179
+ // A draft made against a store that served NO tag, where the store now serves one, is stale by
2180
+ // construction: only a write can make a store tag-bearing, so somebody wrote. `'baseEtag' in d`
2181
+ // separates that from a v1-era row, which has no such key at all and must keep the dataSig fallback.
2182
+ const bornTagless = ('baseEtag' in d) && d.baseEtag == null && !!serverEtag;
2183
+ if(bornTagless || (typeof d.baseEtag==='string'&&d.baseEtag&&serverEtag&&d.baseEtag!==serverEtag)){
2184
+ // PARK it, do not merely leave it: the main row is live, so the user's first edit on the current
2185
+ // version would overwrite these edits — and edit() retires the offer bar before that happens, so
2186
+ // they would never see them go. The banner promises they are still saved on this computer, and
2187
+ // that promise has to survive an ordinary next action.
2188
+ // ONE parked offer per store, and the FIRST one wins. A second refusal (park → ignore → edit → the
2189
+ // server moves again) must not overwrite it: that row is the one the banner already promised was
2190
+ // still saved, so it is the one thing here that must not be the casualty. The newer draft stays in
2191
+ // the live row, which is exactly where it sat before parking existed. An unbounded pile of offers
2192
+ // is the alternative, and one promise kept beats two promises half-kept.
2193
+ try{if(localStorage.getItem(offeredKey())==null){localStorage.setItem(offeredKey(),raw);localStorage.removeItem(LSKEY);}}catch(_){/* the offer is still made from memory below */}
2194
+ showStaleDraftBanner(d);
2195
+ return false;
2196
+ }
2197
+ applyDraftFields(d);return true;}catch(e){console.warn('discarding corrupt local draft',e);return false;}}
1636
2198
  function updUR(){document.getElementById('undoB').disabled=!undo.length;document.getElementById('redoB').disabled=!redo.length;}
1637
2199
  // Canonical, model-global palette rank (B2): EVERY plan's non-blank member profiles ∪ weight-table keys,
1638
2200
  // uppercased + sorted — the SAME basis contract-to-scene.ts uses, so a profile gets ONE hue in the 2D legend
@@ -2078,7 +2640,7 @@ function deleteSelGrids(){
2078
2640
  const glLids=new Set([...selGridIds].filter(id=>id.startsWith('gl:')).map(id=>id.slice(3)));
2079
2641
  const freeToDelete=(P.grid&&Array.isArray(P.grid.lines))?P.grid.lines.filter(l=>glLids.has(String(l.id))):[];
2080
2642
  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();});
2643
+ if(freeToDelete.length)edit(()=>{ModelCmd.removeGridLines(P.grid,glLids);selGridIds.clear();});
2082
2644
  else{selGridIds.clear();render();}
2083
2645
  if(hadReg)toast('Regular grid lines come from the grid spacing — remove them in “Grid lines…”. Only free grid lines are deletable here.');}
2084
2646
  // cursor-following distance readout for grid drags (same chrome as the 3D drag readout)
@@ -2107,10 +2669,10 @@ function gridRenameBubble(axis,gi,anchorEl){
2107
2669
  const nv=inp.value.trim();
2108
2670
  if(!nv||nv===cur)return;
2109
2671
  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;}
2672
+ if(axis==='l'){edit(()=>{ModelCmd.setGridLineLabel(P.grid,gi,nv);});return;}
2111
2673
  const key=axis==='v'?'labels_x':'labels_y',style=axis==='v'?'num':'alpha';
2112
2674
  const toks=gc.labelsFor(P.grid[key],style,lines.length);toks[gi]=nv;
2113
- edit(()=>{P.grid[key]=toks.join(' ');});};
2675
+ edit(()=>{ModelCmd.patchGrid(P.grid,{[key]:toks.join(' ')});});};
2114
2676
  inp.addEventListener('keydown',ev=>{ev.stopPropagation();
2115
2677
  if(ev.key==='Enter'){ev.preventDefault();finish(true);}
2116
2678
  else if(ev.key==='Escape'){ev.preventDefault();finish(false);}});
@@ -2126,7 +2688,7 @@ function sanitizePlanGrid(pl){if(!pl||pl.grid==null)return;const g=pl.grid;
2126
2688
  sanitizeGridLines(g);}
2127
2689
  function gridLineId(){return 'gl'+Date.now().toString(36)+Math.floor(Math.random()*1000).toString(36);}
2128
2690
  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:[]};}
2691
+ 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
2692
  // 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
2693
  // 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
2694
  const GRID_LINE_MIN_DISP=6;
@@ -2135,8 +2697,8 @@ const GRID_LINE_MIN_DISP=6;
2135
2697
  // meaningless while the user is in 3D, so inheriting it would make an identical 3D pick commit or get rejected
2136
2698
  // depending on a hidden viewport (fitted at zoom≈0.2 it would silently refuse lines under ~2.5 ft).
2137
2699
  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;}
2700
+ gridEnsureForLine(a);
2701
+ ModelCmd.addGridLine(P.grid,{id:gridLineId(),label:label||gridNextLineLabel(),a:a.slice(),b:b.slice()});return true;}
2140
2702
  function gridSetPickClass(){document.body.classList.toggle('gridpick',!!gridPick||!!gridLinePick);
2141
2703
  // ONE choke point for the 3D side: every path that arms or tears down the pick (start, cancel, setGridMode,
2142
2704
  // Move/Copy arm, plan switch, view switch) already calls this, so the 3D pick can never outlive the 2D flag.
@@ -2166,7 +2728,7 @@ function gridReadFromDrawing(keep){
2166
2728
  if(keep.labels_y)g.labels_y=keep.labels_y;
2167
2729
  g.labels_z=Array.isArray(keep.labels_z)?keep.labels_z.slice():[];
2168
2730
  if(Array.isArray(keep.hidden_z)&&keep.hidden_z.length)g.hidden_z=keep.hidden_z.slice();}
2169
- edit(()=>{P.grid=g;});
2731
+ edit(()=>{ModelCmd.setPlanGrid(P,g);});
2170
2732
  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
2733
  // The bubble marks on most CAD sets are OUTLINED (not text), so the detector can't read them. The
2172
2734
  // sanctioned path for that gap is the Ask-AI relay (the UI never calls an LLM): pre-fill the existing
@@ -2189,7 +2751,7 @@ function updGridToggle(){const b=document.getElementById('gridToggleB');if(!b)re
2189
2751
  // and the ⋯ menu item — all call this. grid.on is contract data, so the flip is undoable like every
2190
2752
  // other grid operation.
2191
2753
  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();}
2754
+ edit(()=>{ModelCmd.patchGrid(P.grid,{on:!!on});});updGridToggle();refresh3DGrid();if(view3d)build3DLegend();}
2193
2755
  document.addEventListener('gridcore-ready',()=>{try{if(C)render();}catch(_){}}); // module shim finished after boot → paint the grid layer
2194
2756
  function setGridMode(on){if(!C)return;gridMode=!!on;
2195
2757
  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 +2802,8 @@ function renderGridPanel(p){
2240
2802
  <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
2803
  document.getElementById('gridLineB').onclick=gridStartLinePick;
2242
2804
  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);});};
2805
+ 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);});};
2806
+ const bb=document.getElementById('gridBlankB');if(bb)bb.onclick=()=>{const o=gridDefaultOrigin();edit(()=>{ModelCmd.setPlanGrid(P,gc.defaultGrid(o));});};
2245
2807
  return;}
2246
2808
  const g=P.grid,nCols=planColumnCount();
2247
2809
  const normSp=v=>{const r=gc.parseSpacings(v);return r.err?String(v||''):gc.formatSpacings(r.offsets);};
@@ -2311,27 +2873,27 @@ function renderGridPanel(p){
2311
2873
  else if(ev.key==='Escape'){ev.preventDefault();el.value=orig;fbAll();}});
2312
2874
  el.addEventListener('change',()=>commit(el.value.trim(),el));};
2313
2875
  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;});});
2876
+ if(P.grid.ends_x&&r.offsets.length!==gc.parseSpacings(P.grid.x).offsets.length)ModelCmd.patchGrid(P.grid,{ends_x:undefined});
2877
+ ModelCmd.patchGrid(P.grid,{x:next});});});
2316
2878
  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;});});
2879
+ if(P.grid.ends_y&&r.offsets.length!==gc.parseSpacings(P.grid.y).offsets.length)ModelCmd.patchGrid(P.grid,{ends_y:undefined});
2880
+ ModelCmd.patchGrid(P.grid,{y:next});});});
2881
+ 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);});
2882
+ wire('gLX',(v)=>{if(v!==(g.labels_x||''))edit(()=>{ModelCmd.patchGrid(P.grid,{labels_x:v});});});
2883
+ wire('gLY',(v)=>{if(v!==(g.labels_y||''))edit(()=>{ModelCmd.patchGrid(P.grid,{labels_y:v});});});
2884
+ 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});});});});
2885
+ 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});});}));
2886
+ 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
2887
  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)
2888
+ 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
2889
+ 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
2890
  document.getElementById('gridLineB').onclick=gridStartLinePick;
2329
- const gcl=document.getElementById('gridClearLinesB');if(gcl)gcl.onclick=()=>{edit(()=>{delete P.grid.lines;});};
2891
+ const gcl=document.getElementById('gridClearLinesB');if(gcl)gcl.onclick=()=>{edit(()=>{ModelCmd.clearGridLines(P.grid);});};
2330
2892
  document.getElementById('gridPickB').onclick=()=>{gridPick=!gridPick;gridLinePick=null;gridSetPickClass();panel();};
2331
2893
  const r2=document.getElementById('gridReadB2');if(r2)r2.onclick=()=>gridReadFromDrawing(P.grid);
2332
2894
  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;});};
2895
+ 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
2896
+ document.getElementById('gridRemoveB').onclick=()=>{edit(()=>{ModelCmd.setPlanGrid(P,null);});};
2335
2897
  document.getElementById('gridDoneB').onclick=()=>{setGridMode(false);render();};
2336
2898
  }
2337
2899
  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 +2910,11 @@ function repeatLast(){if(lastCmd){lastCmd.run();if(typeof toast==='function')toa
2348
2910
  // Multi: trim/extend the nearest end of EVERY given member to the (tA,tB) target line; members
2349
2911
  // parallel to the target (no intersection) are skipped. One undo for the whole batch.
2350
2912
  function snapEndMulti(ms,tA,tB){const pv=snapshot();let n=0,skipped=0;
2913
+ const mc=MC(); // hoisted: ms is the whole selection, so building the commands object per member would be a batch-latency regression
2351
2914
  for(const m of ms){
2352
2915
  if(isBrace(m)){skipped++;continue;} // extend/trim never moves a brace work point (it must stay on the column ℄) — matches doSplit
2353
2916
  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++;}
2917
+ 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
2918
  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
2919
  if(n){pushUndo(pv);render();sync3D();}return n;}
2357
2920
  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 +2922,15 @@ function doSplit(m,pt){if(isBrace(m)){toast('Braces can’t be split — edit th
2359
2922
  // 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
2923
  // would silently jump — detach every ref to m in its plan before geometry moves (safe-freeze; pv above still has
2361
2924
  // 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];}
2925
+ const own=planeOfMember(m);
2926
+ {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
2927
  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];
2928
+ const mc=MC();
2929
+ mc.replaceEndpoints(m,[a,q]);if(m.ends)m.ends=[m.ends[0],mk()]; // first half keeps its start end, fresh cut end
2930
+ 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
2931
+ mc.replaceEndpoints(c,[q.slice(),b]);
2366
2932
  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();}
2933
+ 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
2934
  // --- duplicates: members with coincident geometry (same two work-points, order-independent, ~3px tol) ---
2369
2935
  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
2936
  // Elevation signature. Two members at the SAME footprint but a DIFFERENT explicit top-of-steel are different
@@ -2391,7 +2957,10 @@ function dedupeFootprintIds(members,rankFn){const byFoot={};for(const m of membe
2391
2957
  function redundantDups(){return dedupeFootprintIds(P.members,dupScore);}
2392
2958
  // --- merge collinear chords: same-profile, end-to-end, STRAIGHT beam runs → one member each.
2393
2959
  // 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.
2960
+ // THE source of truth. There used to be a second copy at server/steel-merge.ts calling itself the
2961
+ // "tested source of truth"; it had zero production callers and had already drifted (it never gained the
2962
+ // affectedIds this one returns), so it was deleted — unit 5, P3c-3c. Its rules are pinned against THIS
2963
+ // copy in server/steel-editor-characterization.test.ts, "merge (live copy): …".
2395
2964
  const MRG_END=3, MRG_ANG=3*Math.PI/180, MRG_TOS=0.5;
2396
2965
  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
2966
  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 +3033,10 @@ function zoomCentered(z){const r=stage.getBoundingClientRect();applyZoom(z,r.lef
2464
3033
  function fitToWindow(){applyZoom(Math.min(stage.clientWidth/EXTX,stage.clientHeight/EXTY)*0.98);}
2465
3034
  // --- duplicate the selected member(s) in place (Ctrl+D) ---
2466
3035
  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);}
3036
+ 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
3037
+ 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)
3038
+ 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
3039
+ mc.addMembers(P,[c]);ns.add(c.id);}
2469
3040
  selIds=ns;selDimIds.clear();mode='sel';setMode();pushUndo(pv);render();}
2470
3041
  function esc(s){return String(s).replace(/[<>&"]/g,c=>({'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'}[c]));}
2471
3042
  function render(){
@@ -2927,8 +3498,8 @@ function panel(){
2927
3498
  '<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
3499
  '<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
3500
  '<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;}}});
3501
+ 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
3502
+ 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
3503
  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
3504
  const _rc=document.getElementById('resetCols');if(_rc)_rc.onclick=()=>{C.profile_colors={};scheduleSave();render();};
2934
3505
  return;}
@@ -3005,11 +3576,11 @@ function panel(){
3005
3576
  const chip=(id,val)=>{const b=document.getElementById(id);if(b)b.onclick=()=>setRot(val);};
3006
3577
  chip('rot0',0);chip('rot90',90);chip('rot180',180);chip('rot270',270);}
3007
3578
  // 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;}});};};
3579
+ 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);});}
3580
+ 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
3581
  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
3582
  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;});}}
3583
+ {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
3584
  wMTos('tosC',cs);wMText('ntC',cs,(o,v)=>o.note=v);wMText('dtC',cs,(o,v)=>o.detail=v);}
3014
3585
  else if(allBeam){const s0=beams.map(m=>m.ends[0]),s1=beams.map(m=>m.ends[1]);
3015
3586
  wMTos('tosA',s0);wMText('ntA',s0,(o,v)=>o.note=v);wMText('dtA',s0,(o,v)=>o.detail=v);
@@ -3019,8 +3590,7 @@ function panel(){
3019
3590
  // edit() pushes undo unconditionally, so an all-brace selection must not enter it (Codex round-4).
3020
3591
  {const me=document.getElementById('matchEnds');if(me)me.onclick=()=>{
3021
3592
  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};});
3593
+ if(targets.length)edit(()=>{for(const m of targets)ModelCmd.copyEndTo(m,0,1);});
3024
3594
  if(sk)toast(sk+' brace'+(sk>1?'s':'')+' skipped — matching ends would flatten the slope its arrows encode');};}}
3025
3595
  return;}
3026
3596
  const m=ensureMeta(arr[0]), wpf=_wt(m.profile), L=_lenFt(m).toFixed(1), col=(m.role==='column'), pos=posDefault(m);
@@ -3124,9 +3694,10 @@ function panel(){
3124
3694
  // plain X/Y move keeps a default-following Top on the sheet default (a tilted-frame local edit that really moves
3125
3695
  // Z still clears it). Same per-end TOS rule for a beam.
3126
3696
  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;}}});
3697
+ const mc=MC();
3698
+ 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]
3699
+ 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
3700
+ else{mc.setEndpoint(m,i,[nx,ny]);if(zChg)ModelCmd.setTosValue(m.ends[i],Pt[2]);}});
3130
3701
  const _dpAxes=['X','Y','Z'];
3131
3702
  const _dpPH='5 3/4&quot; · 1&#39;-0 1/4&quot;';
3132
3703
  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,14 +3774,14 @@ function panel(){
3203
3774
  const _ri=document.getElementById('detRotZ');if(_ri)_ri.onchange=e=>setRot(e.target.value);
3204
3775
  const chip=(id,val)=>{const b=document.getElementById(id);if(b)b.onclick=()=>setRot(val);};
3205
3776
  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;});};
3777
+ const wireTos=(id,o)=>{const ck=document.getElementById(id+'_ck');if(ck)ck.onchange=e=>edit(()=>{ModelCmd.setTosDefault(o,e.target.checked,defaultTOS);});
3778
+ const inp=document.getElementById(id);if(inp)inp.onchange=e=>edit(()=>{ModelCmd.setTosValue(o,parseLen(e.target.value));});};
3208
3779
  const wireDet=(id,o)=>{const i=document.getElementById(id);if(i)i.onchange=e=>edit(()=>{o.detail=e.target.value.trim();});
3209
3780
  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
3781
  const op=document.getElementById(id+'_open');if(op)op.onclick=()=>openPreview(o.detail);};
3211
3782
  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
3783
  if(col){
3213
- document.getElementById('bos').onchange=e=>edit(()=>{m.col.bos=parseLen(e.target.value);});
3784
+ document.getElementById('bos').onchange=e=>edit(()=>{ModelCmd.setBos(m.col,parseLen(e.target.value));});
3214
3785
  wireTos('tosC',m.col);
3215
3786
  document.getElementById('ntC').onchange=e=>edit(()=>{m.col.note=e.target.value;});
3216
3787
  wireDet('dtC',m.col);wireConn('cnC',m.col);
@@ -3235,7 +3806,7 @@ function panel(){
3235
3806
  // Not rendered for a brace — matching ends would FLATTEN the slope its arrowheads encode. Null-guarded
3236
3807
  // (the element is absent) plus a defensive isBrace check. (Codex round-4)
3237
3808
  {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};});};}
3809
+ if(me)me.onclick=()=>{if(isBrace(m))return;edit(()=>{ModelCmd.copyEndTo(m,0,1);});};}
3239
3810
  // shear-plate inspector wiring (per detailed end) — every mutation rides edit() → undoable; editing
3240
3811
  // makes the plate user-owned (survives the auto-detail "Clear"). Bolt grid capped (rows×cols = parts).
3241
3812
  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 +3851,7 @@ function panel(){
3280
3851
  }
3281
3852
  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
3853
  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);
3854
+ applyMemberType([nm],addType);MC().addMembers(P,[nm]); // applyMemberType writes role/memberType, not geometry — it stays here
3284
3855
  if(prof&&!profs.includes(prof)){profs.push(prof);profs.sort();}pushUndo(pv);render();sync3D();}
3285
3856
  // --- marquee hit-test (crossing selection): does segment ab touch rect [x0,y0,x1,y1]? ---
3286
3857
  function inRect(p,r){return p[0]>=r[0]&&p[0]<=r[2]&&p[1]>=r[1]&&p[1]<=r[3];}
@@ -3837,7 +4408,7 @@ function drawClick(e){const s=dimSnapAt(e,drawDraft);const p=[s.x,s.y]; // dim
3837
4408
  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
4409
  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
4410
  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
4411
+ applyMemberType([nm],addType);MC().addMembers(P,[nm]); // the Add-member panel's type owns role + legend category
3841
4412
  if(addProfile&&!profs.includes(addProfile)){profs.push(addProfile);profs.sort();}pushUndo(pv);
3842
4413
  drawDraft=null;render();drawPrev(e);} // commit → clear the draft, keep the tool armed for the next member
3843
4414
  function drawPrevClear(){const g=document.getElementById('drawPrevLine');if(g)g.remove();snapClear();}
@@ -4042,10 +4613,11 @@ function dimEditCommit(){
4042
4613
  const mem=id=>(P.members||[]).find(x=>x&&x.id===id),addv=(p,v)=>[p[0]+v[0],p[1]+v[1]];
4043
4614
  edit(()=>{
4044
4615
  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.
4616
+ 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
4617
  const doEnd=(driven,ref,mv,rawKey)=>{if(!driven)return;
4046
4618
  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);}}
4619
+ 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.
4620
+ 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
4621
  else{d[rawKey]=addv(d[rawKey],mv);}}; // pin OFF, or an unref'd end → move the dim's own coord
4050
4622
  doEnd(effA>0,aRef,mvA,'a');doEnd(effB>0,bRef,mvB,'b');
4051
4623
  });
@@ -4165,11 +4737,8 @@ function cmClick(e){
4165
4737
  function cmApplyOffsets(offs){const sel=sel2d();if(!sel.length){toast('Selection is empty — '+(cmTool==='move'?'Move':'Copy')+' ended');disarmCm();render();return;}
4166
4738
  if(cmArrayMode&&cmCountA*cmCountB>100){toast('Array capped at 100 instances — lower the counts (two passes reach further)');return;}
4167
4739
  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)
4740
+ 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
4741
+ if(cmTool!=='move')selIds=new Set(ns);}); // copy selects the new set (numbered badges); a move leaves the selection alone
4173
4742
  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
4743
  toast((cmTool==='move'?'Moved ':'Copied ')+sel.length+' member'+(sel.length===1?'':'s')+(offs.length>1?' ×'+offs.length:'')+' · '+fmtFtIn(L/FT*12));
4175
4744
  cmHudClose();cmDraft=null;cmPrevClear();panel();} // tool stays armed for the next pick pair; Esc finishes
@@ -4277,19 +4846,19 @@ function openLevelModal(tool){ // works from 2D and 3D — the commit is plan-
4277
4846
  const cancel=document.createElement('button');cancel.textContent='Cancel';cancel.onclick=closeLevelModal;
4278
4847
  go.onclick=()=>{if(pick>=0){toLevelCommit(tool,pick);closeLevelModal();}};
4279
4848
  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)
4849
+ 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
4850
  if(!sel.length){toast('Selection is empty — nothing to '+(tool==='move'?'move':'copy'));return;}
4282
4851
  if(!T)return;
4283
- if(!Array.isArray(T.members))T.members=[];
4852
+ 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
4853
  const dstDef=(T.default_tos!=null?T.default_tos:198);
4285
4854
  const pv=snapshot(); // whole-model pre-mutation → one global-stack entry undoes the source removals AND the target adds
4286
4855
  const moved=[];
4287
4856
  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
4857
  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);}
4858
+ const c=(tool==='copy')?mc.clone(m):m;mc.retargetTos(c,srcDef,dstDef);moved.push(c);}
4290
4859
  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);
4860
+ 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
4861
+ mc.addMembers(T,moved);T.members.forEach(ensureMeta); // forEach normalizes the WHOLE target sheet, not just `moved` — addMembers must not absorb it
4293
4862
  pushUndo(pv);disarmCm();render();sync3D(); // one global-stack entry; disarm BEFORE render so the panel never advertises a dead tool
4294
4863
  toast((tool==='move'?'Moved ':'Copied ')+moved.length+' member'+(moved.length===1?'':'s')+' to '+T.sheet);}
4295
4864
  // --- Local coordinate system "set axes" tool: two snapped clicks (origin, then X-direction) define
@@ -4349,9 +4918,11 @@ function updCS(){const s=document.getElementById('csStat');const r=document.getE
4349
4918
  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
4919
  if(r)r.disabled=!(P&&P.frame);}
4351
4920
  // themed transient toast (baseline tokens — never a native alert)
4352
- function toast(msg){let t=document.getElementById('toast');
4921
+ // `sticky` holds the toast up with no timer — for an operation whose result the user must see land
4922
+ // (the Tekla send takes seconds); the next plain toast() replaces the text and re-arms the timer.
4923
+ function toast(msg,sticky){let t=document.getElementById('toast');
4353
4924
  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);}
4925
+ t.textContent=msg;t.style.opacity='1';clearTimeout(t._h);if(!sticky)t._h=setTimeout(()=>{t.style.opacity='0';},2600);}
4355
4926
  // --- pointer: select(+ctrl toggle / box) + group-move + endpoint (Shift = ortho) ---
4356
4927
  svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
4357
4928
  if(csaxisMode){csClick(e);e.preventDefault();return;} // set-local-axes armed → clicks define origin then X-direction
@@ -4362,7 +4933,7 @@ svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
4362
4933
  else{const a=gridLinePick.a.slice(),b=[x,y],pv=snapshot();if(gridAddFreeLine(a,b)){pushUndo(pv);gridCancelLinePick();render();refresh3DGrid();}else panel();}
4363
4934
  e.preventDefault();return;}
4364
4935
  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;}
4936
+ gridPick=false;gridSetPickClass();if(P.grid)edit(()=>{ModelCmd.patchGrid(P.grid,{origin:[x,y]});});else panel();e.preventDefault();return;}
4366
4937
  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
4938
  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
4939
  {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 +4977,9 @@ svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
4406
4977
  else if(tm)tgt=[tm.wp[0],tm.wp[1]];}
4407
4978
  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
4979
  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)
4980
+ 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
4981
+ 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;}
4982
+ 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
4983
  return;}
4411
4984
  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
4985
  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 +5046,7 @@ svg.addEventListener('pointermove',e=>{
4473
5046
  else{a=[drag.origA[0]+dxc,drag.origA[1]+dyc];b=[drag.origB[0]+dxc,drag.origB[1]+dyc];snapClear();}
4474
5047
  gridReadout(e,gridDelta(Math.hypot(a[0]-drag.origA[0],a[1]-drag.origA[1])),'');
4475
5048
  }
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)
5049
+ 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
5050
  if(drag.type==='gridline'){const dxc=p.x-drag.startPt[0],dyc=p.y-drag.startPt[1];
4478
5051
  if(!drag.moved){if(Math.hypot(dxc,dyc)<=4/zoom)return;drag.moved=true; // past the tolerance = a drag, not a click
4479
5052
  const along=drag.axis==='v'?Math.abs(dyc):Math.abs(dxc),perp=drag.axis==='v'?Math.abs(dxc):Math.abs(dyc);
@@ -4485,7 +5058,7 @@ svg.addEventListener('pointermove',e=>{
4485
5058
  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
5059
  if(bp!=null){np=bp;snapMark(drag.axis==='v'?np:p.x,drag.axis==='v'?p.y:np,'line');}else snapClear();}
4487
5060
  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
5061
+ 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
5062
  const geo=gridGeo(),lines=geo?geo[drag.axis]:null; // live readout: how far it moved + the bay it resizes
4490
5063
  let sub='';
4491
5064
  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 +5069,7 @@ svg.addEventListener('pointermove',e=>{
4496
5069
  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
5070
  if(bp!=null){np=bp;snapMark(drag.axis==='v'?drag.orig:np,drag.axis==='v'?np:drag.orig,'end');}else snapClear();}
4498
5071
  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
5072
+ 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
5073
  gridReadout(e,gridDelta((applied!=null?applied:np)-drag.origEnd),'');
4501
5074
  }
4502
5075
  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 +5078,9 @@ svg.addEventListener('pointermove',e=>{
4505
5078
  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
5079
  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
5080
  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];}}
5081
+ const mcG=MC(); // built inside the grip branch, so the far more common ungripped dim drag pays nothing
5082
+ 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
5083
+ else mcG.setEndpoint(m,gp.pt==='a'?0:1,[x,y]);}}
4510
5084
  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
5085
  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
5086
  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 +5094,8 @@ svg.addEventListener('pointermove',e=>{
4520
5094
  drag.moved=true;
4521
5095
  if(!drag.armed)return; // drag-move OFF, plain grab → never translate (the up-handler teaches the toggle)
4522
5096
  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()});}
5097
+ const ns=new Set(),ci=[],mcD=MC();
5098
+ 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
5099
  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
5100
  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
5101
  if(!drag.armed)return;
@@ -4536,14 +5110,15 @@ svg.addEventListener('pointermove',e=>{
4536
5110
  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
5111
  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
5112
  else snapClear();
5113
+ 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
5114
  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);}
5115
+ 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
5116
  if(selIds.size<=2)for(const m of sel2d())updateHandles(m);refreshMagneticDims2D();return;} // F9: magnetic dims track the moving members live
4542
5117
  // endpoint
4543
5118
  const m=byId(drag.id);if(!m)return;let x=p.x,y=p.y;
4544
5119
  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
5120
  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
5121
+ 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
5122
  {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
5123
  svg.addEventListener('pointerup',()=>{if(!drag)return;snapClear();epPrevClear();
4549
5124
  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 +5233,8 @@ document.getElementById('revB').onclick=()=>{const ids=reversedBeams(); // bea
4658
5233
  toast(ids.length+' reversed beam'+(ids.length>1?'s':'')+' selected — press P to swap direction');}; // select reversed → review → P swaps them
4659
5234
  document.getElementById('mrgB').onclick=()=>{const r=mergeCollinearJS(P.members); // conservative; result is undoable (Ctrl+Z)
4660
5235
  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();});
5236
+ 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.
5237
+ ModelCmd.setPlanMembers(P,r.members);selIds=new Set();selDimIds.clear();});
4663
5238
  toast('Merged '+r.mergedAway+' segment'+(r.mergedAway===1?'':'s')+' into '+r.runs+' member'+(r.runs===1?'':'s'));};
4664
5239
  document.getElementById('undoB').onclick=doUndo;
4665
5240
  document.getElementById('redoB').onclick=doRedo;
@@ -4668,6 +5243,10 @@ setDragMove(dragMoveOn); // reflect the persisted state on load (body class +
4668
5243
  addEventListener('keydown',e=>{
4669
5244
  const inForm=/^(INPUT|SELECT|TEXTAREA)$/.test((document.activeElement||{}).tagName);
4670
5245
  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).
5246
+ // A live drag-out to Tekla owns Escape: the 3D view cancels the gesture on its own handler (this one
5247
+ // runs first). Without this, Escape would fall through to the deselect below and clear the very
5248
+ // selection the gesture is still carrying.
5249
+ if(e.key==='Escape'&&window.Steel3DView&&window.Steel3DView.teklaDragging&&window.Steel3DView.teklaDragging())return;
4671
5250
  if(e.key==='Escape'&&moreOpen()){closeMore();moreBtn.focus();return;}
4672
5251
  if(e.key==='Escape'&&xfMenuC.isOpen()){xfMenuC.close();return;}
4673
5252
  if(lvOpen()){if(e.key==='Escape')closeLevelModal();return;} // the level modal is modal: no Delete/undo/tool keys mutate state underneath it
@@ -4721,7 +5300,7 @@ addEventListener('keydown',e=>{
4721
5300
  if(selDimIds.size){P.dims=P.dims.filter(d=>!selDimIds.has(d.id));selDimIds.clear();}
4722
5301
  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
5302
  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)));
5303
+ if(freeToDelete.length)ModelCmd.removeGridLines(P.grid,glLids);
4725
5304
  selGridIds.clear();});
4726
5305
  else{selGridIds.clear();render();} // only regular grid lines were selected → nothing to delete (no phantom undo step); repaint to drop the highlight
4727
5306
  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 +5353,12 @@ const moreBtn=document.getElementById('moreBtn'),moreMenu=document.getElementByI
4774
5353
  function moreOpen(){return moreMenu.classList.contains('open');}
4775
5354
  function moreOutside(e){if(!moreMenu.contains(e.target)&&e.target!==moreBtn)closeMore();}
4776
5355
  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);}};
5356
+ moreBtn.onclick=e=>{e.stopPropagation();if(moreOpen())closeMore();else{
5357
+ // "Send selection to Tekla" is hidden, not disabled, with nothing selected — there is no action to
5358
+ // offer yet, and a greyed row would read as a broken feature rather than an empty state.
5359
+ document.getElementById('sendTeklaB').hidden=!selArr().length;
5360
+ moreMenu.classList.add('open');moreBtn.setAttribute('aria-expanded','true');document.addEventListener('mousedown',moreOutside,true);}};
5361
+ document.getElementById('sendTeklaB').onclick=()=>{closeMore();sendSelectionToTekla(teklaSelectionIds());};
4778
5362
  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
5363
  // "Snapping" is collapsible to save menu space — the header expands the running-snap switches below it
4780
5364
  // Every ⋯ section is a collapse/expand accordion (Snapping + Display + Detailing + …); state persists in localStorage.
@@ -4899,6 +5483,53 @@ document.getElementById('cpLevelB').onclick=()=>openLevelModal('copy');
4899
5483
  // Coped beams (auto, clash-driven) — cache the cut labels per member as the scene is fetched so the
4900
5484
  // member Inspector can show a read-only "Cope (auto)" note (a coped beam otherwise looks like an error).
4901
5485
  let copesByMember={}, partsById={};
5486
+
5487
+ // --- Send the selection to Tekla (Ctrl+Shift-drag it out of the 3D view, or ⋯ → Session). The
5488
+ // server bakes just these members as native parts in the OPEN model, at their real model
5489
+ // coordinates — where you released the mouse is a gesture, not a location. Each send is its own
5490
+ // insert, so sending the same members twice puts them in twice (undo/delete in Tekla). ---
5491
+ let teklaSendBusy=false;
5492
+ const teklaSelectionIds=()=>selArr().map(m=>m.id); // members only: grid lines, dimensions and connection parts are never sent (selArr matches against real members)
5493
+ async function sendSelectionToTekla(ids){
5494
+ if(teklaSendBusy)return;
5495
+ const list=[...new Set((Array.isArray(ids)?ids:[]).filter(Boolean))];
5496
+ if(!list.length){toast('Select the members you want to send first.');return;}
5497
+ const n=list.length,noun=n===1?'member':'members';
5498
+ teklaSendBusy=true;toast('Sending '+n+' '+noun+' to Tekla…',true);
5499
+ try{
5500
+ // Push the on-screen edits first, or a just-moved beam lands at its old place. NOT in a project:
5501
+ // there the server exports the APPROVED snapshot (not this draft), while every contract PUT clears
5502
+ // that approval — so flushing would only un-approve the project and make the export refuse itself.
5503
+ // Which leaves a project with unsent edits in a bind we must not paper over: inside the autosave
5504
+ // window the project is still approved, so the send would SUCCEED against the approved snapshot and
5505
+ // bake stale geometry — a beam you just moved landing where it used to be, reported as a success.
5506
+ // Refuse instead, and name the step that fixes it.
5507
+ if(PROJECT){
5508
+ if(saveT!==null){toast('Approve this version before sending — your latest edits aren’t in the approved model yet.');return;}
5509
+ } else await window.flushContract();
5510
+ const res=await fetch('/api/contract/'+encodeURIComponent(APP_ID)+'/export-tekla'+PROJECT_QS,
5511
+ {method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({memberIds:list})});
5512
+ const j=await res.json().catch(()=>({}));
5513
+ if(!res.ok||!j.ok)throw new Error(j.error||('send failed ('+res.status+')'));
5514
+ // Report what TEKLA received, never what we asked for: the server legitimately drops members it
5515
+ // can't resolve (an RFI with no AISC size) and still succeeds, so the requested count would
5516
+ // overstate a partial send. Mirrors the whole-model export's "sent with gaps" wording.
5517
+ // Count MEMBERS specifically — `counts.native` includes the plates, bolts and welds a connection
5518
+ // brings with it, so one member with a base plate would otherwise be reported as two "members".
5519
+ const em=(j.receipt&&Array.isArray(j.receipt.emitted))?j.receipt.emitted:null;
5520
+ const got=em?em.filter(r=>r&&r.kind==='member').length:n;
5521
+ const gotNoun=got===1?'member':'members',missed=n-got;
5522
+ toast(missed>0
5523
+ ?'Inserted '+got+' of '+n+' '+noun+' into Tekla — '+missed+' had no size to build yet.'
5524
+ :'Inserted '+got+' '+gotNoun+' into Tekla.');
5525
+ }catch(e){
5526
+ console.error('send to Tekla failed',e);
5527
+ // The server's own messages are plain English; a transport failure ("Failed to fetch") is not.
5528
+ const msg=e&&e.message?e.message:'';
5529
+ 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.'));
5530
+ }finally{teklaSendBusy=false;}
5531
+ }
5532
+
4902
5533
  const view3dApi={
4903
5534
  onFrame3dChange:()=>{updCS();if(typeof csSyncF3d==='function')csSyncF3d();
4904
5535
  // F14: the Definition-points local (X′/Y′/Z′) row reads the 3D frame — refresh the inspector when the
@@ -4946,20 +5577,30 @@ const view3dApi={
4946
5577
  ptPerFt:()=>(P&&P.pt_per_ft>0?P.pt_per_ft:1),
4947
5578
  defaultTosMm:()=>(defaultTOS!=null?defaultTOS*25.4:0), // editor stores default T.O.S in inches
4948
5579
  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.
5580
+ 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
5581
  dragMoveEnabled:()=>dragMoveOn, // the 3D view gates its plain member-drag on this
4951
5582
  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)
5583
+ 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)
5584
+ 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
5585
  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;});});},
5586
+ 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)
5587
+ 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)
5588
+ 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
5589
+ 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
5590
  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)
5591
+ 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
5592
+ // ponytail: PLAN-LOCAL. snapEndMulti works in one sheet's display px, so this is exact only while the
5593
+ // target and every selected member live on the ACTIVE sheet. Cross-sheet it degrades twice: an
5594
+ // off-sheet target's wp is read in the active sheet's scale, and sel2d() silently drops off-sheet
5595
+ // members (3D selection is model-wide, so the user can select them). Guarded below rather than
5596
+ // silently doing the wrong thing. Upgrade path: intersect in scene mm, then invert each result with
5597
+ // that member's own plan scale (scaleFor/planScaleOf) — i.e. the same seam, once members are
5598
+ // model-level and no longer carry per-sheet display coordinates.
5599
+ if(!tm)return;
5600
+ 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
5601
+ 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;}
5602
+ 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;}
5603
+ 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
5604
  onSplit:(id,wp)=>{const m=byId(id);if(m){doSplit(m,wp);sync3D();}}, // 3D Split → cut at the clicked point on the member
4964
5605
  getDims3d:()=>C.dims3d||[],
4965
5606
  getGrid:()=>(P&&P.grid)||null, // the ACTIVE plan's structural grid for the 3D render + plan-locked snapping (per-plan, display-space)
@@ -4989,10 +5630,15 @@ const view3dApi={
4989
5630
  newDim3dId:()=>'d3'+Date.now()+'_'+(dimSeq++), // same scheme as 2D dim ids (Date.now + dimSeq tie-breaker)
4990
5631
  fmtLen:(mm)=>fmtFtIn(mm/304.8*12),
4991
5632
  toast:(m)=>toast(m),
5633
+ teklaSelectionIds, // Ctrl+Shift drag-out: the sendable member ids (the badge count and the payload are the same list)
5634
+ teklaSendBusy:()=>teklaSendBusy, // one drop at a time — the view refuses to start a second drag mid-send
5635
+ onSendToTekla:(ids)=>sendSelectionToTekla(ids),
4992
5636
  // 3D Move/Copy: the 3D view reads the armed tool + counts, and hands commit offsets back in scene mm.
4993
5637
  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)]));},
5638
+ // mm → plan px (Y FLIPPED) + inches for dz, now owned by the model boundary. toDisplayOffsets MUTATES
5639
+ // NOTHING on purpose: cmApplyOffsets below is what moves the members, and it also owns the empty-selection
5640
+ // toast, the 100-copy cap and the distance toast — which measures from these same ROUNDED offsets.
5641
+ onTransform3d:(offsMm)=>{cmApplyOffsets(MC().toDisplayOffsets(offsMm));},
4996
5642
  disarmTransform:()=>{if(cmTool){disarmCm();render();}}, // the 3D dim tool arming kicks Move/Copy off the left-click
4997
5643
  // 3D draw-on-plane (spec §7): the editor's add-member mode + profile drive it; two plane picks (scene mm) come back here.
4998
5644
  addModeActive:()=>mode==='add',
@@ -5012,7 +5658,7 @@ const view3dApi={
5012
5658
  const mfNote=/(^|[^A-Z])MF/i.test(addProfile||'')?'moment':''; // a moment-frame profile keeps the auto note ensureMeta gives 2D-drawn members
5013
5659
  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
5660
  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);
5661
+ m.rfi=(_wt(addProfile)==null);MC().addMembers(P,[m]);
5016
5662
  if(addProfile&&!profs.includes(addProfile)){profs.push(addProfile);profs.sort();}
5017
5663
  selIds=new Set([id]);});
5018
5664
  const asCol=hIn<6&&dzIn>6;
@@ -5032,7 +5678,7 @@ const view3dApi={
5032
5678
  const cur=(m.col.bos!=null?m.col.bos:0);
5033
5679
  if(Math.abs(bosIn-cur)<0.02){toast('Column base already at that level');return;}
5034
5680
  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
5681
+ 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
5682
  // Report the ACTUAL result: a snapped level when honored, else the ft-in elevation; call out the clamp so a
5037
5683
  // pick above the min stub isn't misreported as landing on the snapped level.
5038
5684
  const where=clamped?(fmtFtIn(bosIn)+' (clamped to a 1′ minimum stub)'):(p.snapped?(p.label||'a level'):fmtFtIn(bosIn));
@@ -6110,7 +6756,7 @@ let bar3dWired=false;
6110
6756
  function seg3dActive(sel,attr,val){document.querySelectorAll(sel+' button').forEach(b=>b.classList.toggle('on',b.getAttribute(attr)===val));}
6111
6757
  // 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
6758
  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')+' ▾';}
6759
+ 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
6760
  function wire3DBar(){if(bar3dWired||!window.Steel3DView)return;bar3dWired=true;
6115
6761
  // Camera + Display dropdowns — open/close like Clip/Work/Plane; picking an item sets the mode, ticks it, and relabels the trigger (reflectProj/reflectMode).
6116
6762
  const projBtn=document.getElementById('m3dProjBtn'),projMenu=document.getElementById('m3dProj');
@@ -6903,7 +7549,7 @@ function setPlan(i){C.active=i;P=C.plans[i];
6903
7549
  snapOnlyClear2d();closeSnapMenu(); // a snap override never outlives its plan (different geometry)
6904
7550
  disarmCm(); // Move/Copy resets per plan too (its counts persist — they're session prefs, not plan data)
6905
7551
  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)
7552
+ 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
7553
  if(!P.autofilled){autofillTOS();P.autofilled=true;}
6908
7554
  const ds=new Set([...(P.details||[]).map(d=>d.text),...Object.keys(C.custom_details)]);document.getElementById('detailsBtn').textContent='Details ('+ds.size+')';
6909
7555
  setMode();render();fitToWindow();
@@ -6912,7 +7558,26 @@ function setPlan(i){C.active=i;P=C.plans[i];
6912
7558
  const planSel=document.getElementById('planSel');
6913
7559
  planSel.innerHTML=C.plans.map((p,i)=>`<option value="${i}">${esc(p.sheet)} · ${esc(p.title)}</option>`).join('');
6914
7560
  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();}};
7561
+ // "Revert to an earlier version…" — a POINTER into the workspaces shell's History step, never a
7562
+ // revert of its own. The project version ledger already restores any version as a NEW version
7563
+ // (audited, itself undoable, and it re-locks exports); this item only makes it reachable from
7564
+ // inside the editor. It therefore exists ONLY when we're embedded in that shell with a project
7565
+ // open — Workflows mode has no history to point at, and a standalone project tab has no shell to
7566
+ // switch. See docs/superpowers/specs/2026-07-21-steel-editor-revert-signpost-design.md.
7567
+ function wsShell(){ // the parent shell's bridge, or null when we aren't embedded in it
7568
+ try{const p=window.parent;if(!p||p===window)return null;
7569
+ const b=p.flolessWorkspaces;return b&&typeof b.openHistory==='function'?b:null;}
7570
+ catch(_){return null;}} // cross-origin or torn-down parent — treat as not embedded, never throw
7571
+ if(PROJECT&&wsShell()){
7572
+ document.body.classList.add('in-workspace'); // the CSS above reveals #revertB + #revertSep
7573
+ 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
7574
+ // Flush the debounced autosave BEFORE navigating. History renders server state derived from this
7575
+ // contract (the version list and the sign-off), so a still-pending PUT would have it paint a stale
7576
+ // approvedAt — and the moment the shell hides this iframe the save pill goes with it, so a failed
7577
+ // save would never be seen. Same order, same reason, as the shell's pre-Approve flush. A rejected
7578
+ // save keeps us here, where the red pill is visible, rather than navigating away from the problem.
7579
+ try{await flushContract();}catch(_){return;}
7580
+ b.openHistory();};}
6916
7581
  const _restored=restoreSaved(); // bring back this browser's saved edits before first paint
6917
7582
  // B4: normalize brace sub-objects across ALL plans — seed defaults on a brace, strip a stale m.brace off a
6918
7583
  // non-brace, clamp bad values. Covers reader-emitted, partial and localStorage-restored payloads, so it runs
@@ -7127,21 +7792,12 @@ if(new URLSearchParams(location.search).get('selftest')==='1'){(function(){
7127
7792
  // 7) Move/Copy transform core (spec §4.1)
7128
7793
  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
7794
  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');
7795
+ // unit 5 P3b-1: the three translateMembers, one cloneMember and two retargetTos assertions that lived
7796
+ // here moved to server/steel-model-commands.test.ts when the functions themselves did. They tested the
7797
+ // translate / clone / retarget contracts directly, and those contracts are now the boundary's.
7138
7798
  ok((()=>{const v=parseVec("16'");return !!v&&near(v.dist,192);})(),'parseVec single ft → inches');
7139
7799
  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
7800
  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
7801
  // 8) GLOBAL undo stack (whole-model). The regression the per-plane stacks caused: editing sheet A,
7146
7802
  // then sheet B, then undoing must revert ONLY the last edit (B) and leave A's edit intact — with the
7147
7803
  // old per-plane design a whole-model snapshot on A's stack silently reverted B. Also: a cross-plane
@@ -7367,6 +8023,54 @@ if(new URLSearchParams(location.search).get('selftest')==='1'){(function(){
7367
8023
  {const br=normBrace(mk({id:'brD',wp:[[0,0],[100,0]]}));P.members=[br];
7368
8024
  doSplit(br,[50,0]);ok(P.members.length===1,'doSplit refuses to cut a brace');}
7369
8025
 
8026
+ // --- cross-sheet coordinate seam: the 3D reaches members on ANY sheet, so these editor callbacks
8027
+ // must resolve the OWNING plane, never the active one. Ids are only sheet-unique, so resolution is
8028
+ // by object identity throughout. ---
8029
+
8030
+ // doSplit puts the second half on the sheet that OWNS the member, not the active one
8031
+ {const savedPlans=C.plans,savedP=P;
8032
+ const off={sheet:'S-OFF',pt_per_ft:36,default_tos:348,members:[],dims:[]};
8033
+ const bm={id:'sp1',role:'beam',profile:'W16X26',wp:[[0,0],[100,0]],ends:[{},{}]};
8034
+ off.members=[bm];P.members=[];C.plans=[savedP,off];
8035
+ doSplit(bm,[50,0]);
8036
+ ok(off.members.length===2&&P.members.length===0,'doSplit lands the second half on the OWNING sheet, not the active one');
8037
+ C.plans=savedPlans;P=savedP;}
8038
+
8039
+ // onElevateMember materialises an unset T.O.S from the OWNING sheet's datum (and from 0, like the
8040
+ // bake, when that sheet has none) — never from the active sheet's defaultTOS
8041
+ {const savedPlans=C.plans,savedP=P,savedTos=defaultTOS;defaultTOS=198;
8042
+ const off={sheet:'S-OFF2',pt_per_ft:36,default_tos:348,members:[],dims:[]};
8043
+ const bm={id:'el1',role:'beam',profile:'W16X26',wp:[[0,0],[100,0]],ends:[{},{}]};
8044
+ const noDef={sheet:'S-NODEF',pt_per_ft:12,members:[],dims:[]};
8045
+ const bm2={id:'el2',role:'beam',profile:'W16X26',wp:[[0,0],[100,0]],ends:[{},{}]};
8046
+ off.members=[bm];noDef.members=[bm2];C.plans=[savedP,off,noDef];
8047
+ view3dApi.onElevateMember('el1',12);
8048
+ 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)');
8049
+ view3dApi.onElevateMember('el2',12);
8050
+ 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');
8051
+ C.plans=savedPlans;P=savedP;defaultTOS=savedTos;}
8052
+
8053
+ // The Trim/Extend off-sheet guard. It filters by OBJECT identity, so it reports exactly the members
8054
+ // that are not on the open sheet — no count arithmetic that a duplicate id could skew.
8055
+ {const savedPlans=C.plans,savedP=P,savedSel=selIds;
8056
+ const mine={id:'t1',role:'beam',profile:'W16X26',wp:[[0,0],[100,0]],ends:[{},{}]};
8057
+ const other={id:'t2',role:'beam',profile:'W16X26',wp:[[0,50],[100,50]],ends:[{},{}]};
8058
+ const off={sheet:'S-OFF3',pt_per_ft:36,default_tos:348,members:[other],dims:[]};
8059
+ P.members=[mine];C.plans=[savedP,off];
8060
+ selIds=new Set(['t1']);
8061
+ ok(selArr().filter(m=>!P.members.includes(m)).length===0,'an all-active-sheet selection does not trip the off-sheet guard');
8062
+ selIds=new Set(['t1','t2']);
8063
+ ok(selArr().filter(m=>!P.members.includes(m)).length===1,'a selection reaching another sheet trips it, naming exactly the off-sheet member');
8064
+ // Known limitation, pinned so it is a decision and not a surprise: selIds keys by ID, and ids are
8065
+ // only SHEET-unique, so selecting a bare id shared by two sheets selects BOTH — the guard then
8066
+ // (correctly) reports the selection as cross-sheet and Trim/Extend refuses. Model-level member
8067
+ // identity removes the ambiguity; until then refusing beats silently trimming one of the two.
8068
+ const dupA={id:'dupT',role:'beam',profile:'W16X26',wp:[[0,0],[100,0]],ends:[{},{}]};
8069
+ const dupB={id:'dupT',role:'beam',profile:'W16X26',wp:[[0,50],[100,50]],ends:[{},{}]};
8070
+ P.members=[dupA];off.members=[dupB];selIds=new Set(['dupT']);
8071
+ 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)');
8072
+ C.plans=savedPlans;P=savedP;selIds=savedSel;}
8073
+
7370
8074
  // swapSelectionEnds skips braces (the bulk path that used to flip a brace's offset side)
7371
8075
  {const br=normBrace(mk({id:'brW',wp:[[0,0],[100,0]],brace:{type:'vertical',floor:'above',offset:24}}));
7372
8076
  P.members=[br];const si=selIds;selIds=new Set(['brW']);const u0=undo.length;