@floless/app 0.163.0 → 0.164.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.
@@ -330,7 +330,7 @@
330
330
  drifted ? `<button type="button" class="ghost" data-pr-again="${id}" data-command-id="shell.project-rfi-file-again#${esc(rfi.id)}" ${label}
331
331
  data-tip="Opens New RFI with this title and question and the items that still match">File again from this…</button>` : '',
332
332
  ].join('');
333
- return `<div class="pg-row pr-row" role="listitem"${(state.form?.busy && state.form.rfiId === rfi.id) || recovering ? ' aria-busy="true"' : ''}>
333
+ return `<div class="pg-row pr-row${state.mentioned === rfi.id ? ' is-mentioned' : ''}" role="listitem"${(state.form?.busy && state.form.rfiId === rfi.id) || recovering ? ' aria-busy="true"' : ''}>
334
334
  <div class="pg-row-line"><span class="pg-row-title" tabindex="-1" data-pr-title="${id}">${id} · ${esc(rfi.title)}</span>
335
335
  <span class="pw-chip${rfi.status === 'closed' ? ' is-muted' : ''}">${esc(STATUS[rfi.status] || rfi.status)}</span>${pending ? `<span class="pw-chip is-muted">${d.status === 'prepared' ? 'Unfinished' : 'Not confirmed'}</span>` : ''}</div>
336
336
  <span class="pg-row-meta">${meta.join(' · ')}</span>
@@ -411,6 +411,7 @@
411
411
  mine.view = { status: 'ready', data, error: null };
412
412
  if (mine.form && !data.rfis.some((r) => r.id === mine.form.rfiId)) mine.form = null;
413
413
  paint();
414
+ settleWant();
414
415
  if (data.store === 'ok') {
415
416
  const n = data.rfis.length;
416
417
  if (!mine.quietLoad) announce(n === 0 ? 'No RFIs in this project yet' : `${n} RFI${n === 1 ? '' : 's'}`);
@@ -422,6 +423,7 @@
422
423
  mine.view = { status: gone ? 'gone' : 'failed', data: null,
423
424
  error: said(error, 'FloLess couldn’t read them just now. Check that FloLess is still running, then try again.') };
424
425
  paint();
426
+ settleWant();
425
427
  announce(gone ? 'FloLess couldn’t find this project any more.' : 'FloLess couldn’t load this project’s RFIs.');
426
428
  } finally {
427
429
  mine.inflight = false;
@@ -429,12 +431,60 @@
429
431
  }
430
432
  }
431
433
 
434
+ /**
435
+ * #2874: show one RFI a chat message mentioned. Settles once this project's RFIs are read: the filter widens to All
436
+ * when it hides the RFI, and its row title is focused and outlined. Every outcome is `{ok, said?}`, never a throw; a
437
+ * later request, or the pane drawn again for another project, answers an earlier one `{superseded:true}`.
438
+ */
439
+ function focus(projectId, rfiId) {
440
+ if (!state || state.project.id !== projectId) return Promise.resolve({ ok: false, said: `The RFIs step is not showing this project, so ${rfiId} was not shown.` });
441
+ state.want?.resolve({ superseded: true });
442
+ return new Promise((resolve) => {
443
+ state.want = { rfiId, resolve };
444
+ if (state.view.status !== 'loading' && !state.inflight) settleWant();
445
+ });
446
+ }
447
+
448
+ function settleWant() {
449
+ const want = state?.want;
450
+ if (!want) return;
451
+ state.want = null;
452
+ const { rfiId } = want;
453
+ // A failure is shown on this pane, where the person is looking, as well as returned for the chat's own line.
454
+ const resolve = (outcome) => { if (outcome.ok === false) toast(outcome.said, 'warn'); want.resolve(outcome); };
455
+ const data = state.view.status === 'ready' ? state.view.data : null;
456
+ if (!data || data.store !== 'ok') { resolve({ ok: false, said: `FloLess couldn’t read this project’s RFIs just now, so ${rfiId} was not shown. Click the mention again in a moment.` }); return; }
457
+ const rfi = data.rfis.find((r) => r.id === rfiId);
458
+ if (!rfi) { resolve({ ok: false, reason: 'missing', said: `${rfiId} is no longer one of this project’s RFIs. The list on screen shows the RFIs it has now.` }); return; }
459
+ const widened = !visible([rfi], state.filter).length;
460
+ if (widened) state.filter = 'all';
461
+ state.focusAfter = `[data-pr-title="${CSS.escape(rfiId)}"]`;
462
+ // Outlined for a moment, through any repaint meanwhile (a readiness check, a background read).
463
+ const mine = state;
464
+ mine.mentioned = rfiId;
465
+ if (mine.form) readDraft(); // an open form keeps what was typed across the repaint
466
+ paint();
467
+ const row = state.pane.querySelector(`[data-pr-title="${CSS.escape(rfiId)}"]`)?.closest('.pr-row');
468
+ if (!row) { mine.mentioned = null; resolve({ ok: false, said: `${rfiId} could not be shown. Choose All and find it there.` }); return; }
469
+ row.scrollIntoView?.({ block: 'center' });
470
+ setTimeout(() => {
471
+ if (mine.mentioned !== rfiId) return;
472
+ mine.mentioned = null;
473
+ mine.pane.querySelector(`[data-pr-title="${CSS.escape(rfiId)}"]`)?.closest('.pr-row')?.classList.remove('is-mentioned');
474
+ }, 2400);
475
+ resolve(widened ? { ok: true, said: `Showing all RFIs, so ${rfiId} is in view.` } : { ok: true });
476
+ }
477
+
432
478
  function render(pane, project) {
433
479
  if (!pane || !project) return;
434
480
  const same = state && state.pane === pane && state.project.id === project.id;
481
+ // The same project drawn again (the step shown again while its list loads) keeps the RFI a mention asked for, and
482
+ // shows it once this read is in; another project answers that request as overtaken.
483
+ const want = same ? state.want : null;
484
+ if (!same) state?.want?.resolve({ superseded: true });
435
485
  state = { pane, project, generation: (state?.generation || 0) + 1, view: { status: 'loading', data: null },
436
486
  filter: same ? state.filter : 'open', form: null, inflight: false, again: false, focusAfter: null,
437
- readiness: { status: 'loading' }, recovering: null, alertFor: null };
487
+ readiness: { status: 'loading' }, recovering: null, alertFor: null, want: want ?? null };
438
488
  paint();
