File size: 34,319 Bytes
81a8217
 
 
 
 
 
e14c2fd
 
 
 
 
 
 
 
 
 
c72f0a1
4ca2251
 
 
 
 
 
 
 
 
 
 
e14c2fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3998487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e14c2fd
 
 
 
 
c72f0a1
 
 
 
 
 
 
 
 
e14c2fd
 
 
 
 
 
c72f0a1
 
 
 
 
 
 
 
 
 
 
e14c2fd
c72f0a1
e14c2fd
 
 
c72f0a1
e14c2fd
 
 
 
 
 
 
c72f0a1
e14c2fd
 
 
 
c72f0a1
e14c2fd
c72f0a1
e14c2fd
 
 
 
 
 
 
 
c72f0a1
 
 
 
 
e14c2fd
 
 
3998487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e14c2fd
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ca2251
81a8217
 
 
 
 
4ca2251
81a8217
e14c2fd
c72f0a1
 
 
e14c2fd
 
 
81a8217
 
 
 
 
e14c2fd
 
3998487
 
 
 
 
 
 
 
 
 
e14c2fd
3998487
 
 
 
 
 
 
 
c72f0a1
 
 
3998487
 
 
81a8217
 
 
 
c72f0a1
81a8217
c72f0a1
 
3998487
 
c72f0a1
 
81a8217
c72f0a1
 
 
 
 
 
3998487
 
 
 
 
 
 
 
c72f0a1
3998487
 
 
 
c72f0a1
3998487
81a8217
e14c2fd
3998487
 
 
 
 
 
e14c2fd
 
 
3998487
 
 
e14c2fd
3998487
 
 
 
 
 
 
 
c72f0a1
3998487
 
 
81a8217
3998487
 
 
e14c2fd
3998487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e14c2fd
3998487
e14c2fd
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e14c2fd
81a8217
 
 
 
e14c2fd
81a8217
 
 
 
e14c2fd
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e14c2fd
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e14c2fd
81a8217
 
 
 
 
4ca2251
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e14c2fd
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
// R31 puts field controls on one database in Connectors or Data, never in Settings.

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { API_V1, CREDENTIALS, WORKSPACE_STALE_EVENT, signal } from "../apiContract";
import { useEscapeClose } from "../ui/useEscapeClose";
import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
// `.set-perm-back` — the way out of a full-pane takeover, already shipped for
// the Manage User one. Wearing it rather than redrawing it is half of why this
// pane and that one can be shot side by side and match (W46-T39).
import "./perms.css";
// ⛔ C6 — the lane sheet is imported HERE, from the component, not added to
// `index.css`. `index.css` `@import`s the older sheets at its top, so a sheet
// arriving that way loses every equal-specificity fight with the thousands of
// rules below it; a sheet imported from a component lands after `index.css` in
// the bundle and wins. `AssistantPage.tsx:17` is the shipped precedent.
import "../styles/wave46/manage-database.css";
import "../styles/sdlc74/settings.css";
import "../styles/sdlc77/fields-disclosure.css";
import type { ConnectorDatabase, ConnectorIntrospection } from "../connectors/ConnectorModal";

/** R21 behind the Fields click: a connector database's raw source fields and what its catalogue left out. */
export interface FieldDisclosure {
  database: ConnectorDatabase;
  introspection: ConnectorIntrospection;
  /** A failed deferred field read; empty while it loads. */
  readError: string;
  onRetry: () => void;
}

// ── the wire (contract C1) ──────────────────────────────────────────────────
//
// Store key `ut_schema_overlay`, one document per tenant, shaped
//   { "<database_key>": { "<field_key>": {hidden, label, order} } }
// with an absent key meaning "inherit the canonical contract".
//
// `GET /api/v1/admin/schema-overlay` returns the MERGED view (contract plus
// overlay) as `{fields:[{key,label,type,source,hidden,order,locked}]}`; `PATCH`
// takes a partial of the document above and returns the merged view again.