439
489
  void load();
440
490
  void checkReadiness();
@@ -1193,5 +1243,5 @@
1193
1243
  window.addEventListener('floless:projects-changed', refresh);
1194
1244
  // Back from Integrations (or any window): a send that waited on Google may be possible now.
1195
1245
  window.addEventListener('focus', () => { if (state && shown(state.pane) && state.readiness?.status !== 'ready' && !state.form?.busy) void checkReadiness(); });
1196
- window.flolessProjectRfis = { render, refresh, html, transferNote };
1246
+ window.flolessProjectRfis = { render, refresh, html, transferNote, focus };
1197
1247
  })();
@@ -907,6 +907,7 @@ function renderSteelFrame() {
907
907
  controls.update();
908
908
  refreshCameraClipping();
909
909
  sizeEndpoints();
910
+ sizeAiMarks();
910
911
  sizeClipHandles();
911
912
  clipCreationPreview?.resize();
912
913
  sizeFrameHandle();
@@ -5448,6 +5449,7 @@ function rebuildEndpoints() {
5448
5449
  const g = geoOf(m); if (!g) continue;
5449
5450
  addEndpoint(g.line[0], epMatStart, id, 0); addEndpoint(g.line[1], epMatEnd, id, 1);
5450
5451
  }
5452
+ applyAiMarks(); // #2521 row 6: the AI-decision marks follow the same visibility
5451
5453
  }
5452
5454
  function addEndpoint(p, mat, id, end) {
5453
5455
  const s = new THREE.Mesh(epGeom, mat);
@@ -5470,6 +5472,155 @@ function sizeEndpoints() {
5470
5472
  }
5471
5473
  }
5472
5474
 
5475
+ // ---- #2521 row 6: what rests on an AI decision ----
5476
+ // A Quick model's member ends whose height the AI chose (an open square) and its connections the AI assumed (a ring),
5477
+ // pushed by the editor through setAiMarks. Plan: docs/superpowers/specs/2026-10-29-quick-model-row6-PLAN.md (R9, R10,
5478
+ // V3, V4). Member materials are never touched, so selection, hover and the amber "needs review" lift keep their
5479
+ // meaning. The SPEC lives here, not on meshes, so every rebuild re-draws it (rebuildEndpoints calls applyAiMarks).
5480
+ const AI_JOINT_OFFSET_PX = 36; // a ring at a member end sits this far along the member on screen, clear of the end's labels
5481
+ const AI_MARK_PX = 13; // on-screen size of a mark, held in both cameras by pxToWorldAt (sizeAiMarks)
5482
+ let aiMarkSpec = null; // { ends: [[memberId, end]], joints: [{ jointId, memberIds, main }] } | null
5483
+ let aiMarkGroup = null;
5484
+ let aiMarkMats = null; // { key, square, ring }: owned, disposed only on a theme change or teardown
5485
+ function aiMarkMaterials() {
5486
+ const css = getComputedStyle(document.documentElement);
5487
+ const warn = css.getPropertyValue('--warn').trim() || '#fbbf24', panel = css.getPropertyValue('--panel').trim() || '#111827';
5488
+ const key = warn + '|' + panel;
5489
+ if (aiMarkMats && aiMarkMats.key === key) return aiMarkMats;
5490
+ disposeAiMarkMats();
5491
+ const make = (draw) => {
5492
+ const S = 64, c = document.createElement('canvas'); c.width = c.height = S;
5493
+ const g = c.getContext('2d'); g.lineWidth = 7; g.strokeStyle = warn; g.fillStyle = panel; draw(g, S);
5494
+ const tex = new THREE.CanvasTexture(c); tex.colorSpace = THREE.SRGBColorSpace;
5495
+ return new THREE.SpriteMaterial({ map: tex, transparent: true, depthTest: false, depthWrite: false });
5496
+ };
5497
+ aiMarkMats = {
5498
+ key,
5499
+ square: make((g, S) => { g.globalAlpha = 0.85; g.fillRect(12, 12, S - 24, S - 24); g.globalAlpha = 1; g.strokeRect(12, 12, S - 24, S - 24); }),
5500
+ ring: make((g, S) => { g.beginPath(); g.arc(S / 2, S / 2, S / 2 - 8, 0, Math.PI * 2); g.stroke(); }),
5501
+ };
5502
+ return aiMarkMats;
5503
+ }
5504
+ function disposeAiMarkMats() {
5505
+ if (!aiMarkMats) return;
5506
+ for (const m of [aiMarkMats.square, aiMarkMats.ring]) { m.map?.dispose(); m.dispose(); }
5507
+ aiMarkMats = null;
5508
+ }
5509
+ /** Where a joint's ring goes: the main member's end its `at` names; else the end of a secondary member nearest the main
5510
+ * member's line (where it frames in); else the middle of the main member. The same order as the 2D ring. */
5511
+ function aiJointPoint(j, byId) {
5512
+ const main = j.main ? byId.get(j.main) : null, mg = main && geoOf(main);
5513
+ const others = j.memberIds.filter((id) => id !== j.main).map((id) => byId.get(id)).filter(Boolean);
5514
+ if (!mg || !mg.line) { // main member gone: the ring still lands on the joint's members, at the first one's middle
5515
+ const g = others.map(geoOf).find((x) => x && x.line);
5516
+ return g ? g.line[0].map((v, i) => (v + g.line[1][i]) / 2) : null;
5517
+ }
5518
+ if (j.mainEnd === 0 || j.mainEnd === 1) {
5519
+ // At the member end its `at` names, set off along the member by AI_JOINT_OFFSET_PX on screen (sizeAiMarks), so the
5520
+ // ring never hides under the joint's own dimension label drawn at that end (a base plate's "e 1 9/16\"", QA run).
5521
+ const end = mg.line[j.mainEnd], other = mg.line[1 - j.mainEnd];
5522
+ const along = new THREE.Vector3(...other).sub(new THREE.Vector3(...end));
5523
+ const len = along.length(); // the offset never passes the member's middle, so a short member keeps its ring on it
5524
+ return len > 0 ? { at: end, along: along.normalize(), half: len / 2 } : end;
5525
+ }
5526
+ const a = new THREE.Vector3(...mg.line[0]), b = new THREE.Vector3(...mg.line[1]), seg = new THREE.Line3(a, b), q = new THREE.Vector3();
5527
+ let best = null, bestD = Infinity;
5528
+ for (const m of others) {
5529
+ const g = geoOf(m); if (!g || !g.line) continue;
5530
+ for (const p of g.line) { const v = new THREE.Vector3(...p); seg.closestPointToPoint(v, true, q); const d = q.distanceTo(v); if (d < bestD) { bestD = d; best = p; } }
5531
+ }
5532
+ return best || mg.line[0].map((v, i) => (v + mg.line[1][i]) / 2);
5533
+ }
5534
+ function applyAiMarks() {
5535
+ if (!scene) return;
5536
+ if (!aiMarkGroup) { aiMarkGroup = new THREE.Group(); aiMarkGroup.name = 'ai-decision-marks'; scene.add(aiMarkGroup); }
5537
+ // Sprite geometry is SHARED by every THREE.Sprite in the page: never dispose it (Codex plan review, round 2).
5538
+ for (const c of [...aiMarkGroup.children]) aiMarkGroup.remove(c);
5539
+ if (!aiMarkSpec) return;
5540
+ const mats = aiMarkMaterials();
5541
+ // ONE lookup per redraw: memberById scans the list, and this runs on every selection change.
5542
+ const byId = new Map(((api && api.allMembers && api.allMembers()) || members()).map((m) => [m.id, m]));
5543
+ const shown = (id) => { const mesh = meshById.get(id); return !!mesh && mesh.visible !== false; }; // hidden, isolated away or a hidden group: no mark
5544
+ const add = (p, mat, data) => {
5545
+ const sp = new THREE.Sprite(mat);
5546
+ sp.position.set(p[0], p[1], p[2]); sp.renderOrder = 997; sp.raycast = () => {}; sp.userData = data; // never a pick target
5547
+ aiMarkGroup.add(sp);
5548
+ return sp;
5549
+ };
5550
+ for (const [id, end] of aiMarkSpec.ends) {
5551
+ if (!shown(id)) continue;
5552
+ const m = byId.get(id), g = m && geoOf(m), p = g && g.line && g.line[end];
5553
+ if (p) add(p, mats.square, { aiMark: 'end', id, end });
5554
+ }
5555
+ for (const j of aiMarkSpec.joints) {
5556
+ if (!j.memberIds.some(shown)) continue;
5557
+ const p = aiJointPoint(j, byId);
5558
+ // A plain point is an array, and arrays have their own `.at` method: test for the offset form, never `p.at`.
5559
+ if (p && !Array.isArray(p)) { const sp = add(p.at, mats.ring, { aiMark: 'joint', id: j.jointId }); sp.userData.anchor = p.at; sp.userData.along = p.along; sp.userData.half = p.half; }
5560
+ else if (p) add(p, mats.ring, { aiMark: 'joint', id: j.jointId });
5561
+ }
5562
+ sizeAiMarks();
5563
+ }
5564
+ /** World distance along `dir` from `a` that covers `px` on screen, never past `cap`. Searched, not estimated: in
5565
+ * perspective a member running into the depth covers fewer pixels per unit the further it goes, so a one-step rate is
5566
+ * wrong over 36 px. Along a member in front of the camera the screen distance from its end only grows, so bisection is
5567
+ * exact; a point behind the near plane counts as too far. A member that never reaches `px` (seen end-on) moves `cap`. */
5568
+ function worldAlongForPx(a, dir, px, cap) {
5569
+ if (!camera || !canvasEl || !(cap > 0)) return Math.max(0, Math.min(cap, pxToWorldAt(px, a)));
5570
+ camera.updateMatrixWorld();
5571
+ const behind = (v) => v.clone().applyMatrix4(camera.matrixWorldInverse).z > -camera.near;
5572
+ // The end itself behind the camera (orbiting inside the model): nothing on screen to measure from, so the ring takes
5573
+ // the whole cap, where the member is most likely in view, rather than staying behind the camera unseen (Codex R6).
5574
+ if (behind(a)) return cap;
5575
+ const w = canvasEl.clientWidth / 2, h = canvasEl.clientHeight / 2, p0 = a.clone().project(camera), q = new THREE.Vector3();
5576
+ const screenAt = (t) => { // px from the anchor at distance t, or Infinity behind the near plane
5577
+ q.copy(a).addScaledVector(dir, t);
5578
+ if (behind(q)) return Infinity;
5579
+ q.project(camera);
5580
+ return Math.hypot((q.x - p0.x) * w, (q.y - p0.y) * h);
5581
+ };
5582
+ if (screenAt(cap) < px) return cap;
5583
+ let lo = 0, hi = cap;
5584
+ for (let k = 0; k < 40; k++) { const mid = (lo + hi) / 2; if (screenAt(mid) < px) lo = mid; else hi = mid; }
5585
+ return lo;
5586
+ }
5587
+ function sizeAiMarks() {
5588
+ if (!aiMarkGroup) return;
5589
+ for (const c of aiMarkGroup.children) {
5590
+ const { anchor, along, half } = c.userData;
5591
+ if (anchor && along) {
5592
+ // Measured on screen, not in world units: a member foreshortened by the view would otherwise barely move its ring.
5593
+ const a = new THREE.Vector3(...anchor);
5594
+ c.position.copy(a).addScaledVector(along, worldAlongForPx(a, along, AI_JOINT_OFFSET_PX, half));
5595
+ }
5596
+ c.scale.setScalar(pxToWorldAt(AI_MARK_PX, c.position));
5597
+ }
5598
+ }
5599
+ /** The editor's push: the latest spec replaces the last; null clears (the switch off, or nothing to mark). */
5600
+ function setAiMarks(spec) {
5601
+ aiMarkSpec = spec && Array.isArray(spec.ends) && Array.isArray(spec.joints)
5602
+ ? { ends: spec.ends.map((e) => [String(e[0]), e[1] === 1 ? 1 : 0]), joints: spec.joints.map((j) => ({ jointId: String(j.jointId), memberIds: (j.memberIds || []).map(String), main: j.main == null ? null : String(j.main), ...(j.mainEnd === 0 || j.mainEnd === 1 ? { mainEnd: j.mainEnd } : {}) })) }
5603
+ : null;
5604
+ applyAiMarks();
5605
+ }
5606
+ /** For tests and the E2E: what is drawn, and each mark's on-screen size in px. */
5607
+ function aiMarksProbe() {
5608
+ const h = (canvasEl && canvasEl.clientHeight) || 1;
5609
+ return (aiMarkGroup ? aiMarkGroup.children : []).map((c) => {
5610
+ const { anchor, along, half, ...data } = c.userData, r = canvasEl ? canvasEl.getBoundingClientRect() : null;
5611
+ const toScreen = (pos) => { const v = pos.clone().project(camera); return [r.left + (v.x + 1) / 2 * r.width, r.top + (1 - v.y) / 2 * r.height]; };
5612
+ return {
5613
+ ...data, screen: r ? toScreen(c.position) : null, anchorScreen: r && anchor ? toScreen(new THREE.Vector3(...anchor)) : null, sizePx: c.scale.x / Math.max(1e-12, pxToWorldAt(1, c.position)), material: c.material === aiMarkMats?.square ? 'square' : 'ring', viewportH: h,
5614
+ };
5615
+ });
5616
+ }
5617
+ if (typeof window !== 'undefined' && window.matchMedia) {
5618
+ // A theme change re-colours the marks: the next apply sees a new key and remakes the two materials.
5619
+ const retheme = () => { if (aiMarkSpec) applyAiMarks(); };
5620
+ try { new MutationObserver(retheme).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'class'] }); } catch (_) {}
5621
+ try { window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', retheme); } catch (_) {}
5622
+ }
5623
+
5473
5624
  // ---- placed 3D dimensions ----