/**
 * ⭐⭐ `database` IS REQUIRED HERE, AND THE PATCH SHAPE IS WHY. C1 declares the
 * GET's rows without spelling the database key out, but the document a PATCH
 * carries is keyed by `database_key` FIRST. A row that cannot name its database
 * therefore cannot be written back at all — the key is load-bearing for the
 * write path, not a grouping nicety for the list.
 *
 * ⛔ SO IT IS NEVER GUESSED. `source` is a FIELD property (where the column comes
 * from) and reusing it as the database key would be the "a grep for a NAME is not
 * a wire key" defect exactly: plausible groups the server never meant, and a
 * PATCH addressed to a database that does not exist. A row missing the key is
 * dropped by the parser and counted, and the pane says how many it dropped.
 */
export interface OverlayField {
  /** The `database_key` a PATCH is addressed to. */
  database: string;
  /** What to call that database on screen. Absent ⇒ the key, which is honest if ugly. */
  databaseLabel?: string;
  field: string;
  label: string;
  type: string;
  source: string;
  hidden: boolean;
  order: number | null;
  /**
   * A join key or the record id. ⛔ The overlay MAY NOT HIDE IT (C1), and that is
   * the whole of what this flag means. It is NOT the "locked database" lock and
   * NOT the "pre-set field" lock (DESIGN.md §4) — neither vocabulary is borrowed
   * for it, because a shared word would have an admin read a guarantee about
   * records or about editing that nothing here makes.
   */
  locked: boolean;
}

interface ParsedOverlay {
  fields: OverlayField[];
  /** Rows the server sent that carry no database key, so nothing may be written for them. */
  dropped: number;
}

function str(v: unknown, fallback = ""): string {
  return typeof v === "string" && v ? v : fallback;
}

/**
 * The parse lives at the BOUNDARY, in one testable function, rather than being
 * spread through the render — the same arrangement `permsModel.parsePermsPayload`
 * uses for the permissions wire and for the same reason: a shape check half in a
 * fetch wrapper and half in JSX is a shape check nobody can read.
 */
export function parseOverlay(body: unknown): ParsedOverlay {
  const raw = (body as { fields?: unknown } | null)?.fields;
  if (!Array.isArray(raw)) return { fields: [], dropped: 0 };
  const fields: OverlayField[] = [];
  let dropped = 0;
  for (const item of raw) {
    const r = item as Record<string, unknown> | null;
    if (!r || typeof r !== "object") {
      dropped += 1;
      continue;
    }
    // ⚠ TWO SPELLINGS, NOT THREE, AND BOTH ARE EVIDENCED. `database` is the
    // camelCase dialect this client's wires already speak (`accessSummary`,
    // `canBusiness`, `tenantWideTypes`); `database_key` is the name the data
    // layer itself uses (`platform/core/schema_overlay.py`, `locked_keys` and
    // `merge`). Anything else would be a guess wearing a defensive costume — and
    // a wrong-but-accepted spelling is worse than none, because it silently
    // defeats the honest degrade below.
    const database = str(r.database) || str(r.database_key);
    const field = str(r.key);
    if (!database || !field) {
      dropped += 1;
      continue;
    }
    fields.push({
      database,
      databaseLabel: str(r.databaseLabel) || undefined,
      field,
      label: str(r.label, field),
      // An unknown or absent type reads as text, the house fallback the field
      // vocabulary already uses; it is never blank, because a blank cell in a
      // schema list reads as "this field has no type" rather than "not stated".
      type: str(r.type, "text"),
      source: str(r.source, "unknown"),
      hidden: r.hidden === true,
      order: typeof r.order === "number" ? r.order : null,
      locked: r.locked === true,
    });
  }
  return { fields, dropped };
}

// ── the SEMANTIC wire (owner instruction 8) ─────────────────────────────────
//
// ⛔⛔ A SECOND DESCRIPTION STORE IS THE ONE THING THIS MUST NOT BUILD, and it is
// the obvious way to write it. The schema overlay above owns `label`, `hidden`
// and `order` and nothing else. The description and the governance state are the
// SEMANTIC REGISTRY's `purpose` and `state`, which already exist, are already
// admin-gated and are already persisted:
//
//   GET   /api/v1/query/semantics/{database}          -> {database, fields:[...], router}
//   PATCH /api/v1/query/semantics/{database}/{field}  <- {purpose}
//
// Both halves shipped in an earlier wave and NOBODY EVER CONNECTED THEM to this
// pane, which is the whole of instruction 8 ("I don't see the semantic .md file
// or description per field under manage database"). So this reads and writes
// THOSE routes, and adds no key to the overlay document and none to `patch_field`.
//
// ⚠ THE MARKDOWN IS A GENERATED PROJECTION (`semantic_registry.generated_markdown`)
// and is never hand-edited, so no markdown editor is offered here. What an admin
// edits is `purpose`; the .md the instruction names is that value, rendered.
//
// ⚠ TWO STORES, TWO PERMISSION WALLS, AND THEY ARE NOT THE SAME WALL. The overlay
// sits behind the admin gate; the semantic routes sit behind Query's own source
// boundary plus `is_admin` inside the registry. A database with no semantic
// contract answers 404 by design. Neither refusal may be dressed as an empty
// list, so both are STATED and the description control still renders.

/** One field's governed meaning. `purpose` IS the description an admin edits. */
export interface SemanticField {
  field: string;
  purpose: string;
  /** `draft` | `approved` | `disabled` — the registry's closed set. */
  state: string;
  role: string;
  sensitivity: string;
}

/** The same boundary parse the overlay gets, for the same reason. */
export function parseSemantics(body: unknown): Record<string, SemanticField> {
  const raw = (body as { fields?: unknown } | null)?.fields;
  const out: Record<string, SemanticField> = {};
  if (!Array.isArray(raw)) return out;
  for (const item of raw) {
    const r = item as Record<string, unknown> | null;
    if (!r || typeof r !== "object") continue;
    const field = str(r.field);
    if (!field) continue;
    out[field] = {
      field,
      purpose: str(r.purpose),
      state: str(r.state, "draft"),
      role: str(r.role),
      sensitivity: str(r.sensitivity),
    };
  }
  return out;
}

/** The chip word for a governance state. Sentence case: DESIGN.md §2 forbids
 *  ALL-CAPS app chrome, and the registry's own values are lower case. */
function stateWord(state: string | undefined): string {
  if (state === "approved") return "Approved";
  if (state === "disabled") return "Disabled";
  if (state === "draft") return "Draft";
  return "No semantic record";
}

/** The explanation, in the tooltip rather than on the row (DESIGN.md §2). */
function stateHint(state: string | undefined): string {
  if (state === "approved") return "This field is approved for retrieval by the assistant.";
  if (state === "disabled") return "This field is withheld from retrieval.";
  if (state === "draft")
    return "This field is not approved for retrieval yet, so the assistant will not use it.";
  return "This database publishes no governed meaning for this field.";
}

/** The chip tone. Blue is the interactive or affirmed state and red is the
 *  withheld one, per DESIGN.md §3; draft earns no colour, the way Member does not. */
function stateChipClass(state: string | undefined): string {
  if (state === "approved") return "set-chip set-chip--admin";
  if (state === "disabled") return "set-chip set-chip--off";
  return "set-chip";
}

/** One database's PATCH body: `{ "<field_key>": {hidden, label, order} }`. */
type FieldPatch = { hidden?: boolean; label?: string | null; order?: number | null };

type Result<T> = { ok: true; data: T } | { ok: false; message: string };

const READ_LIMIT_MS = 2000;
const DETAIL_READ_LIMIT_MS = 10000;

function LoadingDatabases() {
  return <div className="set-skeleton" role="status" aria-label="Loading databases">
    {[0, 1, 2, 3].map((key) => <span key={key} className="set-skeleton-line" />)}
  </div>;
}

/**
 * The fetch idiom is `settingsApi.call`'s, deliberately not an import of it:
 * that module's helper is private to it, and C1's routes are this pane's, so a
 * widening of a shared file for one caller would be a fence this ticket does not
 * own. Same credentials word, same "never surface a 5xx verbatim" rule.
 */