5474
5625
  // 45° CAD terminator ticks at each end of a placed dim line (p1,p2 world arrays). The tick lies in the plane
5475
5626
  // of the line and world-up — perpendicular biased to vertical (or world-X when the line is itself vertical) —
@@ -9047,6 +9198,7 @@ function setInputActive(on) { inputActive = on !== false; viewportController?.se
9047
9198
  function isReady() { return built; }
9048
9199
 
9049
9200
  function disposeSteel() {
9201
+ if (aiMarkGroup) { scene?.remove(aiMarkGroup); aiMarkGroup = null; } disposeAiMarkMats(); // #2521 row 6 (the spec is kept: a re-init redraws it)
9050
9202
  clipGesture?.dispose(); clipGesture = null;
9051
9203
  sharedClipList?.destroy?.(); sharedClipList = null; releaseClipGestureInput?.(); releaseClipGestureInput = null; releaseClipOverlayInput?.(); releaseClipOverlayInput = null;
9052
9204
  releaseClipSession?.(); releaseClipSession = null; releaseClipSpatial?.(); releaseClipSpatial = null;
@@ -9338,6 +9490,8 @@ window.Steel3DView = {
9338
9490
  // Re-state the review lift on an already-built scene — the review state can move without the geometry
9339
9491
  // moving (a sign-off elsewhere, or the client re-deriving after its own edit), and neither rebuilds.
9340
9492
  setConnReview,
9493
+ // #2521 row 6: the member ends and connections that rest on an AI decision (the editor's ⋯ Display switch).
9494
+ setAiMarks, aiMarksProbe,
9341
9495
  // Reference models (#278) — an editor-only layer. `setReferences` takes the geometry the editor
9342
9496
  // fetched from the reference route; nothing here ever passes through contractToScene, which is what
9343
9497
  // keeps borrowed geometry out of every export by construction rather than by filtering.
@@ -0,0 +1,233 @@
1
+ /**
2
+ * steel-ai-marks — which members of a steel model rest on an AI decision, and how (#2521 row 6).
3
+ *
4
+ * Plan: `docs/superpowers/specs/2026-10-29-quick-model-row6-PLAN.md` (with Revisions 1 and 2, after two Codex rounds).
5
+ * Pattern: #2374's AI-answer marks.
6
+ *
7
+ * A Quick model is built by the AI deciding wherever a precise read would have asked the person, and every such
8
+ * decision is recorded. The model carries what it rests on (#2521 row 4, `server/ai-decision-list.ts`):
9
+ * - a member END whose height the AI decided says so in its own arm (`z.decided`, with `alsoRestsOn` for a split or
10
+ * merge). Exact, and it follows the member through moves, copies and splits; a typed height clears it;
11
+ * - every other decision is an entry of the server-owned `ai_decisions` list, which may over-report.
12
+ *
13
+ * What the screens show (owner rulings 2026-10-29):
14
+ * - end marks: each end whose height the AI decided (canvas, 3D, Inspect);
15
+ * - joint marks: each connection whose assumption the AI decided, once on the joint (canvas, 3D), and a line in the
16
+ * Inspect of each of its members;
17
+ * - view lines: a plan view whose scale or level the AI decided, a note on that view and a line in the Inspect of
18
+ * each member that view shows (the editor's own presence rule), never a canvas mark;
19
+ * - the model note: everything that bears on the whole model (the Drawing Filter, the origin, audit gaps, unmodelled
20
+ * details) and anything that cannot be placed on a member, said once.
21
+ *
22
+ * A MARK IS A FINDING, never a claim that the unmarked rest was drawn. Nothing is dropped unseen: what cannot be placed
23
+ * goes to the model note, and what cannot be read makes the state `unknown` (the server's "Possibly Quick model").
24
+ *
25
+ * The counting and readability follow the server's (`quickDependenciesOf`, `armsReadable`, `isWellFormedAiDecisionList`),
26
+ * except that a Filter value's digest cannot be checked here; `aiMarksDisplayState` therefore also reads the server's
27
+ * last-saved verdict, so the screen never says less than the label (plan Revision 2, V1).
28
+ *
29
+ * Pure, and read from the LIVE model the editor holds, so a mark sits on the member on screen.
30
+ */
31
+ import { planViewId } from './steel-plan-view-id.js';
32
+ import { createMemberPresenceIndex, memberPresence } from './steel-model-v2-projection.js';
33
+
34
+ const AI_ID = /^[0-9a-f]{12}$/;
35
+ const DIGEST = /^[0-9a-f]{64}$/;
36
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
37
+ const only = (o, keys) => Object.keys(o).every((k) => keys.includes(k));
38
+ const str = (v, max) => typeof v === 'string' && v.trim().length > 0 && v.length <= max;
39
+ const finite = (v) => typeof v === 'number' && Number.isFinite(v);
40
+ const nonNegInt = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
41
+ const ENDS = /** @type {const} */ (['from', 'to']);
42
+ const ID_MAX = 200;
43
+
44
+ /** `parseCovers` (`server/connection-assumption-store.ts`), shape only. */
45
+ function coversOk(v) {
46
+ if (!isObj(v)) return false;
47
+ if (v.kind === 'fact') return only(v, ['kind', 'factId']) && str(v.factId, 200);
48
+ if (v.kind === 'unmeasured') return only(v, ['kind', 'text']) && str(v.text, 600);
49
+ if (v.kind === 'issue') return only(v, ['kind', 'code']) && str(v.code, 120);
50
+ return false;
51
+ }
52
+
53
+ /** `parseSubject` (`server/ai-decision-store.ts`), every channel. */
54
+ export function subjectOk(v) {
55
+ if (!isObj(v)) return false;
56
+ switch (v.channel) {
57
+ case 'height': return only(v, ['channel', 'memberId', 'end']) && str(v.memberId, ID_MAX) && (v.end === 0 || v.end === 1);
58
+ case 'setup':
59
+ if (v.row === 'origin') return only(v, ['channel', 'row']);
60
+ return (v.row === 'scale' || v.row === 'level') && only(v, ['channel', 'row', 'viewId']) && str(v.viewId, ID_MAX);
61
+ case 'audit-gap': {
62
+ if (!only(v, ['channel', 'gapKind', 'fields']) || !str(v.gapKind, 120) || !isObj(v.fields)) return false;
63
+ const fields = Object.entries(v.fields);
64
+ return fields.length > 0 && fields.length <= 12 && fields.every(([key, value]) => /^[A-Za-z][A-Za-z0-9]{0,39}$/.test(key)
65
+ && (typeof value === 'number' ? Number.isFinite(value) : str(value, ID_MAX)));
66
+ }
67
+ case 'connection': return only(v, ['channel', 'jointId', 'covers']) && str(v.jointId, ID_MAX) && coversOk(v.covers);
68
+ case 'unmodelled-detail': return only(v, ['channel', 'sheetId', 'detailRef']) && str(v.sheetId, ID_MAX) && str(v.detailRef, ID_MAX);
69
+ case 'filter': return only(v, ['channel', 'checkpointDigest']) && typeof v.checkpointDigest === 'string' && DIGEST.test(v.checkpointDigest);
70
+ default: return false;
71
+ }
72
+ }
73
+
74
+ /** `parseDecisionValue`'s SHAPE, per channel. The Filter value's digest binding is the server's alone (V1). */
75
+ export function valueOk(subject, v) {
76
+ switch (subject.channel) {
77
+ case 'height': return isObj(v) && only(v, ['mm']) && finite(v.mm);
78
+ case 'filter': {
79
+ if (v === undefined) return true;
80
+ if (!isObj(v) || !only(v, ['manifestHash', 'savedFilterHash', 'exclusionDigest', 'valueCount', 'dismissibleCount'])) return false;
81
+ if (v.dismissibleCount !== undefined && !nonNegInt(v.dismissibleCount)) return false;
82
+ if (typeof v.manifestHash !== 'string' || !DIGEST.test(v.manifestHash) || typeof v.savedFilterHash !== 'string' || !DIGEST.test(v.savedFilterHash)) return false;
83
+ if (v.exclusionDigest !== null && (typeof v.exclusionDigest !== 'string' || !DIGEST.test(v.exclusionDigest))) return false;
84
+ return nonNegInt(v.valueCount) && !(v.exclusionDigest === null && v.valueCount !== 0);
85
+ }
86
+ case 'setup':
87
+ if (!isObj(v)) return false;
88
+ if (subject.row === 'scale') return only(v, ['mmPerPx']) && finite(v.mmPerPx) && v.mmPerPx > 0;
89
+ if (subject.row === 'level') return (only(v, ['noSingleLevel']) && v.noSingleLevel === true) || (only(v, ['mm']) && finite(v.mm));
90
+ return only(v, ['xAxisId', 'yAxisId', 'xLabel', 'yLabel']) && [v.xAxisId, v.yAxisId, v.xLabel, v.yLabel].every((s) => str(s, ID_MAX));
91
+ default: return v === undefined;
92
+ }
93
+ }
94
+
95
+ /** One entry of `ai_decisions`, as `isWellFormedAiDecisionList` reads it (less the Filter digest). */
96
+ function entryOk(entry) {
97
+ return isObj(entry) && only(entry, ['id', 'buildId', 'channel', 'subject', 'chosen', 'value'])
98
+ && typeof entry.id === 'string' && AI_ID.test(entry.id) && str(entry.buildId, ID_MAX) && typeof entry.chosen === 'string'
99
+ && subjectOk(entry.subject) && entry.subject.channel === entry.channel && valueOk(entry.subject, entry.value);
100
+ }
101
+
102
+ /**
103
+ * @param {unknown} model a steel.model/v2 document (the editor's `C`)
104
+ */
105
+ export function aiDecisionMarksOf(model) {
106
+ const members = new Map();
107
+ const ends = [];
108
+ const views = new Map();
109
+ const note = [];
110
+ const entries = new Map();
111
+ const jointsById = new Map();
112
+ const dependencies = new Set();
113
+ let readable = isObj(model) && model.type === 'steel.model/v2' && Array.isArray(model.members);
114
+ const push = (memberId, mark) => {
115
+ if (!members.has(memberId)) members.set(memberId, []);
116
+ members.get(memberId).push(mark);
117
+ };
118
+ const live = new Set();
119
+
120
+ // 1. Heights, from the member ends themselves. A malformed end could hide an arm (`armsReadable`), so it makes the
121
+ // whole reading unknown; an arm that names its decision oddly is still marked (over-mark, never drop).
122
+ for (const member of isObj(model) && Array.isArray(model.members) ? model.members : []) {
123
+ if (!isObj(member) || typeof member.id !== 'string') { readable = false; continue; }
124
+ live.add(member.id);
125
+ ENDS.forEach((key, end) => {
126
+ const point = member[key];
127
+ if (!isObj(point) || !isObj(point.z)) { readable = false; return; }
128
+ const decided = point.z.decided;
129
+ if (decided === undefined) return;
130
+ if (!isObj(decided) || decided.by !== 'ai' || typeof decided.decisionId !== 'string' || !AI_ID.test(decided.decisionId)
131
+ || (decided.alsoRestsOn !== undefined && !(Array.isArray(decided.alsoRestsOn) && decided.alsoRestsOn.every((id) => typeof id === 'string' && AI_ID.test(id))))) {
132
+ readable = false;
133
+ }
134
+ const ids = isObj(decided)
135
+ ? [decided.decisionId, ...(Array.isArray(decided.alsoRestsOn) ? decided.alsoRestsOn : [])].filter((id) => typeof id === 'string' && id)
136
+ : [];
137
+ const mark = { kind: 'height', end, decisionIds: [...new Set(ids)], derived: isObj(decided) && decided.derived === true };
138
+ for (const id of mark.decisionIds) dependencies.add(id);
139
+ ends.push({ memberId: member.id, end, decisionIds: mark.decisionIds, derived: mark.derived });
140
+ push(member.id, mark);
141
+ });
142
+ }
143
+
144
+ // 2. Everything else, from the list the model carries. A height entry is evidence for an arm, never a mark or a
145
+ // dependency of its own (`quickDependenciesOf`); it is kept for the words Inspect shows.
146
+ const list = isObj(model) ? model.ai_decisions : undefined;
147
+ if (list !== undefined && !Array.isArray(list)) readable = false;
148
+ const plans = isObj(model) && Array.isArray(model.plans) ? model.plans.filter(isObj) : [];
149
+ const plansByView = new Map();
150
+ for (const plan of plans) { const v = planViewId(plan); if (v && !plansByView.has(v)) plansByView.set(v, plan); }
151
+ const jointIndex = new Map();
152
+ for (const joint of isObj(model) && Array.isArray(model.joints) ? model.joints : []) {
153
+ if (isObj(joint) && typeof joint.id === 'string' && !jointIndex.has(joint.id)) jointIndex.set(joint.id, joint);
154
+ }
155
+ let presence = null;
156
+ const presenceIndex = () => (presence ??= createMemberPresenceIndex(model));
157
+ for (const entry of Array.isArray(list) ? list : []) {
158
+ const ok = entryOk(entry) && !entries.has(entry.id);
159
+ if (!ok) {
160
+ readable = false;
161
+ const id = isObj(entry) && typeof entry.id === 'string' && AI_ID.test(entry.id) && !entries.has(entry.id) ? entry.id : null;
162
+ if (id && !(isObj(entry) && entry.channel === 'height')) dependencies.add(id);
163
+ note.push({ decisionId: id, channel: isObj(entry) && typeof entry.channel === 'string' ? entry.channel : 'unknown', reason: 'unreadable' });
164
+ continue;
165
+ }
166
+ entries.set(entry.id, entry);
167
+ if (entry.channel === 'height') continue;
168
+ const id = entry.id, subject = entry.subject;
169
+ dependencies.add(id);
170
+ switch (entry.channel) {
171
+ case 'connection': {
172
+ const joint = jointIndex.get(subject.jointId);
173
+ const named = joint ? [joint.main, ...(Array.isArray(joint.secondaries) ? joint.secondaries : [])] : [];
174
+ const memberIds = [...new Set(named.filter((m) => typeof m === 'string' && live.has(m)))];
175
+ if (!memberIds.length) { note.push({ decisionId: id, channel: 'connection', reason: joint ? 'unplaced' : 'gone' }); break; }
176
+ if (!jointsById.has(joint.id)) {
177
+ jointsById.set(joint.id, { jointId: joint.id, decisionIds: [], memberIds, main: live.has(joint.main) ? joint.main : null,
178
+ ...(mainEndOf(joint) !== null && live.has(joint.main) ? { mainEnd: mainEndOf(joint) } : {}),
179
+ ...(Array.isArray(joint.place) && joint.place.length === 3 && joint.place.every(finite) ? { place: joint.place } : {}) });
180
+ }
181
+ jointsById.get(joint.id).decisionIds.push(id);
182
+ for (const m of memberIds) push(m, { kind: 'connection', decisionId: id, jointId: joint.id });
183
+ break;
184
+ }
185
+ case 'setup': {
186
+ if (subject.row === 'origin') { note.push({ decisionId: id, channel: 'setup-origin', reason: 'model' }); break; }
187
+ const plan = plansByView.get(subject.viewId);
188
+ if (!plan) { note.push({ decisionId: id, channel: 'setup', reason: 'gone' }); break; }
189
+ if (!views.has(subject.viewId)) views.set(subject.viewId, []);
190
+ views.get(subject.viewId).push({ decisionId: id, row: subject.row });
191
+ const index = presenceIndex();
192
+ for (const member of index.members.values()) {
193
+ if (memberPresence(model, plan, member, index).visible) push(member.id, { kind: 'view', decisionId: id, viewId: subject.viewId, row: subject.row });
194
+ }
195
+ break;
196
+ }
197
+ default: // filter, audit-gap, unmodelled-detail: they bear on the whole model
198
+ note.push({ decisionId: id, channel: entry.channel, reason: 'model' });
199
+ }
200
+ }
201
+
202
+ return {
203
+ state: !readable ? 'unknown' : dependencies.size ? 'marks' : 'none',
204
+ members, ends, joints: [...jointsById.values()], views, model: note, entries,
205
+ decisionCount: dependencies.size,
206
+ };
207
+ }
208
+
209
+ /**
210
+ * What every surface shows (plan Revision 2, V1): the live analysis and the server's verdict on the last saved model,
211
+ * whichever says more. `savedQuick`: `null` (the last save was precise), `{ state: 'quick'|'unknown' }`, or `undefined`
212
+ * when the editor never received a verdict it could read. Never `none` when either side cannot vouch for it.
213
+ */
214
+ export function aiMarksDisplayState(marks, savedQuick) {
215
+ const saved = savedQuick === null ? 'none' : isObj(savedQuick) && savedQuick.state === 'quick' ? 'marks' : 'unknown';
216
+ if (marks.state === 'unknown' || saved === 'unknown') return 'unknown';
217
+ return marks.state === 'marks' || saved === 'marks' ? 'marks' : 'none';
218
+ }
219
+
220
+ /** The end of its main member a joint sits at, when its `at` names one ('base' and 'end0' the start, 'top' and 'end1' the end). */
221
+ export function mainEndOf(joint) {
222
+ const at = isObj(joint) ? joint.at : undefined;
223
+ return at === 'base' || at === 'end0' ? 0 : at === 'top' || at === 'end1' ? 1 : null;
224
+ }
225
+
226
+ /** The canvas and 3D payload: only the specific cases (owner ruling 2026-10-29), never view or model-wide decisions. */
227
+ export function canvasMarksOf(marks) {
228
+ return {
229
+ ends: marks.ends.map((e) => [e.memberId, e.end]),
230
+ joints: marks.joints.map((j) => ({ jointId: j.jointId, memberIds: j.memberIds, main: j.main,
231
+ ...(j.mainEnd !== undefined ? { mainEnd: j.mainEnd } : {}), ...(j.place ? { place: j.place } : {}) })),
232
+ };
233
+ }