async function callOverlay<T>(
  init?: RequestInit & { body?: string },
  path = "",
  readLimitMs = READ_LIMIT_MS,
): Promise<Result<T>> {
  const controller = new AbortController();
  const abort = () => controller.abort();
  init?.signal?.addEventListener("abort", abort, { once: true });
  if (init?.signal?.aborted) abort();
  const timer = !init?.method || init.method === "GET"
    ? window.setTimeout(abort, readLimitMs) : undefined;
  try {
    const res = await fetch(`${API_V1}/admin/schema-overlay${path}`, {
      credentials: CREDENTIALS,
      headers: init?.body ? { "Content-Type": "application/json" } : undefined,
      ...init,
      signal: controller.signal,
    });
    let body: unknown = null;
    try {
      body = await res.json();
    } catch {
      /* an empty body is not fatal; the status below decides */
    }
    if (controller.signal.aborted) throw new Error("Read aborted");
    if (!res.ok) {
      const err = (body as { error?: { message?: string } } | null)?.error;
      const message =
        res.status === 404
          ? "The database could not be found."
          : res.status >= 500
            ? "The databases could not be loaded."
            : err?.message ||
              (res.status === 403
                ? "Administrators only."
                : "That change could not be saved.");
      return { ok: false, message };
    }
    return { ok: true, data: body as T };
  } catch {
    return { ok: false, message: controller.signal.aborted
      ? "The database request took too long." : "The server could not be reached." };
  } finally {
    window.clearTimeout(timer);
    init?.signal?.removeEventListener("abort", abort);
  }
}

/**
 * The semantic half's fetch, deliberately a sibling of `callOverlay` rather than
 * a generalisation of it: the two speak different routes with different refusals,
 * and one helper taking a path would make the 404 sentence below impossible to
 * write honestly. Same credentials word, same "never surface a 5xx verbatim" rule.
 */
async function callSemantics<T>(
  path: string,
  init?: RequestInit & { body?: string },
): Promise<Result<T>> {
  try {
    const res = await fetch(`${API_V1}/query/semantics/${path}`, {
      credentials: CREDENTIALS,
      headers: init?.body ? { "Content-Type": "application/json" } : undefined,
      ...init,
    });
    let body: unknown = null;
    try {
      body = await res.json();
    } catch {
      /* an empty body is not fatal; the status below decides */
    }
    if (!res.ok) {
      const err = (body as { error?: { message?: string } } | null)?.error;
      const message =
        // ⛔ 404 IS A REAL ANSWER HERE, NOT AN OUTAGE. Only a database with a
        // declared topic contract has governed meanings, so a plain user table
        // answers 404 and that is correct. Reporting it as a broken service
        // would send an admin looking for a fault that is not there.
        res.status === 404
          ? "This database publishes no semantic contract, so it carries no field descriptions."
          : res.status >= 500
            ? "Something went wrong on our side. Try again in a moment."
            : err?.message ||
              (res.status === 403
                ? "Administrators only."
                : "That description could not be saved.");
      return { ok: false, message };
    }
    return { ok: true, data: body as T };
  } catch {
    return { ok: false, message: "The server could not be reached." };
  }
}

// ── the pane ────────────────────────────────────────────────────────────────

/** Sort by the overlay's order where it has one, then by label, so a database
 *  with no stored order still lists in a stable, readable sequence rather than
 *  in whatever order the server happened to serialise. */
function inOrder(rows: OverlayField[]): OverlayField[] {
  return [...rows].sort((a, b) => {
    const ao = a.order ?? Number.MAX_SAFE_INTEGER;
    const bo = b.order ?? Number.MAX_SAFE_INTEGER;
    if (ao !== bo) return ao - bo;
    return a.label.localeCompare(b.label);
  });
}

/** Data's drawer keeps the shared editor, focus trap and saving guard together. */
export function DatabaseFieldsDrawer({ databaseKey, databaseLabel, onBack }: {
  databaseKey: string;
  databaseLabel: string;
  onBack: () => void;
}) {
  const panelRef = useRef<HTMLElement>(null);
  const [busy, setBusy] = useState(false);
  useOverlayLayer({ panelRef, onDismiss: () => { if (!busy) onBack(); },
    dismissOnOutside: false, trapFocus: true, restoreFocus: false });
  return <BodyPortal>
    <div className="w46-db-drawer-backdrop">
      <section className="w46-db-drawer" ref={panelRef} role="dialog" aria-modal="true"
        aria-label={`${databaseLabel} fields`} tabIndex={-1} data-overlay-kind="database-fields">
        <DatabaseFieldsEditor databaseKey={databaseKey} databaseLabel={databaseLabel}
          onBack={onBack} backLabel="Back to database" onBusyChange={setBusy} />
      </section>
    </div>
  </BodyPortal>;
}

/** Each database uses the same overlay and semantic stores from Connectors or Data. */
export function DatabaseFieldsEditor({ databaseKey, databaseLabel, onBack, onBusyChange,
  backLabel = "Back to databases", disclosure }: {
  databaseKey: string;
  databaseLabel: string;
  onBack: () => void;
  onBusyChange?: (busy: boolean) => void;
  backLabel?: string;
  disclosure?: FieldDisclosure;
}) {
  const [parsed, setParsed] = useState<ParsedOverlay | null>(null);
  const [detailReload, setDetailReload] = useState(0);
  const [addingField, setAddingField] = useState(false);
  const [fieldName, setFieldName] = useState("");
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");
  const [saving, setSaving] = useState(false);
  useEscapeClose(true, () => { if (!saving) onBack(); });
  useEffect(() => {
    onBusyChange?.(saving);
    return () => onBusyChange?.(false);
  }, [onBusyChange, saving]);
  /** The unsaved relabel and reorder for the open database, keyed by field. */
  const [draft, setDraft] = useState<Record<string, FieldPatch>>({});
  /**
   * The open database's governed meanings, keyed by field. `null` is "not asked
   * yet"; an empty object is "asked, and there are none", which is a different
   * thing and the row renders differently for it.
   */
  const [semantics, setSemantics] = useState<Record<string, SemanticField> | null>(null);
  /** Why there are no descriptions, when there are none. Empty means there are. */
  const [semNote, setSemNote] = useState("");
  /** The unsaved description edits for the open database, keyed by field. */
  const [semDraft, setSemDraft] = useState<Record<string, string>>({});

  /**
   * The governed meanings are fetched PER DATABASE, when one is opened, because
   * the route is per database and the list page shows no field rows to hang them
   * on. Closing the takeover drops them, so re-opening a database cannot paint a
   * previous one's descriptions for a moment.
   */
  useEffect(() => {
    let live = true;
    const controller = new AbortController();
    setParsed(null);
    setError("");
    setSemantics(null);
    setSemNote("");
    setSemDraft({});
    setDraft({});
    setNotice("");
    setAddingField(false);
    setFieldName("");
    void callOverlay<{ semantics?: unknown; semanticNote?: string }>(
      { signal: controller.signal }, `/databases/${encodeURIComponent(databaseKey)}`,
      DETAIL_READ_LIMIT_MS,
    ).then((r) => {
      if (!live) return;
      if (r.ok) {
        const fields = parseOverlay(r.data);
        if (!Array.isArray((r.data as { fields?: unknown } | null)?.fields) || fields.dropped
          || fields.fields.some((field) => field.database !== databaseKey)) {
          setError("The database fields could not be loaded.");
          return;
        }
        setParsed(fields);
        setSemantics(parseSemantics(r.data.semantics));
        setSemNote(r.data.semanticNote || "");
      } else {
        // ⛔ NOT an error page, and NOT an empty list dressed as success. The
        // rows still render their description control; what changes is that the
        // pane SAYS why every one of them is empty. A refusal that removes the
        // control would read as "this feature is missing" rather than as "this
        // database has no governed meanings", which is the exact confusion
        // instruction 8 reports about the previous wave.
        setSemantics({});
        setError(r.message);
      }
    });
    return () => {
      live = false;
      controller.abort();
    };
  }, [databaseKey, detailReload]);

  /**
   * ONE ACTION, TWO STORES, AND THE CODE SAYS SO. The overlay owns label, hidden
   * and order; the semantic registry owns the description. An admin edits both in
   * one row and saves once, but neither write is allowed to pretend to be the
   * other, and a refusal on one must not silently discard the other's edits.
   */
  const save = useCallback(
    (database: string) => {
      const patch = draft;
      const notes = semDraft;
      const noteFields = Object.keys(notes);
      if (Object.keys(patch).length === 0 && noteFields.length === 0) return;
      setSaving(true);
      void (async () => {
        let failure = "";

        // 1. the overlay half.
        if (Object.keys(patch).length) {
          const r = await callOverlay<unknown>({
            method: "PATCH",
            body: JSON.stringify({ [database]: patch }),
          }, `?database_key=${encodeURIComponent(database)}`);
          if (r.ok) {
            setParsed(parseOverlay(r.data));
            setDraft({});
            signal(WORKSPACE_STALE_EVENT);
          } else {
            failure = r.message;
          }
        }

        // 2. the semantic half, ONE FIELD AT A TIME because the route is per
        //    field. Only the fields the server actually accepted are cleared
        //    from the draft; a field it refused keeps the admin's text on screen
        //    rather than throwing away typing the row still appears to hold.
        const stillDraft: Record<string, string> = {};
        for (const field of noteFields) {
          const one = await callSemantics<{ field?: unknown }>(
            `${encodeURIComponent(database)}/${encodeURIComponent(field)}`,
            { method: "PATCH", body: JSON.stringify({ purpose: notes[field] }) },
          );
          if (one.ok) {
            const written = parseSemantics({
              fields: [(one.data as { field?: unknown } | null)?.field],
            })[field];
            if (written) setSemantics((s) => ({ ...(s ?? {}), [field]: written }));
          } else {
            stillDraft[field] = notes[field];
            if (!failure) failure = one.message;
          }
        }
        setSemDraft(stillDraft);

        setSaving(false);
        setError(failure);
        setNotice(failure ? "" : "Saved.");
      })();
    },
    [draft, semDraft],
  );

  const db = useMemo(() => ({ key: databaseKey, label: databaseLabel,
    rows: parsed?.fields ?? [] }), [databaseKey, databaseLabel, parsed]);
  const rows = inOrder(db.rows).map((f) => ({ ...f, ...pick(draft[f.field]) }));
  // The draft's own order wins over the server's, so a move shows immediately.
  rows.sort((a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER));

  /** Reorder writes an order for EVERY row, not only the two that swapped: a
   *  sparse order over a list that was previously unordered would leave the
   *  rest to the tiebreak and read as a random shuffle. */
  const move = (index: number, delta: number) => {
    const next = [...rows];
    const to = index + delta;
    if (to < 0 || to >= next.length) return;
    const [row] = next.splice(index, 1);
    next.splice(to, 0, row);
    setDraft((d) => {
      const out = { ...d };
      next.forEach((r, i) => {
        out[r.field] = { ...out[r.field], order: i };
      });
      return out;
    });
    setNotice("");
  };

  // Both stores count. A description edited on its own must arm Save and
  // Discard exactly as a relabel does, or the row holds typing the page says
  // there is nothing to save.
  const dirty = Object.keys(draft).length > 0 || Object.keys(semDraft).length > 0;

  return (
    <div className="set-pane set-manage-database" data-database-fields={db.key}>
      <button type="button" className="set-perm-back" onClick={onBack} disabled={saving} autoFocus>
        {/* The chevron the accounts takeover already draws, at the same
            geometry: the house vocabulary extended rather than a second icon
            language imported (DESIGN.md §4). */}
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden focusable="false">
          <path
            d="M9.5 4 5.5 8l4 4"
            stroke="currentColor"
            strokeWidth={1.3}
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>
        {backLabel}
      </button>
      <div className="set-perm-ident">
        <h3 className="set-h">{db.label}</h3>
        <span className="set-username">{db.key}</span>
      </div>

      {error ? <div className="set-error" role="alert">
        <span>{error}</span>
        {parsed === null ? <button type="button" className="set-secondary"
          onClick={() => setDetailReload((value) => value + 1)}>Retry</button> : null}
      </div> : null}
      {notice ? <p className="set-notice" role="status">{notice}</p> : null}
      {parsed === null && !error ? <LoadingDatabases /> : null}
      {parsed !== null && db.key.startsWith("ut_") ? <div className="set-actions">
        <button type="button" className="set-secondary" disabled={saving || dirty}
          onClick={() => setAddingField((value) => !value)}>
          Add field
        </button>
        {addingField ? <form className="set-db-add-field" onSubmit={(event) => {
          event.preventDefault();
          if (!fieldName.trim() || saving) return;
          setSaving(true);
          void fetch(`${API_V1}/tables/${encodeURIComponent(db.key)}/fields`, {
            method: "POST", credentials: CREDENTIALS,
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ label: fieldName.trim(), type: "text" }),
          }).then((response) => {
            if (!response.ok) { setError("The field could not be added."); return; }
            setAddingField(false); setFieldName("");
            setDetailReload((value) => value + 1);
          }).catch(() => setError("The server could not be reached."))
            .finally(() => setSaving(false));
        }}>
          <label className="set-field"><span className="set-label">Field name</span>
            <input className="set-input" value={fieldName} required maxLength={100}
              onChange={(event) => setFieldName(event.currentTarget.value)} />
          </label>
          <button type="submit" className="set-secondary" disabled={saving || !fieldName.trim()}>Add text field</button>
        </form> : null}
      </div> : null}
      {/* ⭐ STANDING RULE 1's SECOND SENTENCE, which is the half that gets
          dropped: a limit that cannot be removed is REPORTED with its cause,
          never silently enforced. Here the limit is that only a database with
          a declared topic contract has governed meanings at all. Saying so is
          what stops an empty Description column reading as a broken feature. */}
      {semNote ? <p className="set-help">{semNote}</p> : null}

      <ul className="w46-db-fields">
        {rows.map((f, i) => (
          <li className="w46-db-field" key={f.field}>
            <div className="w46-db-idline">
              <span className="w46-db-key">{f.field}</span>
              <span className="w46-db-meta">
                {f.type} in {f.source}
              </span>
              {f.locked ? (
                <span
                  className="set-chip"
                  title="This field is a join key or the record id, so it cannot be hidden."
                >
                  Always shown
                </span>
              ) : null}
              {/* The GOVERNANCE state, in the chip vocabulary this row already
                  speaks. The explanation rides the tooltip rather than the row
                  (DESIGN.md §2: explanations go in a hover, not on screen). */}
              <span
                className={stateChipClass(semantics?.[f.field]?.state)}
                title={stateHint(semantics?.[f.field]?.state)}
              >
                {stateWord(semantics?.[f.field]?.state)}
              </span>
            </div>
            {/* ⛔⛔ ONE GRID CHILD, NOT TWO, AND THAT IS STRUCTURAL RATHER THAN
                TIDY. `.w46-db-field` is a THREE column grid declared in
                `styles/wave46/manage-database.css`, and that sheet is in NO
                lane's fence this wave — so a fourth child here would wrap into
                an implicit fourth row and break every row on the page, with no
                way to correct it from this file. The description therefore
                sits INSIDE the relabel block, which stays the second column.
                ⚠ `.set-field`'s 13px bottom margin is what separates the two
                boxes; the second label deliberately carries no class, so the
                block has no trailing margin to fight `align-items: end`. */}
            <div className="w46-db-relabel">
              <label className="set-field">
                <span className="set-label">Label</span>
                <input
                  className="set-input"
                  type="text"
                  disabled={saving}
                  value={f.label}
                  onChange={(e) => {
                    const value = e.currentTarget.value;
                    setDraft((d) => ({ ...d, [f.field]: { ...d[f.field], label: value } }));
                    setNotice("");
                  }}
                />
              </label>
              {/* ⭐ INSTRUCTION 8. Always rendered, including for a field with
                  no governed meaning and for a database with no contract at
                  all: the done-when is that an absent description "reads as
                  empty rather than as missing UI". The 500 character cap is
                  the registry's own (`semantic_registry._text(..., 500)`), so
                  the box refuses what the server would have truncated. */}
              <label>
                <span className="set-label">Description</span>
                <input
                  className="set-input"
                  type="text"
                  maxLength={500}
                  disabled={saving}
                  placeholder="No description yet"
                  value={semDraft[f.field] ?? semantics?.[f.field]?.purpose ?? ""}
                  onChange={(e) => {
                    const value = e.currentTarget.value;
                    setSemDraft((d) => ({ ...d, [f.field]: value }));
                    setNotice("");
                  }}
                />
              </label>
            </div>
            <div className="w46-db-acts">
              <label className="set-check">
                <input
                  type="checkbox"
                  checked={f.hidden}
                  disabled={f.locked || saving}
                  onChange={(e) => {
                    const value = e.currentTarget.checked;
                    setDraft((d) => ({ ...d, [f.field]: { ...d[f.field], hidden: value } }));
                    setNotice("");
                  }}
                />
                Hidden
              </label>
              <button
                type="button"
                className="w46-db-move"
                onClick={() => move(i, -1)}
                disabled={saving || i === 0}
                aria-label={`Move ${f.label} up`}
              >
                Up
              </button>
              <button
                type="button"
                className="w46-db-move"
                onClick={() => move(i, 1)}
                disabled={saving || i === rows.length - 1}
                aria-label={`Move ${f.label} down`}
              >
                Down
              </button>
            </div>
          </li>
        ))}
      </ul>

      {disclosure ? (
        <details className="set-db-source">
          <summary>Source fields</summary>
          {disclosure.database.fieldsDeferred ? (
            disclosure.readError ? (
              <div className="set-error" role="alert">
                <span>{disclosure.readError}</span>
                <button type="button" className="set-secondary" onClick={disclosure.onRetry}>Retry</button>
              </div>
            ) : <p className="set-help" role="status" aria-live="polite">Reading the source fields.</p>
          ) : (
            <>
              {disclosure.database.fields.length ? (
                <ul className="set-db-source-list">
                  {disclosure.database.fields.map((field) => (
                    <li key={field.key}>
                      <span className="w46-db-key">{field.sourceField || field.key}</span>
                      <span className="w46-db-meta">{field.type}, shown as {field.label}</span>
                    </li>
                  ))}
                </ul>
              ) : <p className="set-help">The source reported no fields for this database.</p>}
              <h4 className="set-label">Excluded</h4>
              {disclosure.database.excluded.length ? (
                <ul className="set-db-source-list">
                  {disclosure.database.excluded.map((item) => (
                    <li key={item.sourceField}>
                      <span className="w46-db-key">{item.sourceField}</span>
                      <span className="w46-db-meta">{item.reason}</span>
                    </li>
                  ))}
                </ul>
              ) : <p className="set-help">The field catalogue held nothing back from this database.</p>}
              {/* The server's own sentence: an empty diff is not a claim about policy. */}
              <p className="set-help">{disclosure.introspection.excludedBasis || "No exclusion basis was recorded."}</p>
            </>
          )}
        </details>
      ) : null}

      <div className="set-actions">
        <button
          type="button"
          className="set-primary"
          disabled={!dirty || saving || parsed === null}
          onClick={() => save(db.key)}
        >
          {saving ? "Saving" : "Save changes"}
        </button>
        <button
          type="button"
          className="set-secondary"
          disabled={!dirty || saving}
          onClick={() => {
            setDraft({});
            setSemDraft({});
            setNotice("");
          }}
        >
          Discard
        </button>
      </div>
    </div>
  );
}

/** The draft merged over a server row, so the list shows unsaved edits without
 *  the draft having to carry the parts nobody touched. */
function pick(patch: FieldPatch | undefined): Partial<OverlayField> {
  if (!patch) return {};
  const out: Partial<OverlayField> = {};
  if (typeof patch.label === "string") out.label = patch.label;
  if (typeof patch.hidden === "boolean") out.hidden = patch.hidden;
  if (patch.order !== undefined) out.order = patch.order;
  return out;
}