fsanyoto commited on
Commit
1904e77
·
verified ·
1 Parent(s): 2f6862d

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. RELEASES.json +1 -1
  2. VERSION +1 -1
  3. api/automation_engine.py +102 -4
  4. api/rollup_sql.py +2 -33
  5. api/routes_automation.py +2 -2
  6. api/routes_customers.py +137 -608
  7. api/routes_geo.py +193 -0
  8. api/routes_grid.py +33 -473
  9. api/routes_odoo_tables.py +5 -40
  10. api/routes_shares.py +99 -463
  11. api/routes_tables.py +31 -271
  12. platform/aios_grid.py +242 -298
  13. platform/aios_grid_fields.json +44 -3
  14. platform/core/field_permissions.py +9 -194
  15. platform/core/shares.py +148 -1
  16. platform/core/store.py +3 -5
  17. platform/core/user_tables.py +315 -1074
  18. platform/harness/filter_eval.py +217 -1
  19. platform/harness/measure_filter.py +0 -6
  20. platform/harness/runtime.py +1 -5
  21. platform/harness/semantic.py +17 -124
  22. platform/model/topics/odoo_products.yml +28 -3
  23. platform/model/topics/sales_lines.yml +0 -37
  24. platform/modules/product_data.py +62 -234
  25. platform/modules/products.py +21 -235
  26. web/src/customer-grid/ColumnMenu.tsx +75 -851
  27. web/src/customer-grid/CustomerGrid.tsx +324 -764
  28. web/src/customer-grid/DatePicker.tsx +165 -0
  29. web/src/customer-grid/MapView.tsx +694 -711
  30. web/src/customer-grid/RecordDetail.tsx +2 -2
  31. web/src/customer-grid/SwipeView.tsx +586 -586
  32. web/src/customer-grid/Toolbar.tsx +38 -116
  33. web/src/customer-grid/ViewSidebar.tsx +197 -684
  34. web/src/customer-grid/apiBridge.ts +0 -168
  35. web/src/customer-grid/folders.ts +0 -163
  36. web/src/customer-grid/formulaEngine.ts +9 -434
  37. web/src/customer-grid/icons.tsx +0 -15
  38. web/src/customer-grid/map.css +48 -2
  39. web/src/customer-grid/mapProjection.ts +19 -6
  40. web/src/customer-grid/types.ts +31 -557
  41. web/src/customer-grid/useVisibleRows.ts +28 -170
  42. web/src/customer-grid/viewEcho.ts +1 -159
  43. web/src/customer-grid/viewModes.tsx +63 -114
  44. web/src/filter-kit/FieldsHidePanel.tsx +74 -384
  45. web/src/filter-kit/fieldClass.ts +0 -177
  46. web/src/index.css +42 -49
  47. web/src/shell/NavExtras.tsx +8 -19
  48. web/src/shell/ShareDialog.tsx +4 -124
  49. web/src/shell/Shell.tsx +98 -442
  50. web/src/shell/nav.ts +0 -160
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "5d8aacc",
3
  "releases": [
4
  {
5
  "version": "v53",
 
1
  {
2
+ "current": "b89a27e",
3
  "releases": [
4
  {
5
  "version": "v53",
VERSION CHANGED
@@ -1 +1 @@
1
- 5d8aacc
 
1
+ b89a27e
api/automation_engine.py CHANGED
@@ -156,6 +156,9 @@ TT_POST_SNAPSHOTS_TABLE = "ut_tt_post_snapshots"
156
  TT_COMMENTS_TABLE = "ut_tt_comments"
157
 
158
  AUTOMATION_RECORD_MODE = "automation"
 
 
 
159
  #: ⚠ THE RAISED CEILING FOLLOWS THE APPEND SHAPE, NOT THE PLATFORM. `ut_tt_snapshots` and
160
  #: `ut_tt_post_snapshots` are append tables for exactly the reason their IG twins are — one row per
161
  #: profile per pull, `maxPosts` rows per pull — so they inherit the ceiling by JOINING THIS SET,
@@ -179,7 +182,13 @@ APPEND_TABLES = frozenset({IG_SNAPSHOTS_TABLE, IG_POST_SNAPSHOTS_TABLE,
179
  #: `tiktok_profile_match` trigger (the same law that makes `discover_instagram` reachable). It
180
  #: lands here IN THE SAME CHANGE as its `RUNNERS` entry and its flip law: a kind in this tuple
181
  #: with no runner is a control that must refuse.
182
- KINDS = ("plain", "scrape_db", "field_instagram", "discover_instagram", "discover_tiktok")
 
 
 
 
 
 
183
  #: ⭐⭐ WAVE 30 · T04 — THE DISCOVERY KINDS UNDER ONE NAME, and this constant is a bug fix rather
184
  #: than tidying. `discover_tiktok` shipped in wave 29 by being added to `KINDS`, `RUNNERS`,
185
  #: `clean_config` and `TRIGGER_*` — four sites that were found — while FIVE more tested the string
@@ -252,7 +261,8 @@ RETIRED_KIND_REPLACEMENT = {
252
  KIND_LABELS = {"plain": "Agent", "scrape_db": "Web page to database",
253
  "field_instagram": "Instagram profile column",
254
  "discover_instagram": "Find Instagram profiles",
255
- "discover_tiktok": "Find TikTok profiles"}
 
256
  #: ⭐⭐ WAVE 34 · CONTRACTS C3 + C4 — WHY A SYSTEM AGENT CANNOT BE DELETED, one sentence per slug.
257
  #:
258
  #: ⛔ ONE PLACE, because two doors ask this question (the DELETE route refuses with it, and the
@@ -1643,6 +1653,57 @@ def clean_config(kind, raw, previous=None):
1643
  raw = raw if isinstance(raw, dict) else {}
1644
  prev = previous if isinstance(previous, dict) else {}
1645
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1646
  def flag(name):
1647
  return bool(raw[name]) if name in raw else bool(prev.get(name))
1648
  if kind == "plain":
@@ -1659,7 +1720,12 @@ def clean_config(kind, raw, previous=None):
1659
  target = UT_PREFIX + target
1660
  return {"targetTable": target,
1661
  "targetLabel": _s(raw.get("targetLabel"), 60).strip()}, None
1662
- if kind == "scrape_db":
 
 
 
 
 
1663
  url = _s(raw.get("url"), 2000).strip()
1664
  if not url:
1665
  return None, "a source URL is required"
@@ -8271,6 +8337,38 @@ def seed_statements_agent(rt, username="system"):
8271
  return defn
8272
 
8273
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8274
  def run_plain(rt, defn, username="automation", log=print, step=_no_step, rows=None):
8275
  """⭐ WAVE 24 / R6 — the runner for an automation with NO machine step: its flow IS the whole
8276
  automation. Returns the same 5-tuple every other runner does, so `run_now` needs no special
@@ -8408,7 +8506,7 @@ def run_plain(rt, defn, username="automation", log=print, step=_no_step, rows=No
8408
  counts, ids, {})
8409
 
8410
 
8411
- RUNNERS = {"plain": run_plain, "scrape_db": run_scrape_db,
8412
  "field_instagram": run_field_instagram,
8413
  # ⭐ WAVE 30 · T09 (D-129) — BOTH DISCOVERY KINDS MAP ONTO THE SAME FUNCTION. The kind is
8414
  # no longer chosen by which callable this dict holds; `run_discovery` reads it off the
 
156
  TT_COMMENTS_TABLE = "ut_tt_comments"
157
 
158
  AUTOMATION_RECORD_MODE = "automation"
159
+ # C2/R3: a scheduled route snapshots an existing map route. Keep this transport ceiling aligned
160
+ # with the map/router ceiling without importing a client module into the automation engine.
161
+ ROUTE_STOP_CAP = 100
162
  #: ⚠ THE RAISED CEILING FOLLOWS THE APPEND SHAPE, NOT THE PLATFORM. `ut_tt_snapshots` and
163
  #: `ut_tt_post_snapshots` are append tables for exactly the reason their IG twins are — one row per
164
  #: profile per pull, `maxPosts` rows per pull — so they inherit the ceiling by JOINING THIS SET,
 
182
  #: `tiktok_profile_match` trigger (the same law that makes `discover_instagram` reachable). It
183
  #: lands here IN THE SAME CHANGE as its `RUNNERS` entry and its flip law: a kind in this tuple
184
  #: with no runner is a control that must refuse.
185
+ KINDS = ("plain", "scrape_db", "field_instagram", "discover_instagram", "discover_tiktok",
186
+ "route_delivery")
187
+ #: Kinds exposed by the generic Automation rail. A scheduled route is a real automation, but it
188
+ #: has no generic editor: it is created and configured from the Map route index, which owns the
189
+ #: immutable View snapshot and Inbox recipient. Showing it here would offer a door that cannot
190
+ #: correctly configure it.
191
+ PICKER_KINDS = tuple(kind for kind in KINDS if kind != "route_delivery")
192
  #: ⭐⭐ WAVE 30 · T04 — THE DISCOVERY KINDS UNDER ONE NAME, and this constant is a bug fix rather
193
  #: than tidying. `discover_tiktok` shipped in wave 29 by being added to `KINDS`, `RUNNERS`,
194
  #: `clean_config` and `TRIGGER_*` — four sites that were found — while FIVE more tested the string
 
261
  KIND_LABELS = {"plain": "Agent", "scrape_db": "Web page to database",
262
  "field_instagram": "Instagram profile column",
263
  "discover_instagram": "Find Instagram profiles",
264
+ "discover_tiktok": "Find TikTok profiles",
265
+ "route_delivery": "Scheduled route"}
266
  #: ⭐⭐ WAVE 34 · CONTRACTS C3 + C4 — WHY A SYSTEM AGENT CANNOT BE DELETED, one sentence per slug.
267
  #:
268
  #: ⛔ ONE PLACE, because two doors ask this question (the DELETE route refuses with it, and the
 
1653
  raw = raw if isinstance(raw, dict) else {}
1654
  prev = previous if isinstance(previous, dict) else {}
1655
 
1656
+ # W43C-T03 / C2 — a scheduled route is a FROZEN delivery, not a second view
1657
+ # evaluator. Its source-view identity and revision are provenance; the ordered stops are
1658
+ # the exact route the recipient will receive when the cron fires. Keeping this in the
1659
+ # automation definition gives it the existing native schedule, run history and single
1660
+ # scheduler without teaching the generic field persistence layer about routes.
1661
+ if kind == "route_delivery":
1662
+ snap = raw.get("routeSnapshot") if isinstance(raw.get("routeSnapshot"), dict) else {}
1663
+ source_view = str(snap.get("sourceViewId") or "").strip()[:120]
1664
+ revision = str(snap.get("sourceViewRevision") or "").strip()[:128]
1665
+ recipient = str(raw.get("recipient") or "").strip()[:120]
1666
+ timezone = str(snap.get("timezone") or raw.get("timezone") or "UTC").strip()[:80]
1667
+ source_name = " ".join(str(snap.get("sourceViewName") or "").split())[:120]
1668
+ route_field = str(snap.get("routeField") or "").strip()[:120]
1669
+ try:
1670
+ links_per_map = int(snap.get("mapsPerLink", raw.get("mapsPerLink", 10)))
1671
+ except (TypeError, ValueError):
1672
+ links_per_map = 10
1673
+ # R5: Google directions requires at least an origin and destination. The map UI exposes
1674
+ # the same 2–10 bound; this server normalisation is the wall for hand-written bodies too.
1675
+ links_per_map = max(2, min(10, links_per_map))
1676
+ ordered = []
1677
+ seen = set()
1678
+ for raw_pid in snap.get("orderedStopIds") or []:
1679
+ try:
1680
+ pid = int(raw_pid)
1681
+ except (TypeError, ValueError):
1682
+ continue
1683
+ if pid > 0 and pid not in seen:
1684
+ ordered.append(pid)
1685
+ seen.add(pid)
1686
+ if not recipient:
1687
+ return None, "choose the Inbox recipient for this route"
1688
+ if not source_view or not revision:
1689
+ return None, "a scheduled route needs the source View and its frozen revision"
1690
+ if len(ordered) < 2:
1691
+ return None, "a scheduled route needs at least two ordered stops"
1692
+ if len(ordered) > ROUTE_STOP_CAP:
1693
+ return None, f"a scheduled route may contain at most {ROUTE_STOP_CAP} stops"
1694
+ return {
1695
+ "recipient": recipient,
1696
+ "routeSnapshot": {
1697
+ "sourceViewId": source_view,
1698
+ "sourceViewRevision": revision,
1699
+ "sourceViewName": source_name or source_view,
1700
+ "timezone": timezone or "UTC",
1701
+ "routeField": route_field,
1702
+ "orderedStopIds": ordered,
1703
+ "mapsPerLink": links_per_map,
1704
+ },
1705
+ }, None
1706
+
1707
  def flag(name):
1708
  return bool(raw[name]) if name in raw else bool(prev.get(name))
1709
  if kind == "plain":
 
1720
  target = UT_PREFIX + target
1721
  return {"targetTable": target,
1722
  "targetLabel": _s(raw.get("targetLabel"), 60).strip()}, None
1723
+ if kind == "route_delivery":
1724
+ snap = cfg.get("routeSnapshot") or {}
1725
+ body = (f"deliver {len(snap.get('orderedStopIds') or [])} frozen route stops from "
1726
+ f"{snap.get('sourceViewName') or snap.get('sourceViewId') or 'a View'} to "
1727
+ f"{cfg.get('recipient') or 'an Inbox'}")
1728
+ elif kind == "scrape_db":
1729
  url = _s(raw.get("url"), 2000).strip()
1730
  if not url:
1731
  return None, "a source URL is required"
 
8337
  return defn
8338
 
8339
 
8340
+ def run_route_delivery(rt, defn, username="automation", log=print, step=_no_step, rows=None):
8341
+ """Deliver one immutable C2 route snapshot to its assignee's Inbox.
8342
+
8343
+ The runner deliberately never reads a View or recalculates stops. A schedule is a promise to
8344
+ send the route that was saved, not a second evaluator whose answer can drift when the source
8345
+ View changes overnight. `core.alerts.notify` is the existing tenant-scoped Inbox writer; it
8346
+ is passed the runtime explicitly so scheduler work cannot land in tenant #0 by accident.
8347
+ """
8348
+ cfg = defn.get("config") or {}
8349
+ snap = cfg.get("routeSnapshot") if isinstance(cfg.get("routeSnapshot"), dict) else {}
8350
+ recipient = str(cfg.get("recipient") or "").strip()
8351
+ stops = [int(pid) for pid in (snap.get("orderedStopIds") or [])]
8352
+ if not recipient or len(stops) < 2:
8353
+ return ("error", "the saved route delivery no longer has a recipient and at least two stops",
8354
+ {}, [], {})
8355
+ title = str(defn.get("name") or snap.get("sourceViewName") or "Scheduled route").strip()
8356
+ source = str(snap.get("sourceViewName") or snap.get("sourceViewId") or "the saved View")
8357
+ cap = int(snap.get("mapsPerLink") or 10)
8358
+ detail = (f"{len(stops)} frozen stops from {source}. Google Maps links use up to {cap} stops "
8359
+ f"per link; timezone {snap.get('timezone') or 'UTC'}.")
8360
+ step(f"Delivering {len(stops)} frozen stops to {recipient}'s Inbox")
8361
+ try:
8362
+ from core import alerts
8363
+ alerts.notify(recipient, title, topic="automation", key=str(defn.get("id") or ""),
8364
+ row_id=str((defn.get("schedule") or {}).get("enabledAt") or "route"),
8365
+ detail=detail, actor=str(defn.get("createdBy") or ""), st=rt)
8366
+ except Exception as exc: # the run must name a delivery failure; pretending it delivered is worse
8367
+ return ("error", f"the route could not be delivered to Inbox ({type(exc).__name__})", {}, [], {})
8368
+ return ("ok", f"Delivered {len(stops)} frozen route stops to {recipient}'s Inbox.",
8369
+ {"stops": len(stops), "inboxDelivered": 1}, stops, {})
8370
+
8371
+
8372
  def run_plain(rt, defn, username="automation", log=print, step=_no_step, rows=None):
8373
  """⭐ WAVE 24 / R6 — the runner for an automation with NO machine step: its flow IS the whole
8374
  automation. Returns the same 5-tuple every other runner does, so `run_now` needs no special
 
8506
  counts, ids, {})
8507
 
8508
 
8509
+ RUNNERS = {"plain": run_plain, "route_delivery": run_route_delivery, "scrape_db": run_scrape_db,
8510
  "field_instagram": run_field_instagram,
8511
  # ⭐ WAVE 30 · T09 (D-129) — BOTH DISCOVERY KINDS MAP ONTO THE SAME FUNCTION. The kind is
8512
  # no longer chosen by which callable this dict holds; `run_discovery` reads it off the
api/rollup_sql.py CHANGED
@@ -39,35 +39,7 @@ for _p in (str(_HERE), str(_PLATFORM)):
39
 
40
 
41
  class RollupSourceError(Exception):
42
- """The rollup could not be computed HONESTLY — no cells are written when this is raised.
43
-
44
- ⛔⛔ THE ORIGINAL EXCEPTION IS CARRIED AS `.cause`, AND THAT ATTRIBUTE IS THE CONTRACT.
45
- `group_values` wraps whatever the semantic layer raises, and it used to keep only
46
- `f"{type(e).__name__}: {e}"` — the TYPE survived as TEXT and nothing else. A caller wanting to
47
- tell "you named a column this topic does not have" (a 400 naming the column) apart from "this
48
- topic has no store binding" (a 503) then had no choice but to match words in a sentence, which
49
- is exactly the discriminator amendment A8 exists to forbid: that sentence is copy that reaches
50
- a screen, so it WILL be reworded, and the branch stops firing without a word.
51
-
52
- ⚠ `__cause__` is set as well (every wrap keeps its `from e`), but it is NOT the contract.
53
- `__cause__` is traceback chaining, dropped silently by the first later `raise
54
- RollupSourceError(...)` written without `from`; a named attribute set at the raise site cannot
55
- go missing that quietly, and `isinstance(err.__cause__, X)` is a DIFFERENT contract from the
56
- one A8 wrote.
57
-
58
- ⚠ `cause` DEFAULTS TO None and the message argument is unchanged, so single-argument
59
- construction and `str(err)` behave exactly as before — `verify_odoo_relational.py`'s
60
- `except R.RollupSourceError` needs no edit. The two refusals raised by this module's own logic
61
- (an unresolvable window, a truncated group set) have no underlying exception, so they leave it
62
- None: `.cause is None` means "this module refused", not "nothing was wrapped".
63
-
64
- Test it as `isinstance(err.cause, semantic.UnknownColumnError)`, NEVER as
65
- `"UnknownColumnError" in str(err)`.
66
- """
67
-
68
- def __init__(self, message, cause=None):
69
- super().__init__(message)
70
- self.cause = cause
71
 
72
 
73
  def _ut():
@@ -118,10 +90,7 @@ def group_values(bag, today=None):
118
  date_from=date_from, date_to=date_to,
119
  limit=sem.MAX_GROUPS, today=today)
120
  except Exception as e: # noqa: BLE001
121
- # ⛔ `cause=e` IS THE POINT OF THIS LINE, not decoration. The message keeps the type name
122
- # for a human reading a log; a CALLER branches on `err.cause`, never on that text. See
123
- # `RollupSourceError`'s docstring for why the text is not a discriminator.
124
- raise RollupSourceError(f"{type(e).__name__}: {e}", cause=e) from e
125
 
126
  if res.get("truncated"):
127
  # ⛔ THE REFUSAL THAT MATTERS. See the module header: a truncated GROUP set is a wrong
 
39
 
40
 
41
  class RollupSourceError(Exception):
42
+ """The rollup could not be computed HONESTLY — no cells are written when this is raised."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
 
45
  def _ut():
 
90
  date_from=date_from, date_to=date_to,
91
  limit=sem.MAX_GROUPS, today=today)
92
  except Exception as e: # noqa: BLE001
93
+ raise RollupSourceError(f"{type(e).__name__}: {e}") from e
 
 
 
94
 
95
  if res.get("truncated"):
96
  # ⛔ THE REFUSAL THAT MATTERS. See the module header: a truncated GROUP set is a wrong
api/routes_automation.py CHANGED
@@ -844,14 +844,14 @@ def list_automations(session: Session = Depends(_GATE)):
844
  items = sorted(items + _field_agent_rows(session) + _sys_rows,
845
  key=lambda r: str(r.get("name") or "").lower())
846
  return {"automations": items,
847
- # ⭐ WAVE 24 — DERIVED from the engine's own `KINDS`, not a hand-written trio. It was
848
  # three literals that happened to match, which is a second copy of a server
849
  # vocabulary; R6 has just made two of them uncreatable and `plain` has joined, so a
850
  # hand list would now be wrong in three ways at once. `creatable` carries R6 onto the
851
  # wire, so the ruling is a fact the client can read rather than one it must remember.
852
  "kinds": [{"key": k, "label": engine.KIND_LABELS.get(k, k),
853
  "creatable": k not in engine.RETIRED_KINDS}
854
- for k in engine.KINDS],
855
  "cronPresets": engine.CRON_PRESETS,
856
  # ⚠ A BOOLEAN, NEVER THE KEY. The surface needs to say "the paid rung is not
857
  # configured" honestly instead of offering a tier that will silently refuse — and
 
844
  items = sorted(items + _field_agent_rows(session) + _sys_rows,
845
  key=lambda r: str(r.get("name") or "").lower())
846
  return {"automations": items,
847
+ # ⭐ WAVE 24 — DERIVED from the engine's public `PICKER_KINDS`, not a hand-written trio. It was
848
  # three literals that happened to match, which is a second copy of a server
849
  # vocabulary; R6 has just made two of them uncreatable and `plain` has joined, so a
850
  # hand list would now be wrong in three ways at once. `creatable` carries R6 onto the
851
  # wire, so the ruling is a fact the client can read rather than one it must remember.
852
  "kinds": [{"key": k, "label": engine.KIND_LABELS.get(k, k),
853
  "creatable": k not in engine.RETIRED_KINDS}
854
+ for k in engine.PICKER_KINDS],
855
  "cronPresets": engine.CRON_PRESETS,
856
  # ⚠ A BOOLEAN, NEVER THE KEY. The surface needs to say "the paid rung is not
857
  # configured" honestly instead of offering a tier that will silently refuse — and
api/routes_customers.py CHANGED
@@ -87,8 +87,8 @@ def _pool_for(rt, team_id, agent):
87
  rt.pool_cache[key] = snap # seed, so the memo stamps stay coherent
88
  return snap[1]
89
  raise err(503, "connector_paused",
90
- "this data source is paused and no snapshot exists for your scope. "
91
- "An admin can resume it under Settings, then Connectors.")
92
 
93
  def _build():
94
  # ⚠ THE SCOPE GOES INTO THE BUILDER. `pool(agent_name, team_id)` is the same reconciled
@@ -203,32 +203,7 @@ def shared_cells(pids, st=None):
203
  return {}
204
 
205
 
206
- def _canonical_field_keys():
207
- """The keys THE CANONICAL CONTRACT declares, read from `aios_grid.FIELDS`.
208
-
209
- ⭐ W42-T46 — this is the discriminator `_merge_shared_fields` narrows its precedence rule on,
210
- and the one `grid_assembly` tells `contract` from `personal` with when it lends C10's strata
211
- map. Derived from the contract list itself rather than from a mark on the definition, because
212
- every mark on a definition survives being copied out of the document it came from (the whole
213
- of `field_permissions.field_stratum`'s docstring is that proof).
214
-
215
- ⛔⛔ THE IMPORT IS LOCAL, LIKE EVERY OTHER `aios_grid` USE IN THIS FILE (nine of them), AND
216
- LEAVING IT OUT WAS A LIVE DEFECT RATHER THAN AN UNTIDINESS. `routes_customers` never imports
217
- `aios_grid` at module scope, so a bare `aios_grid.FIELDS` here raised `NameError` on EVERY call
218
- -- and `_merge_shared_fields` calls this unconditionally, on the main grid read path.
219
- ⚠ WHAT MADE IT INVISIBLE IS THE INTERESTING HALF: `routes_nav.nav_schema` wraps its customer
220
- branch in `except Exception: fields = []`, whose own comment calls that fail-closed and correct.
221
- So the NameError did not surface as an error; it surfaced as a schema drawer serving an EMPTY
222
- field contract, and the only thing that noticed was `verify_api.py:786` indexing `[0]` of it.
223
- A lenient except turned a typo into a silent empty payload.
224
- """
225
- import aios_grid
226
-
227
- return {str(f.get("key") or "").strip()
228
- for f in (aios_grid.FIELDS or ()) if isinstance(f, dict)}
229
-
230
-
231
- def _merge_shared_fields(fields, defs, session=None, strata=None):
232
  """`fields` PLUS the tenant-wide columns this topic declares — `routes_tables._ut_shared_fields`
233
  on the customer topic.
234
 
@@ -237,74 +212,15 @@ def _merge_shared_fields(fields, defs, session=None, strata=None):
237
  closure's reach otherwise and carries the hidden value out wearing a second name. It is also
238
  the only order in which `field_grant_hidden` can ever see the `granted` marker at all — merge
239
  afterwards and the per-field wall is inert while every test still passes.
240
-
241
- ⭐⭐ W42-T46 / R15 / R16 — THE PRECEDENCE RULE, NARROWED, AND IT IS THE ROOT CAUSE OF
242
- INSTRUCTION 17. The old rule was flat: `if k in have: continue`, so a viewer holding ANY
243
- same-key entry silently discarded the tenant-wide definition and read their own. Their own was
244
- never marked shared, so it filed as private, which is the owner's *"Gabriel created the Route
245
- and it ends up being MY field"* verbatim: a route IS a field (`kind: "route_order"`, key
246
- `route_<slug>`) minted tenant-wide, and it landed in every other account's private list.
247
-
248
- The rule is now:
249
-
250
- * a key the canonical contract declares AND the incoming list already carries -> the LOCAL
251
- entry wins, exactly as before. This is the original guard's whole purpose: a shared overlay
252
- may never redefine a built-in column.
253
- * a key the incoming list carries that the contract does NOT declare (a user-created column,
254
- a route among them) -> the SHARED definition wins, in place, carrying its own `createdBy`
255
- so `field_class` reports its real owner.
256
- * a key the incoming list does not carry -> projected and appended, exactly as before.
257
-
258
- ⛔ THE CANONICAL GUARD IS CONDITIONAL ON `k in have`, AND THAT IS DELIBERATE RATHER THAN
259
- SLOPPY. Skipping a canonical key unconditionally would DROP a key that is projected today
260
- (a contract key absent from the incoming list), and which keys are present is a WALL question,
261
- not a precedence one. Under this rule the outgoing key set is `incoming | (defs - have)` for
262
- every input, byte for byte what it was.
263
-
264
- ⚠ SUPERSEDED, NOT DELETED (R16), AND IT IS STRUCTURAL. This helper is a read-time projection:
265
- it writes nothing, and the viewer's own definition stays in their workspace member exactly as
266
- `TableStore.save_field` left it. A caller recovers it by reading the workspace member before
267
- the merge (`aios_grid.workspace_wire`'s output, the `fields` argument here). What rides on the
268
- wire is a THIN marker under `superseded`, never a copy of the local definition: a nested
269
- definition would be copied verbatim into a fork by `grid_events.field_upsert`
270
- (`base = field_by_key[key]` then `{**base, ...}`) and persisted, and a nested `formula` would
271
- sit outside `hidden_keys`' closure, which walks entries and not nested dicts.
272
-
273
- ⭐ `strata` IS AN OUT-PARAMETER, filled per key with C10's stratum for the definition that
274
- WON: `contract` | `shared` | `personal`. `field_permissions.field_class` cannot derive it (see
275
- `field_stratum`), so the assembly that did the reading lends it. Only `grid_assembly` passes
276
- one; the return type is unchanged for every other call site.
277
  """
278
- incoming = list(fields or ())
279
- canonical = _canonical_field_keys()
280
- lent = strata if isinstance(strata, dict) else None
281
-
282
- # Index the incoming list ONCE, and mark each of its keys with the stratum it was read from:
283
- # a key the contract declares is `contract`, anything else came out of this viewer's own
284
- # workspace member and is `personal`. Keys are stripped because `field_classes` strips both
285
- # sides of its lookup, and an unstripped entry would silently fall back instead of failing.
286
- have = {}
287
- for idx, f in enumerate(incoming):
288
- if not isinstance(f, dict):
289
- continue
290
- k = str(f.get("key") or "").strip()
291
- if not k or k in have:
292
- continue
293
- have[k] = idx
294
- if lent is not None:
295
- lent[k] = "contract" if k in canonical else "personal"
296
-
297
  if not defs:
298
  return fields
 
299
  projected = []
300
  for k, f in defs.items():
301
- k = str(k or "").strip()
302
- if not k:
303
- continue
304
- idx = have.get(k)
305
- if idx is not None and k in canonical:
306
- # THE CANONICAL GUARD, UNCHANGED. A shared column is an ADDITION to this database's
307
- # contract, never a redefinition of a column it already has.
308
  continue
309
  item = dict(f, source="overlay", shared=True)
310
  if session is not None:
@@ -314,82 +230,8 @@ def _merge_shared_fields(fields, defs, session=None, strata=None):
314
  is_admin=session.admin, st=session.runtime)
315
  if role:
316
  item["sharedRole"] = role
317
- if idx is None:
318
- projected.append(item)
319
- else:
320
- local = incoming[idx] if isinstance(incoming[idx], dict) else {}
321
- item["superseded"] = {
322
- "stratum": "personal",
323
- "owner": str(local.get("createdBy") or "").strip() or None,
324
- "label": str(local.get("label") or "").strip() or None,
325
- }
326
- incoming[idx] = item
327
- if lent is not None:
328
- lent[k] = "shared"
329
- return incoming + projected
330
-
331
-
332
- def _mark_offerability(fields):
333
- """Every `route_order` column marked NOT offerable in a field picker, and nothing else touched.
334
-
335
- ⭐⭐ W42-T53 / CONTRACT C11 / R20 / R23 — THE NAVIGATION COMPLAINT, MEASURED: ~64 route
336
- columns on a 53-field grid, each carrying ~21 filled stops against ~3,620 blanks (99.4%
337
- empty), every one of them in every field picker on the topic.
338
-
339
- ⛔⛔ THIS IS PRESENTATION. IT IS NOT A PERMISSION AND IT IS NOT A DELETION, AND THE
340
- DIFFERENCE IS THE WHOLE TICKET. The columns are still SERVED: W42-T20's projection reads
341
- them to build its one column, and `route_order_write` still validates a full 1..N
342
- permutation per column. Filtering them out of the payload would leave the projection with
343
- nothing to project and take the route planner's data off the wire, and R20 keeps the 64 as
344
- the store underneath precisely so that nothing has to be migrated irreversibly on live.
345
- So this adds ONE key to an entry and never removes an entry.
346
-
347
- ⛔ KIND-CHECKED, NEVER PREFIX-CHECKED, the rule `_split_route_updates` and
348
- `route_order_delete` both state: `ROUTE_KEY_PREFIX` is a naming convention and a convention
349
- is not a declaration.
350
-
351
- ⭐ AND THE `kind` IS READ OFF THE **SERVED ENTRY**, NOT OFF `shared_fields`. After W42-T46
352
- narrowed the precedence rule a route key reaches the outgoing list two ways, and `kind`
353
- rides the entry in both: projected from the tenant-wide stratum, and replaced IN PLACE over
354
- a viewer's own same-key entry (the `superseded` branch). Both go through
355
- `dict(f, source="overlay", shared=True)`, which copies the stored definition whole. Reading
356
- the entry rather than the `defs` dict also means this helper is honest about the list it was
357
- actually handed, instead of about a second document that may not describe it.
358
-
359
- ⚠ THE ONE SHAPE IT CANNOT SEE, STATED RATHER THAN GLOSSED: a route key that exists ONLY in a
360
- viewer's own workspace member, with no tenant-wide definition left to supersede it.
361
- `aios_grid.fields_from_workspace` rebuilds a user-created column from a STRICT ALLOWLIST
362
- (`_field_extras` plus a fixed key set) and `kind` is not in it, so such an entry arrives with
363
- no kind at all and is not marked. That is not the ~64 this ticket is about -- those are all
364
- tenant-wide -- and marking by key prefix instead would break the rule this whole file keeps
365
- (a convention is not a declaration). Recorded so the next reader does not assume coverage
366
- that is not there.
367
-
368
- ⭐ THE `routes` KEY PASSES THROUGH (C11). W42-T20's pre-set projection column is the ONE
369
- column a person picks a route with, so withholding it would remove the feature this ticket
370
- exists to deliver. It is exempted by KEY, because that key is what C11 fixes; whether T20
371
- gives it `kind: "route_order"` or no kind at all (the `cohort_field` precedent carries no
372
- kind), it comes out offerable either way.
373
-
374
- ⚠ ABSENT-MEANS-OFFERABLE IS PRESERVED BY NEVER STAMPING `True`. A non-route column leaves
375
- this function carrying no `offerable` key whatsoever, so the served bytes for every field
376
- that predates the flag are unchanged and no stored fixture moves.
377
-
378
- ⛔ A NEW DICT PER COLUMN, NEVER AN IN-PLACE STAMP, the same rule `class` and `usage` state a
379
- few lines below: these entries are per-request copies today, and writing through one would
380
- make that a dependency rather than a coincidence.
381
-
382
- Returns a list with the SAME keys in the SAME order as the input.
383
- """
384
- out = []
385
- for f in (fields or ()):
386
- if (isinstance(f, dict)
387
- and f.get("kind") == ROUTE_KIND
388
- and str(f.get("key") or "").strip() != ROUTE_PROJECTION_KEY):
389
- out.append(dict(f, **{OFFERABLE_KEY: False}))
390
- else:
391
- out.append(f)
392
- return out
393
 
394
 
395
  def grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
@@ -480,13 +322,7 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
480
  # ⭐⭐ W38-T20 — AND THE COLUMN DEFINITIONS, BEFORE THE WALL. See `_merge_shared_fields`: this
481
  # position is load-bearing twice, once for the transitive closure and once because it is the
482
  # only order in which the per-field grant marker is ever presented to `hidden_keys`.
483
- # ⭐⭐ W42-T46 / C10 — AND IT FILLS THE STRATA MAP ON THE WAY THROUGH. `_strata` is keyed by
484
- # field key and covers EVERY key in the outgoing list by construction: the merge marks each
485
- # incoming key as it indexes it and re-marks any key whose shared definition wins. Nothing
486
- # between this line and the `field_classes` call below adds or renames a column, so lending it
487
- # there is a complete map rather than a partial one.
488
- _strata = {}
489
- fields = _merge_shared_fields(fields, _defs, session=session, strata=_strata)
490
  # ⭐⭐ W41-T01 / RULING R5 / CONTRACTS C1 + C8 — **THE THREE BADGES, STAMPED ONCE, HERE.**
491
  #
492
  # C1 makes `field_permissions.field_class` the ONE producer of `{origin, audience, sharedBy,
@@ -525,24 +361,12 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
525
  # definition would be one account's answer served to the next reader of the same cached
526
  # structure. The copy makes that impossible to reintroduce rather than merely untrue now, which
527
  # is the same rule `_payload` states over `rows_src`.
528
- # ⛔ `agg` belongs to another ticket, and C8 is explicit that an absent key means "not built
529
- # yet", never "false".
530
- # ⭐⭐ W42-T14 / C4 — C8's `usage` IS NO LONGER ONE OF THEM; it is stamped a few lines below,
531
- # in this same window between the merge and the wall. Until then this topic sent `class` with
532
- # no `usage` while every `ut_*` grid sent `usage` with no `class`, and
533
- # `filter-kit/fieldClass.ts::deleteImpactTitle(fc, usage)` composes its delete warning as two
534
- # independent halves and DROPS whichever argument is null -- so both surfaces rendered half a
535
- # sentence with every gate on both sides green.
536
  try:
537
  from core import field_permissions as _fp
538
- # ⭐⭐ W42-T46 / W42-T47 / R15 / C10 — `strata=_strata` IS THE LENDER T47 WAITED FOR, and
539
- # without this argument T47 is a no-op: `field_stratum`'s fallback cannot see a fork and
540
- # names one `shared`, because `{**base}` copies `shared`/`granted`/`source` into the fork
541
- # verbatim. This assembly is the one place that KNOWS which document each definition came
542
- # out of, so it is the only honest source of the fact.
543
  _classes = _fp.field_classes(fields, session.uname, table_key=_shared_key(),
544
- grant_topic=SHARE_TOPIC, values_shared=set(_defs),
545
- strata=_strata, st=rt)
546
  fields = [dict(f, **{"class": _classes[f["key"]]})
547
  if isinstance(f, dict) and _classes.get(f.get("key")) else f
548
  for f in fields]
@@ -564,79 +388,6 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
564
  # makes this degrade safe: a client renders NOTHING for a missing `class` rather than a
565
  # wrong badge, so a registry that will not open costs the badges and not the grid.
566
  pass
567
- # ⭐⭐ W42-T14 / C4 — **C8's `usage`, THE EXPENSIVE DIRECTION, STAMPED ONCE, HERE.**
568
- #
569
- # ⛔ ONE PRODUCER, REUSED, NEVER A SECOND COUNTER FOR THIS TOPIC. `routes_tables._field_usage`
570
- # already answers "what breaks if this column goes" over the WHOLE workspace rather than over
571
- # this caller's stratum, which is the clause the count exists for and the one a second
572
- # implementation would quietly get wrong. It is imported here rather than restated for the same
573
- # reason `_tenant_of` is imported inside it: two spellings of one count is
574
- # [[two-lanes-one-contract-dead-feature]] with a number instead of a key. Imported lazily,
575
- # because `routes_tables` imports this module's siblings at module scope.
576
- #
577
- # ⛔⛔ ONE MEMO KEY SPELLING, AND IT IS `MODULE`. The memo is `{(tenant, table_key): …}` and it
578
- # is invalidated by a change token, never by time, so a second spelling of the topic on this
579
- # door would pin a stale answer under a key nothing invalidates for the life of the process.
580
- # `MODULE` ("customer_data") is the string `apply_row_scope`, `hidden_keys` and
581
- # `routes_admin._clean_perms` already spell for this topic, and it is what the permission
582
- # records inside `_field_usage` are keyed by, so any other choice would also report
583
- # `permRules: 0` for every account. ⚠ NOT `scope`, which is a ROUTE PARAMETER (`"customer"` by
584
- # default) two callers may pass differently, and not `_shared_key()`, which names the DOCUMENT.
585
- #
586
- # ⚠ THE DOCUMENT IS HANDED IN SEPARATELY, and that is the whole re-parameterisation: this
587
- # topic's strata live in `customer_table_workspace`, a name no `f"{table_key}_table_workspace"`
588
- # literal can produce. `rt` carries it, exactly as `_ctx_for` already opens this topic's
589
- # workspace through `_customer_table(session)`.
590
- #
591
- # ⚠ `defn=None` IS NOT A SHORTCUT. That argument is the SHARED CONTRACT leg of
592
- # `_usage_field_corpus`, and on this topic the merge above has already folded both the
593
- # canonical contract (`aios_grid.FIELDS`) and the tenant-wide stratum (`_defs`) into `fields`,
594
- # which the corpus reads as its second source. The third leg -- every OTHER account's `fields`
595
- # stratum -- comes out of the workspace document, which is the half no caller-scoped list can
596
- # contain and the half the count is about. Passing `_defs` too would add nothing but a
597
- # second shape to keep in step, since it is a `{key: field}` dict and not a `{'fields': [...]}`
598
- # definition.
599
- #
600
- # ⚠ AFTER THE MERGE AND BEFORE THE WALL, the same window and the same two reasons as `class`
601
- # above: after, or the tenant-wide columns are neither in the list to stamp nor in the corpus
602
- # to count from; before, so `hidden_keys` deletes a column's usage bag along with the column
603
- # and a reader who may not see a column never learns how much of the workspace depends on it.
604
- # ⚠ A NEW DICT PER COLUMN AND A COPY OF THE BAG -- `_field_usage` MEMOISES, so handing its own
605
- # dict out would let anything downstream write into the number the next request reads.
606
- # ⚠ LENIENT, AND THE ABSENT-KEY POLARITY IS WHAT MAKES THAT SAFE: `_field_usage` returns `{}`
607
- # rather than zeros on a failed read, and this stamps NO key for a column it has no bag for,
608
- # because a confident "0 uses" beside a delete button reads as safe to delete.
609
- try:
610
- from routes_tables import _field_usage as _fu
611
- _usage = _fu(session, MODULE, fields, None, rt, _shared_key(), st=rt)
612
- except Exception: # noqa: BLE001
613
- _usage = {}
614
- if _usage:
615
- fields = [dict(f, usage=dict(_usage[f["key"]]))
616
- if isinstance(f, dict) and _usage.get(f.get("key")) else f
617
- for f in fields]
618
- # ⭐⭐ W42-T53 / C11 — **ROUTE OFFERABILITY, STAMPED ONCE, HERE.** See `_mark_offerability`
619
- # for what it does and does not do (it adds a key; it removes nothing from any wire).
620
- #
621
- # ⛔ IN `grid_assembly` AND NOT IN `_merge_shared_fields`, for the two reasons already
622
- # written out over `class` above: that helper returns `fields` untouched when `defs` is
623
- # empty and otherwise only builds the PROJECTED additions, so a route column that reached
624
- # the list through the viewer's own stratum would leave it unmarked -- and it is called from
625
- # five places (`_hidden_for`, `_route_defs`, and the three route doors) that want a field
626
- # list purely to ask the WALL a question and then throw it away. `grid_assembly` is the
627
- # single assembly both client doors serve verbatim (`_payload` returns `g["fields"]` on
628
- # `/customers`, `routes_grid` assigns `workspace["fields"] = g["fields"]` on `/workspace`),
629
- # so it is the only position in which the two wires cannot disagree about a column.
630
- #
631
- # ⚠ AFTER THE MERGE AND BEFORE THE WALL, the same window and the same two reasons as `class`
632
- # and `usage`: after, or the tenant-wide route columns are not in the list to mark; before,
633
- # so a column this reader may not see loses the mark along with the column rather than
634
- # leaving a mark behind on nothing.
635
- # ⚠ NOT LENIENT, and deliberately not: this is a pure list transform over data already in
636
- # hand, with no store read, no registry open and nothing to raise. A `try` here would be a
637
- # place for a real defect to hide, which is exactly how a `NameError` in
638
- # `_canonical_field_keys` shipped as an EMPTY field contract earlier in this lane.
639
- fields = _mark_offerability(fields)
640
  # THE FIELD WALL — a TRANSITIVE closure (C-PERM amendment 5), so hiding a field also hides
641
  # every formula computed FROM it. Formulas evaluate in the browser from `{ref}`s, so
642
  # shipping a dependent formula while withholding its input either leaks the input through
@@ -669,50 +420,6 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
669
  ws["overlays"] = {pid: {k: v for k, v in (cells or {}).items() if k not in hidden}
670
  for pid, cells in _ov.items()}
671
 
672
- # ⭐⭐ W42-T20 / C11 / R9 / R20 / R23 — **THE ONE ROUTE PROJECTION COLUMN, APPENDED HERE.**
673
- #
674
- # ⛔⛔ AFTER THE WALL, WHICH IS THE OPPOSITE POSITION TO `class`, `usage` AND `offerable`, AND
675
- # THE INVERSION IS THE POINT. Those three are marks ON columns the wall then narrows. This is a
676
- # column DERIVED FROM what the wall left standing: `hidden` is exactly the set of route columns
677
- # this session was not granted, so narrowing first and projecting second is what makes the
678
- # projection incapable of naming a route the reader may not see. Projecting before the wall and
679
- # narrowing afterwards would have to re-parse the joined string to take an entry back out, and
680
- # a value that has already been assembled has already leaked.
681
- #
682
- # ⛔ THE SAME PREDICATE AS `_route_defs`, NOT A SECOND OPINION. That helper is
683
- # `shared_fields` filtered by `kind == ROUTE_KIND` minus `perm_scope.hidden_keys(...)`, and
684
- # `_defs` / `hidden` here are those same two reads on this assembly. Calling `_route_defs`
685
- # instead would repeat a whole `_merge_shared_fields` and a second `hidden_keys` per request to
686
- # recompute a set already in hand; what must not diverge is the PREDICATE, and it does not.
687
- #
688
- # ⚠ THE APPEND IS CONDITIONED ON THE TENANT HAVING ROUTES AT ALL, AND THE CELLS ON THE VIEWER
689
- # HAVING GRANTS -- two different questions with two different answers. A tenant that has never
690
- # planned a route gets no column, which is the cost `cohort_field`'s own note gives for staying
691
- # out of the canonical contract (an always-present column nobody can fill). A viewer with no
692
- # route grants on a tenant that HAS routes gets the column BLANK on every row, which is the
693
- # done-when: hiding the column from them instead would make its presence a signal.
694
- #
695
- # ⚠ NOT LENIENT, deliberately, for `_mark_offerability`'s stated reason: this is a pure
696
- # transform over data already in hand, with no store read and nothing to raise, and a `try`
697
- # here would be a place for a real defect to hide -- which is exactly how a `NameError` in
698
- # `_canonical_field_keys` shipped as an EMPTY field contract earlier in this lane.
699
- #
700
- # ⚠ THE DUPLICATE-KEY GUARD IS `fields_from_workspace`'s, for its reason: a person can create a
701
- # column literally called "Routes", whose slug is this key. The client indexes fields by key, so
702
- # a duplicate does not error -- it silently paints one column's values under the other's header.
703
- # The user's own column wins and the derived one steps aside.
704
- #
705
- # ⚠ IT IS APPENDED AFTER `_mark_offerability` RUNS, so T53's `ROUTE_PROJECTION_KEY` exemption
706
- # never actually fires for this column. Absent-means-offerable gives the right answer either
707
- # way; recorded so the next reader does not read that exemption as load-bearing.
708
- _route_vis = {k: v for k, v in (_defs or {}).items()
709
- if isinstance(v, dict) and v.get("kind") == ROUTE_KIND
710
- and k not in (hidden or ())}
711
- if (any(isinstance(v, dict) and v.get("kind") == ROUTE_KIND for v in (_defs or {}).values())
712
- and not any(isinstance(f, dict) and f.get("key") == ROUTE_PROJECTION_KEY
713
- for f in fields)):
714
- fields = fields + [aios_grid.route_projection_field(ROUTE_PROJECTION_KEY, _route_vis)]
715
-
716
  today = time.strftime("%Y-%m-%d")
717
  stamp = _pool_stamp(rt, team_id, agent)
718
  # ⭐⭐ W38-T19 — THE METRICS CAPABILITY, AND THIS GRAIN NEEDS **THREE** GUARDS WHERE THE
@@ -732,20 +439,6 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
732
  # The derived channel: cohort membership cells + measure column values, ONE dict — the
733
  # same read-only channel the embed host hands to rows_from_pool.
734
  derived = aios_grid.cohort_cells(lists)
735
- # ⭐⭐ W42-T20 — THE ROUTE PROJECTION'S CELLS, ON THE SAME CHANNEL AND NOT A SECOND ONE.
736
- #
737
- # ⛔ `_shared` IS THE SOURCE, AND IT IS THE ONLY ONE THERE IS. `_patch_route_ranks::_held`
738
- # states the mapping: a record is on a route iff its shared-overlay cell for that route key is
739
- # non-empty. There is no reverse index and `route.stops` is a COUNT, so the projection is a
740
- # scan of the cells this assembly already read once for the rows it already scoped.
741
- # ⚠ `_shared` is STRING-keyed and `derived` is INT-keyed; `route_projection_cells` bridges the
742
- # two and its docstring says why inverting them is invisible (a blank column reads exactly like
743
- # a working grant wall).
744
- # ⛔ NOTHING IS WRITTEN BACK ANYWHERE. The ~64 route columns REMAIN the store underneath (R20);
745
- # this reads them and T53 only stops a picker offering them.
746
- for _pid, _cells in aios_grid.route_projection_cells(
747
- ROUTE_PROJECTION_KEY, _route_vis, _shared, pids).items():
748
- derived.setdefault(_pid, {}).update(_cells)
749
  # ⭐ W33-T43 / owner item 12 ("One unique ID per database always"). The customer grid carried
750
  # NO Odoo id column at all, while its retiring twin `ut_odoo_customers` carried `partner_id`
751
  # as its join key — so the merge would have lost the one value every Odoo document joins on.
@@ -1097,7 +790,7 @@ def patch_customer(pid: int, body: dict = Body(default=None),
1097
  "pid": pid, "updates": updates}, ctx)
1098
  except grid_events.StoreUnavailable:
1099
  raise err(503, "store_unavailable",
1100
- "the tenant store is unavailable, so your change was not saved")
1101
 
1102
  route_accepted, route_swaps, route_taken = ({}, [], set())
1103
  if route_updates:
@@ -1165,28 +858,6 @@ ROUTE_KEY_PREFIX = "route_"
1165
  #: convention is not a declaration.
1166
  ROUTE_KIND = "route_order"
1167
 
1168
- #: ⭐⭐ W42-T53 / CONTRACT C11 — **THE OFFERABILITY KEY, AS ONE LITERAL, EXPORTED.**
1169
- #:
1170
- #: `offerable?: boolean` — ABSENT or `True` means offerable; `False` means a field picker
1171
- #: WITHHOLDS the column. Optional and absent-means-offerable, so every field that predates the
1172
- #: flag and every stored fixture stays byte-identical (the same reasoning that made C-A2's
1173
- #: `strict?` optional: the alternative silently reclassifies everything older than the flag).
1174
- #:
1175
- #: ⛔⛔ IT IS A MODULE CONSTANT AND NOT A LITERAL TYPED INTO THE STAMP, BECAUSE THE FAILURE C11
1176
- #: WAS WRITTEN ABOUT IS A SPELLING DISAGREEMENT ACROSS TWO LANES, NOT A LOGIC ERROR. This lane
1177
- #: was about to emit `notOfferable: true` while the client half (W42-T54) was about to read
1178
- #: `offerable === false`: both correct, both sides' gates green, and ~64 route columns still
1179
- #: filling every picker on screen. A per-side negative control cannot see that. Exporting the
1180
- #: name lets a parity leg DERIVE the server's emitted key from this module instead of retyping
1181
- #: it, which is the only shape of assertion that can compare the two literals to each other.
1182
- OFFERABLE_KEY = "offerable"
1183
-
1184
- #: ⭐ CONTRACT C11 — the key of W42-T20's ONE pre-set projection column, which passes THROUGH the
1185
- #: filter that withholds the other route columns. Mirrors the `cohort_field` precedent's
1186
- #: `{key: 'cohorts'}`: served, special, and offered. Named here so the exemption is a fact about
1187
- #: this module rather than a string repeated in two places.
1188
- ROUTE_PROJECTION_KEY = "routes"
1189
-
1190
  #: ⭐⭐ W41-T05 / CONTRACT C3 — THE DESCRIPTION EVERY ROUTE COLUMN IS BORN WITH.
1191
  #:
1192
  #: `shared_overlay.mint_field` refuses a tenant-wide column that has no description, and the
@@ -1356,147 +1027,6 @@ def _own_route_fork(session: Session, key: str):
1356
  return entry
1357
 
1358
 
1359
- #: ⭐⭐ W42-T23's FOLDER SURFACE NAME, DECLARED HERE SO THERE IS ONE SPELLING OF IT.
1360
- #:
1361
- #: T22 carried `folderId` on the wire as an honest `None`, because no store document could hold a
1362
- #: route's placement: `aios_grid.FOLDER_SURFACES` was `{"views", "cohorts"}`, `clean_folders` and
1363
- #: `clean_item_folders` iterate exactly that set, and the folder write door refused the surface
1364
- #: outright. T23 widened that set, and this is where the value comes from now.
1365
- #:
1366
- #: ⛔⛔ THE PLACEMENT IS PER VIEWER, AND THE ROUTE ITSELF IS TENANT-WIDE. Those two facts sit
1367
- #: badly together until you look at where a folder ROW lives: `TableStore.workspace` is keyed by
1368
- #: USERNAME, so the routes rail's folders are this account's folders and nobody else's. A
1369
- #: tenant-wide placement could therefore only ever name a folder that no other viewer has, and
1370
- #: every other account would watch the route fall back to the root anyway — a shared fact with an
1371
- #: unshareable referent. `aios_grid.clean_folders` states the same rule from the other end:
1372
- #: filing is an ORGANISING act, not part of what the filed thing IS. So the route is one object
1373
- #: every account sees, and where each account keeps it is that account's own business.
1374
- #:
1375
- #: ⛔ THE HOME IS `itemFolders["routes"]` IN THE PER-USER TABLE WORKSPACE — the stratum views and
1376
- #: cohorts already use — and NOT a `folderId` key on the shared definition. A key on the
1377
- #: definition would be tenant-wide by construction (the wrong answer above), and it would ride
1378
- #: through `shared_overlay.put_field` on a record whose every other key is a fact about the
1379
- #: COLUMN rather than about one reader's sidebar.
1380
- ROUTE_FOLDER_SURFACE = "routes"
1381
-
1382
-
1383
- def _route_folder_stratum(session: Session):
1384
- """`(folders, placements)` for the routes rail: this caller's own, never another's.
1385
-
1386
- ⚠ `consume_corrections=False`, like `_own_route_fork` and like every folder read in
1387
- `grid_events`. A filing read that consumed a pending label-correction acknowledgement would
1388
- make the ack's delivery depend on whether somebody had a sidebar open.
1389
- """
1390
- try:
1391
- ws = _customer_table(session).workspace(session.uname, consume_corrections=False)
1392
- except Exception: # noqa: BLE001
1393
- return [], {}
1394
- folders = list((ws.get("folders") or {}).get(ROUTE_FOLDER_SURFACE) or [])
1395
- placed = dict((ws.get("itemFolders") or {}).get(ROUTE_FOLDER_SURFACE) or {})
1396
- return folders, placed
1397
-
1398
-
1399
- def _route_folder_id(placed, folders, key):
1400
- """The folder this route sits in for this caller, or None for the top level.
1401
-
1402
- ⛔ RESOLVED AGAINST THE FOLDERS THAT EXIST, EVERY TIME, and that is not belt-and-braces. A
1403
- folder can be deleted through the generic folder door, which knows nothing about routes; the
1404
- placement it leaves behind names nothing, and answering with it would put the route in a
1405
- section the rail cannot draw. Prune, never invent — `clean_item_folders`' posture, said at
1406
- read time so a stale placement can never outlive its folder on screen.
1407
-
1408
- ⚠ `ROOT_PLACEMENT` SURVIVES THIS, deliberately, and it is not the same as None. Absence means
1409
- "never filed", which the client's `groupByFolder` renders into the Shared group for a route
1410
- somebody shared with you; the reserved id means "this reader deliberately dragged it out to
1411
- the top level". Wave 32 item 20 is the whole account of why one value cannot carry both.
1412
- """
1413
- import aios_grid
1414
-
1415
- fid = placed.get(key)
1416
- if not isinstance(fid, str) or not fid:
1417
- return None
1418
- if fid == aios_grid.ROOT_PLACEMENT:
1419
- return fid
1420
- return fid if any(f.get("id") == fid for f in folders) else None
1421
-
1422
-
1423
- def _route_share_marks(session: Session, defs):
1424
- """Per-route `{owner, shared, sharedOut, hasShares, sharedRole}` from ONE registry read.
1425
-
1426
- ⭐⭐ CONTRACT C6 — THE SPELLINGS ARE `ViewSidebar.tsx::viewShareMark`'s, NAME FOR NAME. That
1427
- function reads `hasShares` / `shared` (line 198), `shared` + `owner` (199), `sharedRole` (203)
1428
- and `sharedOut` (209); a key spelled one letter differently here is a route navigation that
1429
- lists routes, opens the share dialog, passes every gate and never draws the shared icon
1430
- ([[two-lanes-one-contract-dead-feature]]).
1431
-
1432
- ⛔ THE GRANT IS THE EXISTING GENERIC FIELD DOOR, NOT A SECOND MECHANISM. A route IS a field
1433
- (`kind: "route_order"`, key `route_<slug>`), so its share state lives at
1434
- `shares.field_oid(SHARE_TOPIC, key)` and there is no `route` share kind to invent
1435
- (`shares.KINDS` is `view | folder | database | field`).
1436
-
1437
- ⛔ ONE STORE READ FOR THE WHOLE LISTING, and that is measured rather than tidy.
1438
- `field_permissions.grant_records` opens `object_shares` once and returns
1439
- `{field_key: {owner, entries}}` through the SAME `shares._clean_entries` normaliser
1440
- `shares.grants` uses, so this badge and the wall cannot disagree about a junk-role entry. The
1441
- per-key `shares.role_for` in `_merge_shared_fields` is the older shape and it is a fresh deep
1442
- copy of the whole registry PER KEY: this tenant carries dozens of route columns, so the loop
1443
- would be dozens of serialise/deserialise round trips on a listing that is one read.
1444
-
1445
- ⚠ NO `try/except` AROUND THE READ. `grant_records` already fails closed on an unreadable
1446
- bucket. A second, wider swallow here would turn a missing import into "every route reports
1447
- never-shared" behind a clean 200, which is the exact defect this lane shipped once today.
1448
-
1449
- ⭐ THE ROLE SEMANTICS ARE `SavedView`'s, because `viewShareMark` is `SavedView`'s reader:
1450
- `types.ts` declares `sharedRole?: "view" | "edit"` and states that `shared` / `sharedRole` /
1451
- `owner` all mean *granted TO me*, while the sharer's own leg carries `hasShares` + `sharedOut`
1452
- and never `shared`. So `sharedRole` here is the ENTRY role, absent for the owner. ⚠ The field
1453
- surface spells the same member differently (`FieldShareRole` admits `owner`, and
1454
- `_merge_shared_fields` stamps `shares.role_for`, which reads an admin as `owner`). Two
1455
- surfaces, two declared types; this one follows the consumer it was written for.
1456
- """
1457
- from core import field_permissions, shares
1458
-
1459
- records = field_permissions.grant_records(SHARE_TOPIC, st=session.runtime) or {}
1460
- me = str(session.uname or "").strip().lower()
1461
- marks = {}
1462
- for key, defn in (defs or {}).items():
1463
- rec = records.get(key) or {}
1464
- entries = rec.get("entries") or []
1465
- # ⭐ THE OWNER IS RESOLVED ONCE AND OWNERSHIP IS TESTED AGAINST THE RESOLVED VALUE. A route
1466
- # minted before the grant door stamped an owner has `entries` and no `owner` on the
1467
- # record; testing the raw member would leave its creator reading `shared: true` beside
1468
- # their own name, and the mark would tell them the column was shared with them by
1469
- # themselves. `createdBy` is already on the definition and is already on the wire as
1470
- # `solvedBy`, so the fallback leaks nothing new.
1471
- owner = (str(rec.get("owner") or "").strip().lower()
1472
- or str((defn or {}).get("createdBy") or "").strip().lower())
1473
- mine = bool(me) and owner == me
1474
- granted = None
1475
- if me and not mine:
1476
- for entry in entries:
1477
- if entry.get("user") in (me, shares.EVERYONE):
1478
- # The stronger of the two wins, exactly as `shares.role_for` decides it:
1479
- # naming somebody explicitly is how you raise them above the room.
1480
- if entry.get("role") == "edit":
1481
- granted = "edit"
1482
- break
1483
- granted = granted or "view"
1484
- marks[key] = {
1485
- "owner": owner,
1486
- "hasShares": bool(entries),
1487
- "shared": granted is not None,
1488
- "sharedRole": granted,
1489
- # ⚠ WHAT `sharedOut` CAN TRUTHFULLY MEAN HERE IS NARROWER THAN ON A VIEW, and the
1490
- # narrowness is the registry's, not a choice. `field` is excluded from
1491
- # `shares.RESHARE_KINDS` and `routes_shares._owns_object`'s field branch requires
1492
- # `createdBy == session.uname`, so an `edit` grantee can never hand a column on. The
1493
- # only account that can have shared a route out is the one that owns it, which is
1494
- # what this says: I own it AND somebody holds a grant on it.
1495
- "sharedOut": bool(mine and entries),
1496
- }
1497
- return marks
1498
-
1499
-
1500
  @router.get("/customers/route-order")
1501
  def route_order_list(session: Session = Depends(module_gate(MODULE))):
1502
  """The route-order columns this session may see, with the fingerprint each was solved from.
@@ -1508,18 +1038,8 @@ def route_order_list(session: Session = Depends(module_gate(MODULE))):
1508
  about a moment that has already passed.
1509
  """
1510
  out = []
1511
- # ⛔ THE WALL IS READ ONCE AND NOT RE-ASKED. `_route_defs` is still the ONLY source of the key
1512
- # set below, and the share marks are looked up BY the keys it returned: a route this session
1513
- # may not see is absent from `defs`, so it can have no mark, and its existence is not leaked
1514
- # by a share key either. Nothing here widens what `perm_scope.hidden_keys` let through.
1515
- defs = _route_defs(session)
1516
- marks = _route_share_marks(session, defs)
1517
- # ⭐⭐ W42-T23 — ONE workspace read for the whole listing, not one per route. See
1518
- # `ROUTE_FOLDER_SURFACE` for why the placement is per viewer and lives in this stratum.
1519
- folders, placed = _route_folder_stratum(session)
1520
- for key, defn in sorted(defs.items()):
1521
  route = defn.get("route") if isinstance(defn.get("route"), dict) else {}
1522
- mark = marks.get(key) or {}
1523
  out.append({
1524
  "key": key,
1525
  "label": defn.get("label") or key,
@@ -1530,27 +1050,13 @@ def route_order_list(session: Session = Depends(module_gate(MODULE))):
1530
  "depot": route.get("depot") if isinstance(route.get("depot"), dict) else None,
1531
  "solvedAt": route.get("solvedAt") or "",
1532
  "solvedBy": defn.get("createdBy") or "",
 
 
 
1533
  # Who may re-solve it. The same creator-or-admin wall the write door enforces, said on
1534
  # the way out so the client can grey the control instead of discovering a 403.
1535
  "mine": bool(session.admin
1536
  or str(defn.get("createdBy") or "") == session.uname),
1537
- # ⭐⭐ CONTRACT C6 — THE SHARE STATE, SPELLED AS `viewShareMark` READS IT. Every one of
1538
- # the five is present on every route, negatives included: a MISSING key and a false
1539
- # one are the same thing to `viewShareMark`, but they are not the same thing to the
1540
- # next reader, who cannot tell "not shared" from "this door does not know".
1541
- #
1542
- # ⛔⛔ `shared` HERE IS NOT `shared` ON A FIELD, AND THE TWO LIVE IN THIS ONE FILE.
1543
- # `_merge_shared_fields` stamps `shared: True` on every tenant-wide column, meaning
1544
- # *this definition came out of the shared stratum* - and EVERY route is that, always.
1545
- # `viewShareMark` reads `shared` as *granted to me*, which is FALSE on a tenant-wide
1546
- # route the caller owns. Same word, two questions; this row answers the client's.
1547
- "owner": mark.get("owner") or "",
1548
- "shared": bool(mark.get("shared")),
1549
- "sharedOut": bool(mark.get("sharedOut")),
1550
- "hasShares": bool(mark.get("hasShares")),
1551
- "sharedRole": mark.get("sharedRole"),
1552
- # C6's spelling, and it reports a real placement now. See `ROUTE_FOLDER_SURFACE`.
1553
- "folderId": _route_folder_id(placed, folders, key),
1554
  })
1555
  # ⭐⭐ OWNER ITEM 5 — THE DEFAULT NAME IS ALLOCATED **HERE**, NEVER ON THE CLIENT.
1556
  #
@@ -1563,12 +1069,7 @@ def route_order_list(session: Session = Depends(module_gate(MODULE))):
1563
  #
1564
  # ⚠ IT LEAKS NOTHING. What travels is the first FREE name, which is a fact about absence.
1565
  import aios_grid
1566
- # ⭐ W42-T23 — the rail's own folder ROWS travel with the listing, because a `folderId` with
1567
- # no folder list beside it names a section the client cannot draw. Same rows the generic
1568
- # folder door writes, read back from the same stratum; `parent` rides along, which is what
1569
- # makes the routes rail nest exactly as deep as the views rail does.
1570
  return {"fields": out,
1571
- "folders": [{k: v for k, v in f.items()} for f in folders],
1572
  "nextLabel": _next_route_label(shared_fields(st=session.runtime) or {},
1573
  aios_grid.FIELDS)}
1574
 
@@ -2047,101 +1548,129 @@ def route_order_rename(field_key: str, body: dict = Body(default=None),
2047
  "note": patch.get("note") or ""}
2048
 
2049
 
2050
- @router.patch("/customers/route-order/{field_key}/folder")
2051
- def route_order_file(field_key: str, body: dict = Body(default=None),
2052
- session: Session = Depends(module_gate(MODULE))):
2053
- """File a route into one of this caller's route folders. `{folderId: str | null}`.
2054
-
2055
- ⭐⭐ W42-T23 — A ROUTE'S OWN DOOR, AND THAT IS THE POINT OF IT EXISTING AT ALL.
2056
-
2057
- ⛔⛔ THE GENERIC DOOR IS NOT AVAILABLE HERE, AND IT IS NOT A STYLE CHOICE. `grid_events`'
2058
- `item_move` gates the mover on `_own_ids(surface, ws)`, which is written as
2059
- `if sfc == 'views': ...` with an ELSE returning the caller's COHORT ids — a two-way split,
2060
- not a lookup. A route key is never a cohort id, so filing a route through that door answers
2061
- *"You can file only the items you own"* about a column the person planned themselves. The
2062
- matching read-side hazard is answered in `aios_grid.FOLDER_SURFACES_TENANT_WIDE`, which is
2063
- what stops an unrelated folder rename from erasing what this door writes.
2064
-
2065
- ⛔ THE WALL IS "CAN YOU SEE IT", NOT "IS IT YOURS", and the two differ here on purpose.
2066
- `route_order_rename` and `route_order_delete` are creator-or-admin because they change what
2067
- every account in the workspace reads. A placement changes ONE account's sidebar — this one's
2068
- — so requiring ownership would leave a shared route permanently unfileable by the very people
2069
- it was shared with. A caller who cannot see the column still gets the answer a nonexistent
2070
- key gets, for `route_order_rename`'s reason: a refusal that said "forbidden" would confirm a
2071
- route exists here.
2072
-
2073
- ⚠ THREE INPUTS, NOT TWO. `null` unfiles (no record at all, which is where a new route
2074
- starts), the reserved root id records a deliberate move to the top level, and any other value
2075
- must name a folder that exists. Wave 32 item 20 is the full account of why the first two
2076
- cannot be the same stored state.
2077
- """
2078
- from core import shared_overlay
2079
- from core.table_store import FolderTreeError
2080
- import core.perm_scope as perm_scope
2081
- import aios_grid
2082
 
2083
- body = body if isinstance(body, dict) else {}
2084
- key = str(field_key or "").strip()
2085
 
2086
- all_defs = shared_fields(st=session.runtime) or {}
2087
- defn = all_defs.get(key) if isinstance(all_defs.get(key), dict) else None
2088
- unknown = err(404, "unknown_field",
2089
- "that column is not a route order column on this database")
2090
- if not defn or defn.get("kind") != ROUTE_KIND:
2091
- raise unknown
2092
- if key in perm_scope.hidden_keys(
2093
- session.user, MODULE,
2094
- _merge_shared_fields(list(aios_grid.FIELDS), all_defs), st=session.runtime):
2095
- raise unknown
 
 
 
 
 
 
 
 
 
 
 
 
 
2096
 
2097
- raw = body.get("folderId")
2098
- target = None if raw is None else str(raw).strip()[:80]
2099
 
2100
- store = _customer_table(session)
 
2101
  try:
2102
- ws = store.workspace(session.uname, consume_corrections=False)
2103
- except Exception: # noqa: BLE001
2104
- raise err(503, "store_unavailable",
2105
- "your folders could not be saved because the workspace store is not reachable "
2106
- "right now, so nothing was changed. Try again in a moment")
2107
-
2108
- # ⛔⛔ `save_folders` REPLACES THE WHOLE STRATUM (`ws['folders'] = tree`), so the picture sent
2109
- # in has to be the COMPLETE one. Passing only the routes surface would file this route and
2110
- # delete every views and cohorts folder the caller had, with a 200 and no way back.
2111
- folders = {s: [dict(f) for f in rows]
2112
- for s, rows in (ws.get("folders") or {}).items() if isinstance(rows, list)}
2113
- placed = {s: dict(m) for s, m in (ws.get("itemFolders") or {}).items()
2114
- if isinstance(m, dict)}
2115
- rows = folders.get(ROUTE_FOLDER_SURFACE) or []
2116
- mine = dict(placed.get(ROUTE_FOLDER_SURFACE) or {})
2117
-
2118
- if target is None:
2119
- mine.pop(key, None) # unfiled: no record is how a route is born
2120
- elif target == aios_grid.ROOT_PLACEMENT:
2121
- mine[key] = target
2122
- else:
2123
- if not any(str(f.get("id") or "") == target for f in rows):
2124
- raise err(404, "folder_gone",
2125
- "that folder is not on this sidebar any more, so the route stayed where it "
2126
- "was. Reload the page to see the folders you have, then try again")
2127
- mine[key] = target
2128
- placed[ROUTE_FOLDER_SURFACE] = mine
2129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2130
  try:
2131
- receipt = store.save_folders(session.uname, folders, placed)
2132
- except FolderTreeError as e: # noqa: BLE001
2133
- # The validator already words this for a person, and it names the folder. Re-wording it
2134
- # here would be a second sentence about one rule, drifting from the first the day the cap
2135
- # moves. 400 rather than 500: the tree is illegal, and nothing was written.
2136
- raise err(400, "folder_tree_illegal", str(e))
2137
-
2138
- saved = (receipt.get("itemFolders") or {}).get(ROUTE_FOLDER_SURFACE) or {}
2139
- kept = [dict(f) for f in (receipt.get("folders") or {}).get(ROUTE_FOLDER_SURFACE) or []]
2140
- return {"ok": True, "field": key,
2141
- "folderId": _route_folder_id(saved, kept, key),
2142
- "folders": kept,
2143
- # ⚠ The receipt travels. `validate_folder_tree` REPAIRS a placement whose folder was
2144
- # deleted rather than refusing it, and a repair the caller never hears about is a
2145
- # route that quietly moved. `save_folders`' own docstring makes this the point of its
2146
- # return value.
2147
- "repairs": list(receipt.get("repairs") or [])}
 
87
  rt.pool_cache[key] = snap # seed, so the memo stamps stay coherent
88
  return snap[1]
89
  raise err(503, "connector_paused",
90
+ "this data source is paused and no snapshot exists for your scope — "
91
+ "an admin can resume it under Settings → Connectors")
92
 
93
  def _build():
94
  # ⚠ THE SCOPE GOES INTO THE BUILDER. `pool(agent_name, team_id)` is the same reconciled
 
203
  return {}
204
 
205
 
206
+ def _merge_shared_fields(fields, defs, session=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  """`fields` PLUS the tenant-wide columns this topic declares — `routes_tables._ut_shared_fields`
208
  on the customer topic.
209
 
 
212
  closure's reach otherwise and carries the hidden value out wearing a second name. It is also
213
  the only order in which `field_grant_hidden` can ever see the `granted` marker at all — merge
214
  afterwards and the per-field wall is inert while every test still passes.
215
+ ⚠ A key the canonical contract already declares WINS. A shared column is an ADDITION to this
216
+ database's contract, never a redefinition of a column it already has.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  if not defs:
219
  return fields
220
+ have = {f.get("key") for f in (fields or ()) if isinstance(f, dict)}
221
  projected = []
222
  for k, f in defs.items():
223
+ if k in have:
 
 
 
 
 
 
224
  continue
225
  item = dict(f, source="overlay", shared=True)
226
  if session is not None:
 
230
  is_admin=session.admin, st=session.runtime)
231
  if role:
232
  item["sharedRole"] = role
233
+ projected.append(item)
234
+ return list(fields or ()) + projected
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
 
236
 
237
  def grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
 
322
  # ⭐⭐ W38-T20 — AND THE COLUMN DEFINITIONS, BEFORE THE WALL. See `_merge_shared_fields`: this
323
  # position is load-bearing twice, once for the transitive closure and once because it is the
324
  # only order in which the per-field grant marker is ever presented to `hidden_keys`.
325
+ fields = _merge_shared_fields(fields, _defs, session=session)
 
 
 
 
 
 
326
  # ⭐⭐ W41-T01 / RULING R5 / CONTRACTS C1 + C8 — **THE THREE BADGES, STAMPED ONCE, HERE.**
327
  #
328
  # C1 makes `field_permissions.field_class` the ONE producer of `{origin, audience, sharedBy,
 
361
  # definition would be one account's answer served to the next reader of the same cached
362
  # structure. The copy makes that impossible to reintroduce rather than merely untrue now, which
363
  # is the same rule `_payload` states over `rows_src`.
364
+ # ⛔ AND ONLY `class`. C8's `usage`, `agg` and `descriptionEdited` belong to other tickets, and
365
+ # C8 is explicit that an absent key means "not built yet", never "false".
 
 
 
 
 
 
366
  try:
367
  from core import field_permissions as _fp
 
 
 
 
 
368
  _classes = _fp.field_classes(fields, session.uname, table_key=_shared_key(),
369
+ grant_topic=SHARE_TOPIC, values_shared=set(_defs), st=rt)
 
370
  fields = [dict(f, **{"class": _classes[f["key"]]})
371
  if isinstance(f, dict) and _classes.get(f.get("key")) else f
372
  for f in fields]
 
388
  # makes this degrade safe: a client renders NOTHING for a missing `class` rather than a
389
  # wrong badge, so a registry that will not open costs the badges and not the grid.
390
  pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
  # THE FIELD WALL — a TRANSITIVE closure (C-PERM amendment 5), so hiding a field also hides
392
  # every formula computed FROM it. Formulas evaluate in the browser from `{ref}`s, so
393
  # shipping a dependent formula while withholding its input either leaks the input through
 
420
  ws["overlays"] = {pid: {k: v for k, v in (cells or {}).items() if k not in hidden}
421
  for pid, cells in _ov.items()}
422
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
  today = time.strftime("%Y-%m-%d")
424
  stamp = _pool_stamp(rt, team_id, agent)
425
  # ⭐⭐ W38-T19 — THE METRICS CAPABILITY, AND THIS GRAIN NEEDS **THREE** GUARDS WHERE THE
 
439
  # The derived channel: cohort membership cells + measure column values, ONE dict — the
440
  # same read-only channel the embed host hands to rows_from_pool.
441
  derived = aios_grid.cohort_cells(lists)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442
  # ⭐ W33-T43 / owner item 12 ("One unique ID per database always"). The customer grid carried
443
  # NO Odoo id column at all, while its retiring twin `ut_odoo_customers` carried `partner_id`
444
  # as its join key — so the merge would have lost the one value every Odoo document joins on.
 
790
  "pid": pid, "updates": updates}, ctx)
791
  except grid_events.StoreUnavailable:
792
  raise err(503, "store_unavailable",
793
+ "the tenant store is unavailable — your change was not saved")
794
 
795
  route_accepted, route_swaps, route_taken = ({}, [], set())
796
  if route_updates:
 
858
  #: convention is not a declaration.
859
  ROUTE_KIND = "route_order"
860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
861
  #: ⭐⭐ W41-T05 / CONTRACT C3 — THE DESCRIPTION EVERY ROUTE COLUMN IS BORN WITH.
862
  #:
863
  #: `shared_overlay.mint_field` refuses a tenant-wide column that has no description, and the
 
1027
  return entry
1028
 
1029
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1030
  @router.get("/customers/route-order")
1031
  def route_order_list(session: Session = Depends(module_gate(MODULE))):
1032
  """The route-order columns this session may see, with the fingerprint each was solved from.
 
1038
  about a moment that has already passed.
1039
  """
1040
  out = []
1041
+ for key, defn in sorted(_route_defs(session).items()):
 
 
 
 
 
 
 
 
 
1042
  route = defn.get("route") if isinstance(defn.get("route"), dict) else {}
 
1043
  out.append({
1044
  "key": key,
1045
  "label": defn.get("label") or key,
 
1050
  "depot": route.get("depot") if isinstance(route.get("depot"), dict) else None,
1051
  "solvedAt": route.get("solvedAt") or "",
1052
  "solvedBy": defn.get("createdBy") or "",
1053
+ # The route index's gear edits the same named detail the field editor owns. Serving
1054
+ # it here prevents a rename from accidentally clearing an existing description.
1055
+ "note": str(defn.get("note") or ""),
1056
  # Who may re-solve it. The same creator-or-admin wall the write door enforces, said on
1057
  # the way out so the client can grey the control instead of discovering a 403.
1058
  "mine": bool(session.admin
1059
  or str(defn.get("createdBy") or "") == session.uname),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1060
  })
1061
  # ⭐⭐ OWNER ITEM 5 — THE DEFAULT NAME IS ALLOCATED **HERE**, NEVER ON THE CLIENT.
1062
  #
 
1069
  #
1070
  # ⚠ IT LEAKS NOTHING. What travels is the first FREE name, which is a fact about absence.
1071
  import aios_grid
 
 
 
 
1072
  return {"fields": out,
 
1073
  "nextLabel": _next_route_label(shared_fields(st=session.runtime) or {},
1074
  aios_grid.FIELDS)}
1075
 
 
1548
  "note": patch.get("note") or ""}
1549
 
1550
 
1551
+ # ---------------------------------------------------------------------------
1552
+ # W43C-T03 / C2 — scheduled, frozen route delivery
1553
+ # ---------------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1554
 
1555
+ def _route_delivery_wire(defn):
1556
+ """The compact C2 record consumed by the Map route index.
1557
 
1558
+ The generic automation payload deliberately remains generic. This route is the domain seam
1559
+ that names a frozen View route as such, so the map never has to infer it from an arbitrary
1560
+ agent's config bag.
1561
+ """
1562
+ cfg = defn.get("config") if isinstance(defn.get("config"), dict) else {}
1563
+ snap = cfg.get("routeSnapshot") if isinstance(cfg.get("routeSnapshot"), dict) else {}
1564
+ return {
1565
+ "id": str(defn.get("id") or ""),
1566
+ "name": str(defn.get("name") or "Scheduled route"),
1567
+ "recipient": str(cfg.get("recipient") or ""),
1568
+ "schedule": dict(defn.get("schedule") or {}),
1569
+ "snapshot": {
1570
+ "sourceViewId": str(snap.get("sourceViewId") or ""),
1571
+ "sourceViewRevision": str(snap.get("sourceViewRevision") or ""),
1572
+ "sourceViewName": str(snap.get("sourceViewName") or ""),
1573
+ "timezone": str(snap.get("timezone") or "UTC"),
1574
+ "routeField": str(snap.get("routeField") or ""),
1575
+ "orderedStopIds": list(snap.get("orderedStopIds") or []),
1576
+ "mapsPerLink": int(snap.get("mapsPerLink") or 10),
1577
+ },
1578
+ "createdBy": str(defn.get("createdBy") or ""),
1579
+ "created": str(defn.get("created") or ""),
1580
+ }
1581
 
 
 
1582
 
1583
+ def _route_delivery_recipient_or_400(raw):
1584
+ recipient = str(raw or "").strip()
1585
  try:
1586
+ import core.users as users
1587
+ user = (users.registry() or {}).get(recipient)
1588
+ except Exception: # registry unavailable is not permission to queue a phantom Inbox delivery
1589
+ user = None
1590
+ if not recipient or not isinstance(user, dict) or not user.get("active", True):
1591
+ raise err(400, "unknown_route_recipient",
1592
+ "choose an active account to receive this route in Inbox")
1593
+ return recipient
1594
+
1595
+
1596
+ @router.get("/customers/route-deliveries")
1597
+ def route_delivery_list(session: Session = Depends(module_gate(MODULE))):
1598
+ """Saved C2 route deliveries owned by the caller (or all for an administrator)."""
1599
+ import automation_engine as engine
1600
+ out = []
1601
+ for defn in (engine.all_definitions(session.runtime) or {}).values():
1602
+ if not isinstance(defn, dict) or defn.get("kind") != "route_delivery":
1603
+ continue
1604
+ # A recipient can see the delivery arriving in their Inbox; the edit index is the owner's
1605
+ # configuration surface. Admins can support either one.
1606
+ if not session.admin and str(defn.get("createdBy") or "") != session.uname:
1607
+ continue
1608
+ out.append(_route_delivery_wire(defn))
1609
+ return {"deliveries": sorted(out, key=lambda row: (row["name"].casefold(), row["id"]))}
1610
+
 
 
1611
 
1612
+ @router.post("/customers/route-deliveries")
1613
+ def route_delivery_create(body: dict = Body(default=None),
1614
+ session: Session = Depends(module_gate(MODULE))):
1615
+ """Save a daily route delivery as an immutable C2 snapshot and arm its native schedule."""
1616
+ import automation_control
1617
+ import automation_engine as engine
1618
+
1619
+ if not session.runtime.available():
1620
+ raise err(503, "store_unavailable", "the tenant store is unavailable. Nothing was saved")
1621
+ body = body if isinstance(body, dict) else {}
1622
+ recipient = _route_delivery_recipient_or_400(body.get("recipient"))
1623
+ snapshot = body.get("routeSnapshot") if isinstance(body.get("routeSnapshot"), dict) else {}
1624
+ # View IDs are usually supplied by the host. MapView cannot own generic View persistence, so
1625
+ # its explicit snapshot fingerprint is accepted as the revision when the host has not supplied
1626
+ # a persisted view id yet; it still makes the scheduled contents immutable and inspectable.
1627
+ source_view_id = str(snapshot.get("sourceViewId") or "map-current").strip()
1628
+ source_revision = str(snapshot.get("sourceViewRevision") or body.get("inputsHash") or "").strip()
1629
+ raw = {
1630
+ "name": " ".join(str(body.get("name") or snapshot.get("sourceViewName") or "Scheduled route").split())[:120],
1631
+ "kind": "route_delivery",
1632
+ "trigger": {"key": "manual"},
1633
+ "schedule": body.get("schedule") if isinstance(body.get("schedule"), dict)
1634
+ else {"cron": "0 8 * * *", "enabled": True},
1635
+ "config": {
1636
+ "recipient": recipient,
1637
+ "routeSnapshot": {
1638
+ **snapshot,
1639
+ "sourceViewId": source_view_id,
1640
+ "sourceViewRevision": source_revision,
1641
+ "mapsPerLink": snapshot.get("mapsPerLink", body.get("mapsPerLink", 10)),
1642
+ },
1643
+ },
1644
+ "flow": {"actions": []},
1645
+ }
1646
+ defn, problem = engine.create(session.runtime, raw, username=session.uname)
1647
+ if problem:
1648
+ raise err(400, "invalid_route_delivery", problem)
1649
+ try:
1650
+ automation_control.sync_definition(session.tenant, defn)
1651
+ except automation_control.ControlPlaneError as exc:
1652
+ # The definition exists but is not allowed to read as armed if its native schedule did not.
1653
+ raise err(503, "automation_control_unavailable",
1654
+ f"the route was saved, but its daily schedule could not be armed: {exc}")
1655
+ return {"delivery": _route_delivery_wire(defn)}
1656
+
1657
+
1658
+ @router.delete("/customers/route-deliveries/{delivery_id}")
1659
+ def route_delivery_delete(delivery_id: str,
1660
+ session: Session = Depends(module_gate(MODULE))):
1661
+ """Remove one scheduled delivery without touching its immutable route field or rows."""
1662
+ import automation_control
1663
+ import automation_engine as engine
1664
+
1665
+ defn = (engine.all_definitions(session.runtime) or {}).get(str(delivery_id))
1666
+ if not isinstance(defn, dict) or defn.get("kind") != "route_delivery":
1667
+ raise err(404, "unknown_route_delivery", "no scheduled route with that id")
1668
+ if not session.admin and str(defn.get("createdBy") or "") != session.uname:
1669
+ raise err(403, "forbidden", "only the route creator or an administrator can remove its schedule")
1670
+ engine.remove(session.runtime, str(delivery_id))
1671
  try:
1672
+ automation_control.delete_definition(session.tenant, str(delivery_id))
1673
+ except automation_control.ControlPlaneError as exc:
1674
+ raise err(503, "automation_control_unavailable",
1675
+ f"the route schedule was removed, but its native schedule could not be removed: {exc}")
1676
+ return {"deleted": str(delivery_id)}
 
 
 
 
 
 
 
 
 
 
 
 
api/routes_geo.py CHANGED
@@ -116,6 +116,113 @@ _TILE_MAX_Z_DEFAULT = 19
116
 
117
  _CACHE_MAX = 4096
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
  def _env(name, default):
121
  return (os.environ.get(name) or "").strip() or default
@@ -286,6 +393,92 @@ def geo_providers(session: Session = Depends(require_session)):
286
  return provider_config()
287
 
288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  @router.post("/geo/geocode")
290
  def geo_geocode(body: dict = Body(...), session: Session = Depends(require_session)):
291
  """Turn a bounded list of addresses into coordinates.
 
116
 
117
  _CACHE_MAX = 4096
118
 
119
+ # W43C-T03 / C3 — tenant-durable map Zones. This is intentionally a map-domain record, not a
120
+ # generic field type: a Zone has geometry, visibility and a membership snapshot that only the map
121
+ # can interpret. Keeping it out of generic field persistence lets C consume A's DTO without
122
+ # widening unrelated table writes.
123
+ ZONES_KEY = "map_zones"
124
+ MAX_ZONES = 200
125
+ MAX_ZONE_MEMBERSHIPS = 10_000
126
+ _ZONE_COLORS = ("#9DBFF2", "#A5D8B4", "#F5D989", "#F0A8A0", "#C7B7E8")
127
+
128
+
129
+ def _zone_id(raw):
130
+ value = re.sub(r"[^a-z0-9_-]+", "_", str(raw or "").strip().lower()).strip("_")
131
+ return value[:80]
132
+
133
+
134
+ def _finite_coord(raw):
135
+ try:
136
+ value = float(raw)
137
+ except (TypeError, ValueError):
138
+ return None
139
+ return value if value == value and abs(value) != float("inf") else None
140
+
141
+
142
+ def _clean_geometry(raw):
143
+ """One visible Polygon/MultiPolygon GeoJSON value, normalized without inventing geometry."""
144
+ geom = raw.get("geometry") if isinstance(raw, dict) and raw.get("type") == "Feature" else raw
145
+ if not isinstance(geom, dict):
146
+ raise ValueError("a Zone needs GeoJSON Polygon or MultiPolygon geometry")
147
+ kind = str(geom.get("type") or "")
148
+ coords = geom.get("coordinates")
149
+ polys = [coords] if kind == "Polygon" else coords if kind == "MultiPolygon" else None
150
+ if not isinstance(polys, list) or not polys:
151
+ raise ValueError("a Zone needs GeoJSON Polygon or MultiPolygon geometry")
152
+ cleaned_polys = []
153
+ for poly in polys:
154
+ if not isinstance(poly, list) or not poly:
155
+ raise ValueError("each Zone polygon needs at least one ring")
156
+ rings = []
157
+ for ring in poly:
158
+ if not isinstance(ring, list) or len(ring) < 4:
159
+ raise ValueError("each Zone ring needs at least four longitude/latitude points")
160
+ out = []
161
+ for point in ring:
162
+ if not isinstance(point, (list, tuple)) or len(point) < 2:
163
+ raise ValueError("each Zone point needs longitude and latitude")
164
+ lon, lat = _finite_coord(point[0]), _finite_coord(point[1])
165
+ if lon is None or lat is None or not (-180 <= lon <= 180 and -90 <= lat <= 90):
166
+ raise ValueError("each Zone point must be a longitude and latitude on Earth")
167
+ out.append([round(lon, 7), round(lat, 7)])
168
+ if out[0] != out[-1]:
169
+ out.append(list(out[0]))
170
+ rings.append(out)
171
+ cleaned_polys.append(rings)
172
+ return {"type": "Polygon", "coordinates": cleaned_polys[0]} if kind == "Polygon" else {
173
+ "type": "MultiPolygon", "coordinates": cleaned_polys}
174
+
175
+
176
+ def _clean_zone(raw, previous=None, *, zone_id=""):
177
+ raw = raw if isinstance(raw, dict) else {}
178
+ previous = previous if isinstance(previous, dict) else {}
179
+ name = " ".join(str(raw.get("name") if "name" in raw else previous.get("name") or "").split())[:120]
180
+ if not name:
181
+ raise ValueError("name this Zone")
182
+ color = str(raw.get("color") if "color" in raw else previous.get("color") or _ZONE_COLORS[0]).upper()
183
+ if not re.fullmatch(r"#[0-9A-F]{6}", color):
184
+ raise ValueError("a Zone color is a six-digit hex color")
185
+ geometry = _clean_geometry(raw.get("geometryGeoJson") if "geometryGeoJson" in raw
186
+ else previous.get("geometryGeoJson"))
187
+ geographic = str(raw.get("geographicField") if "geographicField" in raw
188
+ else previous.get("geographicField") or "").strip()[:80]
189
+ memberships = raw.get("memberships") if "memberships" in raw else previous.get("memberships") or []
190
+ if not isinstance(memberships, list):
191
+ raise ValueError("Zone memberships must be a list of record IDs")
192
+ member_ids, seen = [], set()
193
+ for value in memberships[:MAX_ZONE_MEMBERSHIPS]:
194
+ try:
195
+ pid = int(value)
196
+ except (TypeError, ValueError):
197
+ continue
198
+ if pid > 0 and pid not in seen:
199
+ member_ids.append(pid)
200
+ seen.add(pid)
201
+ return {
202
+ "id": zone_id or _zone_id(raw.get("id") or name),
203
+ "name": name,
204
+ "color": color,
205
+ "geometryGeoJson": geometry,
206
+ "visible": bool(raw.get("visible")) if "visible" in raw else bool(previous.get("visible", True)),
207
+ "geographicField": geographic,
208
+ "memberships": member_ids,
209
+ }
210
+
211
+
212
+ def _zone_wire(zone):
213
+ return {key: zone.get(key) for key in ("id", "name", "color", "geometryGeoJson", "visible",
214
+ "geographicField", "memberships", "createdBy", "createdAt")}
215
+
216
+
217
+ def _zone_subject(session, zone_id):
218
+ zones = session.runtime.get(ZONES_KEY) or {}
219
+ zone = zones.get(str(zone_id)) if isinstance(zones, dict) else None
220
+ if not isinstance(zone, dict):
221
+ raise err(404, "unknown_zone", "no Zone with that id")
222
+ if not session.admin and str(zone.get("createdBy") or "") != session.uname:
223
+ raise err(403, "forbidden", "only the Zone creator or an administrator can change it")
224
+ return zone
225
+
226
 
227
  def _env(name, default):
228
  return (os.environ.get(name) or "").strip() or default
 
393
  return provider_config()
394
 
395
 
396
+ @router.get("/geo/zones")
397
+ def geo_zones(session: Session = Depends(require_session)):
398
+ """The C3 Zone DTOs this tenant may draw and choose on its Map Views."""
399
+ try:
400
+ raw = session.runtime.get(ZONES_KEY) or {}
401
+ except Exception:
402
+ raw = {}
403
+ zones = [zone for zone in raw.values() if isinstance(zone, dict)] if isinstance(raw, dict) else []
404
+ # Visibility is a display choice carried by the durable zone itself. Creators and admins keep
405
+ # seeing an invisible zone in the chooser so it can be restored or edited rather than orphaned.
406
+ visible = [zone for zone in zones if zone.get("visible", True)
407
+ or session.admin or str(zone.get("createdBy") or "") == session.uname]
408
+ return {"zones": [_zone_wire(zone) for zone in sorted(visible,
409
+ key=lambda zone: (str(zone.get("name") or "").casefold(), str(zone.get("id") or "")))]}
410
+
411
+
412
+ @router.post("/geo/zones")
413
+ def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(require_session)):
414
+ """Persist one drawn Zone as C3's tenant record; no table-field writer is involved."""
415
+ body = body if isinstance(body, dict) else {}
416
+ try:
417
+ zone = _clean_zone(body)
418
+ except ValueError as exc:
419
+ raise err(400, "invalid_zone", str(exc))
420
+ if not zone["id"]:
421
+ raise err(400, "invalid_zone", "name this Zone")
422
+ created = {}
423
+
424
+ def _write(current):
425
+ current = current if isinstance(current, dict) else {}
426
+ if zone["id"] in current:
427
+ raise ValueError("a Zone with that name already exists")
428
+ if len(current) >= MAX_ZONES:
429
+ raise ValueError(f"this tenant has reached the {MAX_ZONES}-Zone limit")
430
+ item = {**zone, "createdBy": session.uname, "createdAt": time.strftime("%Y-%m-%dT%H:%M:%S")}
431
+ current[zone["id"]] = item
432
+ created.update(item)
433
+ return current
434
+ try:
435
+ session.runtime.update(ZONES_KEY, _write, flush="async")
436
+ except ValueError as exc:
437
+ raise err(409, "zone_exists", str(exc))
438
+ return {"zone": _zone_wire(created)}
439
+
440
+
441
+ @router.patch("/geo/zones/{zone_id}")
442
+ def geo_zone_update(zone_id: str, body: dict = Body(default=None),
443
+ session: Session = Depends(require_session)):
444
+ """Edit geometry, membership, geographic source or visibility of a stored Zone."""
445
+ previous = _zone_subject(session, zone_id)
446
+ try:
447
+ zone = _clean_zone(body, previous, zone_id=str(zone_id))
448
+ except ValueError as exc:
449
+ raise err(400, "invalid_zone", str(exc))
450
+ updated = {}
451
+
452
+ def _write(current):
453
+ current = current if isinstance(current, dict) else {}
454
+ old = current.get(str(zone_id))
455
+ if not isinstance(old, dict):
456
+ raise KeyError(zone_id)
457
+ item = {**zone, "createdBy": old.get("createdBy") or session.uname,
458
+ "createdAt": old.get("createdAt") or time.strftime("%Y-%m-%dT%H:%M:%S")}
459
+ current[str(zone_id)] = item
460
+ updated.update(item)
461
+ return current
462
+ try:
463
+ session.runtime.update(ZONES_KEY, _write, flush="async")
464
+ except KeyError:
465
+ raise err(404, "unknown_zone", "no Zone with that id")
466
+ return {"zone": _zone_wire(updated)}
467
+
468
+
469
+ @router.delete("/geo/zones/{zone_id}")
470
+ def geo_zone_delete(zone_id: str, session: Session = Depends(require_session)):
471
+ """Delete exactly one Zone, leaving records and generic fields untouched."""
472
+ _zone_subject(session, zone_id)
473
+
474
+ def _write(current):
475
+ current = current if isinstance(current, dict) else {}
476
+ current.pop(str(zone_id), None)
477
+ return current
478
+ session.runtime.update(ZONES_KEY, _write, flush="async")
479
+ return {"deleted": str(zone_id)}
480
+
481
+
482
  @router.post("/geo/geocode")
483
  def geo_geocode(body: dict = Body(...), session: Session = Depends(require_session)):
484
  """Turn a bounded list of addresses into coordinates.
api/routes_grid.py CHANGED
@@ -24,7 +24,7 @@ back. A 200 over a write that evaporated is the failure this rule exists to prev
24
  import datetime as dt
25
  import time
26
 
27
- from fastapi import APIRouter, Body, Depends, HTTPException
28
 
29
  from deps import Session, err, module_gate, perms, require_session
30
 
@@ -1029,24 +1029,8 @@ def grid_events_route(body: dict = Body(default=None),
1029
  # an UNCAPPED `IN (?,…)` over them. Confirmed orders only, the wholesale teams and the GIFTWARE
1030
  # DEALS exclusion all come from that topic's `scope_sql`, so the ticket's "confirmed orders only"
1031
  # is enforced by the ONE definition of it rather than by a second copy written here.
1032
- # ⛔⛔ `viaField` IS LOAD-BEARING AS OF W42-T05, AND IT USED TO SAY THE OPPOSITE HERE. Until this
1033
- # ticket the key rode the wire and NOTHING read it: the edge came from a compiled-in route table
1034
- # keyed on `(source, target)`, so the request named a link field and the server answered from
1035
- # a different declaration entirely. The table is gone. The edge is now read off the link field the
1036
- # request NAMES, out of C1's `via` bag (`field["link"]["via"]`, written and validated by
1037
- # `core.user_tables._clean_via`), which is what lets a second pair exist without editing this file.
1038
- # ⚠ THE CONSEQUENCE IS STATED RATHER THAN DISCOVERED, AND IT IS BIGGER THAN A MISSING SEED: this
1039
- # door REFUSES a pivot whose `viaField` does not resolve, with a 400 naming the field, and will
1040
- # keep doing so until a link field can EXIST on a topic grid. `scoped_fields('customer_data')`
1041
- # resolves to `aios_grid.FIELDS`, which declares no `link` column, and `user_tables.add_field`
1042
- # refuses any key without the `ut_` prefix, so there is nowhere to put one. See `_pivot_route`'s
1043
- # docstring for the trace. That refusal is the ticket's own instruction and it is the honest
1044
- # answer, because the alternative shape (answer from a table nobody named) is the defect above.
1045
- # ⚰ AMENDED BY WAVE 42 AMENDMENT A23 — ONE PAIR IS EXCEPTED, AND ONLY ONE. The paragraph above
1046
- # described `(customer_data, product_data)` too, and that took a SHIPPING feature dark on a wave
1047
- # that ends on the public live domain. `_PIVOT_ROUTES` below is back as a DATED TOMBSTONE holding
1048
- # exactly that one pair, read ONLY after the strict resolution has already refused. Every other
1049
- # unresolvable case still refuses with the field named, which is T05's real win and is intact.
1050
  #
1051
  # ⛔ AND IT IS STILL NOT CHAINING (R12). `path` is TWO databases. `sales_lines` is the EDGE, not a
1052
  # third stop: none of it reaches the client, no filter over it is accepted, and no caller can name
@@ -1060,192 +1044,36 @@ def grid_events_route(body: dict = Body(default=None),
1060
  #: [[date-window-vocabulary]]. This is a RENAME and nothing else. `all` resolves to `(None, None)`.
1061
  PIVOT_WINDOWS = {"all": "all_time", "last12m": "ltm", "ytd": "ytd"}
1062
 
1063
- #: The `via` keys THIS DOOR needs before it can ask a question. C1 makes all six required and
1064
- #: `core.user_tables._clean_via` refuses a bag missing any of them, so a stored bag always has
1065
- #: them; this tuple is the door's own check rather than a second copy of that rule, because a bag
1066
- #: can also arrive from an older write or a hand-edited document. `filter`, `filterConj` and
1067
- #: `window` are the optional three and are NOT read here (the request's own `window` governs).
1068
- #: ⛔ `measure` IS AMONG THE REQUIRED SIX. There is no default: a bag without it is refused, never
1069
- #: quietly answered with revenue, because the measure decides WHICH relationship the edge reports.
1070
- _PIVOT_VIA_REQUIRED = ("topic", "measure", "scope_key", "source_dim", "target_dim", "target_key")
1071
-
1072
- #: ⚠ THE SOURCE IDENTITY IS `pid` AND NOTHING ELSE, WHICH IS WHY `via` HAS NO `source_key`.
1073
- #: `filter_eval.visible_pids` reads `row['pid']`, so there is exactly one answer and a bag key
1074
- #: offering a second one could only ever disagree with the engine. The old route table carried
1075
- #: `source_key` purely to assert `== "pid"` against itself; it died with the table rather than
1076
- #: being migrated onto `via` (C1, A5). ⭐ W41-T19 measured why the obvious alternative is wrong:
1077
- #: `partner_id` is declared `derived` and is on 0 of 3,643 customer rows, while `pid` IS the
1078
- #: `res.partner` id, so `from: "partner_id"` resolves 0 rows with nothing red.
1079
  #:
1080
- #: ⚠ AND THE MEASUREMENT BEHIND `target_dim: product_code` OUTLIVES THE TABLE IT WAS WRITTEN ON, so
1081
- #: the next author does not re-derive it: the SKU CODE is right and `product_id` is the wrong
1082
- #: obvious choice. `product_code` reproduces the product grid's identity exactly, `pid:<odoo id>`
1083
- #: fallback included; `product` (`l.product_id`) splits a re-SKUed pair whose archived half has no
1084
- #: grid row at all. MEASURED on this store over the wholesale scope: grouping by `product_id` gives
1085
- #: 3,360 buckets and by `product_code` gives 3,352 — 8 codes carry two ids each, and it is the
1086
- #: archived id of each pair that no `product_data` row claims (that module keeps archived products
1087
- #: out, by R12). Joining on the id therefore loses 8 real products while looking fine.
1088
-
1089
-
1090
- #: ⚰⚰ TOMBSTONE — WAVE 42, AMENDMENT A23, 2026-08-25. ONE PAIR. NOT A TABLE. DELETE ME IN WAVE 43.
1091
- #:
1092
- #: ⛔ WHY A DEAD CONSTANT IS BACK, AND IT IS NOT A HACK BOLTED ONTO A CLEAN DESIGN. W42-T05
1093
- #: dissolved the compiled `(source, target)` route table so the pivot reads its edge off the `via`
1094
- #: bag on the link field the request NAMES. That work is correct and is not undone here. But the
1095
- #: old table answered THIS pair while ignoring `viaField` entirely, so the wave's headline
1096
- #: customer-to-product pivot shipped and worked; after T05 it 400s, and ⛔ SEEDING A `via` BAG
1097
- #: CANNOT FIX IT: `aios_grid.FIELDS` is 37 entries with ZERO of type `link`,
1098
- #: `scoped_fields('customer_data')` returns `list(aios_grid.FIELDS)` through `_customer_rows`,
1099
- #: `aios_grid.fields_from_workspace` is the CLIENT wire's separate path (notes / `custom_` /
1100
- #: `measure_` only), and `core.user_tables.add_field` refuses any key without the `ut_` prefix.
1101
- #: A LINK FIELD CANNOT EXIST ON A TOPIC GRID AT ALL — no stratum can hold one.
1102
- #:
1103
- #: ⭐ AND THE LANE BASE PREDICTED THIS IN A COMMENT AT THIS SITE (`648f051:routes_grid.py:1032`):
1104
- #: "`viaField` therefore RIDES THE WIRE AND IS ADVISORY for this pair … a door that refused an
1105
- #: unresolvable `viaField` would refuse R10's headline case." So this restores an invariant the
1106
- #: code documented and the ticket instructed away; it does not invent a new one.
1107
- #:
1108
- #: ⚰ THIS IS A TOMBSTONE, WITH AN EXPIRY THAT IS PROVABLE RATHER THAN HOPED FOR. Wave 43's
1109
- #: storage ticket — the stratum that lets a link field exist on a topic grid — DELETES this
1110
- #: constant and the guarded read in `_pivot_route` below. `verify_pivot.py` section 12 holds the
1111
- #: leg that makes the deletion safe: once a real `via` resolves for this pair the fallback is
1112
- #: UNREACHABLE, so wave 43 can PROVE the tombstone is dead instead of assuming it.
1113
  #:
1114
- #: ⛔ `source_key` IS DELIBERATELY NOT CARRIED. The old table's copy only ever asserted `== "pid"`
1115
- #: against itself; `_clean_via` refuses it by name as an unknown key, so carrying it here would
1116
- #: make this bag illegal as a stored `via` and the two shapes would diverge. The six keys below
1117
- #: are exactly `_PIVOT_VIA_REQUIRED`, and the reasoning behind `order_partner`/`product_code`
1118
- #: lives in the block above rather than being restated.
 
 
1119
  _PIVOT_ROUTES = {
1120
  ("customer_data", "product_data"): {
1121
  "topic": "sales_lines",
1122
  "measure": "revenue",
1123
- "scope_key": "customer",
1124
  "source_dim": "order_partner",
 
1125
  "target_dim": "product_code",
1126
  "target_key": "code",
1127
  },
1128
  }
1129
 
1130
 
1131
- def _pivot_route(fields, source, target, via_field):
1132
- """The strict `via` resolution, with A23's ONE tombstoned pair behind it.
1133
-
1134
- ⛔⛔ THE STRICT DOOR IS TRIED FIRST, ALWAYS, AND THAT ORDER IS THE DESIGN. It is what makes
1135
- the fallback UNREACHABLE the moment a real `via` resolves for this pair, by construction
1136
- rather than by assertion — which is what lets wave 43 delete the tombstone and prove nothing
1137
- was still riding on it. A pre-check on the pair would invert that and is forbidden.
1138
-
1139
- ⚰ THE ESCAPE HATCH IS GUARDED TWICE: the strict door must have refused with `no_pivot_route`,
1140
- AND `(source, target)` must be the one key in `_PIVOT_ROUTES`. Every other unresolvable case
1141
- still raises with the field named. See the tombstone's own comment for why it exists and for
1142
- what deletes it.
1143
- """
1144
- try:
1145
- return _pivot_route_via(fields, source, target, via_field)
1146
- except HTTPException as exc:
1147
- # ⛔ NARROW BY CODE, NOT BY TYPE. Only the "there is no edge" refusal may be excepted; a
1148
- # permission or shape failure raised from anywhere under here must still reach the client.
1149
- detail = exc.detail if isinstance(exc.detail, dict) else {}
1150
- if (detail.get("error") or {}).get("code") != "no_pivot_route":
1151
- raise
1152
- tomb = _PIVOT_ROUTES.get((source, target))
1153
- if tomb is None:
1154
- raise
1155
- return dict(tomb)
1156
-
1157
-
1158
- def _pivot_route_via(fields, source, target, via_field):
1159
- """C1's `via` bag off the link field the REQUEST NAMED, or a 400 that names that field.
1160
-
1161
- ⛔⛔ EVERY UNRESOLVABLE CASE REFUSES, AND THAT IS THE WHOLE POINT OF THE FUNCTION. ⚰ Wave 42
1162
- amendment A23 added EXACTLY ONE exception, and it is not in here: `_pivot_route` above catches
1163
- this function's `no_pivot_route` for the single tombstoned pair. Nothing else is excepted, and
1164
- nothing in this function may soften on account of it. Falling
1165
- through with a partial bag lands as `rows = [r for r in tgt_rows if str(r.get(tkey)) in keys]`
1166
- matching nothing, which is a 200 carrying `rows: []` and no `refusal` — the silent lie
1167
- `_pivot_reply`'s own docstring forbids, and it reads as "these customers ordered nothing".
1168
- "There is no way to get there" and "nothing is related" are two different answers and only one
1169
- of them is ever true.
1170
-
1171
- ⚠ `fields` IS THE READER'S SCOPED CONTRACT, NOT THE SCHEMA, and the wording follows from that.
1172
- It arrives through `perm_scope.scoped_fields`, so a field wall can hide a link field that does
1173
- exist. The refusal therefore says this ACCOUNT cannot resolve the field rather than that the
1174
- database has no such field, which would be a claim about the schema made out of a fact about
1175
- the reader. Resolving from the scoped list is still right for a `ut_*` source, whose link
1176
- fields ARE stored on the table document `scoped_fields` reads.
1177
-
1178
- ⛔⛔ AND IT IS STRUCTURALLY EMPTY OF LINK FIELDS FOR A TOPIC SOURCE, WHICH IS MEASURED, NOT
1179
- FEARED. `scoped_fields('customer_data')` is answered by `_customer_rows` below, which returns
1180
- `list(aios_grid.FIELDS)` — the compiled `aios_grid_fields.json` contract, which carries ZERO
1181
- entries of type `link`. Nothing merges the per-user `<key>_table_workspace` stratum into that
1182
- path (`aios_grid.fields_from_workspace` is a different function, reached only by
1183
- `workspace_wire` on the client wire), and `core.user_tables.add_field` refuses a non-`ut_` key
1184
- outright, so no link field is written there either. ⚠ SO THE CUSTOMER-TO-PRODUCT PIVOT REFUSES
1185
- TODAY NO MATTER WHAT IS SEEDED IN A `via` BAG: that pair needs a link field to exist on a topic
1186
- grid at all, which is a stratum question and not this door's. Refusing is still the right
1187
- answer here; a second field-assembly door opened inside this route to manufacture one would be
1188
- the two-doors-onto-one-vocabulary defect this wave has already paid for twice.
1189
- """
1190
- via_field = str(via_field or "").strip()
1191
- if not via_field:
1192
- raise err(400, "no_pivot_route",
1193
- f"this pivot did not name a link field, so there is no edge to answer it with. "
1194
- f"Send 'viaField' naming a link field on '{source}' that points at '{target}'")
1195
-
1196
- match = None
1197
- for field in fields or ():
1198
- if not isinstance(field, dict):
1199
- continue
1200
- if str(field.get("key") or "") == via_field and field.get("type") == "link":
1201
- match = field
1202
- break
1203
- if match is None:
1204
- raise err(400, "no_pivot_route",
1205
- f"this account cannot resolve a link field named '{via_field}' on '{source}', "
1206
- f"so there is no declared edge to '{target}'. Pivot from a link field this "
1207
- f"account can see on that grid")
1208
-
1209
- link = match.get("link") if isinstance(match.get("link"), dict) else {}
1210
- points_at = str(link.get("table") or "")
1211
- if points_at != target:
1212
- raise err(400, "no_pivot_route",
1213
- f"the link field '{via_field}' points at "
1214
- f"'{points_at or 'nothing this door can name'}', not at '{target}'. Refusing "
1215
- f"rather than pivoting through an edge nobody asked for")
1216
-
1217
- via = link.get("via") if isinstance(link.get("via"), dict) else None
1218
- if not via:
1219
- raise err(400, "no_pivot_route",
1220
- f"the link field '{via_field}' joins '{source}' to '{target}' directly and "
1221
- f"carries no 'via' declaration, so this door has no fact table to ask. A pivot "
1222
- f"needs the edge spelled out: topic, measure, and the two dims it joins on")
1223
-
1224
- missing = [k for k in _PIVOT_VIA_REQUIRED if not via.get(k)]
1225
- if missing:
1226
- raise err(400, "no_pivot_route",
1227
- f"the 'via' declaration on link field '{via_field}' is missing "
1228
- f"{', '.join(missing)}, so the edge is not fully described. Refusing rather "
1229
- f"than filling in a default, which would answer a question nobody asked")
1230
- return via
1231
-
1232
-
1233
- #: ARM 2 of the catch below: the `ModelError` sentences that are an AUTHORING fault, matched by a
1234
- #: needle rather than by type because `harness.semantic` raises the bare class for all of them.
1235
- #: ⛔ `unknown metric` IS THE ONE THAT ACTUALLY FIRES ON THIS DOOR. A bad `via.measure` reaches
1236
- #: `semantic._expand_measures` and comes back as a plain `ModelError`, NOT `UnknownColumnError` —
1237
- #: the subclass covers a bad DIM only. `via.measure` is authored by whoever wrote the link field,
1238
- #: so answering it with 503 "the store is unavailable" sends that author looking at the wrong
1239
- #: thing. The rest are here so a bag naming a bad topic, a foreign measure or an over-wide filter
1240
- #: lands the same way. ⚠ Kept at module level so the set is greppable and can be extended without
1241
- #: reading the route.
1242
- _PIVOT_AUTHORING = (
1243
- "unknown metric", "unknown topic", "belong to another topic", "is company-level",
1244
- "at least one measure required", "filter tree", "filter rule", "must reference",
1245
- "grain must be", "is store-only", "unknown dim", "has no name column",
1246
- )
1247
-
1248
-
1249
  def _pivot_today():
1250
  """The tenant's today, ISO. One clock, so the window and any date leaf agree."""
1251
  import core.periods as periods
@@ -1378,43 +1206,14 @@ def grid_pivot(body: dict = Body(default=None),
1378
  f"window must be one of {', '.join(sorted(PIVOT_WINDOWS))}. Refusing to guess "
1379
  f"which period was meant, because guessing 'all time' would widen the answer "
1380
  f"under a count nobody would doubt")
1381
- # ── C10 / R12 — THE WALL THAT WAS BUILT FOR THIS ROUTE, RUN FIRST (W42-T04) ──────────────
1382
- #
1383
- # ⛔ AHEAD OF EVERYTHING, AND THE ORDER IS THE POINT — MORE SO NOW THAT THE EDGE COMES OFF A
1384
- # FIELD. `_pivot_route` cannot run first even in principle: it reads the SOURCE's scoped field
1385
- # list, which means fetching a database, and fetching before the verdict is the wrong shape.
1386
- # And the two predicates `_pivot_side` has never enforced — `is_linkable_target` on BOTH
1387
- # endpoints and R12's `PIVOT_PATH_LEN` — live only here, so a request naming `users` or
1388
- # `cohort` gets a permission answer with a reason on the wire (C10) rather than a field lookup.
1389
- # W42-T04 wrote this note against a route TABLE that could have shadowed the wall; T05 removed
1390
- # the table and the ordering matters for the same reason under `via`.
1391
- #
1392
- # ⚠ `path` IS NOT READ FROM THE BODY. C1 enumerates the wire keys and `pivot_scope` defaults
1393
- # the walk to `[source, target]`; inventing an undeclared request key so the `chained` leg
1394
- # could be reached from here would widen the contract to exercise a guard. The leg is in
1395
- # force and unreachable from this door by construction while exactly one 2-hop pair is
1396
- # declared; `via` is what will start handing it a longer walk.
1397
- scope = perm_scope.pivot_scope(session.user, source, target, st=session.runtime)
1398
- if not scope.permitted:
1399
- # ⛔ A 200 WITH A REASON, NOT A STATUS. `_pivot_reply` stays the one envelope: it already
1400
- # carries `refusal` and `limits`, and `PivotScope.envelope()` would only re-emit the same
1401
- # `path` this route already writes while raising a key-precedence question nobody needs.
1402
- # `limits` is standing rule 1's second sentence carried across the join; it is empty on
1403
- # this pair because neither key is a `ut_` database, and it stops being empty for free the
1404
- # day one is pivotable.
1405
- return _pivot_reply(source, target, [], [], 0, 0,
1406
- refusal=scope.refusal(),
1407
- limits=scope.limits(st=session.runtime))
1408
-
1409
- # ── THE ROW AND FIELD WALLS, ON BOTH SIDES OF THE JOIN (R12) ─────────────────────────────
1410
- # ⚠ THE VERDICT IS ASKED ONCE, ABOVE; THIS IS THE FETCH. `pivot_scope` decides WHETHER, and
1411
- # `_pivot_side` is what actually gets each side's scoped fields and rows through C1's one door
1412
- # (`scoped_fields` / `scoped_table`) plus the tenant/account module gate `session.require`.
1413
- # ⛔ W42-T05 DECLINED THE OFFERED COLLAPSE INTO `scope.source_grid`/`scope.target_grid`, on
1414
- # purpose: those two NARROW a `(fields, rows)` pair handed to them, they do not fetch one, so
1415
- # the collapse would need an UNWALLED read here to feed them and would drop `session.require`
1416
- # and the refusal shape `_pivot_side` owns. Two callers of one wall is not the redundancy the
1417
- # note warned about; an unwalled fetch to satisfy a shape would be the actual defect.
1418
  src, refusal = _pivot_side(session, source)
1419
  if refusal is not None:
1420
  return _pivot_reply(source, target, [], [], 0, 0, refusal=refusal)
@@ -1425,12 +1224,6 @@ def grid_pivot(body: dict = Body(default=None),
1425
  src_fields, src_rows = src
1426
  tgt_fields, tgt_rows = tgt
1427
 
1428
- # ⭐⭐ W42-T05 — THE EDGE, READ OFF THE LINK FIELD THE REQUEST NAMED. Deliberately AFTER both
1429
- # sides are walled, so a reader who may not open either one gets the permission answer C10
1430
- # specifies rather than a lecture about link fields; and deliberately against `src_fields`,
1431
- # which is the reader's scoped contract and the same list the client chose `viaField` from.
1432
- route = _pivot_route(src_fields, source, target, body.get("viaField"))
1433
-
1434
  today = _pivot_today()
1435
  columns = filter_eval._columns_map(src_fields)
1436
  unanswerable = _pivot_unanswerable(filters, columns)
@@ -1455,9 +1248,10 @@ def grid_pivot(body: dict = Body(default=None),
1455
  for cid, c in cohort_mod.scoped(route["scope_key"]).visible(
1456
  session.uname, pool_pids).items()}
1457
 
1458
- # ⛔ NO `source_key` CHECK ANY MORE, AND ITS ABSENCE IS THE POINT (C1, A5). It only ever
1459
- # compared the old table against itself; `via` declares no such key, so there is nothing left
1460
- # that could disagree with `visible_pids`' one reading of `row['pid']`.
 
1461
  member = sorted({p for p in filter_eval.visible_pids(
1462
  {"conj": filter_conj, "nodes": filters}, src_rows, src_fields,
1463
  ctx=filter_eval.EvalCtx(cohort_sets=cohort_sets, today=today))
@@ -1479,45 +1273,8 @@ def grid_pivot(body: dict = Body(default=None),
1479
  filters={route["source_dim"]: member},
1480
  date_from=date_from, date_to=date_to, team_id=team_id, today=today,
1481
  limit=semantic.MAX_GROUPS)
1482
- # ⛔⛔ THREE ARMS, AND THE CATCH STAYS STRUCTURALLY A CATCH-ALL (W42-T05, amendment A8b). Until
1483
- # this ticket every `ModelError` off this one call became 503 "pivot_unavailable", which told
1484
- # an author whose `via.measure` was a typo that the STORE was down. Narrowing the catch would
1485
- # have been the worse fix: `except semantic.ModelError` still wraps everything, and a future
1486
- # raise site added inside `store_query` lands in arm 3 by DEFAULT rather than escaping as an
1487
- # uncaught 500. Nothing here re-words `harness.semantic`'s sentences; the arms only choose the
1488
- # status that makes the sentence actionable.
1489
- except semantic.UnknownColumnError as exc:
1490
- # ARM 1 — A COLUMN THIS TOPIC DOES NOT HAVE. 400, and the body NAMES IT: a 400 carrying a
1491
- # generic sentence is the same authoring dead end as the 503 was, one status politer.
1492
- # `.column` and `.columns` are attributes of the class, not text to be parsed back out.
1493
- # ⚠ THE REST OF `.columns` IS EMITTED ONLY WHEN THERE IS A REST. It defaults to
1494
- # `[column]`, so an unconditional parenthetical would read "is 'product_kode' (named:
1495
- # product_kode)" on the common single-column case, which is words that say nothing.
1496
- others = [c for c in (exc.columns or ()) if c != exc.column]
1497
- also = f" It also names {', '.join(others)}." if others else ""
1498
- raise err(400, "pivot_unknown_column",
1499
- f"{str(exc).rstrip('. ')}. The column this pivot could not resolve is "
1500
- f"'{exc.column}'.{also} Fix the link field's 'via' declaration, or pivot "
1501
- f"through a link field whose dims this topic actually carries")
1502
  except semantic.ModelError as exc:
1503
- sentence = str(exc)
1504
- low = sentence.lower()
1505
- if any(needle in low for needle in _PIVOT_AUTHORING):
1506
- # ARM 2 — AUTHORING, BUT NOT A COLUMN. An unknown metric (the one that fires on a bad
1507
- # `via.measure`, because `_expand_measures` raises the BARE class), a foreign measure,
1508
- # an unknown or company-level topic, a filter tree over the width, depth or size
1509
- # limits, a sort that names nothing selected, and T06's invalid-operator refusal.
1510
- # Every one of them is a fault in what was ASKED, so the asker is who can fix it.
1511
- raise err(400, "pivot_bad_edge",
1512
- f"{sentence.rstrip('. ')}. This pivot's edge comes from the link "
1513
- f"field's 'via' declaration, so that declaration is what needs correcting")
1514
- # ARM 3 — A GENUINE OUTAGE, 503, UNCHANGED, AND THE DEFAULT. The store is locked, cold or
1515
- # missing, or the topic has no store binding. ⚠ `harness.semantic`'s data-cache sentence
1516
- # says the cache is warming up after a restart; that is TRUE about the store and often
1517
- # FALSE about the cause, which is usually another process holding it. It is not reworded
1518
- # here: that file belongs to W42-T06, and a second copy of the sentence is how one fact
1519
- # gets two definitions.
1520
- raise err(503, "pivot_unavailable", sentence)
1521
 
1522
  # ⛔ `truncated` IS READ, NOT ASSUMED FALSE. `store_query` returns groups plus a flag, and a
1523
  # grouped query's groups ARE the answer, so a dropped one is missing data with nothing to
@@ -1617,200 +1374,3 @@ def _register_topic_rows():
1617
  _PRODUCT_MODULE = "product_data"
1618
 
1619
  _C1_ROW_SOURCES = _register_topic_rows()
1620
-
1621
-
1622
- # -----------------------------------------------------------------------------------------------
1623
- # W42-T07 / contract C2 + amendment A5 - THE HOP OPERAND OFFER.
1624
- #
1625
- # `GET /grid/hop-topics` is the picker behind C1's `via` bag: the filter builder needs a topic's
1626
- # DIMS as operands, the Measure picker needs that topic's MEASURES, and the window select needs
1627
- # the window vocabulary the SAVE DOOR accepts. All three ride one payload because they are one
1628
- # feature - A5's whole point is that dims alone leave the Measure picker permanently empty,
1629
- # `_clean_via` refuses a bag with no `measure`, and no user can ever complete a hop while every
1630
- # key-set parity gate stays green.
1631
- #
1632
- # It lives here and not in `routes_tables`, deliberately: this is pivot machinery.
1633
- # `routes_tables`' `brief=1` branch answers a different question (which DATABASES a link may
1634
- # target), and `_rollup_source_offer` answers a third (which (topic, measure, dim) triples a
1635
- # ROLLUP column may bind). This one is MIRRORED from that offer's logic and calls none of it.
1636
- #
1637
- # MODEL FILES ONLY - NO STORE READ, AND THAT IS A DECISION, NOT AN OMISSION.
1638
- # `_rollup_source_offer` additionally gates each topic on `sem._source_ready(table)`, and this
1639
- # endpoint deliberately does NOT. `core.user_tables._topic_dims` - the VALIDATOR half of this
1640
- # very feature - already ruled on the same question in its own docstring: "THE MODEL FILES,
1641
- # NEVER THE STORE ... a validator that needed the store to say yes would refuse every legal link
1642
- # the moment the file was locked by a `validate.py` run or cold after a restart." An OFFER that
1643
- # failed closed on a locked store is strictly worse than a validator that does: the validator
1644
- # refuses one link out loud, the offer empties the picker for everybody with nothing on screen to
1645
- # explain it - A5's exact catastrophe, reached by a different road. It would also make the C2
1646
- # parity gate flip red or green depending on who holds the duckdb lock.
1647
- # THE COST IS STATED RATHER THAN HIDDEN: a topic with dims and measures but no live table
1648
- # (`stock_moves` is the standing example) IS offered here and refuses at hop time. That is the
1649
- # loud failure `_pivot_route_via` is built around, not the silent blank-column failure W37-T13
1650
- # found on the rollup door. A future ticket may add readiness as a THIRD omission cause; it must
1651
- # then also decide what an INDETERMINATE store answer means for the cache.
1652
- #
1653
- # Because the offer is a pure function of the model files, the cache is unconditionally safe -
1654
- # none of `_ROLLUP_CACHE`'s "never memoise an indeterminate answer" reasoning applies here.
1655
- _HOP_CACHE = {}
1656
-
1657
- #: C2's `Field.source`. Every operand this endpoint offers comes from the TOPIC, never from the
1658
- #: grid's own field contract, and the client needs to tell them apart when it merges the two
1659
- #: lists into one filter builder.
1660
- _HOP_FIELD_SOURCE = "topic"
1661
-
1662
- #: The `FieldType` names this offer may emit - the intersection of `harness.semantic`'s column
1663
- #: types and `customer-grid/types.ts::FieldType`. A type outside this set would reach a renderer
1664
- #: with no branch for it.
1665
- _HOP_FIELD_TYPES = ("text", "int", "date", "currency", "pct")
1666
-
1667
-
1668
- def _hop_dim_type(cols, dim_key):
1669
- """`Field.type` for one dim, READ OUT of `harness.semantic.store_columns`, never mapped here.
1670
-
1671
- C2 asks for a type "from the dim's store column" and this is literally that: `store_columns`
1672
- publishes `{sql, type, aggregate}` per column, and the dim's entry is its NAME column - the
1673
- text a user types "contains" against - so every dim resolves to `text` today, while the
1674
- `<dim>_id` companion column it also publishes is `int`. That is DERIVED, not a mapping
1675
- somebody wrote down: give a future dim a numeric name column and the type follows with no
1676
- edit here.
1677
-
1678
- `store_columns` reads `_model()` (the cached `platform/model/topics/*.yml`) and opens no
1679
- DuckDB connection, so asking it costs nothing and cannot make this endpoint store-dependent.
1680
-
1681
- The `text` fallback is reachable only if `store_columns` and `store.dims` ever disagree about
1682
- which keys exist, which they cannot today (one iterates the other). It is a floor, not a
1683
- guess: it keeps an unknown operand FILTERABLE as text rather than emitting a type no renderer
1684
- has a branch for.
1685
- """
1686
- ftype = ((cols or {}).get(dim_key) or {}).get("type")
1687
- return ftype if ftype in _HOP_FIELD_TYPES else "text"
1688
-
1689
-
1690
- def _hop_topic_offer():
1691
- """`{topics, windows, omissions}` - every topic a `via` hop can actually be completed through.
1692
-
1693
- A DIMLESS TOPIC IS OMITTED, NOT OFFERED EMPTY (amendment A12). The ticket's own done-when
1694
- asked for it to be "offered with an empty operand list rather than omitted silently", and
1695
- that is the LETTER of a rule whose operative word is *silently*: `user_tables._clean_via`
1696
- refuses a `via` whose topic has no dims (`if not dims: return None`), because a hop REQUIRES
1697
- `source_dim` and `target_dim` to BE dims of that topic. A dimless topic can therefore never
1698
- be a legal hop, and offering it with an empty operand list ships a dead option that spends
1699
- the user's time and blanks the column. So it is omitted AND the omission is REPORTED, with a
1700
- machine-readable cause, under `omissions` - the client can say the topic cannot be hopped
1701
- through, and nothing offered is unanswerable.
1702
-
1703
- A TOPIC WITH NO USABLE MEASURE IS OMITTED FOR ITS OWN, DIFFERENT REASON, and the two causes
1704
- are reported separately because seven of the eight topics omitted today are omitted for the
1705
- SECOND one. Reporting them all as "declares no dims" would be false for seven of eight, and a
1706
- client renders a cause verbatim to a user. `odoo_agents` alone carries both codes.
1707
-
1708
- THE MEASURE EXCLUSION IS A PREDICATE, NEVER A NAME LIST. `store_query` refuses a
1709
- `ratio`/`derived` metric the moment a `group_by` is present (cross-topic measures are
1710
- scalar-only), and a hop ALWAYS has a `group_by` - its `target_dim`. Enumerating the excluded
1711
- metrics by NAME instead would be [[two-enumerations-from-different-anchors]]: the names most
1712
- often quoted for this rule are `aov`/`margin_pct`/`returns_pct`, and the live predicate
1713
- catches seven, so a name list would offer four hops that can only ever error, plus every
1714
- ratio metric added after it was written.
1715
-
1716
- ONLY THE DECLARED DIMS ARE OFFERED. `store_columns` also publishes a `<dim>_id` companion and
1717
- a `date` column, and `_clean_tree` would happily validate a filter on either - but C2's
1718
- operand list is the topic's DIMS, and `_clean_via` matches `source_dim`/`target_dim` against
1719
- exactly `store.dims`. Offering `<dim>_id` here would put two names for one operand in one
1720
- picker. A future ticket may add them under their own payload key.
1721
- """
1722
- if _HOP_CACHE.get("offer"):
1723
- return _HOP_CACHE["offer"]
1724
- from harness import semantic as sem
1725
- from harness import windows as W
1726
- import core.user_tables as user_tables
1727
-
1728
- topics, metrics = sem.topics(), sem.metrics()
1729
-
1730
- by_topic = {}
1731
- for key, m in metrics.items():
1732
- # See the docstring: the predicate IS the enumeration. A ratio/derived metric cannot
1733
- # survive the `group_by` a hop always carries.
1734
- if m.get("agg") in ("ratio", "derived"):
1735
- continue
1736
- by_topic.setdefault(m.get("topic"), []).append(
1737
- {"key": key, "label": m.get("label") or key,
1738
- "format": m.get("format") or "usd",
1739
- "description": m.get("description") or ""})
1740
-
1741
- out, omissions = [], []
1742
- for tkey, t in sorted(topics.items()):
1743
- store = t.get("store") or {}
1744
- dims = store.get("dims") or {}
1745
- measures = by_topic.get(tkey) or []
1746
- label = t.get("label") or tkey
1747
- if not dims or not measures:
1748
- # Machine-readable codes, and BOTH when both apply. No prose sentence lives in this
1749
- # payload: the wording belongs to the client, which is the surface that knows what
1750
- # the user was trying to do.
1751
- reasons = []
1752
- if not dims:
1753
- reasons.append("no_dims")
1754
- if not measures:
1755
- reasons.append("no_measures")
1756
- omissions.append({"topic": tkey, "label": label, "reasons": reasons})
1757
- continue
1758
- try:
1759
- cols = sem.store_columns(tkey, include_measures=False)
1760
- except Exception: # noqa: BLE001
1761
- # A topic can declare `store.dims` only inside a `store` block, so this is
1762
- # unreachable today; it is here so a malformed model file drops ONE topic with a
1763
- # stated cause instead of 500-ing the whole picker.
1764
- omissions.append({"topic": tkey, "label": label,
1765
- "reasons": ["no_store_columns"]})
1766
- continue
1767
- out.append({
1768
- "key": tkey,
1769
- "label": label,
1770
- "grain": t.get("grain") or "",
1771
- # C2's `Field[]`. SUPERSET, DECLARED: C2 enumerates `key`/`label`/`type`/`source`,
1772
- # and `keyedBy` rides along because C1's `target_key` is the TARGET GRID's join
1773
- # column and the user cannot pick it without knowing whether this dim keys by an
1774
- # Odoo id or by its own value - the same fact `RollupSourceTopic.dims` carries.
1775
- "dims": [{"key": dkey,
1776
- "label": d.get("label") or dkey,
1777
- "type": _hop_dim_type(cols, dkey),
1778
- "source": _HOP_FIELD_SOURCE,
1779
- "keyedBy": "id" if d.get("name_col") else "value"}
1780
- for dkey, d in dims.items()],
1781
- "measures": sorted(measures, key=lambda m: m["label"].lower()),
1782
- })
1783
-
1784
- # `core.user_tables.LINK_VIA_WINDOWS` IS THE AUTHORITY, not `harness.windows`, because it is
1785
- # the set `_clean_via` accepts (`window not in LINK_VIA_WINDOWS` refuses the field). It
1786
- # aliases `ROLLUP_SOURCE_WINDOWS` and deliberately omits the parameterised kinds
1787
- # (`last_n_days`, `custom`), which have nowhere in the `via` bag to carry their `n`. Offering
1788
- # a kind the save door refuses would let the editor build a field that cannot be stored.
1789
- # The all-time key is `all_time`; `all` is not a window and is refused.
1790
- windows = [{"key": k, "label": W.WINDOW_LABELS.get(k, k).format(n="N")}
1791
- for k in user_tables.LINK_VIA_WINDOWS]
1792
-
1793
- offer = {"topics": out, "windows": windows, "omissions": omissions}
1794
- _HOP_CACHE["offer"] = offer
1795
- return offer
1796
-
1797
-
1798
- @router.get("/grid/hop-topics")
1799
- def grid_hop_topics(session: Session = Depends(require_session)):
1800
- """C2's operand offer for the hop editor: topics, their dims and measures, and the windows.
1801
-
1802
- TENANT-SCOPED, for the reason `rollup_sources` records: `sem.topics()` reads the GLOBAL model
1803
- files, so a tenant with no Odoo mirror behind it would be offered a hop it can never resolve.
1804
- `odoo_relational.is_royal` is the one authority on that and is reused, not re-decided.
1805
-
1806
- `omissions` IS PRESENT ON EVERY RESPONSE, including this early return, so the payload shape is
1807
- unconditional and no reader needs a branch for its absence.
1808
-
1809
- Declared as a LITERAL path under `/grid/`, and there is no `GET /grid/{something}` route in
1810
- this file for it to be swallowed by. If one is ever added it must go BELOW this line - FastAPI
1811
- matches in declaration order.
1812
- """
1813
- import odoo_relational
1814
- if not odoo_relational.is_royal(session.tenant):
1815
- return {"topics": [], "windows": [], "omissions": []}
1816
- return _hop_topic_offer()
 
24
  import datetime as dt
25
  import time
26
 
27
+ from fastapi import APIRouter, Body, Depends
28
 
29
  from deps import Session, err, module_gate, perms, require_session
30
 
 
1029
  # an UNCAPPED `IN (?,…)` over them. Confirmed orders only, the wholesale teams and the GIFTWARE
1030
  # DEALS exclusion all come from that topic's `scope_sql`, so the ticket's "confirmed orders only"
1031
  # is enforced by the ONE definition of it rather than by a second copy written here.
1032
+ # ⚠ `viaField` therefore RIDES THE WIRE AND IS ADVISORY for this pair (C10, and lane D types
1033
+ # against it). A door that refused an unresolvable `viaField` would refuse R10's headline case.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1034
  #
1035
  # ⛔ AND IT IS STILL NOT CHAINING (R12). `path` is TWO databases. `sales_lines` is the EDGE, not a
1036
  # third stop: none of it reaches the client, no filter over it is accepted, and no caller can name
 
1044
  #: [[date-window-vocabulary]]. This is a RENAME and nothing else. `all` resolves to `(None, None)`.
1045
  PIVOT_WINDOWS = {"all": "all_time", "last12m": "ltm", "ytd": "ytd"}
1046
 
1047
+ #: The DECLARED pivot routes: `(source, target) -> the edge that answers it`. A pair with no entry
1048
+ #: is a 400, never an empty grid — "there is no way to get there" and "nothing is related" are two
1049
+ #: different answers and only one of them is true.
 
 
 
 
 
 
 
 
 
 
 
 
 
1050
  #:
1051
+ #: ⚠ `source_key` IS ASSERTED, NOT DECORATION. `filter_eval.visible_pids` reads `row['pid']` and
1052
+ #: nothing else, so a future route whose source identity is NOT `pid` would silently pivot on the
1053
+ #: wrong column. The route refuses instead. ⭐ For `customer_data` this is exactly right and W41-T19
1054
+ #: measured it: `partner_id` is declared `derived` and is on 0 of 3,643 rows, while `pid` IS the
1055
+ #: `res.partner` id. `from: "partner_id"` resolves 0 rows with nothing red.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1056
  #:
1057
+ #: ⚠ `target_dim` IS THE SKU CODE, NOT `product_id`, AND THE OBVIOUS CHOICE IS THE WRONG ONE.
1058
+ #: `product_code` is written to reproduce the product grid's identity exactly, `pid:<odoo id>`
1059
+ #: fallback included; `product` (`l.product_id`) splits a re-SKUed pair whose archived half has no
1060
+ #: grid row at all. MEASURED on this store: over the wholesale scope, grouping by `product_id`
1061
+ #: gives 3,360 buckets and by `product_code` gives 3,352 — 8 codes carry two ids each, and it is
1062
+ #: the archived id of each pair that no `product_data` row claims (that module keeps archived
1063
+ #: products out, by R12). Joining on the id therefore loses 8 real products while looking fine.
1064
  _PIVOT_ROUTES = {
1065
  ("customer_data", "product_data"): {
1066
  "topic": "sales_lines",
1067
  "measure": "revenue",
1068
+ "scope_key": "customer", # the cohort bucket the SOURCE tree's cohort leaves name
1069
  "source_dim": "order_partner",
1070
+ "source_key": "pid",
1071
  "target_dim": "product_code",
1072
  "target_key": "code",
1073
  },
1074
  }
1075
 
1076
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1077
  def _pivot_today():
1078
  """The tenant's today, ISO. One clock, so the window and any date leaf agree."""
1079
  import core.periods as periods
 
1206
  f"window must be one of {', '.join(sorted(PIVOT_WINDOWS))}. Refusing to guess "
1207
  f"which period was meant, because guessing 'all time' would widen the answer "
1208
  f"under a count nobody would doubt")
1209
+ route = _PIVOT_ROUTES.get((source, target))
1210
+ if route is None:
1211
+ raise err(400, "no_pivot_route",
1212
+ f"there is no declared way to get from '{source}' to '{target}'. "
1213
+ f"Declared: " +
1214
+ "; ".join(f"{a} to {b}" for a, b in sorted(_PIVOT_ROUTES)))
1215
+
1216
+ # ── THE WALL, ON BOTH SIDES OF THE JOIN (R12) ────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1217
  src, refusal = _pivot_side(session, source)
1218
  if refusal is not None:
1219
  return _pivot_reply(source, target, [], [], 0, 0, refusal=refusal)
 
1224
  src_fields, src_rows = src
1225
  tgt_fields, tgt_rows = tgt
1226
 
 
 
 
 
 
 
1227
  today = _pivot_today()
1228
  columns = filter_eval._columns_map(src_fields)
1229
  unanswerable = _pivot_unanswerable(filters, columns)
 
1248
  for cid, c in cohort_mod.scoped(route["scope_key"]).visible(
1249
  session.uname, pool_pids).items()}
1250
 
1251
+ if route["source_key"] != "pid":
1252
+ raise err(500, "pivot_source_key",
1253
+ f"this pivot names '{route['source_key']}' as the source identity and the row "
1254
+ f"engine reads 'pid'. Refusing rather than pivoting on the wrong column")
1255
  member = sorted({p for p in filter_eval.visible_pids(
1256
  {"conj": filter_conj, "nodes": filters}, src_rows, src_fields,
1257
  ctx=filter_eval.EvalCtx(cohort_sets=cohort_sets, today=today))
 
1273
  filters={route["source_dim"]: member},
1274
  date_from=date_from, date_to=date_to, team_id=team_id, today=today,
1275
  limit=semantic.MAX_GROUPS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1276
  except semantic.ModelError as exc:
1277
+ raise err(503, "pivot_unavailable", str(exc))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1278
 
1279
  # ⛔ `truncated` IS READ, NOT ASSUMED FALSE. `store_query` returns groups plus a flag, and a
1280
  # grouped query's groups ARE the answer, so a dropped one is missing data with nothing to
 
1374
  _PRODUCT_MODULE = "product_data"
1375
 
1376
  _C1_ROW_SOURCES = _register_topic_rows()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
api/routes_odoo_tables.py CHANGED
@@ -831,24 +831,6 @@ def _json_arg(raw, what):
831
  return val
832
 
833
 
834
- def _clean_include_pids(raw):
835
- """Bounded existing Link choices, or a named bad-argument refusal.
836
-
837
- A picker condition narrows what a person may add. It never rewrites existing links, so a
838
- read-through window carries those ids as an explicit exception. The normal table and row wall
839
- remains outside that exception in `odoo_table_rows` below.
840
- """
841
- if raw is None:
842
- return []
843
- if not isinstance(raw, list):
844
- raise ValueError("includePids must be a JSON list of record ids")
845
- if len(raw) > 500:
846
- raise ValueError("includePids may name at most 500 existing linked records")
847
- if any(type(pid) is not int or pid <= 0 for pid in raw):
848
- raise ValueError("includePids must contain positive integer record ids")
849
- return sorted(set(raw))
850
-
851
-
852
  @router.get("/odoo-tables/{table_key}/rows")
853
  def odoo_table_rows(table_key: str,
854
  offset: int = Query(default=0, ge=0),
@@ -857,7 +839,6 @@ def odoo_table_rows(table_key: str,
857
  filterConj: str = Query(default="and"),
858
  sorts: str = Query(default=None),
859
  search: str = Query(default=None),
860
- includePids: str = Query(default=None),
861
  session: Session = Depends(require_session)):
862
  """ONE WINDOW over a connected grid, read straight from the mirror (contract C2).
863
 
@@ -1004,10 +985,6 @@ def odoo_table_rows(table_key: str,
1004
  base_where = (f'({spec["where"]}) AND {wall_sql}'
1005
  if (spec["where"] and wall_sql) else (wall_sql or spec["where"]))
1006
  limits, tree = [], _json_arg(filters, "filters")
1007
- try:
1008
- include_pids = _clean_include_pids(_json_arg(includePids, "includePids"))
1009
- except ValueError as e:
1010
- raise err(400, "bad_argument", str(e))
1011
  sort_spec = _json_arg(sorts, "sorts") or []
1012
 
1013
  # R6's SECOND SENTENCE, ON THE WALL ITSELF. The precision note further down covers the
@@ -1069,7 +1046,7 @@ def odoo_table_rows(table_key: str,
1069
  "recommendation": "compare against a whole number, or use a range that does not sit "
1070
  "on a fractional boundary"})
1071
 
1072
- predicate_sql, predicate_params = None, []
1073
  try:
1074
  pred = _fs().compile_filter_tree(
1075
  tree, conj=(filterConj if filterConj in ("and", "or") else "and"), columns=cols,
@@ -1083,25 +1060,13 @@ def odoo_table_rows(table_key: str,
1083
  raise err(400, "filter_unsupported",
1084
  "a condition on an aggregate column belongs in HAVING, and that path is "
1085
  "deliberately not built for windowed grids")
1086
- predicate_sql = pred.sql
1087
- predicate_params.extend(pred.params)
1088
  if str(search or "").strip():
1089
  got = _fs().compile_search(search.strip(), cols)
1090
  if got is not None:
1091
- predicate_sql = (f"({predicate_sql}) AND {got.sql}"
1092
- if predicate_sql else got.sql)
1093
- predicate_params.extend(got.params)
1094
-
1095
- # Existing choices survive a new picker condition, but the table's permanent wall stays
1096
- # outside this OR. A caller cannot use an old link id to reveal a record the database wall
1097
- # would otherwise deny.
1098
- if include_pids and predicate_sql:
1099
- slots = ", ".join("?" for _ in include_pids)
1100
- predicate_sql = f"(({predicate_sql}) OR ({spec['id']} IN ({slots})))"
1101
- predicate_params.extend(include_pids)
1102
- where = (f"({base_where}) AND ({predicate_sql})" if base_where and predicate_sql
1103
- else (predicate_sql or base_where))
1104
- params = [*wall_params, *predicate_params]
1105
 
1106
  # ── the order, made TOTAL ─────────────────────────────────────────────────────────────────
1107
  # ⛔ `tiebreak_sql` is not optional here: without a total order, LIMIT/OFFSET may return one
 
831
  return val
832
 
833
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
834
  @router.get("/odoo-tables/{table_key}/rows")
835
  def odoo_table_rows(table_key: str,
836
  offset: int = Query(default=0, ge=0),
 
839
  filterConj: str = Query(default="and"),
840
  sorts: str = Query(default=None),
841
  search: str = Query(default=None),
 
842
  session: Session = Depends(require_session)):
843
  """ONE WINDOW over a connected grid, read straight from the mirror (contract C2).
844
 
 
985
  base_where = (f'({spec["where"]}) AND {wall_sql}'
986
  if (spec["where"] and wall_sql) else (wall_sql or spec["where"]))
987
  limits, tree = [], _json_arg(filters, "filters")
 
 
 
 
988
  sort_spec = _json_arg(sorts, "sorts") or []
989
 
990
  # R6's SECOND SENTENCE, ON THE WALL ITSELF. The precision note further down covers the
 
1046
  "recommendation": "compare against a whole number, or use a range that does not sit "
1047
  "on a fractional boundary"})
1048
 
1049
+ where, params = base_where, list(wall_params)
1050
  try:
1051
  pred = _fs().compile_filter_tree(
1052
  tree, conj=(filterConj if filterConj in ("and", "or") else "and"), columns=cols,
 
1060
  raise err(400, "filter_unsupported",
1061
  "a condition on an aggregate column belongs in HAVING, and that path is "
1062
  "deliberately not built for windowed grids")
1063
+ where = f"({where}) AND {pred.sql}" if where else pred.sql
1064
+ params.extend(pred.params)
1065
  if str(search or "").strip():
1066
  got = _fs().compile_search(search.strip(), cols)
1067
  if got is not None:
1068
+ where = f"({where}) AND {got.sql}" if where else got.sql
1069
+ params.extend(got.params)
 
 
 
 
 
 
 
 
 
 
 
 
1070
 
1071
  # ── the order, made TOTAL ─────────────────────────────────────────────────────────────────
1072
  # ⛔ `tiebreak_sql` is not optional here: without a total order, LIMIT/OFFSET may return one
api/routes_shares.py CHANGED
@@ -202,6 +202,10 @@ def _owns_object(session, kind, oid):
202
  where a caller is about to be stamped OWNER of something nobody owns — so the resolution runs
203
  exactly there, and the common path (a record exists, `may_administer` decides) is untouched.
204
  """
 
 
 
 
205
  if session.admin:
206
  return True
207
  if kind == "field":
@@ -411,422 +415,43 @@ def _unremovable(held_rows, entries, uname):
411
  stuck.add(user)
412
  return stuck
413
 
414
- # ── ⭐⭐ WAVE 42 · T25 — SHARING A VIEW SHARES THE FIELDS IT NAMES ──────────────────────────────
415
- #
416
- # A saved view is a SELECTION expressed in columns: an order, a visible set, a group, a colour,
417
- # a sort and a filter tree, every one of which names a field key. Granting the view alone hands
418
- # the receiver a rail row whose columns resolve to nothing they may read, so the feature that
419
- # looked shipped puts an empty grid on their screen. This block closes that, and it refuses
420
- # LOUDLY in the three places where a grant would otherwise be a lie.
421
- #
422
- # ⛔⛔ TRAP 1 — A FIELD GRANT IS TOPIC-WIDE, NOT VIEW-SCOPED. It is keyed
423
- # `shares.field_oid(topic, key)`, so it hands the receiver that column on EVERY view of that
424
- # database, for as long as the grant stands. That is the existing grant primitive and this
425
- # ticket does not narrow it; what it does is refuse to let the response PRETEND otherwise, which
426
- # is why `sharedFieldScope` rides back beside the list.
427
- #
428
- # ⛔⛔ TRAP 2 — THE SHARER CANNOT GRANT A COLUMN THEY DO NOT OWN. `field` is absent from
429
- # `shares.RESHARE_KINDS` and `_owns_object`'s field branch demands `createdBy == session.uname`,
430
- # so a view built over a colleague's column simply cannot carry that column with it. Silently
431
- # skipping it ships an empty column; silently granting it is a permission hole. It is REFUSED
432
- # BY NAME, inside the 200 response, with the sentence that says who to ask.
433
- #
434
- # ⛔⛔ TRAP 3 — A GRANT CANNOT UN-HIDE AN ADMIN-WALLED COLUMN. `perm_scope.hidden_keys` UNIONS
435
- # the administrator's `hiddenFields` with the field-grant source, so granting a walled column
436
- # answers 200, writes the record, and the receiver still sees nothing: granted with no effect,
437
- # which is the failure this ticket exists to end. Detected BEFORE the grant, refused by name,
438
- # and the receiver it is walled from is named too.
439
- #
440
- # ⚠ THE WALL IS READ FROM THE ADMIN SOURCE DIRECTLY AND NEVER THROUGH `hidden_keys`, AND THAT IS
441
- # NOT AN OPTIMISATION. `hidden_keys` unions `field_grant_hidden` — "hidden because you were not
442
- # granted it" — which is true of every column this route is ABOUT to grant. Asking it here would
443
- # refuse the whole set on the grounds that the grant has not happened yet.
444
-
445
 
446
- def _view_configs(view):
447
- """The dicts a saved view keeps its column state in.
 
448
 
449
- `SavedView.config` is the contract (`types.ts::ViewConfig`) and is where every key below
450
- actually lives. The record ITSELF is read as well because a legacy row that stored the same
451
- members flat costs one dict lookup to cover and would otherwise hand back an empty key set,
452
- which is the shape that grants nothing and reports nothing wrong.
453
  """
454
- out = []
455
- if not isinstance(view, dict):
456
- return out
457
- cfg = view.get("config")
458
- if isinstance(cfg, dict):
459
- out.append(cfg)
460
- out.append(view)
461
- return out
462
-
463
 
464
- def _view_field_keys(view):
465
- """Every field key this view NAMES, in the order a reader would meet them.
466
 
467
- ⚠ `filters[].rhs` IS ONE OF THEM AND IS THE ONE THAT GETS DROPPED. A field-vs-field leaf
468
- (`{colId: price, op: lt, rhs: {kind: field, colId: cost}}`) names TWO columns, and a share
469
- carrying only the left one leaves the receiver a filter that cannot evaluate. `kind` `stat`
470
- is not a column reference and is skipped, matching `perm_scope`'s own reader of the tree.
471
 
472
- ⚠ AND `filters` IS A TREE, NOT A LIST. Condition groups nest under `children`, so the walk
473
- recurses rather than iterating once: a column named only inside a group is still named.
474
- """
475
- keys, seen = [], set()
476
-
477
- def add(raw):
478
- key = str(raw or "").strip()
479
- if key and key not in seen:
480
- seen.add(key)
481
- keys.append(key)
482
-
483
- def walk(node):
484
- if isinstance(node, list):
485
- for child in node:
486
- walk(child)
487
- return
488
- if not isinstance(node, dict):
489
- return
490
- kids = node.get("children")
491
- if isinstance(kids, list):
492
- walk(kids)
493
- add(node.get("colId"))
494
- rhs = node.get("rhs")
495
- if isinstance(rhs, dict) and rhs.get("kind") != "stat":
496
- add(rhs.get("colId"))
497
-
498
- for cfg in _view_configs(view):
499
- for key in (cfg.get("order") or ()):
500
- add(key)
501
- for key in (cfg.get("visible") or ()):
502
- add(key)
503
- walk(cfg.get("filters"))
504
- add(cfg.get("groupBy"))
505
- colour = cfg.get("colorBy")
506
- add(colour.get("colId") if isinstance(colour, dict) else colour)
507
- sorts = cfg.get("sorts")
508
- if isinstance(sorts, dict):
509
- sorts = [sorts]
510
- for spec in (sorts or ()):
511
- if isinstance(spec, dict):
512
- add(spec.get("colId"))
513
- return keys
514
-
515
-
516
- def _find_view_topic(session, oid):
517
- """`(topic, view)` for a saved view living in any personal stratum of any topic, else
518
- `(None, None)`.
519
-
520
- ⚠ THE TOPIC IS HALF THE ANSWER. A field grant is keyed by TOPIC, so resolving the view
521
- without remembering which workspace answered would leave the caller guessing at the oid,
522
- which is exactly how two arms of one route come to write two different keys for one column.
523
- Same loop and same finder as `_owns_object`, which answers a different question about the
524
- same lookup and is deliberately left alone.
525
  """
526
  try:
527
- import core.table_store as table_store
528
- except Exception: # noqa: BLE001
529
- return None, None
530
- for topic in _topics(session):
531
- try:
532
- hit = table_store.make(f"{topic}_table_workspace", st=session.runtime).find_view(oid)
533
- except Exception: # noqa: BLE001
534
- continue
535
- if hit:
536
- return str(topic), (hit[1] if len(hit) > 1 else {})
537
- return None, None
538
 
539
 
540
- def _promote_field_for_grant(session, table_key, field_key):
541
- """Promote a private column exactly once, stamp it shared, and answer its GRANT OID.
542
-
543
- ⛔⛔ ONE SEQUENCE, TWO ARMS, AND THAT IS THE WHOLE REASON THIS IS A FUNCTION. `put_share`'s
544
- `field` arm and its `view` arm (T25) both hand a column to somebody. Two spellings of
545
- "promote, stamp, key the oid" is how two surfaces start disagreeing about what a grant
546
- means, and the oid is the exact member that would drift: it is normalised through
547
- `_field_storage_keys(...)[2]`, never built from whatever key the caller happened to hold.
548
-
549
- Answers `None` for a key with no definition on that database, so the caller decides whether
550
- that is a 404 (the `field` arm, where the column IS the request) or a named refusal (the
551
- `view` arm, where it is one entry in a list).
552
- """
553
- from core import field_permissions, shared_overlay
554
- defn, already_shared, workspace_key, shared_key, grant_topic = _field_definition(
555
- session, table_key, field_key)
556
- if not isinstance(defn, dict):
557
- return None
558
- if not already_shared:
559
- defn = field_permissions.promote_field(
560
- workspace_key, shared_key, grant_topic,
561
- session.uname, defn, st=session.runtime)
562
- stamped = dict(defn)
563
- stamped["shared"] = True
564
- stamped["granted"] = True
565
- shared_overlay.put_field(shared_key, field_key, stamped, st=session.runtime)
566
- return shares.field_oid(grant_topic, field_key)
567
-
568
-
569
- def _grant_receivers(session, entries):
570
- """`{username: display name}` for everybody a grant list actually reaches.
571
-
572
- `shares.EVERYONE` is a real audience, not a placeholder, so it expands to the tenant roster
573
- `_people` already computes for the picker. Reading it from a second place would be a second
574
- answer to "who is in this workspace".
575
- """
576
- people = None
577
- out = {}
578
- for entry in shares._clean_entries(entries):
579
- who = str(entry.get("user") or "").strip().lower()
580
- if not who:
581
- continue
582
- if who == shares.EVERYONE:
583
- if people is None:
584
- people = _people(session.tenant)
585
- for person in people:
586
- out.setdefault(str(person["username"]).strip().lower(), person["name"])
587
- continue
588
- out.setdefault(who, who)
589
- if out:
590
- try:
591
- reg = users.registry() or {}
592
- except Exception: # noqa: BLE001
593
- reg = {}
594
- for uname in list(out):
595
- rec = reg.get(uname)
596
- if isinstance(rec, dict) and rec.get("name"):
597
- out[uname] = str(rec["name"])
598
- return out
599
-
600
-
601
- def _admin_walled(session, grant_topic, defs, receivers):
602
- """`{field key: [display names]}` for receivers an ADMINISTRATOR has already walled off.
603
-
604
- ⛔ THE ADMIN SOURCE ONLY. `perm_scope.entry(rec, module)['hiddenFields']` is the half of
605
- `hidden_keys` a field grant cannot overrule; the other half IS the field grant, so consulting
606
- the closure here would report every column this route is about to grant as hidden and refuse
607
- the lot (see the block note above).
608
-
609
- ⭐ THE MEASURE BINDING IS BORROWED, NEVER RESPELLED. An administrator ticking
610
- "Metric - Gross margin" stores `measure_margin`, while the COLUMNS carrying that number are
611
- keyed `measure_margin_<rand>`; `perm_scope._measure_bound_keys` is the one evaluator that
612
- joins the two, and a second copy here would be the first to drift.
613
-
614
- ⚠ AN ADMINISTRATOR RECEIVER IS NEVER WALLED — `hidden_keys` answers an empty set for one
615
- before it reads anything — so the same short circuit runs here, or this function would refuse
616
- a grant to somebody who can already see the column.
617
-
618
- ⚠ A RECEIVER WITH NO REGISTRY RECORD IS SKIPPED RATHER THAN TREATED AS WALLED: `perm_scope`
619
- reads a permission block off the RECORD (`_rec` answers `{}` for a bare username), so a name
620
- this tenant cannot resolve carries no admin wall to find. `_entries_or_400` has already
621
- refused a grant list naming an account that does not exist.
622
- """
623
- import core.perm_scope as perm_scope
624
- import core.perms as perms
625
  try:
626
- reg = users.registry() or {}
627
- except Exception: # noqa: BLE001
628
- reg = {}
629
- field_list = [dict(defn or {}, key=key) for key, defn in defs.items()
630
- if isinstance(defn, dict)]
631
- walled = {}
632
- for uname, display in sorted(receivers.items()):
633
- rec = reg.get(uname)
634
- if not isinstance(rec, dict) or perms.is_admin(rec):
635
- continue
636
- try:
637
- entry = perm_scope.entry(rec, grant_topic) or {}
638
- except Exception: # noqa: BLE001
639
- continue
640
- hidden = {str(k) for k in (entry.get("hiddenFields") or ()) if k}
641
- if not hidden:
642
- continue
643
- try:
644
- hidden |= set(perm_scope._measure_bound_keys(hidden, field_list))
645
- except Exception: # noqa: BLE001
646
- pass
647
- for key in defs:
648
- if key in hidden:
649
- walled.setdefault(key, []).append(display)
650
- return walled
651
-
652
-
653
- #: ⭐ THE THREE REASONS A VIEW'S COLUMN IS NOT GRANTED, EACH ITS OWN CODE. One fused
654
- #: "could not share" would make the three walls unprovable apart, which is the
655
- #: [[a-declared-gate-is-an-unchecked-claim]] failure `verify_field_doors` section 8 exists to
656
- #: prevent: every cause fails by its own name, or it is not gated at all.
657
- #: ⛔ STANDING RULE 2 — no em dash and no en dash in any sentence below; these reach a screen.
658
- FIELD_REFUSAL_CODES = ("not_a_shared_column", "not_owned", "admin_hidden")
659
-
660
- #: ⭐ TRAP 1, SAID OUT LOUD. A column grant is keyed by DATABASE, so it is not scoped to the view
661
- #: that occasioned it. The response carries this sentence rather than letting a caller infer a
662
- #: narrower promise than the store actually makes.
663
- FIELD_GRANT_SCOPE = ("A column shared this way is shared on the whole database, so the people "
664
- "you named can see it on every view of it, not only on this one.")
665
-
666
-
667
- def _refusal(key, code, names=()):
668
- """One refused column, with the sentence a person reads."""
669
- if code == "not_a_shared_column":
670
- why = ('"{k}" belongs to the database itself rather than to a person, so there was '
671
- 'nothing to grant. Anybody who can open the database already sees it.')
672
- elif code == "not_owned":
673
- why = ('"{k}" is somebody else\'s column, and only its owner (or an administrator) can '
674
- 'share it. Ask them to share it, then share this view again.')
675
- else:
676
- why = ('"{k}" is hidden from {who} by an administrator, so sharing it would change '
677
- 'nothing. Ask an administrator to unhide it first.')
678
- return {"field": key, "reason": code,
679
- "message": why.format(k=key, who=_named(names) if names else "them")}
680
-
681
-
682
- def _classify_view_fields(keys, owned, defined, walled):
683
- """`(sharedFieldKeys, refusedFieldKeys)` for the columns a view names. PURE.
684
-
685
- ⛔ EVERY KEY IS DECIDED BEFORE ANY OF THEM IS WRITTEN, which is the same property the ceiling
686
- block above claims for the three role walls: a refusal must not be able to leave part of the
687
- set promoted and part of it untouched.
688
-
689
- ⚠ THE ORDER OF THE CAUSES IS FIXED AND IT DECIDES WHICH SENTENCE A PERSON READS. A built-in
690
- column is owned by nobody, so "there was nothing to grant" has to be asked before "you do not
691
- own it", or every database column in `visible` would be reported as somebody else's.
692
- """
693
- granted, refused = [], []
694
- for key in keys:
695
- if key not in defined:
696
- refused.append(_refusal(key, "not_a_shared_column"))
697
- elif key not in owned:
698
- refused.append(_refusal(key, "not_owned"))
699
- elif walled.get(key):
700
- refused.append(_refusal(key, "admin_hidden", walled.get(key)))
701
- else:
702
- granted.append(key)
703
- return granted, refused
704
-
705
- def _merge_field_entries(existing, incoming):
706
- """A column's grant list with `incoming` ADDED to it. Nobody is removed, nobody is lowered.
707
-
708
- ⛔⛔ THE SHARE PUT REPLACES, AND A COLUMN'S AUDIENCE IS NOT THE VIEW'S AUDIENCE. This route's
709
- contract is a REPLACING set (`PUT ... entries` at the top of the file), which is right for the
710
- object the caller is looking at and catastrophic for the columns underneath it: a column grant
711
- is TOPIC-WIDE, so handing the view's list straight to `set_grants` would rewrite the column's
712
- audience to whoever this view happens to be shared with. A colleague granted that column
713
- through the `field` door would lose it, on every view of the database, silently, inside a 200.
714
- That is exactly the harm D-474 closed at the view door, arriving one door over.
715
-
716
- ⚠ AND A LENGTH CHECK DOES NOT SEE IT. Replacing a one-person list with a different one-person
717
- list keeps the count identical, so the gate asserts the HELD USER IS STILL THERE AT THEIR OWN
718
- ROLE rather than counting rows.
719
-
720
- ⭐ RAISED, NEVER LOWERED. A receiver already held at `view` who arrives on an `edit` share is
721
- raised, because only the column's owner (or an administrator) reaches this path at all and
722
- that is the access they just asked to hand over. An `edit` holder meeting a `view` share keeps
723
- `edit`: a share is an addition, and nothing here is a revocation.
724
-
725
- ⚠ `by` RIDES ON EXISTING ROWS AND IS NEVER TAKEN FROM AN INCOMING ONE. Provenance decides who
726
- may revoke a grant (`_unremovable`), so an incoming payload must not be able to claim it;
727
- `set_grants` stamps a genuinely new row from `granter`.
728
- """
729
- rank = {"view": 0, "edit": 1}
730
- order, merged = [], {}
731
- for row in (existing or ()):
732
- if not isinstance(row, dict):
733
- continue
734
- who = str(row.get("user") or "").strip().lower()
735
- role = str(row.get("role") or "").strip().lower()
736
- if not who or role not in rank or who in merged:
737
- continue
738
- kept = {"user": who, "role": role}
739
- stamp = str(row.get("by") or "").strip().lower()
740
- if stamp:
741
- kept["by"] = stamp
742
- merged[who] = kept
743
- order.append(who)
744
- for row in (incoming or ()):
745
- if not isinstance(row, dict):
746
- continue
747
- who = str(row.get("user") or "").strip().lower()
748
- role = str(row.get("role") or "").strip().lower()
749
- if not who or role not in rank:
750
- continue
751
- if who not in merged:
752
- merged[who] = {"user": who, "role": role}
753
- order.append(who)
754
- elif rank[role] > rank[merged[who]["role"]]:
755
- merged[who]["role"] = role
756
- return [merged[who] for who in order]
757
-
758
- def _share_view_fields(session, oid, entries):
759
- """The `view` arm's field half: classify every column the view names, then grant the ones
760
- that survive. `(sharedFieldKeys, refusedFieldKeys)`.
761
-
762
- ⛔ CLASSIFY EVERYTHING, THEN WRITE. `_classify_view_fields` sees the whole key set before
763
- `_promote_field_for_grant` touches a single definition, so a refusal cannot leave half the
764
- view's columns promoted.
765
-
766
- ⚠ THE VIEW'S OWN GRANT HAS ALREADY BEEN WRITTEN when this runs, and that order is the safe
767
- one: a `409 grants_changed` on the view must not be preceded by a set of column promotions
768
- for a share that then did not happen.
769
- """
770
- topic, view = _find_view_topic(session, oid)
771
- if not topic or not isinstance(view, dict):
772
- return [], []
773
- keys = _view_field_keys(view)
774
- if not keys:
775
- return [], []
776
- table_key = f"{topic}_table_workspace"
777
- grant_topic = _field_storage_keys(table_key)[2]
778
- defs, defined, owned, owners = {}, set(), set(), {}
779
- for key in keys:
780
- defn, already_shared = _field_definition(session, table_key, key)[:2]
781
- if not isinstance(defn, dict):
782
- continue
783
- defs[key] = defn
784
- defined.add(key)
785
- # ⚠ THE COLUMN'S OWNER, NOT THIS SESSION. `set_grants`' owner is sticky, so stamping the
786
- # SHARER here would hand an administrator sharing somebody else's column the ownership
787
- # of it as a side effect of sharing a view. Same resolver the claim wall uses.
788
- owners[key] = _field_owner(session, defn, already_shared)
789
- # ⛔ ONE OWNERSHIP PREDICATE. `_owns_object` is the wall the `field` arm claims through
790
- # and the DELETE door reads; a second "does this person own this column" here is how the
791
- # two answers come apart. It short circuits True for an administrator, which is right:
792
- # an administrator may already share any column through the `field` door.
793
- if _owns_object(session, "field", shares.field_oid(grant_topic, key)):
794
- owned.add(key)
795
- walled = _admin_walled(session, grant_topic, defs, _grant_receivers(session, entries))
796
- granted, refused = _classify_view_fields(keys, owned, defined, walled)
797
- written = []
798
- for key in granted:
799
- field_oid = _promote_field_for_grant(session, table_key, key)
800
- if not field_oid:
801
- refused.append(_refusal(key, "not_a_shared_column"))
802
- continue
803
- # ⛔⛔ ADDED TO, NEVER REPLACED. `set_grants` writes the list it is given, and this route
804
- # PUTs a REPLACING set, so handing it the view's `entries` would make the view's audience
805
- # the COLUMN's audience: a colleague granted this column through the `field` door would
806
- # lose it, on every view of the database, inside a 200. `_merge_field_entries` says what
807
- # that sentence means once, and it is the only writer of a column list on this path.
808
- held = shares.grants("field", field_oid, st=session.runtime)
809
- # ⚠ NO `expect` HERE, AND THAT IS NOT AN OVERSIGHT. The compare-and-set on the view's own
810
- # grant guards a record TWO PEOPLE ARE EDITING through the same dialog. A column's record
811
- # was just read (and possibly created) inside this call, nobody is looking at it in a
812
- # dialog, and a `409` raised at this point would fail a PUT whose view grant has ALREADY
813
- # been written, which is the half-applied state the refusals above exist to avoid.
814
- shares.set_grants("field", field_oid,
815
- _merge_field_entries(held.get("entries"), entries),
816
- owner=held.get("owner") or owners.get(key) or session.uname,
817
- granter=session.uname, st=session.runtime)
818
- written.append(key)
819
- return written, refused
820
-
821
- @router.get("/share/mine")
822
- def my_shares(session: Session = Depends(require_session)):
823
- """Everything shared WITH me, by kind — the "Shared with me" rail section (R10).
824
-
825
- Registered before `/share/{kind}/{oid}` so the literal path wins the match; FastAPI resolves
826
- in declaration order and `mine` would otherwise be read as a `kind`, answering 400 for a URL
827
- that is not malformed at all.
828
- """
829
- return shares.shared_with(session.uname, st=session.runtime)
830
 
831
 
832
  @router.get("/share/{kind}/{oid}")
@@ -837,8 +462,12 @@ def get_share(kind: str, oid: str, session: Session = Depends(require_session)):
837
  if table_key and field_key:
838
  oid = shares.field_oid(_field_storage_keys(table_key)[2], field_key)
839
  rec = shares.grants(kind, oid, st=session.runtime)
840
- role = shares.role_for(kind, oid, session.uname, is_admin=session.admin, st=session.runtime)
841
- may_admin = shares.may_administer(kind, oid, session.uname, is_admin=session.admin,
 
 
 
 
842
  st=session.runtime)
843
  # W39-T29 — the dialog opens with GET before its first PUT. Until that PUT exists the grant
844
  # registry has no owner to return from `may_administer`, even though the same caller may safely
@@ -878,39 +507,6 @@ def get_share(kind: str, oid: str, session: Session = Depends(require_session)):
878
  }
879
 
880
 
881
- @router.delete("/share/field/{oid}/mine")
882
- def remove_my_field_share(oid: str, session: Session = Depends(require_session)):
883
- """Remove only this session's direct grant on one shared field.
884
-
885
- This is deliberately not a shortened form of the replacing PUT route. A grantee may leave
886
- a column shared to them, but may not submit a list that can revoke anybody else. A wildcard
887
- grant is also not removable here: deleting it would remove the column from everybody.
888
- """
889
- table_key, field_key = shares.split_field_oid(oid)
890
- if not table_key or not field_key:
891
- raise err(404, "no_object", "no such column, or it is not shared with this account")
892
- oid = shares.field_oid(_field_storage_keys(table_key)[2], field_key)
893
- rec = shares.grants("field", oid, st=session.runtime)
894
- uname = str(session.uname or "").strip().lower()
895
- direct = [entry for entry in rec["entries"] if entry.get("user") == uname]
896
- if not direct:
897
- if shares.role_for("field", oid, uname, is_admin=session.admin, st=session.runtime):
898
- raise err(409, "not_direct_grant",
899
- "this column is shared with everyone in this workspace, so there is no "
900
- "personal grant to remove. Nothing was changed.")
901
- raise err(404, "no_object", "no such column, or it is not shared with this account")
902
- if shares.role_for("field", oid, uname, is_admin=session.admin, st=session.runtime) == "owner":
903
- raise err(409, "owner_cannot_leave",
904
- "you own this column. Reassign or delete it instead of removing yourself from it.")
905
- kept = [entry for entry in rec["entries"] if entry.get("user") != uname]
906
- try:
907
- shares.set_grants("field", oid, kept, owner=rec["owner"], st=session.runtime,
908
- expect=rec["entries"])
909
- except shares.GrantsChanged as exc:
910
- raise err(409, "grants_changed", str(exc))
911
- return {"removed": True, "field": field_key}
912
-
913
-
914
  def _people(tenant):
915
  """[{username, name}] for this tenant — same population as `assignable_people`, with the
916
  BINDING identity alongside the display one."""
@@ -948,7 +544,8 @@ def put_share(kind: str, oid: str, body: dict = Body(default=None),
948
  # the alternative (refusing until somebody seeds an owner) would make a brand-new folder
949
  # unshareable by the person who just made it.
950
  if rec["owner"]:
951
- if not shares.may_administer(kind, oid, session.uname, is_admin=session.admin,
 
952
  st=session.runtime):
953
  # ⭐ R4 / W40-T02 — `may_administer` now also admits an `edit` grantee on a VIEW, so
954
  # the population refused here is narrower than the code word `not_owner` suggests: a
@@ -1065,15 +662,21 @@ def put_share(kind: str, oid: str, body: dict = Body(default=None),
1065
  # A field grant is a visibility and edit wall. Promote a private custom
1066
  # field exactly once, then keep the requested Share field role as the
1067
  # authoritative override for the legacy permissions bag.
1068
- # ⭐⭐ W42-T25 — THE SEQUENCE MOVED INTO `_promote_field_for_grant` AND DID NOT CHANGE.
1069
- # The `view` arm below now hands columns to people as well, and one function answering
1070
- # "promote, stamp, key the oid" is what keeps the two arms writing the SAME oid for the
1071
- # same column. `None` here still means the column does not exist on that database.
1072
  table_key, field_key = shares.split_field_oid(oid)
1073
- promoted = _promote_field_for_grant(session, table_key, field_key)
1074
- if promoted is None:
 
1075
  raise err(404, "no_object", "no such field, or it is not shared with this account")
1076
- oid = promoted
 
 
 
 
 
 
 
 
1077
  # ⭐⭐ R4 / W40-T02 (D3) — OWNERSHIP NEVER MOVES ON A RE-SHARE, AND IT IS SAID HERE RATHER
1078
  # THAN LEFT TO FALL OUT. `set_grants`' owner is sticky, so the old `rec["owner"] or
1079
  # session.uname` already happened not to transfer ownership — incidentally, as a property of
@@ -1103,20 +706,6 @@ def put_share(kind: str, oid: str, body: dict = Body(default=None),
1103
  except shares.GrantsChanged as exc:
1104
  raise err(409, "grants_changed", str(exc))
1105
  _notify_new_grantees(session, kind, oid, before=rec["entries"], after=out.get("entries") or [])
1106
- # ⭐⭐ W42-T25 — SHARING A VIEW SHARES THE FIELDS IT NAMES. A view is a selection expressed
1107
- # in columns, so a grant that carries the view and none of its columns puts a rail row on
1108
- # the receiver's screen over an empty grid. The three refusals are named rather than thrown:
1109
- # this PUT succeeded, the view IS shared, and what could not follow it is reported by name
1110
- # with the reason. Throwing instead would make the ordinary case (a view over one built-in
1111
- # column) unshareable.
1112
- # ⛔ THE EXISTING KEYS ARE UNTOUCHED. `{owner, entries}` is what every current client reads
1113
- # off this route; the field report is additive, and a caller that ignores it is unaffected.
1114
- if kind == "view":
1115
- shared_fields, refused_fields = _share_view_fields(session, oid, entries)
1116
- return {**out,
1117
- "sharedFieldKeys": shared_fields,
1118
- "refusedFieldKeys": refused_fields,
1119
- "sharedFieldScope": FIELD_GRANT_SCOPE}
1120
  return out
1121
 
1122
 
@@ -1321,6 +910,14 @@ def _object_ref(session, kind, oid):
1321
  a row that opens nowhere.
1322
  """
1323
  try:
 
 
 
 
 
 
 
 
1324
  if kind == "field":
1325
  # ⭐⭐ W38-T16 — A COLUMN IS NOT ADDRESSABLE ON ITS OWN, exactly as a view is not: it
1326
  # is a column INSIDE a database, so the target that travels is the DATABASE. Without
@@ -1373,4 +970,43 @@ def _object_ref(session, kind, oid):
1373
  except Exception: # noqa: BLE001
1374
  pass
1375
  return ({"view": "A view", "folder": "A folder",
1376
- "field": "A column"}.get(kind, "An item"), None, "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  where a caller is about to be stamped OWNER of something nobody owns — so the resolution runs
203
  exactly there, and the common path (a record exists, `may_administer` decides) is untouched.
204
  """
205
+ if kind == "cohort":
206
+ scope, cohort_id = shares.split_cohort_oid(oid)
207
+ source = shares.cohort_source(scope, cohort_id, st=session.runtime) if scope else None
208
+ return bool(source and source["owner"] == str(session.uname or "").strip().lower())
209
  if session.admin:
210
  return True
211
  if kind == "field":
 
415
  stuck.add(user)
416
  return stuck
417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
 
419
+ @router.get("/share/mine")
420
+ def my_shares(session: Session = Depends(require_session)):
421
+ """Everything shared WITH me, by kind — the "Shared with me" rail section (R10).
422
 
423
+ Registered before `/share/{kind}/{oid}` so the literal path wins the match; FastAPI resolves
424
+ in declaration order and `mine` would otherwise be read as a `kind`, answering 400 for a URL
425
+ that is not malformed at all.
 
426
  """
427
+ return shares.shared_with(session.uname, st=session.runtime)
 
 
 
 
 
 
 
 
428
 
 
 
429
 
430
+ @router.get("/cohorts/{scope}")
431
+ def list_cohorts(scope: str, session: Session = Depends(require_session)):
432
+ """The authorized Cohort list for one database.
 
433
 
434
+ Unlike the former owner-bucket projection, this calls the same predicate as the Cohort
435
+ detail below. An account without a grant receives no entry at all; it never receives an
436
+ id/name shell whose membership has been stripped.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
  """
438
  try:
439
+ records = shares.visible_cohorts(scope, session.uname, st=session.runtime)
440
+ except ValueError as exc:
441
+ raise err(400, "bad_cohort_scope", str(exc))
442
+ return {"cohorts": [{"id": cid, **record} for cid, record in sorted(records.items())]}
 
 
 
 
 
 
 
443
 
444
 
445
+ @router.get("/cohorts/{scope}/{cohort_id}")
446
+ def get_cohort(scope: str, cohort_id: str, session: Session = Depends(require_session)):
447
+ """One authorized Cohort, with an absent-permission answer indistinguishable from absence."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
448
  try:
449
+ record = shares.cohort_record(scope, cohort_id, session.uname, st=session.runtime)
450
+ except ValueError as exc:
451
+ raise err(400, "bad_cohort_scope", str(exc))
452
+ if record is None:
453
+ raise err(404, "no_cohort", "no such cohort, or it is not shared with this account")
454
+ return {"id": record["id"], **record["cohort"]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
455
 
456
 
457
  @router.get("/share/{kind}/{oid}")
 
462
  if table_key and field_key:
463
  oid = shares.field_oid(_field_storage_keys(table_key)[2], field_key)
464
  rec = shares.grants(kind, oid, st=session.runtime)
465
+ # A Cohort is visible only to its source owner or an explicit grant. In particular, an
466
+ # administrator-shaped Farhan session must not turn Shantal's absent grant into a record.
467
+ # Other share kinds retain their established administrator behaviour.
468
+ _admin_share = bool(session.admin) and kind != "cohort"
469
+ role = shares.role_for(kind, oid, session.uname, is_admin=_admin_share, st=session.runtime)
470
+ may_admin = shares.may_administer(kind, oid, session.uname, is_admin=_admin_share,
471
  st=session.runtime)
472
  # W39-T29 — the dialog opens with GET before its first PUT. Until that PUT exists the grant
473
  # registry has no owner to return from `may_administer`, even though the same caller may safely
 
507
  }
508
 
509
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510
  def _people(tenant):
511
  """[{username, name}] for this tenant — same population as `assignable_people`, with the
512
  BINDING identity alongside the display one."""
 
544
  # the alternative (refusing until somebody seeds an owner) would make a brand-new folder
545
  # unshareable by the person who just made it.
546
  if rec["owner"]:
547
+ if not shares.may_administer(kind, oid, session.uname,
548
+ is_admin=bool(session.admin) and kind != "cohort",
549
  st=session.runtime):
550
  # ⭐ R4 / W40-T02 — `may_administer` now also admits an `edit` grantee on a VIEW, so
551
  # the population refused here is narrower than the code word `not_owner` suggests: a
 
662
  # A field grant is a visibility and edit wall. Promote a private custom
663
  # field exactly once, then keep the requested Share field role as the
664
  # authoritative override for the legacy permissions bag.
665
+ from core import field_permissions, shared_overlay
 
 
 
666
  table_key, field_key = shares.split_field_oid(oid)
667
+ defn, already_shared, workspace_key, shared_key, grant_topic = _field_definition(
668
+ session, table_key, field_key)
669
+ if not isinstance(defn, dict):
670
  raise err(404, "no_object", "no such field, or it is not shared with this account")
671
+ if not already_shared:
672
+ defn = field_permissions.promote_field(
673
+ workspace_key, shared_key, grant_topic,
674
+ session.uname, defn, st=session.runtime)
675
+ stamped = dict(defn)
676
+ stamped["shared"] = True
677
+ stamped["granted"] = True
678
+ shared_overlay.put_field(shared_key, field_key, stamped, st=session.runtime)
679
+ oid = shares.field_oid(grant_topic, field_key)
680
  # ⭐⭐ R4 / W40-T02 (D3) — OWNERSHIP NEVER MOVES ON A RE-SHARE, AND IT IS SAID HERE RATHER
681
  # THAN LEFT TO FALL OUT. `set_grants`' owner is sticky, so the old `rec["owner"] or
682
  # session.uname` already happened not to transfer ownership — incidentally, as a property of
 
706
  except shares.GrantsChanged as exc:
707
  raise err(409, "grants_changed", str(exc))
708
  _notify_new_grantees(session, kind, oid, before=rec["entries"], after=out.get("entries") or [])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
709
  return out
710
 
711
 
 
910
  a row that opens nowhere.
911
  """
912
  try:
913
+ if kind == "cohort":
914
+ scope, cohort_id = shares.split_cohort_oid(oid)
915
+ source = shares.cohort_source(scope, cohort_id, st=session.runtime) if scope else None
916
+ if source is None:
917
+ return ("A cohort", None, "")
918
+ from routes_alerts import route_for_topic
919
+ label = str(source["cohort"].get("name") or "").strip() or "A cohort"
920
+ return (label, route_for_topic(source["scope"]) or None, source["id"])
921
  if kind == "field":
922
  # ⭐⭐ W38-T16 — A COLUMN IS NOT ADDRESSABLE ON ITS OWN, exactly as a view is not: it
923
  # is a column INSIDE a database, so the target that travels is the DATABASE. Without
 
970
  except Exception: # noqa: BLE001
971
  pass
972
  return ({"view": "A view", "folder": "A folder",
973
+ "field": "A column", "cohort": "A cohort"}.get(kind, "An item"), None, "")
974
+
975
+
976
+ def _cohort_visible(scope, username, allowed_pids=None):
977
+ """Adapt the Cohort module's existing list projection to the one registry predicate.
978
+
979
+ ``workspace_wire`` is the live Cohort list/open path. It intentionally receives only a
980
+ username and a pid envelope, so the adapter remains at this API boundary and reuses the
981
+ module's membership cleaner rather than creating a second Cohort representation in
982
+ ``core.shares``. ``visible_cohorts`` returns no unauthorized id, which prevents the blank
983
+ locked-view placeholder the old per-user read created.
984
+ """
985
+ import modules.cohort as cohort_mod
986
+
987
+ records = shares.visible_cohorts(scope, username)
988
+ return {cid: {**record,
989
+ "members": cohort_mod._clean_members(record.get("members"), allowed_pids)}
990
+ for cid, record in records.items()}
991
+
992
+
993
+ def _install_cohort_visibility():
994
+ """Route all API Cohort list/detail reads through the normal share predicate once."""
995
+ try:
996
+ import modules.cohort as cohort_mod
997
+
998
+ def _customer_visible(username, allowed_pids=None):
999
+ return _cohort_visible("customer", username, allowed_pids)
1000
+
1001
+ def _scoped_visible(self, username, allowed_pids=None):
1002
+ return _cohort_visible(self.scope, username, allowed_pids)
1003
+
1004
+ cohort_mod.visible = _customer_visible
1005
+ cohort_mod.CohortStore.visible = _scoped_visible
1006
+ except Exception:
1007
+ # The API route still has its direct, fail-closed list/detail paths if the retired module
1008
+ # is unavailable during an import-only tool invocation.
1009
+ return
1010
+
1011
+
1012
+ _install_cohort_visibility()
api/routes_tables.py CHANGED
@@ -1050,32 +1050,10 @@ def _usage_column_refs(field):
1050
  return rollup, automation
1051
 
1052
 
1053
- def _field_usage(session, table_key, fields, defn, ws_st, ws_key, st=None):
1054
  """`{field_key: {views, filters, rollups, automations, permRules}}` — C8's `usage`, computed
1055
  over the WHOLE workspace, or `{}` when it cannot be established.
1056
 
1057
- ⭐⭐ W42-T14 / C4 — **PARAMETERISED OFF `(ws_st, ws_key)`, NOT OFF A `user_tables` OPS OBJECT.**
1058
- The only two things the old `ops` argument was ever asked for were `ops.st` (the bound store
1059
- handle) and `ops.table_key` (the name of the document every account's strata live in), so
1060
- taking those two directly is what lets a SECOND surface call this. It matters because the
1061
- document is NOT named `<key>_table_workspace` everywhere: on the customer topic it is
1062
- `modules.customer_data.TABLE_KEY` (`customer_table_workspace`), a name no `f"{table_key}_…"`
1063
- literal can produce. Rebuilding the string here rather than being handed it is exactly the
1064
- second spelling `_ops`' own note refuses.
1065
-
1066
- ⛔⛔ `table_key` IS THE MEMO KEY AND IT IS THE TOPIC, NEVER THE DOCUMENT. `(tenant, table_key)`
1067
- addresses the memo, `rec['perms'][table_key]` addresses the permission record and
1068
- `config.targetTable == table_key` addresses the flow binding — three reads that must all name
1069
- the SAME thing the registry calls this database. `ut_assembly` passes its `table_key`;
1070
- `routes_customers.grid_assembly` passes its module constant `customer_data`, which is the key
1071
- `apply_row_scope`, `hidden_keys` and `routes_admin._clean_perms` already spell there. A caller
1072
- that spelled it differently (the topic on one door, the bucket on another) would pin a stale
1073
- answer under a key nothing ever invalidates, for the life of the process.
1074
- ⚠ ON THE CUSTOMER TOPIC THE FLOW LEG IS A TRUE ZERO, not a missed read: `automation_engine`
1075
- resolves `targetTable` out of `user_tables` only, so no flow can bind to that topic at all.
1076
- The COLUMN leg (`field['automation']['urlField']`) still counts there, which is the half a
1077
- customer column can actually carry.
1078
-
1079
  ⭐⭐ W41-T10 / R3 / C8. The `done-when`'s load-bearing clause is *"over the whole workspace,
1080
  not from a partial client list"*: the assembly's own `ws` holds this caller's stratum merged
1081
  with the views shared TO them, so a count taken from it would miss every private view every
@@ -1121,18 +1099,18 @@ def _field_usage(session, table_key, fields, defn, ws_st, ws_key, st=None):
1121
  return {}
1122
  lent = st if st is not None else session.runtime
1123
  memo_key = (str(getattr(session, "tenant", "") or ""), str(table_key))
1124
- token = _usage_token(lent, ws_key)
1125
  if token is not None:
1126
  hit = _USAGE_MEMO.get(memo_key)
1127
  if hit and hit[0] == token:
1128
  return hit[1]
1129
  try:
1130
- # ⚠ THE HANDLE AND THE NAME ARE BOTH HANDED IN, never rebuilt from `table_key`: the store
1131
- # key the calling assembly closed over is the one this database's strata actually live
1132
- # under, and a second spelling of it is a second thing to keep in step. A lend passes a
1133
- # workspace document straight through to the runtime (a lend serves only `user_tables` and
1134
- # `object_shares`), so this is the tenant's own document either way.
1135
- ws_doc = ws_st.get(ws_key) or {}
1136
  except Exception: # noqa: BLE001
1137
  return {}
1138
  try:
@@ -1285,6 +1263,17 @@ def ut_assembly(session: Session, table_key: str, storage_key: str = "",
1285
  # lines and for the same reason: the closure must be recomputed on the MERGED contract or a
1286
  # formula in a shared column reaches past it.
1287
  fields = _ut_shared_fields(session, table_key, fields)
 
 
 
 
 
 
 
 
 
 
 
1288
  # ⭐⭐ W41-T10 / RULING R3 / CONTRACT C8 — **`usage`, STAMPED ONCE, HERE.**
1289
  #
1290
  # ⛔ IN THE ASSEMBLY AND ON BOTH ARMS, WHICH IS NOT THE CHEAP CHOICE AND IS THE ONLY CORRECT
@@ -1307,14 +1296,8 @@ def ut_assembly(session: Session, table_key: str, storage_key: str = "",
1307
  # `dict(f, source=…)` copies for the shared stratum but passes the rest through by reference,
1308
  # and `_usage_field_corpus` hands those same objects back. Mutating one would write a count
1309
  # into a definition the next reader shares.
1310
- # ⛔ `agg` belongs to lanes B and D; C8 is explicit that an absent key means "not built yet".
1311
- # ⭐⭐ W42-T14 / C4 — `class` NOW RIDES BESIDE IT, and the pair is the contract. `class` shipped
1312
- # on `customer_data` with W41-T01 and stopped at that fence, so a `ut_*` grid sent `usage` with
1313
- # no `class` while the customer grid sent `class` with no `usage` — and
1314
- # `filter-kit/fieldClass.ts::deleteImpactTitle(fc, usage)` composes its warning as two
1315
- # independent halves and DROPS whichever argument is null. Both live readers (`ColumnMenu`,
1316
- # `FieldsHidePanel`) pass both. So each surface was rendering half a sentence with every gate on
1317
- # both sides green, which is [[two-lanes-one-contract-dead-feature]] wearing a third face.
1318
  #
1319
  # ⚠ LENIENT, LIKE EVERY OTHER DISPLAY READ ON THIS ASSEMBLY, and C8's absent-key polarity is
1320
  # what makes degrading safe: a client renders nothing for a missing `usage` rather than a
@@ -1323,59 +1306,13 @@ def ut_assembly(session: Session, table_key: str, storage_key: str = "",
1323
  # ⚠ A COPY OF THE BAG, because `_field_usage` MEMOISES its answer: handing the memo's own dict
1324
  # out would let anything downstream write into the number the next request reads.
1325
  try:
1326
- _usage = _field_usage(session, table_key, fields, defn,
1327
- ops.st, ops.table_key, st=st)
1328
  except Exception: # noqa: BLE001
1329
  _usage = {}
1330
  if _usage:
1331
  fields = [dict(f, usage=dict(_usage[f["key"]]))
1332
  if isinstance(f, dict) and _usage.get(f.get("key")) else f
1333
  for f in fields]
1334
- # ⭐⭐ W42-T14 / C4 — **THE THREE BADGES, THE CHEAP DIRECTION.** `field_classes` is O(1) in
1335
- # store reads for the whole list (one `object_shares` read via `grant_records`, one
1336
- # `<key>__shared` read for the value stratum) and this is the only line on a `ut_*` grid that
1337
- # calls it.
1338
- #
1339
- # ⚠ THE TWO KEYS ARE THE SAME STRING HERE AND THAT IS NOT A TYPO. On the customer topic the
1340
- # bucket (`customer_table_workspace`) and the grant topic (`customer_data`) are different
1341
- # names; on a user table both are `table_key` itself, which is what `delete_shared_field`
1342
- # already spells three lines apart (`shared_overlay.fields(table_key)` and
1343
- # `grant_topic=table_key`) and what `_ut_shared_fields` passes as `shared_key=table_key`.
1344
- #
1345
- # ⚠ `st=st` IS THE LEND, AND IT IS SAFE ON A NON-LENDABLE BUCKET. `grant_records` reads
1346
- # `object_shares`, which IS lendable, so the badges ride the document this pass already holds
1347
- # (the D-214 shape). `_shared_value_keys` then reads `<key>__shared`, which is NOT in
1348
- # `_LENDABLE` -- and `_Lent.get`'s first branch forwards exactly that case straight to the
1349
- # runtime rather than answering empty, which is checked in `verify_field_row` rather than
1350
- # assumed: a lend that swallowed it would make every `values` badge read `personal` under a
1351
- # lenient try, which is this ticket's own failure class.
1352
- #
1353
- # ⛔ NO `strata` MAP IS LENT, DELIBERATELY, AND THE ABSENCE IS THE HONEST ANSWER. W42-T47 gates
1354
- # its behaviour change on the stratum being ASSERTED by the caller that did the reading, and
1355
- # a guessed `personal` would MOVE A PERMISSION — `user_tables.delete_field_refusal` reads
1356
- # `bag['owner']` to decide DELETE. This assembly cannot assert one: `workspace_wire` returns
1357
- # the contract and this account's fork already merged into one list with no record of which
1358
- # document each entry came out of. What it CAN say is not needed either: `_ut_shared_fields`
1359
- # only ADDS keys the list does not already have, never replaces one, so no fork with a copied
1360
- # `shared` mark is created here and `field_stratum`'s per-key fallback answers correctly. An
1361
- # unlent map is today's answer plus the new member, which is exactly T47's designed fallback.
1362
- #
1363
- # ⚠ A NEW DICT PER COLUMN, NEVER AN IN-PLACE STAMP — the same rule as `usage` above and for a
1364
- # sharper reason: `class` carries THIS viewer's `sharedBy` and `owner`, and `_ut_shared_fields`
1365
- # passes non-shared entries through BY REFERENCE, so an in-place stamp would write one
1366
- # account's answer into a definition the next reader shares.
1367
- # ⚠ LENIENT AND ABSENT-KEY, like every other display read on this assembly: a registry that
1368
- # will not open costs the badges and not the grid, and a client renders nothing for a missing
1369
- # `class` rather than a wrong badge.
1370
- try:
1371
- from core import field_permissions as _fp
1372
- _classes = _fp.field_classes(fields, session.uname, table_key=table_key,
1373
- grant_topic=table_key, st=st)
1374
- fields = [dict(f, **{"class": _classes[f["key"]]})
1375
- if isinstance(f, dict) and _classes.get(f.get("key")) else f
1376
- for f in fields]
1377
- except Exception: # noqa: BLE001
1378
- pass
1379
  # ⭐⭐ C8's `descriptionEdited`, AND IT CLOSES A CONSUMER THAT WAS ALREADY WRITTEN.
1380
  # W41-T11 built the producer (`user_tables.description_edited`, R19's custody mark scoped to the
1381
  # description) and correctly stopped at its own fence, which is one core file. Measured across
@@ -1414,7 +1351,7 @@ def ut_assembly(session: Session, table_key: str, storage_key: str = "",
1414
  # whose entity topic declares a `measures:` binding (today `ut_odoo_agents`) serves a real
1415
  # lookback catalogue AND the cells to go with it; every other user table still serves `[]`,
1416
  # which is the honest answer for a hand-typed one rather than a descope.
1417
- today = time.strftime("%Y-%m-%d")
1418
  measures = ut_measures(table_key, session)
1419
  derived = aios_grid.cohort_cells(lists) # R9: this table's own lists
1420
  for _pid, _cells in _ut_measure_cells(table_key, fields, pids, today, measures,
@@ -2190,7 +2127,14 @@ def table_rows(table_key: str, session: Session = Depends(require_session)):
2190
  # missing key has been silently switching the feature off. ⛔ ONE shared serialiser with the
2191
  # customer scope — `grid_events.docs_for` — never a twin here.
2192
  from core import grid_events as _ge
 
 
 
 
 
 
2193
  return {"fields": g["fields"], "rows": rows, "today": g["today"],
 
2194
  "docs": _ge.docs_for(g["pids"], scope_key=table_key, uname=session.uname,
2195
  admin=session.admin, st=session.runtime),
2196
  "pulled_at": time.strftime("%Y-%m-%d %H:%M"),
@@ -2491,11 +2435,6 @@ def _with_dropped(ut, out, body):
2491
  def _refusal_sentence(ut, session, body, table_key="", fkey=""):
2492
  """Why was this column refused? The specific reason when we can name one, the general list
2493
  otherwise — never a specific-sounding guess."""
2494
- # W42-T36: the validator returns only ``None``. Keep the option-cap wording in its
2495
- # single owner so both add and patch tell the person exactly what was refused.
2496
- option_refusal = ut.option_cap_refusal((body or {}).get("options"))
2497
- if option_refusal:
2498
- return option_refusal
2499
  # ⭐ WAVE-34 (R13): the enrichment column's own sentence, named BEFORE the automation bag
2500
  # below. `_clean_field` DERIVES `field.automation` for this kind, so a refused enrichment
2501
  # column would otherwise be explained by the flow law -- "pick a flow, or make this an
@@ -2574,11 +2513,7 @@ def patch_field(table_key: str, fkey: str, body: dict = Body(default=None),
2574
  migrated = dict(migrated or {}, workspace=True)
2575
  except Exception: # noqa: BLE001
2576
  migrated = dict(migrated or {}, workspace=False)
2577
- # A type change can clear values that no longer have a meaning in the target column. Keep
2578
- # that report separate from the field itself: callers that only need the field retain the
2579
- # established shape, while a future editor can state the consequence from the same response.
2580
- retype = {}
2581
- field = ut.patch_field(table_key, fkey, body, st=session.runtime, preview=retype)
2582
  if not field:
2583
  # C3: the same narrator as `add_field`. Flagging a SECOND column is the same act as
2584
  # adding one, so it must get the same sentence naming the column that already holds the
@@ -2590,8 +2525,6 @@ def patch_field(table_key: str, fkey: str, body: dict = Body(default=None),
2590
  field = synced.get("field") or field
2591
  _refresh_relations(session)
2592
  out = {"field": field}
2593
- if retype:
2594
- out["retype"] = retype
2595
  # ⭐⭐ W41-T15 / C5 — the same report `add_field` carries, on the door that RETARGETS a link.
2596
  # This one matters more: pointing an existing link at `customer_data` deletes the backlink the
2597
  # old target held (the stale-inverse sweep) and cannot make a new one, so the column silently
@@ -2691,179 +2624,6 @@ def delete_field(table_key: str, fkey: str, session: Session = Depends(require_s
2691
  return {"deleted": fkey}
2692
 
2693
 
2694
- #: ⭐⭐ W42-T28 — THE SENTENCES THE BULK DOOR SAYS **FOR ITSELF**, and why they are not next door.
2695
- #:
2696
- #: ⛔ NONE OF THESE IS A RIGHTS REFUSAL, so none of them belongs in `_delete_field_sentence`. That
2697
- #: function renders `user_tables.delete_field_refusal`'s stable codes and nothing else, which is
2698
- #: C2's *"no surface re-implements either test"* read the other way round: a door that folded its
2699
- #: own execution outcomes into the rights renderer would make the two indistinguishable to the next
2700
- #: reader, and the first person to add a code there would be writing a second opinion about who may
2701
- #: delete what. These four are outcomes of the EXECUTOR or of this door's read wall.
2702
- #:
2703
- #: ⛔ STANDING RULE 2 — NO EM DASH AND NO EN DASH. Every one of these reaches a toast beside a
2704
- #: column name, so they are user-facing copy; they are written to read naturally without the
2705
- #: punctuation rather than having it stripped out afterwards.
2706
- _BULK_DELETE_SENTENCES = {
2707
- "unknown_field": ("that column is not on this database. It may already have been removed, so "
2708
- "reload and check before trying again"),
2709
- "field_hidden": ("this database has no column by that name that you may remove"),
2710
- "last_field": ("a database must keep at least one column, so this one cannot be removed. Add "
2711
- "another column first, then remove this one"),
2712
- "delete_failed": ("that column could not be removed. Reload the database and try again"),
2713
- }
2714
-
2715
-
2716
- def _bulk_delete_refusal(key, code):
2717
- """One refused outcome, in the same shape a deleted one has: a key, a status, a machine code
2718
- and a sentence. The code is what a client switches on; the sentence is what a person reads."""
2719
- return {"key": key, "status": "refused", "code": code,
2720
- "reason": _BULK_DELETE_SENTENCES.get(code, _BULK_DELETE_SENTENCES["delete_failed"])}
2721
-
2722
-
2723
- def _contract_holds_field(ut, table_key, fkey, st):
2724
- """Is `fkey` STILL a declared column of this database's contract? Asked only on the failure
2725
- path, because it is a whole-document read and it separates two very different refusals:
2726
- `user_tables.delete_field` answers False both for *"a database must keep at least one"* and for
2727
- a key that is already gone (an ordinary link's reciprocal disappears when its source column
2728
- does, so key B can vanish while key A of the same request is being deleted)."""
2729
- fields = (ut.get(table_key, st=st) or {}).get("fields") or []
2730
- return any(isinstance(f, dict) and str(f.get("key")) == str(fkey) for f in fields)
2731
-
2732
-
2733
- @router.post("/tables/{table_key}/fields/delete")
2734
- @router.delete("/tables/{table_key}/fields")
2735
- def delete_fields(table_key: str, body: dict = Body(default=None),
2736
- session: Session = Depends(require_session)):
2737
- """⭐⭐ W42-T28 / CONTRACT C4 — **REMOVE N COLUMNS IN ONE CALL, AND ANSWER PER KEY.**
2738
-
2739
- `{"keys": [...]}` in, `{"results": [{key, status, ...}, ...]}` out. Both a POST to
2740
- `…/fields/delete` and a DELETE to `…/fields` reach this one handler, because a body on a DELETE
2741
- is legal and unevenly supported by clients, and the two spellings must not become two doors.
2742
-
2743
- ⛔ THIS IS NOT A LOOP OVER `delete_field`, AND THE DIFFERENCE IS THE OWNER'S BUG. Instruction 21
2744
- of wave 41 was a column that *"reappeared three times"*: the singular route below deletes ONE
2745
- stratum, the `user_tables` contract, and leaves the shared bucket, every other account's fork
2746
- and the grant record alive for `migrate_legacy_fields` to promote straight back on the next
2747
- read. W41-T07 fixed that in `field_permissions.delete_field_everywhere`, which is the five-leg
2748
- executor, and this door goes through it once per key. Multiplying the broken delete by N would
2749
- have multiplied the resurrection by N.
2750
-
2751
- ⛔ PARTIAL SUCCESS IS THE POINT, NOT A TOLERANCE. A key the caller may not delete is refused
2752
- while the rest still go, so the outcomes are per key and there is no transaction around them.
2753
- A field manager offers a multi-select over columns a person may own only some of; an
2754
- all-or-nothing answer would make the one column they cannot touch block the nine they can, and
2755
- a bare 200 would leave them believing all ten went.
2756
-
2757
- ⛔ THE RIGHT IS NOT DECIDED HERE. `user_tables.delete_field_refusal` is C2's one pair and it
2758
- answers both halves in one call (the decision, and the reason a person reads);
2759
- `_delete_field_sentence` turns its code into this door's sentence, exactly as
2760
- `delete_shared_field` already does. Spelling the owner-or-admin test a second time is how the
2761
- two delete doors came apart in the first place.
2762
-
2763
- ⚠ `deleted` IS EARNED BY A TRUTHY REMOVAL, NEVER BY THE ABSENCE OF A REFUSAL. `tombstoned` is
2764
- always True and is deliberately not counted; a key that passed every wall and still moved
2765
- nothing is reported refused, because a `deleted` that removed nothing reads exactly like a
2766
- working delete and is the failure this ticket exists to end.
2767
-
2768
- ⚠ NO `fields` LIST COMES BACK, and the omission is the answer. A list assembled here has been
2769
- through neither `ut_assembly`'s hidden closure nor C4's `class`/`usage` stamps, so a client
2770
- that trusted it would render columns C1 walls away. `rerender: True` is the instruction to
2771
- refetch, which is what `delete_shared_field` ships for the same reason.
2772
-
2773
- ⚠ `st=session.runtime` FOR BOTH EXECUTORS, NEVER THE WALL'S LEND. The last-column rule is
2774
- evaluated against the field list as of the PREVIOUS key's deletion; answering it from a
2775
- pre-write snapshot would refuse the wrong key of a request that empties a database.
2776
- """
2777
- # ⛔ NO `defs_only`, matching every other write wall in this file: a projected snapshot must
2778
- # never reach a post-write read (contract C5), and this door writes.
2779
- defn = _defn_or_refuse(session, table_key, scope_applied=True)
2780
- ut = _ut()
2781
- if not ut.is_user_table(table_key, st=session.runtime):
2782
- raise err(400, "not_a_user_table",
2783
- "only a user-created database has an editable schema. A connected source "
2784
- "owns its own columns")
2785
- raw = (body or {}).get("keys")
2786
- if not isinstance(raw, list):
2787
- raise err(400, "bad_keys", "send `keys`, the list of columns to remove")
2788
- ordered = []
2789
- for k in raw:
2790
- k = str(k or "").strip()
2791
- if k and k not in ordered:
2792
- ordered.append(k)
2793
- if not ordered:
2794
- raise err(400, "bad_keys", "name at least one column to remove")
2795
-
2796
- from core import field_permissions, shared_overlay
2797
- declared = [f for f in (defn.get("fields") or []) if isinstance(f, dict)]
2798
- contract_keys = {str(f.get("key")) for f in declared}
2799
- # ⚠ Read ONCE for the whole request rather than per key: neither the hidden closure nor the
2800
- # shared bucket can change under us mid-request, and both are whole-document reads.
2801
- hidden = _ut_hidden(session, table_key, declared)
2802
- # ⛔ AND THE LENIENT BRANCH REMEMBERS THAT IT FAILED, which the display reads on this
2803
- # assembly deliberately do not. An unreadable bucket that silently became `{}` would report a
2804
- # tenant-wide column as `unknown_field` — *"that column is not on this database"* — which is a
2805
- # confident false statement about a destructive act, and the person would go looking for who
2806
- # else deleted it. A read that did not happen answers "try again", not "it is not there".
2807
- bucket_read = True
2808
- try:
2809
- shared_defs = shared_overlay.fields(table_key, st=session.runtime) or {}
2810
- except Exception: # noqa: BLE001
2811
- shared_defs, bucket_read = {}, False
2812
-
2813
- results = []
2814
- landed = []
2815
- for key in ordered:
2816
- field = next((f for f in declared if str(f.get("key")) == key), None)
2817
- if field is None and isinstance(shared_defs.get(key), dict):
2818
- # A tenant-wide column lives in `<key>__shared`, a document the contract cannot see.
2819
- field = shared_defs[key]
2820
- if field is None:
2821
- results.append(_bulk_delete_refusal(
2822
- key, "unknown_field" if bucket_read else "delete_failed"))
2823
- continue
2824
- # ⭐⭐ W36-T21's wall, per key. An account that cannot SEE a column must not be able to
2825
- # delete it for the whole tenant. The sentence is delete-flavoured on purpose: the schema
2826
- # wall's own says "that you may edit", which would be the server explaining the wrong rule.
2827
- if key in hidden:
2828
- results.append(_bulk_delete_refusal(key, "field_hidden"))
2829
- continue
2830
- refusal = ut.delete_field_refusal(
2831
- table_key, key, session.uname, session.admin, session.runtime,
2832
- field=field, grant_topic=table_key)
2833
- if refusal is not None:
2834
- results.append({"key": key, "status": "refused", "code": refusal,
2835
- "reason": _delete_field_sentence(
2836
- refusal, str(field.get("createdBy") or ""))})
2837
- continue
2838
- # ⚠ ONE `try` PER KEY, and that is what makes partial success real rather than claimed: a
2839
- # store that fails on key 3 must not cost keys 4 and 5 their turn, and must not turn a
2840
- # request that already deleted keys 1 and 2 into a bare 500 the client will repeat.
2841
- try:
2842
- dropped = False
2843
- if key in contract_keys:
2844
- dropped = bool(ut.delete_field(table_key, key, st=session.runtime))
2845
- if not dropped and _contract_holds_field(ut, table_key, key, session.runtime):
2846
- results.append(_bulk_delete_refusal(key, "last_field"))
2847
- continue
2848
- removed = field_permissions.delete_field_everywhere(
2849
- f"{table_key}_table_workspace", table_key, table_key, key,
2850
- st=session.runtime)
2851
- except Exception: # noqa: BLE001
2852
- results.append(_bulk_delete_refusal(key, "delete_failed"))
2853
- continue
2854
- if not (dropped or removed.get("shared") or removed.get("personal")):
2855
- results.append(_bulk_delete_refusal(key, "delete_failed"))
2856
- continue
2857
- landed.append(key)
2858
- results.append({"key": key, "status": "deleted", "contract": dropped,
2859
- "removed": removed})
2860
-
2861
- if landed:
2862
- _refresh_relations(session)
2863
- return {"ok": True, "rerender": True, "results": results, "deleted": landed,
2864
- "refused": [r["key"] for r in results if r["status"] == "refused"]}
2865
-
2866
-
2867
  @router.delete("/tables/{table_key}/rows/{rid}")
2868
  def delete_row(table_key: str, rid: str, session: Session = Depends(require_session)):
2869
  # ⭐⭐ W31 QA — ONE SNAPSHOT FOR THE WHOLE DELETE, and the owner reported what it cost.
 
1050
  return rollup, automation
1051
 
1052
 
1053
+ def _field_usage(session, table_key, fields, defn, ops, st=None):
1054
  """`{field_key: {views, filters, rollups, automations, permRules}}` — C8's `usage`, computed
1055
  over the WHOLE workspace, or `{}` when it cannot be established.
1056
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1057
  ⭐⭐ W41-T10 / R3 / C8. The `done-when`'s load-bearing clause is *"over the whole workspace,
1058
  not from a partial client list"*: the assembly's own `ws` holds this caller's stratum merged
1059
  with the views shared TO them, so a count taken from it would miss every private view every
 
1099
  return {}
1100
  lent = st if st is not None else session.runtime
1101
  memo_key = (str(getattr(session, "tenant", "") or ""), str(table_key))
1102
+ token = _usage_token(lent, ops.table_key)
1103
  if token is not None:
1104
  hit = _USAGE_MEMO.get(memo_key)
1105
  if hit and hit[0] == token:
1106
  return hit[1]
1107
  try:
1108
+ # ⚠ `ops.st` and `ops.table_key`, not a rebuilt literal: the store key `_ops` closed over
1109
+ # is the one this database's strata actually live under, and a second spelling of the
1110
+ # suffix is a second thing to keep in step. A lend passes `<key>_table_workspace` straight
1111
+ # through to the runtime (it serves only `user_tables` and `object_shares`), so this is
1112
+ # the tenant's own document.
1113
+ ws_doc = ops.st.get(ops.table_key) or {}
1114
  except Exception: # noqa: BLE001
1115
  return {}
1116
  try:
 
1263
  # lines and for the same reason: the closure must be recomputed on the MERGED contract or a
1264
  # formula in a shared column reaches past it.
1265
  fields = _ut_shared_fields(session, table_key, fields)
1266
+ # W43C C2: store compact recurrence configuration, then derive next/preview under the
1267
+ # request's server day only after every field stratum is merged.
1268
+ _recurrence_today = time.strftime("%Y-%m-%d")
1269
+
1270
+ def _wire_recurrence(field):
1271
+ if not isinstance(field, dict) or field.get("type") != "date":
1272
+ return field
1273
+ payload = aios_grid.recurrence_payload(field.get("recurrence"), today=_recurrence_today)
1274
+ return dict(field, recurrence=payload) if payload else field
1275
+
1276
+ fields = [_wire_recurrence(field) for field in fields]
1277
  # ⭐⭐ W41-T10 / RULING R3 / CONTRACT C8 — **`usage`, STAMPED ONCE, HERE.**
1278
  #
1279
  # ⛔ IN THE ASSEMBLY AND ON BOTH ARMS, WHICH IS NOT THE CHEAP CHOICE AND IS THE ONLY CORRECT
 
1296
  # `dict(f, source=…)` copies for the shared stratum but passes the rest through by reference,
1297
  # and `_usage_field_corpus` hands those same objects back. Mutating one would write a count
1298
  # into a definition the next reader shares.
1299
+ # ⛔ AND ONLY `usage`. `class` shipped with W41-T01, `agg` belongs to lanes B and D and
1300
+ # `descriptionEdited` to W41-T11; C8 is explicit that an absent key means "not built yet".
 
 
 
 
 
 
1301
  #
1302
  # ⚠ LENIENT, LIKE EVERY OTHER DISPLAY READ ON THIS ASSEMBLY, and C8's absent-key polarity is
1303
  # what makes degrading safe: a client renders nothing for a missing `usage` rather than a
 
1306
  # ⚠ A COPY OF THE BAG, because `_field_usage` MEMOISES its answer: handing the memo's own dict
1307
  # out would let anything downstream write into the number the next request reads.
1308
  try:
1309
+ _usage = _field_usage(session, table_key, fields, defn, ops, st=st)
 
1310
  except Exception: # noqa: BLE001
1311
  _usage = {}
1312
  if _usage:
1313
  fields = [dict(f, usage=dict(_usage[f["key"]]))
1314
  if isinstance(f, dict) and _usage.get(f.get("key")) else f
1315
  for f in fields]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1316
  # ⭐⭐ C8's `descriptionEdited`, AND IT CLOSES A CONSUMER THAT WAS ALREADY WRITTEN.
1317
  # W41-T11 built the producer (`user_tables.description_edited`, R19's custody mark scoped to the
1318
  # description) and correctly stopped at its own fence, which is one core file. Measured across
 
1351
  # whose entity topic declares a `measures:` binding (today `ut_odoo_agents`) serves a real
1352
  # lookback catalogue AND the cells to go with it; every other user table still serves `[]`,
1353
  # which is the honest answer for a hand-typed one rather than a descope.
1354
+ today = _recurrence_today
1355
  measures = ut_measures(table_key, session)
1356
  derived = aios_grid.cohort_cells(lists) # R9: this table's own lists
1357
  for _pid, _cells in _ut_measure_cells(table_key, fields, pids, today, measures,
 
2127
  # missing key has been silently switching the feature off. ⛔ ONE shared serialiser with the
2128
  # customer scope — `grid_events.docs_for` — never a twin here.
2129
  from core import grid_events as _ge
2130
+ # Zone memberships are row identities and therefore pass through the same row wall as the
2131
+ # rows themselves. A map reader cannot infer a hidden record from a saved zone boundary.
2132
+ _zone_pids = {str(pid) for pid in g["pids"]}
2133
+ _zones = [dict(zone, memberships=[pid for pid in zone.get("memberships", [])
2134
+ if str(pid) in _zone_pids])
2135
+ for zone in _ut().zones(table_key, st=_lent)]
2136
  return {"fields": g["fields"], "rows": rows, "today": g["today"],
2137
+ "zones": _zones,
2138
  "docs": _ge.docs_for(g["pids"], scope_key=table_key, uname=session.uname,
2139
  admin=session.admin, st=session.runtime),
2140
  "pulled_at": time.strftime("%Y-%m-%d %H:%M"),
 
2435
  def _refusal_sentence(ut, session, body, table_key="", fkey=""):
2436
  """Why was this column refused? The specific reason when we can name one, the general list
2437
  otherwise — never a specific-sounding guess."""
 
 
 
 
 
2438
  # ⭐ WAVE-34 (R13): the enrichment column's own sentence, named BEFORE the automation bag
2439
  # below. `_clean_field` DERIVES `field.automation` for this kind, so a refused enrichment
2440
  # column would otherwise be explained by the flow law -- "pick a flow, or make this an
 
2513
  migrated = dict(migrated or {}, workspace=True)
2514
  except Exception: # noqa: BLE001
2515
  migrated = dict(migrated or {}, workspace=False)
2516
+ field = ut.patch_field(table_key, fkey, body, st=session.runtime)
 
 
 
 
2517
  if not field:
2518
  # C3: the same narrator as `add_field`. Flagging a SECOND column is the same act as
2519
  # adding one, so it must get the same sentence naming the column that already holds the
 
2525
  field = synced.get("field") or field
2526
  _refresh_relations(session)
2527
  out = {"field": field}
 
 
2528
  # ⭐⭐ W41-T15 / C5 — the same report `add_field` carries, on the door that RETARGETS a link.
2529
  # This one matters more: pointing an existing link at `customer_data` deletes the backlink the
2530
  # old target held (the stale-inverse sweep) and cannot make a new one, so the column silently
 
2624
  return {"deleted": fkey}
2625
 
2626
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2627
  @router.delete("/tables/{table_key}/rows/{rid}")
2628
  def delete_row(table_key: str, rid: str, session: Session = Depends(require_session)):
2629
  # ⭐⭐ W31 QA — ONE SNAPSHOT FOR THE WHOLE DELETE, and the owner reported what it cost.
platform/aios_grid.py CHANGED
@@ -23,6 +23,7 @@ Design notes:
23
  into the React app and returns guarded events for persistence in the tenant store. The old
24
  injected-HTML path remains a read/local-write fallback when component assets are absent.
25
  """
 
26
  import json
27
  import math
28
  import re
@@ -339,92 +340,9 @@ def _clean_permissions(raw):
339
  #: drift risk this file's docstring names. The charset says which characters may appear; the
340
  #: engine says what they mean. `_quotes_balanced` below is the one structural rule the quote
341
  #: character brings with it.
342
- #: ⭐⭐ WAVE 42 G7 (2026-08-25) — THE SAME SCAR, WIDENED IN THE SAME CHANGE THIS TIME.
343
- #:
344
- #: The client engine gained REGEX_EXTRACT, REGEX_REPLACE, SUBSTITUTE, FIND, SWITCH, DATEADD,
345
- #: DATETIME_DIFF and DATETIME_FORMAT. Each added character below is admitted because a token
346
- #: the client's tokenizer parses would otherwise die here:
347
- #:
348
- #: ' a SINGLE-QUOTED literal. Airtable's own documentation spells every unit and date
349
- #: format that way -- DATETIME_DIFF({a}, {b}, 'days') -- and a user pastes what the
350
- #: documentation prints. Without this, EVERY date function is refused on save.
351
- #: [ ] a regex character class, the commonest construct there is: "[0-9]+".
352
- #: | regex alternation.
353
- #: ? regex optional, and the non-capturing group "(?:...)".
354
- #: \ regex escapes: \d \s \. \w.
355
- #: : "(?:...)", and a class such as "[a-z:]".
356
- #: @ SUBSTITUTE/FIND over an email or a URL, the canonical use of both.
357
- #:
358
- #: ⚠ AND THREE THAT THE EIGHT DO NOT NEED, admitted because they are the SAME BUG already
359
- #: sitting here unnoticed: `textFormat` in the client accepts "#,##0", "$#,##0.00" and "0%",
360
- #: so `TEXT({x}, "0%")` parses client-side and is refused here TODAY. That is the 2026-08-03
361
- #: failure still live for three format shapes, so:
362
- #: # $ % the TEXT() number formats the client already implements. ($ doubles as the regex
363
- #: end-anchor and % as a literal in text, so all three earn their place twice.)
364
- #:
365
- #: ⛔ `;` STAYS REFUSED, and the fields-contract gate asserts it. Nothing in the grammar needs
366
- #: a statement separator, and it is the shape an injection attempt takes.
367
- _FORMULA_CHARS = re.compile(r"^[\w\s{}()+\-*/.,<>=!^&\"'\[\]|?:\\#$%@]*$")
368
  _FORMULA_REF = re.compile(r"\{([^{}]*)\}")
369
 
370
- #: Longest single string literal a formula may carry. A regex pattern is a string literal, and
371
- #: an unbounded pattern reaching a regex engine in the tenant's ONE process is a denial of
372
- #: service rather than a slow cell. 200 inside a 500-character formula is far above honest use.
373
- MAX_FORMULA_LITERAL_LEN = 200
374
-
375
- #: The catastrophic-backtracking SHAPE: a group whose body already carries an unbounded
376
- #: quantifier, quantified again -- `(a+)+`, `(a*)*`, `(?:\d+)*`.
377
- #:
378
- #: ⛔ IT IS APPLIED TO STRING LITERALS ONLY, NEVER TO THE WHOLE EXPRESSION. `({a} + {b}) * 2`
379
- #: has exactly this character shape and is ordinary arithmetic; scanning the whole source would
380
- #: refuse it.
381
- #:
382
- #: ⚠ AND IT IS A STATIC, EARLY refusal, not the guarantee. A pattern assembled at run time --
383
- #: `REGEX_EXTRACT({a}, "(x" & "+)+")`, or a pattern read out of another field -- is invisible
384
- #: to any check here. The LOAD-BEARING bound is the client's `safeRegex`, which sees the actual
385
- #: pattern at evaluation time and caps the SUBJECT too. This wall stops the obvious one early
386
- #: and cheaply; it does not pretend to be the wall.
387
- _NESTED_QUANT = re.compile(r"\((?:[^()\\]|\\.)*[*+](?:[^()\\]|\\.)*\)\??\s*[*+]")
388
-
389
-
390
- def _string_literals(s):
391
- """Every string literal's BODY, in order, or None if one is unterminated.
392
-
393
- Mirrors the client tokenizer exactly: `"..."` and `'...'` are the same literal in two
394
- spellings, a DOUBLED quote of the opening kind is one character of body, and a quote of the
395
- OTHER kind inside is ordinary text. That last part is why this is a scanner and not a parity
396
- count: `"Owner's report"` is one literal containing an apostrophe, and counting `'` would
397
- refuse it.
398
-
399
- ⚠ This is NOT the second grammar the module refuses to write. It answers one question --
400
- where does a literal begin and end -- which is the same structural question `_quotes_balanced`
401
- and the `{ref}` scan already answer. It assigns no MEANING to anything it finds.
402
- """
403
- out = []
404
- i = 0
405
- n = len(s)
406
- while i < n:
407
- ch = s[i]
408
- if ch not in ('"', "'"):
409
- i += 1
410
- continue
411
- j = i + 1
412
- body = []
413
- while True:
414
- if j >= n:
415
- return None # unterminated
416
- if s[j] == ch:
417
- if j + 1 < n and s[j + 1] == ch:
418
- body.append(ch)
419
- j += 2
420
- continue
421
- break
422
- body.append(s[j])
423
- j += 1
424
- out.append("".join(body))
425
- i = j + 1
426
- return out
427
-
428
 
429
  def _quotes_balanced(s):
430
  """An even number of `"` — the structural half of string support.
@@ -519,32 +437,6 @@ def _clean_formula(raw, valid_keys=None):
519
  return None
520
  if not _quotes_balanced(s):
521
  return None
522
- # ⭐⭐ WAVE 42 G7 — the regex bound, and it runs at READ TIME TOO, deliberately.
523
- #
524
- # Every other refusal in this function is split write/read because a `{ref}`'s validity
525
- # CHANGES with the world: a column referenced today can be deleted tomorrow, and refusing
526
- # then would vaporise a stored column. A string literal's SHAPE is intrinsic to the
527
- # expression and cannot become invalid later, so there is no stored-and-later-invalid case
528
- # for the split to protect. Applying it both ways is what makes it reach the user-tables
529
- # door, which calls this validator with `valid_keys=None` on WRITE as well as on read
530
- # (core/user_tables.py::_clean_field) -- a write-only gate would simply miss `ut_*`.
531
- #
532
- # ⚠ THE TWO LEGS ARE SCOPED DIFFERENTLY, and the difference is data loss.
533
- # The SHAPE test is safe everywhere: no formula written before today contains `"(a+)+"`,
534
- # so it can only fire on something new. The LENGTH cap is not: a formula stored yesterday
535
- # could carry a 250-character message literal and still sit under MAX_FORMULA_LEN, and
536
- # refusing it at read time does not blank a cell -- `user_tables` drops the whole COLUMN.
537
- # So the cap applies only where a literal can BE a pattern, which is a formula that names
538
- # a regex function at all. That is a substring test, not a second grammar.
539
- literals = _string_literals(s)
540
- if literals is None:
541
- return None
542
- regexy = 'REGEX_' in s.upper()
543
- for lit in literals:
544
- if regexy and len(lit) > MAX_FORMULA_LITERAL_LEN:
545
- return None
546
- if _NESTED_QUANT.search(lit):
547
- return None
548
  refs = _FORMULA_REF.findall(s)
549
  leftover = _FORMULA_REF.sub("", s)
550
  if "{" in leftover or "}" in leftover: # unbalanced / nested braces
@@ -602,6 +494,198 @@ def _clean_geocode(raw):
602
  return out
603
 
604
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
605
  def _field_extras(saved, ftype):
606
  """createdBy / permissions / format / scope — the validated passthrough the created strata
607
  share (wave 5). `createdBy` is only ever WRITTEN host-side (the handler stamps it); here it
@@ -642,6 +726,12 @@ def _field_extras(saved, ftype):
642
  geo = _clean_geocode(saved.get("geocode"))
643
  if geo:
644
  out["geocode"] = geo
 
 
 
 
 
 
645
  corrected_from = saved.get("labelCorrectedFrom")
646
  correction_id = saved.get("labelCorrectionId")
647
  if (isinstance(corrected_from, str) and corrected_from.strip()
@@ -715,152 +805,6 @@ def cohort_cells(cohorts, allowed_pids=None):
715
  return {pid: {COHORT_COLUMN: ', '.join(names)} for pid, names in cells.items()}
716
 
717
 
718
- # --- W42-T20: THE ROUTE PROJECTION COLUMN (owner instructions 7 + 19, R9/R20/R23, C11) -------
719
- #
720
- # ⭐⭐ THE SHAPE IS `cohort_field` / `cohort_cells`, FLAG FOR FLAG, AND THAT IS DELIBERATE: the
721
- # grouping behaviour this column exists for is FREE only in that shape. `useVisibleRows::groupRows`
722
- # fans a row out per element for a `multi` (or `multiselect`) field and it does so with
723
- # `cell.split(",")`, so the value is a COMMA-JOINED STRING and nothing else can be substituted.
724
- #
725
- # ⛔⛔ THE KEY IS NOT DECLARED HERE, IT IS PASSED IN. C11 fixes the literal at
726
- # `routes_customers.ROUTE_PROJECTION_KEY`, because `_mark_offerability` exempts this column BY KEY
727
- # and two spellings of one key is the failure C11 was written about. `platform/` cannot import the
728
- # API layer (layers point one way), so the caller hands the key down rather than this module
729
- # holding a second copy of it.
730
- #
731
- # ⛔⛔ AND THE APPEND IS NOT HERE EITHER. `fields_from_workspace` appends `cohort_field()` for every
732
- # grain that calls it, PRODUCT GRIDS INCLUDED; this column is appended by exactly one caller,
733
- # `routes_customers.grid_assembly`. That absence of a call is the mechanism by which `product_data`
734
- # does not offer this column at all: nothing on that grain builds route definitions and nothing on
735
- # that grain calls either of these two functions.
736
-
737
-
738
- def _route_label(fkey, defn):
739
- """The route's name AS THE CELL SHOWS IT, which is the name minus any comma.
740
-
741
- ⚠ The COMMA is the separator the client splits on to group a record into every route it is
742
- on, so it cannot also occur inside a name. Route labels are free text ("North loop, Tuesday"
743
- is a name somebody will type), so a comma is replaced here rather than left to break the split
744
- silently: one group called "North loop" and another called "Tuesday" would be two routes that
745
- do not exist. The cost is cosmetic and confined to the cell; the route listing still shows the
746
- name the person typed.
747
- """
748
- return str((defn or {}).get('label') or fkey or '').replace(',', ' ').strip()
749
-
750
-
751
- def route_projection_field(key, defs=None, label='Routes'):
752
- """The derived column listing the routes a record is on, one descriptor per request.
753
-
754
- ⭐ `source: 'odoo'` is doing the same ONE job it does on `cohort_field` and it is not
755
- provenance: the client keys editability off `source == 'overlay'` and `_cl_handle_grid_event`
756
- accepts cell writes only for overlay keys, so 'odoo' is what makes this column READ-ONLY at
757
- both ends. It is a mechanism and not a UI decision, which is why it is stated here rather than
758
- left to a renderer. `derived: True` stops the column menu calling it a source field.
759
-
760
- ⚠ IT IS PRE-SET IN THE SENSE THAT NO PERSON MADE IT, AND THAT IS NOT A BADGE ON THE WIRE.
761
- The descriptor carries no `createdBy`, which is what `field_permissions.field_origin` WOULD
762
- answer `"preset"` from -- and it is never asked, because the one caller appends this column
763
- AFTER the badge pass (`class`), after `usage` and after `offerable`, so the served entry
764
- carries none of those three keys. Each of them is absent-means-nothing by design, so a client
765
- renders no badge rather than a wrong one. The clause a reader should observe for read-only-ness
766
- is `source != 'overlay'`, above, which is a mechanism both ends already enforce.
767
-
768
- ⚠ `filterable: False`, for `cohort_field`'s reason exactly. Text ops over a joined string
769
- almost work and disagree at the edges (`contains "North"` also matches "North loop extra"),
770
- and a filter that is nearly right is worse than one that is absent. ⛔ THAT DOES NOT CONTRADICT
771
- `routeOwners`: the replacement is a CONDITION (`Where [Route author] ...`) reading the map
772
- below, exactly as `cohort_field`'s replacement is the `Where [Cohort]` condition and not a text
773
- op on its own joined string.
774
-
775
- ⭐⭐ `routeOwners` IS THE SIDE CHANNEL FOR `createdBy`, AND ITS DERIVATION RULE IS PART OF THE
776
- CONTRACT. Each cell entry is `<label> - <position>`, so the author cannot be written into the
777
- entry without changing the format the owner asked for. It rides beside it instead, as
778
- `{<label as it appears in the cell>: <createdBy>}`. A reader recovers the label from an entry
779
- by stripping a trailing ` - <digits>` ANCHORED AT THE END (`/ - \\d+$/`): a position is always
780
- digits, so that stays exact even for a route whose own name contains " - ". Named here so the
781
- later filter ticket reads THIS key instead of inventing a second one, which is
782
- [[two-lanes-one-contract-dead-feature]] with a map instead of a flag.
783
-
784
- ⚠ TWO ROUTES WITH ONE LABEL RESOLVE TO NO AUTHOR RATHER THAN TO THE WRONG ONE. The map is
785
- keyed by what the cell shows, and a duplicate label cannot name one author; a filter offering
786
- a confident wrong name is worse than one offering none.
787
-
788
- ⚠ THE MAP IS BUILT FROM THE **WALLED** defs the caller passes, so it can never name a route
789
- this viewer was not granted. Absent when empty, so a viewer with no grants receives no map at
790
- all rather than an empty one to reason about.
791
- """
792
- owners = {}
793
- for fkey, defn in (defs or {}).items():
794
- name = _route_label(fkey, defn)
795
- who = str((defn or {}).get('createdBy') or '').strip()[:80]
796
- if name in owners and owners[name] != who:
797
- owners[name] = ''
798
- else:
799
- owners.setdefault(name, who)
800
- return {
801
- 'key': key, 'label': label, 'type': 'text', 'source': 'odoo',
802
- 'default': False, 'filterable': False, 'derived': True, 'multi': True,
803
- 'note': 'Every saved route this customer is a stop on, written as "Route name - position" '
804
- 'and sorted by route name. A route holds a SET of stops, so grouping by this '
805
- 'column puts a customer under EVERY route they are on, and the group counts '
806
- 'therefore add up to more than the record count, which stays the number of '
807
- 'distinct customers. It names only the routes you have been granted. Read-only: '
808
- 'a position changes only when somebody plans that route again.',
809
- **({'routeOwners': owners} if owners else {}),
810
- }
811
-
812
-
813
- def route_projection_cells(key, defs, shared, pids):
814
- """`{pid: {key: 'North loop - 3, South loop - 11'}}` for the rows named by `pids`.
815
-
816
- `defs` is `{route_key: definition}` ALREADY NARROWED BY THE VIEWER'S GRANT WALL, and that
817
- narrowing is the whole security property: ORing across every route on the tenant would tell a
818
- reader that a route they hold no grant on exists ([[enriching-a-wall-leaks-what-it-judges]]).
819
- This function projects what it is given and never widens it, so the wall is testable by handing
820
- it walled defs and then unwalled defs and comparing the two answers.
821
-
822
- Built per render from the CALLER'S OWN walled view and handed to `rows_from_pool` as `derived`,
823
- never merged into the cached pool rows: those are shared across users and carry no `uname`, so
824
- stamping one viewer's route visibility onto them would serve it to everybody else on the next
825
- render.
826
-
827
- ⚠ `shared` IS STRING-KEYED AND THE RESULT IS INT-KEYED, because the two dicts are read by
828
- different halves of `rows_from_pool` (`overlays.get(str(pid))` against `derived.get(pid)`).
829
- Inverting them yields a blank column, which is indistinguishable from the grant wall working.
830
-
831
- ⚠ `pids` IS THE ROW WALL, INHERITED. It is the set the caller has already narrowed with
832
- `apply_row_scope`, so iterating it rather than the cells dict means a route stop belonging to
833
- the other business unit has no row to attach itself to.
834
-
835
- ⚠ A record on no visible route gets NO ENTRY, not an empty one: `rows_from_pool` already writes
836
- `''` for a derived key it has no value for, and `is empty` on a text column is the question
837
- somebody will ask of it.
838
- """
839
- order = sorted((defs or {}).items(),
840
- key=lambda kv: (_route_label(kv[0], kv[1]).lower(), str(kv[0])))
841
- out = {}
842
- for pid in (pids or ()):
843
- cells = (shared or {}).get(str(pid)) or {}
844
- parts = []
845
- for fkey, defn in order:
846
- # ⛔⛔ THE MEMBERSHIP TEST IS `_patch_route_ranks::_held`'s, CLAUSE FOR CLAUSE, AND IT
847
- # IS NOT MERELY "NON-EMPTY". That function skips `None` and `''` and then does
848
- # `int(str(cell).strip())` inside a `try`, so a cell holding junk is NOT a stop. Read
849
- # off the code rather than off the prose, because two spellings of one membership rule
850
- # is [[two-lanes-one-contract-dead-feature]] with a predicate instead of a key: the
851
- # looser one here would paint `North loop - False` on a row the route planner and the
852
- # write door both agree is not on that route. There is no reverse index to check it
853
- # against either -- `route.stops` is a COUNT, not a pid list.
854
- try:
855
- rank = int(str(cells.get(fkey)).strip())
856
- except (TypeError, ValueError):
857
- continue
858
- parts.append(_route_label(fkey, defn) + ' - ' + str(rank))
859
- if parts:
860
- out[pid] = {key: ', '.join(parts)}
861
- return out
862
-
863
-
864
  def clean_measure_field(raw, offered):
865
  """Validate one UNTRUSTED formula-measure field (owner item 7) against the caller's OFFER.
866
 
@@ -1050,11 +994,6 @@ def fields_from_workspace(workspace=None, cohorts=False, scope_key=None, fields_
1050
  continue
1051
  options = (_clean_options(field.get("options"))
1052
  if ftype in ("select", "multiselect") else [])
1053
- if ftype in ("select", "multiselect") and not options:
1054
- # A select with no surviving choices can never hold a value. Dropping the COLUMN
1055
- # would lose the user's data; degrading it to text keeps every stored value
1056
- # readable and lets them re-add choices.
1057
- ftype = "text"
1058
  out.append({
1059
  "key": str(key)[:80],
1060
  "label": str(field.get("label") or "Untitled")[:120],
@@ -1067,6 +1006,9 @@ def fields_from_workspace(workspace=None, cohorts=False, scope_key=None, fields_
1067
  # silent half of this feature.
1068
  "agg": field.get("agg") if field.get("agg") in FIELD_AGGS else None,
1069
  "note": str(field.get("note") or "")[:2000],
 
 
 
1070
  **({"options": options} if ftype in ("select", "multiselect") else {}),
1071
  **(_choice_appearance(field, options)
1072
  if ftype in ("select", "multiselect") else {}),
@@ -2176,37 +2118,7 @@ def _clean_display(raw, valid_keys):
2176
  #: id happened to be 'folders'. (2) Folder placement is a per-user ORGANISING act, not part of
2177
  #: what a view IS: keeping it out of the view config means duplicating or exporting a view does
2178
  #: not drag a folder reference along with it. One map, one home, both surfaces.
2179
- #: ⭐⭐ W42-T23 / AMENDMENT A21 — `routes` IS THE THIRD SURFACE, AND WIDENING THIS SET IS THE
2180
- #: WHOLE OF THE STORE-SIDE CHANGE. Both `clean_folders` and `clean_item_folders` iterate exactly
2181
- #: this set and DROP anything outside it, and `core/grid_events.py` refuses a folder event whose
2182
- #: `surface` is not in it (`surface_unknown`). So before this line a route's placement could not
2183
- #: be written, could not be read back, and the write door said the sidebar did not exist. One
2184
- #: constant, three refusals.
2185
- #: ⚠ THE VIEWS RAIL IS UNTOUCHED BY THIS, and it was checked rather than assumed:
2186
- #: `workspace_wire` folds ONLY the literal `'cohorts'` surface into `views` at serve time (it
2187
- #: names the string, it does not iterate this set), and it emits `_folders['views']` alone. A
2188
- #: routes folder is therefore invisible to the views rail by construction, not by luck.
2189
- FOLDER_SURFACES = {"views", "cohorts", "routes"}
2190
-
2191
- #: ⛔⛔ SURFACES WHOSE ITEMS ARE TENANT-WIDE, SO "IS THIS ITEM YOURS" HAS NO ANSWER TO GIVE.
2192
- #:
2193
- #: `clean_item_folders` drops a placement whose ITEM is not in the caller-supplied `valid_ids`.
2194
- #: That test is right for views and cohorts, which are per-user objects. A route-order column is
2195
- #: tenant-wide (`routes_customers.ROUTE_KEY_PREFIX`'s own note: the other two created-column
2196
- #: namespaces are per user, "this one is tenant-wide"), so no per-user id set describes it.
2197
- #:
2198
- #: ⛔ AND THE EXEMPTION IS LOAD-BEARING, NOT TIDINESS. `grid_events`'s `_own_ids(surface, ws)`
2199
- #: reads `if sfc == 'views': ... return cohorts` — an ELSE, not a lookup. The moment `routes`
2200
- #: joined the set above, every folder event on ANY surface began handing this function the
2201
- #: caller's COHORT ids as the legal item set for `routes`, and a route key is never a cohort id.
2202
- #: Every stored route placement would have been silently erased by the next unrelated folder
2203
- #: rename, and the drag that wrote it would have reported success. `grid_events.py` is not this
2204
- #: ticket's to edit; the surface it asks about is, so the answer is given here.
2205
- #:
2206
- #: ⚠ Nothing is fail-open: a placement on an exempt surface must STILL name a folder that exists
2207
- #: (or `ROOT_PLACEMENT`), and its reader re-resolves the route key against the columns that
2208
- #: reader may actually see. What is skipped is the ownership test alone.
2209
- FOLDER_SURFACES_TENANT_WIDE = {"routes"}
2210
  MAX_FOLDERS = 60
2211
  MAX_FOLDER_NAME = 80
2212
 
@@ -2399,12 +2311,8 @@ def clean_item_folders(raw, folders, valid_ids):
2399
  # scrubbed here on the way back out, so the mark would be stored and instantly lost:
2400
  # the two halves are ONE change and shipping either alone is worse than shipping
2401
  # neither ([[lost-write-looks-like-failed-read]]).
2402
- # ⭐⭐ W42-T23 — THE OWNERSHIP TEST IS SKIPPED ON A TENANT-WIDE SURFACE. See
2403
- # `FOLDER_SURFACES_TENANT_WIDE` for why it has to be, and for what it does not relax:
2404
- # the folder must still exist, or be the deliberate `ROOT_PLACEMENT`.
2405
- owned = (surface in FOLDER_SURFACES_TENANT_WIDE
2406
- or item_id in (valid_ids or {}).get(surface, ()))
2407
- if owned and (fid == ROOT_PLACEMENT or fid in fids):
2408
  ok[item_id[:120]] = fid
2409
  if ok:
2410
  out[surface] = ok
@@ -2576,6 +2484,17 @@ def clean_filter_tree(raw, valid_keys, depth=1, budget=None, cohort_ids=None,
2576
  # free of the date vocabulary it would otherwise have to keep in step.
2577
  if isinstance(mode, str) and 0 < len(mode) <= 40:
2578
  leaf['dateMode'] = mode
 
 
 
 
 
 
 
 
 
 
 
2579
  rhs = _clean_rhs(node.get('rhs'), valid_keys)
2580
  if rhs is not None:
2581
  leaf['rhs'] = rhs
@@ -2583,6 +2502,31 @@ def clean_filter_tree(raw, valid_keys, depth=1, budget=None, cohort_ids=None,
2583
  return out
2584
 
2585
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2586
  def _is_default_visible(field):
2587
  """Does this column open SHOWN in a view that has never recorded its own `visible`?
2588
 
 
23
  into the React app and returns guarded events for persistence in the tenant store. The old
24
  injected-HTML path remains a read/local-write fallback when component assets are absent.
25
  """
26
+ import datetime as _dt
27
  import json
28
  import math
29
  import re
 
340
  #: drift risk this file's docstring names. The charset says which characters may appear; the
341
  #: engine says what they mean. `_quotes_balanced` below is the one structural rule the quote
342
  #: character brings with it.
343
+ _FORMULA_CHARS = re.compile(r"^[\w\s{}()+\-*/.,<>=!^&\"]*$")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
  _FORMULA_REF = re.compile(r"\{([^{}]*)\}")
345
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
 
347
  def _quotes_balanced(s):
348
  """An even number of `"` — the structural half of string support.
 
437
  return None
438
  if not _quotes_balanced(s):
439
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
440
  refs = _FORMULA_REF.findall(s)
441
  leftover = _FORMULA_REF.sub("", s)
442
  if "{" in leftover or "}" in leftover: # unbalanced / nested braces
 
494
  return out
495
 
496
 
497
+ # --- DATE RECURRENCE ---------------------------------------------------------
498
+ # A date cell remains an ISO scalar. Its optional field recurrence is a separate, explicit
499
+ # configuration bag: persisting a JavaScript Date, locale label, or a client-computed next value
500
+ # would make an identical record mean different things to two hosts. The host computes the
501
+ # next occurrence and preview at projection time from this compact, durable shape.
502
+ _RECURRENCE_KINDS = frozenset({'daily', 'weekly', 'monthly', 'yearly', 'holiday'})
503
+ _PUBLIC_HOLIDAY_CALENDARS = frozenset({'US'})
504
+
505
+
506
+ def _iso_day(value):
507
+ if isinstance(value, _dt.datetime):
508
+ value = value.date()
509
+ if isinstance(value, _dt.date):
510
+ return value
511
+ if not isinstance(value, str):
512
+ return None
513
+ try:
514
+ return _dt.date.fromisoformat(value.strip()[:10])
515
+ except ValueError:
516
+ return None
517
+
518
+
519
+ def _observed(day):
520
+ """US federal-observed day: Saturday -> Friday, Sunday -> Monday."""
521
+ if day.weekday() == 5:
522
+ return day - _dt.timedelta(days=1)
523
+ if day.weekday() == 6:
524
+ return day + _dt.timedelta(days=1)
525
+ return day
526
+
527
+
528
+ def _nth_weekday(year, month, weekday, nth):
529
+ day = _dt.date(year, month, 1)
530
+ shift = (weekday - day.weekday()) % 7
531
+ return day + _dt.timedelta(days=shift + 7 * (nth - 1))
532
+
533
+
534
+ def _last_weekday(year, month, weekday):
535
+ if month == 12:
536
+ day = _dt.date(year + 1, 1, 1) - _dt.timedelta(days=1)
537
+ else:
538
+ day = _dt.date(year, month + 1, 1) - _dt.timedelta(days=1)
539
+ return day - _dt.timedelta(days=(day.weekday() - weekday) % 7)
540
+
541
+
542
+ def public_holidays(calendar, year):
543
+ """The supported public holiday calendar, returned as deterministic ISO-day objects.
544
+
545
+ US federal holidays are intentionally calculated locally rather than fetched from a public
546
+ endpoint during a render: a recurrence must keep its answer during an outage and historical
547
+ previews must not move when a third party updates a feed. The field accepts other ISO
548
+ country codes for forward compatibility, but an unavailable calendar yields no candidates
549
+ rather than pretending it is the US calendar.
550
+ """
551
+ if str(calendar or '').upper() not in _PUBLIC_HOLIDAY_CALENDARS:
552
+ return frozenset()
553
+ days = {
554
+ _observed(_dt.date(year, 1, 1)),
555
+ _nth_weekday(year, 1, 0, 3), # Martin Luther King Jr. Day
556
+ _nth_weekday(year, 2, 0, 3), # Washington's Birthday
557
+ _last_weekday(year, 5, 0), # Memorial Day
558
+ _observed(_dt.date(year, 7, 4)),
559
+ _nth_weekday(year, 9, 0, 1), # Labor Day
560
+ _nth_weekday(year, 10, 0, 2), # Columbus Day
561
+ _observed(_dt.date(year, 11, 11)),
562
+ _nth_weekday(year, 11, 3, 4), # Thanksgiving
563
+ _observed(_dt.date(year, 12, 25)),
564
+ }
565
+ # Juneteenth became a federal holiday in 2021; earlier recurrence previews must not
566
+ # retroactively invent it.
567
+ if year >= 2021:
568
+ days.add(_observed(_dt.date(year, 6, 19)))
569
+ return frozenset(days)
570
+
571
+
572
+ def clean_date_recurrence(raw):
573
+ """One date field's recurrence config, or ``None`` for absent/malformed input.
574
+
575
+ ``rules`` are an intentional union: selecting weekday + public holiday means either makes
576
+ a valid next date. The stored config carries neither a process clock nor generated preview;
577
+ those derived values belong to ``recurrence_payload`` and are evaluated by the server.
578
+ """
579
+ if not isinstance(raw, dict):
580
+ return None
581
+ start = _iso_day(raw.get('startDate', raw.get('anchor')))
582
+ if start is None:
583
+ return None
584
+ out_rules = []
585
+ for raw_rule in list(raw.get('rules') or [])[:12]:
586
+ if not isinstance(raw_rule, dict):
587
+ continue
588
+ kind = str(raw_rule.get('kind') or '').lower()
589
+ if kind not in _RECURRENCE_KINDS:
590
+ continue
591
+ interval = raw_rule.get('interval', 1)
592
+ if not isinstance(interval, int) or isinstance(interval, bool) or not 1 <= interval <= 366:
593
+ continue
594
+ rule = {'kind': kind, 'interval': interval}
595
+ if kind == 'weekly':
596
+ weekdays = sorted({day for day in (raw_rule.get('weekdays') or [])
597
+ if isinstance(day, int) and not isinstance(day, bool)
598
+ and 0 <= day <= 6})
599
+ rule['weekdays'] = weekdays or [start.weekday()]
600
+ elif kind == 'monthly':
601
+ day = raw_rule.get('day', start.day)
602
+ if not isinstance(day, int) or isinstance(day, bool) or not 1 <= day <= 31:
603
+ continue
604
+ rule['day'] = day
605
+ elif kind == 'yearly':
606
+ month, day = raw_rule.get('month', start.month), raw_rule.get('day', start.day)
607
+ if (not isinstance(month, int) or isinstance(month, bool) or not 1 <= month <= 12
608
+ or not isinstance(day, int) or isinstance(day, bool) or not 1 <= day <= 31):
609
+ continue
610
+ # Validate the month/day without reinterpreting 29 February.
611
+ try:
612
+ _dt.date(2024, month, day)
613
+ except ValueError:
614
+ continue
615
+ rule.update({'month': month, 'day': day})
616
+ elif kind == 'holiday':
617
+ calendar = str(raw_rule.get('calendar') or 'US').strip().upper()
618
+ if not re.fullmatch(r'[A-Z]{2}', calendar):
619
+ continue
620
+ offset = raw_rule.get('offset', 0)
621
+ if not isinstance(offset, int) or isinstance(offset, bool) or offset not in (-1, 0, 1):
622
+ continue
623
+ rule.update({'calendar': calendar, 'offset': offset})
624
+ if rule not in out_rules:
625
+ out_rules.append(rule)
626
+ if not out_rules:
627
+ return None
628
+ preview_count = raw.get('previewCount', raw.get('preview', 10))
629
+ if not isinstance(preview_count, int) or isinstance(preview_count, bool):
630
+ preview_count = 10
631
+ return {'startDate': start.isoformat(), 'rules': out_rules,
632
+ 'previewCount': max(1, min(preview_count, 50))}
633
+
634
+
635
+ def _recurrence_matches(day, start, rule):
636
+ kind, interval = rule['kind'], rule['interval']
637
+ if day < start:
638
+ return False
639
+ if kind == 'daily':
640
+ return (day - start).days % interval == 0
641
+ if kind == 'weekly':
642
+ return ((day - start).days // 7) % interval == 0 and day.weekday() in rule['weekdays']
643
+ if kind == 'monthly':
644
+ months = (day.year - start.year) * 12 + day.month - start.month
645
+ return months >= 0 and months % interval == 0 and day.day == rule['day']
646
+ if kind == 'yearly':
647
+ return (day.year - start.year) % interval == 0 and day.month == rule['month'] and day.day == rule['day']
648
+ return False
649
+
650
+
651
+ def recurrence_preview(raw, today=None, count=None):
652
+ """The next distinct ISO dates, anchored to the server's supplied/current day."""
653
+ config = clean_date_recurrence(raw)
654
+ if config is None:
655
+ return []
656
+ now = _iso_day(today) or _dt.date.today()
657
+ start = _iso_day(config['startDate'])
658
+ want = config['previewCount'] if count is None else max(1, min(int(count), 50))
659
+ lower = max(start, now)
660
+ # A preview of at most fifty values needs no unbounded search. Ten years also makes an
661
+ # unavailable public calendar visibly empty instead of spinning a request forever.
662
+ horizon = lower + _dt.timedelta(days=3660)
663
+ found, day = set(), lower
664
+ holiday_rules = [rule for rule in config['rules'] if rule['kind'] == 'holiday']
665
+ ordinary_rules = [rule for rule in config['rules'] if rule['kind'] != 'holiday']
666
+ while day <= horizon and len(found) < want:
667
+ if any(_recurrence_matches(day, start, rule) for rule in ordinary_rules):
668
+ found.add(day)
669
+ for rule in holiday_rules:
670
+ if (day.year - start.year) % rule['interval']:
671
+ continue
672
+ for holiday in public_holidays(rule['calendar'], day.year):
673
+ occurrence = holiday + _dt.timedelta(days=rule['offset'])
674
+ if occurrence == day and occurrence >= start:
675
+ found.add(day)
676
+ day += _dt.timedelta(days=1)
677
+ return [item.isoformat() for item in sorted(found)[:want]]
678
+
679
+
680
+ def recurrence_payload(raw, today=None):
681
+ """Durable config plus server-authoritative ``nextDate`` and finite ``preview``."""
682
+ config = clean_date_recurrence(raw)
683
+ if config is None:
684
+ return None
685
+ preview = recurrence_preview(config, today=today)
686
+ return {**config, 'nextDate': preview[0] if preview else None, 'preview': preview}
687
+
688
+
689
  def _field_extras(saved, ftype):
690
  """createdBy / permissions / format / scope — the validated passthrough the created strata
691
  share (wave 5). `createdBy` is only ever WRITTEN host-side (the handler stamps it); here it
 
726
  geo = _clean_geocode(saved.get("geocode"))
727
  if geo:
728
  out["geocode"] = geo
729
+ # W43C C2 — the ISO date remains scalar in each row; recurrence is field metadata. Serve
730
+ # the compact persisted config together with a server-derived next date and preview so the
731
+ # client never substitutes its browser clock or holiday library for the tenant contract.
732
+ recurrence = recurrence_payload(saved.get("recurrence")) if ftype == "date" else None
733
+ if recurrence:
734
+ out["recurrence"] = recurrence
735
  corrected_from = saved.get("labelCorrectedFrom")
736
  correction_id = saved.get("labelCorrectionId")
737
  if (isinstance(corrected_from, str) and corrected_from.strip()
 
805
  return {pid: {COHORT_COLUMN: ', '.join(names)} for pid, names in cells.items()}
806
 
807
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
808
  def clean_measure_field(raw, offered):
809
  """Validate one UNTRUSTED formula-measure field (owner item 7) against the caller's OFFER.
810
 
 
994
  continue
995
  options = (_clean_options(field.get("options"))
996
  if ftype in ("select", "multiselect") else [])
 
 
 
 
 
997
  out.append({
998
  "key": str(key)[:80],
999
  "label": str(field.get("label") or "Untitled")[:120],
 
1006
  # silent half of this feature.
1007
  "agg": field.get("agg") if field.get("agg") in FIELD_AGGS else None,
1008
  "note": str(field.get("note") or "")[:2000],
1009
+ # A new choice field starts with no vocabulary and learns it from real writes. Its
1010
+ # empty options list must not silently retype it to text: the picker needs to stay a
1011
+ # picker so the first typed/pasted/imported value can create the first option.
1012
  **({"options": options} if ftype in ("select", "multiselect") else {}),
1013
  **(_choice_appearance(field, options)
1014
  if ftype in ("select", "multiselect") else {}),
 
2118
  #: id happened to be 'folders'. (2) Folder placement is a per-user ORGANISING act, not part of
2119
  #: what a view IS: keeping it out of the view config means duplicating or exporting a view does
2120
  #: not drag a folder reference along with it. One map, one home, both surfaces.
2121
+ FOLDER_SURFACES = {"views", "cohorts"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2122
  MAX_FOLDERS = 60
2123
  MAX_FOLDER_NAME = 80
2124
 
 
2311
  # scrubbed here on the way back out, so the mark would be stored and instantly lost:
2312
  # the two halves are ONE change and shipping either alone is worse than shipping
2313
  # neither ([[lost-write-looks-like-failed-read]]).
2314
+ if item_id in (valid_ids or {}).get(surface, ()) and (fid == ROOT_PLACEMENT
2315
+ or fid in fids):
 
 
 
 
2316
  ok[item_id[:120]] = fid
2317
  if ok:
2318
  out[surface] = ok
 
2484
  # free of the date vocabulary it would otherwise have to keep in step.
2485
  if isinstance(mode, str) and 0 < len(mode) <= 40:
2486
  leaf['dateMode'] = mode
2487
+ # W43C C1/R1 — rank is a set-wide question. A saved leaf says whether it ranks
2488
+ # the residual domain globally or once per the view's group. The concise ``group``
2489
+ # form deliberately relies on the view's ``groupBy`` at evaluation time; the object
2490
+ # form pins a particular field and therefore survives a later view regroup. Unknown
2491
+ # shapes are dropped, never coerced to global, because that would change a narrowing
2492
+ # question while preserving its friendly-looking label.
2493
+ if node.get('op') in {'topN', 'bottomN', 'inTopPct', 'inBottomPct',
2494
+ 'aboveAvg', 'belowAvg', 'inQuartile', 'inDecile'}:
2495
+ rank_scope = _clean_rank_scope(node.get('rankScope'), valid_keys)
2496
+ if rank_scope is not None:
2497
+ leaf['rankScope'] = rank_scope
2498
  rhs = _clean_rhs(node.get('rhs'), valid_keys)
2499
  if rhs is not None:
2500
  leaf['rhs'] = rhs
 
2502
  return out
2503
 
2504
 
2505
+ def _clean_rank_scope(raw, valid_keys):
2506
+ """The persisted rank scope, or ``None`` when absent/malformed.
2507
+
2508
+ ``None`` retains legacy global semantics. ``'group'`` is intentionally valid without a
2509
+ column here: it means *the view's selected group*, and the server resolver refuses it when
2510
+ a caller later supplies no real group field. An explicit field is accepted only when this
2511
+ table exposes it, so a stale saved scope cannot silently collect every row in one bucket.
2512
+ """
2513
+ if raw in (None, ''):
2514
+ return None
2515
+ if raw == 'global':
2516
+ return 'global'
2517
+ if raw in ('group', 'perGroup'):
2518
+ return 'group'
2519
+ if not isinstance(raw, dict):
2520
+ return None
2521
+ mode = raw.get('mode', raw.get('scope'))
2522
+ field = str(raw.get('field', raw.get('groupBy')) or '').strip()[:80]
2523
+ if mode == 'global' and not field:
2524
+ return 'global'
2525
+ if mode == 'group' and field and field in valid_keys:
2526
+ return {'mode': 'group', 'field': field}
2527
+ return None
2528
+
2529
+
2530
  def _is_default_visible(field):
2531
  """Does this column open SHOWN in a view that has never recorded its own `visible`?
2532
 
platform/aios_grid_fields.json CHANGED
@@ -390,11 +390,52 @@
390
  "shared": true
391
  },
392
  {
393
- "key": "price_fisch",
394
- "label": "Fisch price",
395
  "type": "currency",
396
  "source": "odoo",
397
- "description": "Fisch pricelist price for this SKU. Blank when that list prices it nowhere."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
398
  },
399
  {
400
  "key": "price_fisch_t1",
 
390
  "shared": true
391
  },
392
  {
393
+ "key": "price_1",
394
+ "label": "Price 1",
395
  "type": "currency",
396
  "source": "odoo",
397
+ "default": false,
398
+ "description": "Cheapest live price for this SKU, across active pricelists."
399
+ },
400
+ {
401
+ "key": "unit_1",
402
+ "label": "Unit 1",
403
+ "type": "text",
404
+ "source": "odoo",
405
+ "default": false,
406
+ "description": "Package label for Price 1. Blank means Odoo has no package reference for that price."
407
+ },
408
+ {
409
+ "key": "price_2",
410
+ "label": "Price 2",
411
+ "type": "currency",
412
+ "source": "odoo",
413
+ "default": false,
414
+ "description": "Second-cheapest live price for this SKU."
415
+ },
416
+ {
417
+ "key": "unit_2",
418
+ "label": "Unit 2",
419
+ "type": "text",
420
+ "source": "odoo",
421
+ "default": false,
422
+ "description": "Package label for Price 2."
423
+ },
424
+ {
425
+ "key": "price_3",
426
+ "label": "Price 3",
427
+ "type": "currency",
428
+ "source": "odoo",
429
+ "default": false,
430
+ "description": "Third-cheapest live price for this SKU."
431
+ },
432
+ {
433
+ "key": "unit_3",
434
+ "label": "Unit 3",
435
+ "type": "text",
436
+ "source": "odoo",
437
+ "default": false,
438
+ "description": "Package label for Price 3."
439
  },
440
  {
441
  "key": "price_fisch_t1",
platform/core/field_permissions.py CHANGED
@@ -26,26 +26,6 @@ FIELD_ORIGINS = ("preset", "user")
26
  FIELD_AUDIENCES = ("private", "users", "everyone")
27
  FIELD_VALUE_STRATA = ("shared", "personal")
28
 
29
- #: ⭐⭐ W42-T47 / RULING R15 / CONTRACT C10 — WHICH STRATUM A DEFINITION WAS READ FROM.
30
- #:
31
- #: C10: *"`field_classes` reports, beside `{origin, audience, sharedBy, values, owner}`, WHICH
32
- #: STRATUM the definition was read from, so the client sections on ownership without re-deriving
33
- #: it."* The three are the three places a field definition can physically live in this codebase:
34
- #:
35
- #: * ``contract`` — the canonical contract file (`aios_grid_fields.json`) or a module's declared
36
- #: columns. Nobody made it here; it is the same document for every account.
37
- #: * ``shared`` — `shared_overlay`'s tenant-wide bucket (`<topic>_table_workspace__shared`),
38
- #: which is where `mint_field` and `promote_field` put a definition. ONE document, read by
39
- #: every account.
40
- #: * ``personal`` — the reader's OWN member of the `<topic>_table_workspace` document. A
41
- #: per-user definition: no other account ever receives it.
42
- #:
43
- #: ⛔ IT IS NOT `FIELD_VALUE_STRATA` WEARING A SECOND HAT, AND THE TWO MUST NOT BE COMPARED. That
44
- #: tuple says where a column's VALUES live; this one says where its DEFINITION was read from. A
45
- #: column can be `stratum='personal'` with `values='shared'` — that pair is R15's report, not R15's
46
- #: bug (see `field_stratum`).
47
- FIELD_DEFINITION_STRATA = ("contract", "shared", "personal")
48
-
49
  #: `permissions_from_grants`' edit vocabulary -> C1's audience vocabulary. The two answer the SAME
50
  #: question in different words (who can reach this column), so this map is the whole of the
51
  #: translation and there is no second derivation to drift from it
@@ -220,82 +200,6 @@ def field_origin(field):
220
  return "preset"
221
 
222
 
223
- def _grant_mark():
224
- """The name of the wall's own mark, read from `perm_scope` and never re-spelled locally.
225
-
226
- ⛔ `_governed`'s note forbids a second reader by name: *"Re-spelling `f.get('granted') is True`
227
- locally would be a second reader of the mark, and a second reader is how the two come apart."*
228
- The stratum fallback below needs the same mark, so it takes the CONSTANT rather than the
229
- literal, and the two cannot drift apart on a rename.
230
-
231
- ⚠ THE FAILURE DIRECTION IS DELIBERATE AND IS THE OPPOSITE OF `_governed`'S. `_governed`
232
- degrades to `False` (not governed), which is right for a WALL question. Here an unresolvable
233
- import must not tip a definition toward `personal`, because `personal` zeroes the grant record
234
- in `field_class`; falling back to the mark's own spelling keeps the conservative answer
235
- (`shared`, i.e. trust the registry) when `core.perm_scope` cannot be loaded at all.
236
- """
237
- try:
238
- import core.perm_scope as perm_scope
239
- return str(perm_scope.FIELD_GRANT_MARK)
240
- except Exception: # noqa: BLE001
241
- return "granted"
242
-
243
-
244
- def field_stratum(field):
245
- """⭐⭐ W42-T47 / R15 / C10 — THE **FALLBACK** DERIVATION OF WHICH STRATUM A DEFINITION CAME
246
- FROM, for a caller that cannot lend the fact. See `FIELD_DEFINITION_STRATA`.
247
-
248
- ⛔⛔ IT IS A FALLBACK AND NOT THE ANSWER, AND THE REASON IS THE WHOLE OF THIS TICKET: **NOTHING
249
- ON A FIELD DEFINITION RECORDS WHICH DOCUMENT IT WAS READ FROM.** Every mark that looks like
250
- evidence survives being COPIED OUT of that document:
251
-
252
- * `routes_customers._merge_shared_fields` projects a shared definition as
253
- `dict(f, source="overlay", shared=True)`;
254
- * that merged list reaches `grid_events.field_upsert`, whose fork-minting branch is
255
- `base = field_by_key[key]` then `field = {**base, 'note': ...}` — `{**base}` copies EVERY
256
- key, `shared` and `granted` and `source` included;
257
- * `TableStore.save_field` then writes that copy into THIS user's own workspace member.
258
-
259
- So a personal fork of a tenant-wide route carries `shared: True` verbatim, and a mark-based
260
- test calls it `shared`. That is R15's own reproduction (gabriel mints `route_x`; another
261
- account forks it through Format or Summary), which is exactly the case this member exists to
262
- report, so the mark test cannot be the producer of the answer.
263
-
264
- ⛔ ADDING MORE MARKS DOES NOT RESCUE IT. `source == "overlay"` is copied by the same `{**base}`
265
- and fails identically. A key-keyed store (the grant registry, `shared_overlay.fields()`
266
- membership, the lent `values_shared`) fails the other way: it answers about whichever
267
- definition of that key lives in ITS document, which on a fork is a DIFFERENT definition from
268
- the dict in hand, so it can never report the conflict either.
269
-
270
- ⚠ THE BLIND SPOT, STATED RATHER THAN HIDDEN: **this fallback cannot see a fork, and names one
271
- `shared`.** A documented blind spot beats a silent one; the honest answer is lent by the
272
- assembly that DID the reading, through `field_class(stratum=...)` / `field_classes(strata=...)`.
273
-
274
- The marks are still the best available evidence for everything else, and the polarity matches
275
- `field_origin`'s: unmarked plus a demonstrable author is `personal`, everything else `contract`.
276
- """
277
- if not isinstance(field, dict):
278
- return "contract"
279
- if field.get("shared") is True or field.get(_grant_mark()) is True:
280
- return "shared"
281
- if field_origin(field) == "user":
282
- return "personal"
283
- return "contract"
284
-
285
-
286
- def _clean_stratum(value, field=None):
287
- """One lent stratum, canonicalised, falling back to `field_stratum` on anything unrecognised.
288
-
289
- ⛔ AN UNKNOWN TOKEN FALLS BACK RATHER THAN FAILING CLOSED TO `personal`. `personal` is not the
290
- safe direction here: it ZEROES the grant record in `field_class`, so a typo in a lent map would
291
- silently strip the owner and the audience off every column it named.
292
- """
293
- token = str(value or "").strip().lower()
294
- if token in FIELD_DEFINITION_STRATA:
295
- return token
296
- return field_stratum(field)
297
-
298
-
299
  def _shared_value_keys(table_key, st=None):
300
  """The columns of `table_key` whose VALUES are one tenant-wide stratum."""
301
  key = str(table_key or "").strip()
@@ -368,24 +272,12 @@ def grant_records(grant_topic, st=None):
368
 
369
 
370
  def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
371
- values_shared=None, stratum=None, st=None):
372
  """⭐⭐ W41-T01 / R5 / CONTRACT C1 — **THE ONE PRODUCER OF A FIELD'S THREE BADGES.**
373
 
374
- Returns `{origin, audience, sharedBy, values, owner, stratum}` and nothing else derives a badge
375
- independently. The member spellings are C1's and C10's, and they are the wire's: the payload key
376
- is `class`, its members are `origin`, `audience`, `sharedBy`, `values`, `owner`, `stratum`.
377
-
378
- **stratum** — ⭐⭐ W42-T47 / R15 / C10, and it is the member the other five are now ANCHORED to.
379
- `contract` | `shared` | `personal`: WHICH DOCUMENT this definition was read from. The client
380
- sections on ownership (My fields / From my colleagues / Built in) from `stratum` plus `owner`
381
- WITHOUT re-deriving either.
382
- ⚠ IT IS **LENT BY THE CALLER**, for `values_shared`'s reason turned up one notch: not merely
383
- that `core` never imports up, but that the fact is not present in ANY of this function's
384
- inputs. Nothing on a definition records the document it came from, because every mark on it
385
- survives being copied out of that document (`field_stratum` carries the proof and the copying
386
- doors). Only the assembly that DID the reading knows, so it lends
387
- `field_classes(strata={key: stratum})`, and absent that the derivation falls back to
388
- `field_stratum`, whose blind spot is stated there rather than hidden here.
389
 
390
  `viewer` is a USERNAME STRING (`session.uname`), never a user dict — a dict compares unequal to
391
  every stored name, which would make `sharedBy` silently never match and `owner` never equal the
@@ -434,19 +326,6 @@ def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
434
  contract-declared one), else `personal`. This is R5's new information and it is INDEPENDENT of
435
  audience: a route column is `private` with `shared` values, Supplier is `everyone` with `shared`
436
  values, and a column you made is `private` with `personal` ones.
437
- ⛔⛔ W42-T47 / R15 — `values` AND `audience` KEEP READING GENUINELY DIFFERENT STORES, AND THEY
438
- ARE STILL INCAPABLE OF DESCRIBING DIFFERENT DEFINITIONS. The independence is required (one is
439
- membership of the shared-overlay stratum, the other is `shares.grants`), so it is not removed;
440
- what is removed is the second opinion about WHICH DEFINITION is being described. `stratum` is
441
- computed once, from the definition in hand, and both legs are anchored to it: the registry is
442
- not consulted at all on a `personal` definition, and `values` no longer decides an audience for
443
- one. R15's *"`Private` + `Shared values` is NOT a state to preserve, it IS the bug"* is
444
- therefore answered by making the pair UNAMBIGUOUS rather than by suppressing either member: a
445
- column whose cells come from the shared pool but whose definition is the reader's own now reads
446
- `{stratum: 'personal', values: 'shared', audience: 'private', owner: <its own author>}`, which
447
- is one coherent sentence and the exact fact the owner reported, instead of two badges that
448
- contradict each other about who has this column.
449
-
450
  ⚠ `values_shared` IS LENT BY THE CALLER because the key set is a MODULE-level fact
451
  (`product_data.SHARED_KEYS()`), and `core` never imports up. Absent, it is derived from
452
  `shared_overlay.fields(table_key)`, which is right for an overlay topic and blind to a
@@ -463,45 +342,8 @@ def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
463
  me = _uname(viewer)
464
 
465
  origin = field_origin(field)
466
- # ⛔⛔ W42-T47 — AN **ASSERTED** STRATUM ANCHORS THE BAG; A GUESSED ONE REPORTS AND NOTHING MORE.
467
- # `user_tables._field_badges` calls `field_class` on a RIGHTS path: `delete_field_refusal` reads
468
- # `bag['owner']` and returns `NOT_FIELD_OWNER` on a mismatch, so anything that moves `owner`
469
- # moves a delete. That caller lends no stratum, and the fallback derivation is a guess by its
470
- # own docstring, so letting a guess re-source `owner` could hand somebody a delete they did not
471
- # have. This ticket makes a REPORT honest; it moves no wall, and this line is where that
472
- # promise is kept rather than asserted. A caller that KNOWS which document it read (C10's lent
473
- # map) gets the anchored answer; every existing caller keeps today's behaviour byte for byte.
474
- asserted = str(stratum or "").strip().lower() in FIELD_DEFINITION_STRATA
475
- stratum = _clean_stratum(stratum, field)
476
- anchored_personal = asserted and stratum == "personal"
477
  record = grants if isinstance(grants, dict) else _grant_record(
478
  key, table_key=table_key, grant_topic=grant_topic, st=st)
479
- # ⛔⛔ W42-T47 / R15 / C10 — THE REGISTRY RECORD IS KEYED BY FIELD **KEY**, SO ON A PERSONAL
480
- # DEFINITION IT DESCRIBES A DIFFERENT DEFINITION AND IS DROPPED ENTIRELY.
481
- #
482
- # `shares.field_oid(topic, key)` names a KEY, not a document. A grant record for `route_x` was
483
- # written about the definition in the tenant-wide bucket; when the dict in hand came from the
484
- # reader's own workspace member instead, those are two different definitions of one key, and
485
- # `routes_customers._merge_shared_fields` makes that routine rather than exotic — its rule is
486
- # `if k in have: continue`, so a reader holding ANY same-key entry silently keeps their own and
487
- # never sees the shared one (that merge is W42-T46's, not this ticket's).
488
- #
489
- # Reading `owner`, `sharedBy` and `audience` off that record while reading `origin`, `values`
490
- # and the marks off the personal dict is how ONE bag came to describe TWO definitions, which is
491
- # R15's *"Gabriel created the Route and it ends up being MY field"* — the owner fact and the
492
- # audience were answering about different documents. Zeroing the record here is what makes the
493
- # anchoring STRUCTURAL: after this line there is no path by which a registry-derived member can
494
- # describe a definition the `stratum` member does not name.
495
- #
496
- # ⚠ NO PERMISSION MOVES, AND IT IS CHECKED RATHER THAN REASONED — BUT NOT FOR THE REASON IT
497
- # FIRST LOOKS LIKE. A fork carries `granted: True` copied verbatim, so a `personal` definition
498
- # CAN be one the wall does consult the registry about; this arm is exactly where R15's fork
499
- # lands. What makes it safe is that the wall reads the registry ITSELF
500
- # (`perm_scope.field_grant_hidden` -> `shares.role_for`) and never reads this bag, so zeroing
501
- # here changes the REPORT and nothing else. The report is the thing that was wrong: a personal
502
- # definition's grant record describes a document the reader is not reading.
503
- if anchored_personal:
504
- record = _empty_record()
505
  owner = _uname(record.get("owner")) or None
506
  entries = [e for e in (record.get("entries") or ()) if isinstance(e, dict)]
507
 
@@ -512,19 +354,10 @@ def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
512
  if _governed(field):
513
  audience = _AUDIENCE_FROM_EDIT.get(
514
  permissions_from_grants(entries).get("edit"), "private")
515
- elif not anchored_personal and (values == "shared" or origin == "preset"):
516
  # Ungoverned AND tenant-wide: the database's holders all hold this column. `origin` covers
517
  # a contract-declared column whose VALUES are per-user (a canonical Odoo column); the
518
  # `values` leg covers a shared-stratum column the contract never named.
519
- #
520
- # ⛔ W42-T47 — THE `stratum != "personal"` GUARD IS THIS TICKET'S BEHAVIOUR CHANGE, AND IT
521
- # FIRES ON EXACTLY ONE SHAPE: a definition read from the reader's OWN workspace member
522
- # whose key ALSO has a definition (and therefore shared cells) in the tenant-wide bucket.
523
- # Without it, `values` — a fact about the SHARED document — promoted a definition nobody
524
- # else can even receive to `everyone`. The reader would be told the whole tenant can see a
525
- # column that exists only in their own stratum, which is a promise the merge cannot keep.
526
- # ⚠ It cannot touch a shared or contract definition: both answer a `stratum` this test
527
- # admits, so Supplier and every minted route badge exactly as they did before.
528
  audience = "everyone"
529
  else:
530
  audience = "private"
@@ -539,30 +372,13 @@ def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
539
  if shared_by == me:
540
  shared_by = None
541
 
542
- # ⚠ THE `createdBy` FALLBACK IS NOW THE WHOLE ANSWER ON A PERSONAL DEFINITION, not merely the
543
- # create-window stopgap it was written as, because `record` was zeroed above. That is the
544
- # intended reading of C10's *"whose it is"*: the author mark rides on the definition that was
545
- # read, so `owner` and `stratum` cannot name different documents.
546
  return {"origin": origin, "audience": audience, "sharedBy": shared_by,
547
- "values": values, "owner": owner or _uname(field.get("createdBy")) or None,
548
- "stratum": stratum}
549
 
550
 
551
  def field_classes(fields, viewer, *, table_key=None, grant_topic=None, values_shared=None,
552
- strata=None, st=None):
553
- """`{field_key: <C1 + C10 bag>}` for a whole field list, on ONE registry read. See `grant_records`.
554
-
555
- ⭐⭐ W42-T47 / C10 — every bag carries `stratum` (`contract` | `shared` | `personal`), so a
556
- caller sections on ownership without re-deriving it.
557
-
558
- ⛔ `strata` IS THE LENT MAP AND IT IS THE ONLY HONEST SOURCE: `{field_key: <one of
559
- FIELD_DEFINITION_STRATA>}`, supplied by the assembly that READ each definition and therefore
560
- knows which document each entry of `fields` came out of. Partial maps are fine — a key the map
561
- does not name falls back to `field_stratum`, per key, so a caller can lend only the keys it is
562
- sure about. ⚠ THE PER-FIELD ANSWER IS NOT DERIVABLE FROM ANYTHING THIS FUNCTION HOLDS:
563
- `records` and `values_shared` are both keyed by field key, so they describe whichever
564
- definition of that key lives in THEIR store, which on a forked column is a different definition
565
- from the one in `fields`. That is why the fact is lent rather than computed here.
566
 
567
  ⚠ EVERY COLUMN GETS A BAG, INCLUDING ONE THE REGISTRY HAS NEVER HEARD OF: the missing record is
568
  substituted explicitly rather than left to `field_class` to re-read, which is what keeps the
@@ -573,7 +389,6 @@ def field_classes(fields, viewer, *, table_key=None, grant_topic=None, values_sh
573
  if values_shared is None:
574
  values_shared = _shared_value_keys(table_key, st=st)
575
  shared_keys = {str(k) for k in (values_shared or ())}
576
- lent = {str(k).strip(): v for k, v in strata.items()} if isinstance(strata, dict) else {}
577
  out = {}
578
  for field in (fields or ()):
579
  if not isinstance(field, dict):
@@ -583,7 +398,7 @@ def field_classes(fields, viewer, *, table_key=None, grant_topic=None, values_sh
583
  continue
584
  out[key] = field_class(field, viewer, grants=records.get(key) or _empty_record(),
585
  table_key=table_key, grant_topic=topic,
586
- values_shared=shared_keys, stratum=lent.get(key), st=st)
587
  return out
588
 
589
 
 
26
  FIELD_AUDIENCES = ("private", "users", "everyone")
27
  FIELD_VALUE_STRATA = ("shared", "personal")
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  #: `permissions_from_grants`' edit vocabulary -> C1's audience vocabulary. The two answer the SAME
30
  #: question in different words (who can reach this column), so this map is the whole of the
31
  #: translation and there is no second derivation to drift from it
 
200
  return "preset"
201
 
202
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  def _shared_value_keys(table_key, st=None):
204
  """The columns of `table_key` whose VALUES are one tenant-wide stratum."""
205
  key = str(table_key or "").strip()
 
272
 
273
 
274
  def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
275
+ values_shared=None, st=None):
276
  """⭐⭐ W41-T01 / R5 / CONTRACT C1 — **THE ONE PRODUCER OF A FIELD'S THREE BADGES.**
277
 
278
+ Returns `{origin, audience, sharedBy, values, owner}` and nothing else derives a badge
279
+ independently. The five member spellings are C1's and they are the wire's: the payload key is
280
+ `class`, its members are `origin`, `audience`, `sharedBy`, `values`, `owner`.
 
 
 
 
 
 
 
 
 
 
 
 
281
 
282
  `viewer` is a USERNAME STRING (`session.uname`), never a user dict — a dict compares unequal to
283
  every stored name, which would make `sharedBy` silently never match and `owner` never equal the
 
326
  contract-declared one), else `personal`. This is R5's new information and it is INDEPENDENT of
327
  audience: a route column is `private` with `shared` values, Supplier is `everyone` with `shared`
328
  values, and a column you made is `private` with `personal` ones.
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  ⚠ `values_shared` IS LENT BY THE CALLER because the key set is a MODULE-level fact
330
  (`product_data.SHARED_KEYS()`), and `core` never imports up. Absent, it is derived from
331
  `shared_overlay.fields(table_key)`, which is right for an overlay topic and blind to a
 
342
  me = _uname(viewer)
343
 
344
  origin = field_origin(field)
 
 
 
 
 
 
 
 
 
 
 
345
  record = grants if isinstance(grants, dict) else _grant_record(
346
  key, table_key=table_key, grant_topic=grant_topic, st=st)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
347
  owner = _uname(record.get("owner")) or None
348
  entries = [e for e in (record.get("entries") or ()) if isinstance(e, dict)]
349
 
 
354
  if _governed(field):
355
  audience = _AUDIENCE_FROM_EDIT.get(
356
  permissions_from_grants(entries).get("edit"), "private")
357
+ elif values == "shared" or origin == "preset":
358
  # Ungoverned AND tenant-wide: the database's holders all hold this column. `origin` covers
359
  # a contract-declared column whose VALUES are per-user (a canonical Odoo column); the
360
  # `values` leg covers a shared-stratum column the contract never named.
 
 
 
 
 
 
 
 
 
361
  audience = "everyone"
362
  else:
363
  audience = "private"
 
372
  if shared_by == me:
373
  shared_by = None
374
 
 
 
 
 
375
  return {"origin": origin, "audience": audience, "sharedBy": shared_by,
376
+ "values": values, "owner": owner or _uname(field.get("createdBy")) or None}
 
377
 
378
 
379
  def field_classes(fields, viewer, *, table_key=None, grant_topic=None, values_shared=None,
380
+ st=None):
381
+ """`{field_key: <C1 bag>}` for a whole field list, on ONE registry read. See `grant_records`.
 
 
 
 
 
 
 
 
 
 
 
 
382
 
383
  ⚠ EVERY COLUMN GETS A BAG, INCLUDING ONE THE REGISTRY HAS NEVER HEARD OF: the missing record is
384
  substituted explicitly rather than left to `field_class` to re-read, which is what keeps the
 
389
  if values_shared is None:
390
  values_shared = _shared_value_keys(table_key, st=st)
391
  shared_keys = {str(k) for k in (values_shared or ())}
 
392
  out = {}
393
  for field in (fields or ()):
394
  if not isinstance(field, dict):
 
398
  continue
399
  out[key] = field_class(field, viewer, grants=records.get(key) or _empty_record(),
400
  table_key=table_key, grant_topic=topic,
401
+ values_shared=shared_keys, st=st)
402
  return out
403
 
404
 
platform/core/shares.py CHANGED
@@ -80,7 +80,7 @@ SHARES_KEY = 'object_shares'
80
  #: here is this tuple member. That is the point of one registry: the new object's WALL is written
81
  #: once in `core.perm_scope`, and its DOORS once in `routes_shares.py` — never a fourth
82
  #: permission decision in a fourth file ([[one-evaluator-per-question]]).
83
- KINDS = ('view', 'folder', 'database', 'field')
84
 
85
  #: `*` is "everyone who can already open the surface". It is NOT "every account on the platform".
86
  #: Spelled as a single character so it can never collide with a username (usernames are lower-case
@@ -157,6 +157,153 @@ class GrantsChanged(Exception):
157
  FIELD_OID_SEP = ':'
158
 
159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  def field_oid(table_key, field_key):
161
  """`"<table_key>:<field_key>"` — the share id of ONE column on ONE database."""
162
  table = str(table_key or '').strip()
 
80
  #: here is this tuple member. That is the point of one registry: the new object's WALL is written
81
  #: once in `core.perm_scope`, and its DOORS once in `routes_shares.py` — never a fourth
82
  #: permission decision in a fourth file ([[one-evaluator-per-question]]).
83
+ KINDS = ('view', 'folder', 'database', 'field', 'cohort')
84
 
85
  #: `*` is "everyone who can already open the surface". It is NOT "every account on the platform".
86
  #: Spelled as a single character so it can never collide with a username (usernames are lower-case
 
157
  FIELD_OID_SEP = ':'
158
 
159
 
160
+ def _cohort_scope(scope):
161
+ """The durable topic spelling for a Cohort share id and its store bucket.
162
+
163
+ The retired ``cohort`` surface is the customer topic, not a second database. Keeping that
164
+ alias here means its share record and its source record can never be split by a request that
165
+ happens to use the old spelling. Other scopes deliberately stay distinct: a cohort id is
166
+ only unique inside its database bucket.
167
+ """
168
+ value = str(scope or 'customer').strip().lower()
169
+ if value in ('', 'customer', 'cohort'):
170
+ return 'customer'
171
+ if not value or ':' in value:
172
+ raise ValueError('a cohort scope must name one database and cannot contain a colon')
173
+ return value
174
+
175
+
176
+ def cohort_oid(scope, cohort_id):
177
+ """``"<scope>:<cohort_id>"`` — one Cohort's share identity.
178
+
179
+ ``modules.cohort`` intentionally permits the same generated id in two topic buckets. A
180
+ bare id in the global share registry would therefore let a Product grant surface a Customer
181
+ cohort (or the reverse). Qualifying it is the same collision wall ``field_oid`` provides
182
+ for reused custom-field keys.
183
+ """
184
+ topic = _cohort_scope(scope)
185
+ cid = str(cohort_id or '').strip()
186
+ if not cid or ':' in cid:
187
+ raise ValueError('a cohort share needs a non-empty id without a colon')
188
+ return f'{topic}{FIELD_OID_SEP}{cid}'
189
+
190
+
191
+ def split_cohort_oid(oid):
192
+ """``(scope, cohort_id)`` or ``(None, None)`` for a malformed Cohort share id."""
193
+ raw = str(oid or '')
194
+ scope, sep, cid = raw.partition(FIELD_OID_SEP)
195
+ if not sep or not scope.strip() or not cid.strip() or FIELD_OID_SEP in cid:
196
+ return (None, None)
197
+ try:
198
+ return (_cohort_scope(scope), cid.strip())
199
+ except ValueError:
200
+ return (None, None)
201
+
202
+
203
+ def _cohort_key(scope):
204
+ """The Cohort source bucket for one canonical scope (without importing ``modules/``)."""
205
+ topic = _cohort_scope(scope)
206
+ return 'customer_cohorts' if topic == 'customer' else f'{topic}_cohorts'
207
+
208
+
209
+ def cohort_source(scope, cohort_id, st=None):
210
+ """``{owner, cohort}`` for one durable Cohort, or ``None`` when it is absent/ambiguous.
211
+
212
+ Cohorts are stored under their creator's username rather than carrying a duplicate owner
213
+ field. The source is therefore the authority for ownership; the share registry only adds
214
+ recipients. A duplicated id within one bucket has no safe single share target, so this
215
+ reader deliberately returns no source rather than selecting whichever owner a dict happens
216
+ to enumerate first.
217
+ """
218
+ try:
219
+ topic = _cohort_scope(scope)
220
+ cid = str(cohort_id or '').strip()
221
+ data = _st(st).get(_cohort_key(topic)) or {}
222
+ except Exception:
223
+ return None
224
+ if not cid or not isinstance(data, dict):
225
+ return None
226
+ found = []
227
+ for raw_owner, book in data.items():
228
+ if not isinstance(book, dict):
229
+ continue
230
+ cohort = book.get(cid)
231
+ if isinstance(cohort, dict):
232
+ owner = str(raw_owner or '').strip().lower()
233
+ if owner:
234
+ found.append((owner, dict(cohort)))
235
+ if len(found) != 1:
236
+ return None
237
+ owner, cohort = found[0]
238
+ return {'scope': topic, 'id': cid, 'owner': owner, 'cohort': cohort}
239
+
240
+
241
+ def cohort_role(scope, cohort_id, user, st=None):
242
+ """The normal Cohort read role, or ``None`` without a source/grant relationship.
243
+
244
+ The creator owns an unshared cohort by source residency. Everyone else must satisfy the
245
+ ordinary share registry predicate. Administrators are intentionally *not* a bypass: the
246
+ reported defect was an unshared Shantal cohort appearing to Farhan/Leadership, and an
247
+ administrator-shaped account must not turn absent permission into a blank surrogate record.
248
+ """
249
+ source = cohort_source(scope, cohort_id, st=st)
250
+ principal = str(user or '').strip().lower()
251
+ if source is None or not principal:
252
+ return None
253
+ if source['owner'] == principal:
254
+ return 'owner'
255
+ # Deliberately omit is_admin: normal Cohort sharing is explicit, including for admins.
256
+ return role_for('cohort', cohort_oid(source['scope'], source['id']), principal, st=st)
257
+
258
+
259
+ def cohort_record(scope, cohort_id, user, st=None):
260
+ """The authorized Cohort detail, or ``None``. Never manufacture a blank placeholder."""
261
+ source = cohort_source(scope, cohort_id, st=st)
262
+ if source is None:
263
+ return None
264
+ role = cohort_role(source['scope'], source['id'], user, st=st)
265
+ if role is None:
266
+ return None
267
+ return {**source, 'role': role}
268
+
269
+
270
+ def visible_cohorts(scope, user, st=None):
271
+ """Authorized Cohorts for one database, keyed by id, with no unauthorized placeholders.
272
+
273
+ This is the list-side companion to :func:`cohort_record`. Both delegate to
274
+ :func:`cohort_role`, so an owner check and a recipient grant cannot diverge between a rail
275
+ listing and the detail it opens. Colliding ids fail closed for the same reason
276
+ ``cohort_source`` does.
277
+ """
278
+ try:
279
+ topic = _cohort_scope(scope)
280
+ data = _st(st).get(_cohort_key(topic)) or {}
281
+ except Exception:
282
+ return {}
283
+ if not isinstance(data, dict):
284
+ return {}
285
+ ids = set()
286
+ duplicate_ids = set()
287
+ for book in data.values():
288
+ if not isinstance(book, dict):
289
+ continue
290
+ for cid, cohort in book.items():
291
+ if not isinstance(cohort, dict):
292
+ continue
293
+ cid = str(cid or '').strip()
294
+ if not cid:
295
+ continue
296
+ if cid in ids:
297
+ duplicate_ids.add(cid)
298
+ ids.add(cid)
299
+ out = {}
300
+ for cid in sorted(ids - duplicate_ids):
301
+ record = cohort_record(topic, cid, user, st=st)
302
+ if record is not None:
303
+ out[cid] = dict(record['cohort'])
304
+ return out
305
+
306
+
307
  def field_oid(table_key, field_key):
308
  """`"<table_key>:<field_key>"` — the share id of ONE column on ONE database."""
309
  table = str(table_key or '').strip()
platform/core/store.py CHANGED
@@ -656,15 +656,13 @@ class Store:
656
  def upload_bytes(self, path_in_repo, data, message=None):
657
  """Persist RAW BYTES at an arbitrary path in the tenant dataset (wave-8 C5, documents).
658
  Bytes are never cached in-process: large, cold, fetched on explicit user action."""
659
- # Refusal dominates availability: an uncredentialed staging process must still learn that
660
- # it is forbidden from targeting production, rather than receive a generic token error.
661
- data_binding.check_write(self.repo, f'write bytes {path_in_repo!r}')
662
  if not self.available():
663
  raise RuntimeError('No HF_TOKEN configured — persistence is unavailable.')
664
  # D-315: a blob is still this tenant's data. ⚠ No `parent_commit` here and that is correct,
665
  # not an omission: a blob is written at its own path and read whole, so two writers cannot
666
  # silently merge into one damaged document the way `{name}.json` can. The concurrency
667
  # hazard D-305 describes is specific to the shared JSON blob.
 
668
  with self._lock:
669
  self._ensure_repo()
670
  HfApi(token=_token()).upload_file(
@@ -695,9 +693,9 @@ class Store:
695
  tolerable no-op. "You are not allowed to touch this store" is not a no-op — it is the
696
  thing the operator has to be told.
697
  """
698
- data_binding.check_write(self.repo, f'delete {path_in_repo!r}')
699
  if not self.available():
700
  return False
 
701
  try:
702
  HfApi(token=_token()).delete_file(
703
  path_in_repo=path_in_repo, repo_id=self.repo, repo_type='dataset',
@@ -731,9 +729,9 @@ class Store:
731
  have actually SEEN — and that any `update` queued behind it replays on top — instead of
732
  being uploaded over an hour of unseen work.
733
  """
734
- data_binding.check_write(self.repo, f'put {name!r}')
735
  if not self.available():
736
  raise RuntimeError('No HF_TOKEN configured — persistence is unavailable.')
 
737
  with self._key_lock(name):
738
  def _replace(_current):
739
  return json.loads(json.dumps(data))
 
656
  def upload_bytes(self, path_in_repo, data, message=None):
657
  """Persist RAW BYTES at an arbitrary path in the tenant dataset (wave-8 C5, documents).
658
  Bytes are never cached in-process: large, cold, fetched on explicit user action."""
 
 
 
659
  if not self.available():
660
  raise RuntimeError('No HF_TOKEN configured — persistence is unavailable.')
661
  # D-315: a blob is still this tenant's data. ⚠ No `parent_commit` here and that is correct,
662
  # not an omission: a blob is written at its own path and read whole, so two writers cannot
663
  # silently merge into one damaged document the way `{name}.json` can. The concurrency
664
  # hazard D-305 describes is specific to the shared JSON blob.
665
+ data_binding.check_write(self.repo, f'write bytes {path_in_repo!r}')
666
  with self._lock:
667
  self._ensure_repo()
668
  HfApi(token=_token()).upload_file(
 
693
  tolerable no-op. "You are not allowed to touch this store" is not a no-op — it is the
694
  thing the operator has to be told.
695
  """
 
696
  if not self.available():
697
  return False
698
+ data_binding.check_write(self.repo, f'delete {path_in_repo!r}')
699
  try:
700
  HfApi(token=_token()).delete_file(
701
  path_in_repo=path_in_repo, repo_id=self.repo, repo_type='dataset',
 
729
  have actually SEEN — and that any `update` queued behind it replays on top — instead of
730
  being uploaded over an hour of unseen work.
731
  """
 
732
  if not self.available():
733
  raise RuntimeError('No HF_TOKEN configured — persistence is unavailable.')
734
+ data_binding.check_write(self.repo, f'put {name!r}')
735
  with self._key_lock(name):
736
  def _replace(_current):
737
  return json.loads(json.dumps(data))
platform/core/user_tables.py CHANGED
@@ -47,11 +47,14 @@ inherits C1 by construction — there is no list to add it to, which is R6's act
47
  import datetime as _dt
48
  import hashlib
49
  import json as _json
 
50
  import re
 
51
 
52
  import core.store as store
53
 
54
  STORE_KEY = 'user_tables'
 
55
  MAX_TABLES = 40
56
  MAX_LABEL = 60
57
 
@@ -355,51 +358,7 @@ def limit_report(table_key, st=None):
355
  }
356
 
357
 
358
- #: ⭐⭐ W42-T36 — **60 -> 100, AND THE NUMBER IS MEASURED RATHER THAN CHOSEN.** Copying one table
359
- #: document at each shape, on this box:
360
- #:
361
- #: rows 60 fields 100 fields delta
362
- #: 0 1.42ms 1.65ms +0.23ms
363
- #: 5000 203.32ms 437.35ms +234.03ms
364
- #: 20000 1535.34ms 2254.67ms +719.33ms
365
- #: 60000 4015ms 9593ms 2.39x <- MAX_ROWS, the true worst case
366
- #:
367
- #: ⛔⛔ THE `MAX_ROWS` ARM IS THE ONE TO READ, AND IT WAS NOT IN THE ORIGINAL MEASUREMENT. Every
368
- #: arm above 20,000 rows was an extrapolation until this one was run; the extrapolation said ~1.6x
369
- #: and the measurement says **2.39x, at 9.6 SECONDS for one full-document copy**. A store copy is
370
- #: not linear in document size at that scale, so the honest statement is that the cost was
371
- #: measured at the ceiling rather than reasoned toward it.
372
- #: ⚠ THIS IS A CEILING, NOT A TYPICAL COST: it needs a table simultaneously at `MAX_ROWS` AND at
373
- #: the new `MAX_FIELDS`, which no tenant document is today. Recorded so the next person raising
374
- #: either cap knows which one they are multiplying, and books the async-flush question rather than
375
- #: rediscovering it under an incident.
376
- #:
377
- #: ⛔ **`MAX_FIELDS` IS A ROW COST, NOT A FIELD-DEFINITION COST**, and that is the mechanism a
378
- #: later reader needs rather than the milliseconds. With no rows the cap is free (0.23 ms); every
379
- #: ROW carries a cell per field, so raising it multiplies the ~99%-of-document part. The ratio is
380
- #: what travels: ~+47% copy time at 20,000 rows for +67% columns.
381
- #: ⛔ DO NOT QUOTE THESE ABSOLUTES AS CONSTANTS. The identical shape measured 791 ms and then
382
- #: 1535 ms on this machine, a 1.94x spread under lane contention; one arm of the first run came
383
- #: back NEGATIVE, which is impossible and is the tell that the absolutes are noise.
384
- #: ⚠ 100 IS THE CEILING THE MEASUREMENT COVERS. Anything above it is estimated, and this cap
385
- #: exists precisely so the number is not guessed.
386
- MAX_FIELDS = 100
387
- #: ⭐⭐ W42-T36 / CONTRACT C8b — THE OPTION CAP, DECLARED ONCE AND USED AT BOTH DOORS.
388
- #:
389
- #: ⛔ IT WAS TWO BARE `[:50]` SLICES, WHICH IS THE PART THAT MATTERED MORE THAN THE NUMBER. A
390
- #: slice DROPS THE TAIL SILENTLY: the 51st option vanished, the request answered 200, and the
391
- #: column came back short with nothing anywhere to notice. Standing rule 1's second half is
392
- #: explicit that *"a limit that genuinely cannot be removed must be REPORTED, with cause and a
393
- #: recommended fix, never silently enforced"* — so raising the number without changing the
394
- #: BEHAVIOUR would only have moved where the silence happens. Over the cap now REFUSES the field.
395
- #:
396
- #: ⚠ MEASURED, LIKE `MAX_FIELDS`, AND IT IS THE CHEAP ONE. Options live in the field DEFINITION
397
- #: and never scale with rows: 50 options 3.03 ms -> 200 options 9.64 ms at rows=0, and that delta
398
- #: does not grow with the row count because no row carries an option. The ticket's own `how:`
399
- #: warned about this cap; the measurement says `MAX_FIELDS` is the expensive one.
400
- #: ⭢ The CLIENT half (`types.ts::parseOptions`, still `slice(0, 50)`) is lane B's W42-T37. Until
401
- #: that lands the two ends disagree, and the server is the permissive one.
402
- MAX_OPTIONS = 200
403
  #: the badge the nav paints for a table with no connector behind it
404
  BLANK_SOURCE = 'Blank'
405
  #: automation-created tables carry their maker instead (wave 18 C4-AUTO)
@@ -818,6 +777,12 @@ def _ag_geocode(raw):
818
  return _agg._clean_geocode(raw)
819
 
820
 
 
 
 
 
 
 
821
  #: Display formats a field may declare. ⛔ DISPLAY ONLY — none of these touches the stored value,
822
  #: which stays the scalar the fold or the mapper wrote. That separation is the whole safety of the
823
  #: feature: a `thousands` setting can never make a number wrong, only easier to read.
@@ -843,176 +808,8 @@ FIELD_AGGS = ('sum', 'average', 'median', 'min', 'max', 'count')
843
  #: A choice colour, as the client's editor spells one. `#RRGGBB`, upper-cased on the way in so a
844
  #: stored value has exactly ONE spelling and two fields cannot disagree about `#ebf6ef`.
845
  _OPTION_COLOR_RE = re.compile(r'#[0-9A-F]{6}')
846
-
847
- #: ⭐⭐ W42-T32 — THE RATING SYMBOL VOCABULARY, AND IT HAS EXACTLY ONE MEMBER TODAY.
848
- #:
849
- #: ⛔ THE HONEST LIST IS THE SHORT ONE. `iconShapes.ts::TYPE_SHAPES` (:54) is keyed by field TYPE,
850
- #: not by symbol, and its `rating` entry holds ONE path: a star. A repo-wide sweep for
851
- #: `ratingSymbol` / `rating_symbol` / `RATING_SHAPES` / `symbolChoices` returns zero hits — no
852
- #: rating-symbol vocabulary exists anywhere in the product. So this list names what the client can
853
- #: genuinely DRAW and nothing else. Inventing `heart`/`flag`/`thumb` here would ship a picker whose
854
- #: members render as nothing: a list that LOOKS complete and is not is worse than an honest single
855
- #: member, because the gap is then invisible to the next reader instead of stated.
856
- #: ⭢ A wave-43 ticket that wants more symbols extends `iconShapes.ts::TYPE_SHAPES` FIRST and this
857
- #: tuple second. The order matters: a name here with no path there is a blank cell.
858
- RATING_SYMBOLS = ('star',)
859
- RATING_SYMBOL_DEFAULT = 'star'
860
-
861
- #: ⭐⭐ W42-T32 — THE CHECKBOX MARK. Same posture and the same honesty as `RATING_SYMBOLS`: the
862
- #: only checkbox geometry in the client is `TYPE_SHAPES.checkbox` (a square plus a tick), and the
863
- #: cell itself paints glide's stock `BooleanCell` tick (`cells.ts:539`) in the shared theme accent
864
- #: `LP_BLUE_DEEP` (`theme.ts:100`). That accent IS "today's mark", recorded here as the value an
865
- #: unset column means.
866
- #: ⛔ THE DEFAULTS ARE NOT EMITTED BY THE VALIDATOR, and that is deliberate rather than lazy.
867
- #: `verify_api.py` and `verify_automation.py` assert `_clean_field(f) == f` over every
868
- #: engine-seeded field list, so a branch stamping `icon`/`color` onto every checkbox column would
869
- #: redden both gates for every preset column in the product ([[default-must-pass-its-own-guard]]).
870
- #: ABSENCE MEANS THE DEFAULT, and `checkbox_mark()` below is the one reader that resolves it.
871
- CHECKBOX_ICONS = ('check',)
872
- CHECKBOX_ICON_DEFAULT = 'check'
873
- CHECKBOX_COLOR_DEFAULT = '#768FB6'
874
-
875
- #: The column kinds that can carry a `defaultValue` at all. ⛔ A TEXT COLUMN IS DELIBERATELY OUT:
876
- #: the done-when names seven kinds, and every one of them has a vocabulary or a shape the
877
- #: validator can check a default AGAINST. A free-text default would be a string nothing can refuse,
878
- #: which is a stored preference rather than a validated setting.
879
- #: ⛔ Every COMPUTED kind is out by construction (`rollup`, `formula`, `link`, `ai_enrich`,
880
- #: `metric`), and `row_defaults` re-checks that with `is_computed_cell` before applying one: a
881
- #: default written into a cell the server recomputes is an invented value with a delay on it.
882
- DEFAULT_VALUE_TYPES = ('select', 'multiselect', 'checkbox', 'int', 'currency', 'pct', 'date')
883
-
884
- #: The "this default is unusable" answer, distinct from `None` which means "no default here".
885
- #: ⚠ A SENTINEL OBJECT RATHER THAN A FALSY VALUE, because `0` and `False` are both legitimate
886
- #: defaults: `defaultValue: 0` on an int column and `defaultValue: False` on a checkbox are
887
- #: exactly the settings a person would set, and a truthiness test would silently discard them.
888
- _DEFAULT_REFUSED = object()
889
-
890
-
891
- def _clean_default_value(value, ftype, options):
892
- """One `defaultValue` → the stored value, `None` (none set / cleared), or `_DEFAULT_REFUSED`.
893
-
894
- ⭐⭐ W42-T32 — A FIELD CARRIES ITS OWN CONFIGURATION, NOT JUST ITS TYPE.
895
-
896
- ⛔ AN OUT-OF-VOCABULARY SELECT DEFAULT REFUSES THE FIELD rather than dropping the key, and the
897
- posture is `metric`/`profile`'s rather than `agg`'s on purpose. A dropped key is a setting the
898
- user chose, saved, and will not find again — the exact silent-loss shape this module is a
899
- museum of. A refusal is a sentence at the door. `select` and `multiselect` are the two kinds
900
- where "outside the declared options" is even askable, which is why the done-when names them.
901
-
902
- ⚠ THE NUMERIC AND DATE FAMILIES DELEGATE TO `cell_type_refusal`, the module's existing
903
- evaluator for "can this value be this column's value". A second opinion on whether a string is
904
- a date is how two doors start disagreeing ([[one-evaluator-per-question]]).
905
-
906
- ⚠ `bool` IS AN `int` SUBCLASS, so `True` in an int column's default would otherwise store as
907
- the number 1. Refused, not interpreted — the same guard `decimals` carries in `_clean_format`.
908
- """
909
- if value is None:
910
- return None
911
- if ftype not in DEFAULT_VALUE_TYPES:
912
- return _DEFAULT_REFUSED
913
- if ftype == 'checkbox':
914
- return value if isinstance(value, bool) else _DEFAULT_REFUSED
915
- if ftype == 'select':
916
- text = ' '.join(str(value).split())[:60]
917
- return text if text and text in (options or []) else _DEFAULT_REFUSED
918
- if ftype == 'multiselect':
919
- if not isinstance(value, (list, tuple)):
920
- return _DEFAULT_REFUSED
921
- picked = [' '.join(str(v).split())[:60] for v in value]
922
- if not picked or any(p not in (options or []) for p in picked):
923
- return _DEFAULT_REFUSED
924
- return picked
925
- if ftype in _NUMERIC_CELL_TYPES:
926
- if isinstance(value, bool) or not isinstance(value, (int, float)):
927
- return _DEFAULT_REFUSED
928
- return value
929
- if cell_type_refusal({'type': ftype, 'label': 'default'}, value):
930
- return _DEFAULT_REFUSED
931
- return ' '.join(str(value).split())
932
-
933
-
934
- def checkbox_mark(field):
935
- """The icon and colour a checkbox column actually renders with. ⛔ THE ONE RESOLVER.
936
-
937
- Absence means the default (see `CHECKBOX_ICONS`' note for why the validator does not stamp
938
- one), so every reader must come through here or two surfaces will disagree about what an
939
- unconfigured checkbox looks like.
940
- """
941
- f = field if isinstance(field, dict) else {}
942
- return {'icon': f.get('icon') or CHECKBOX_ICON_DEFAULT,
943
- # ``colour`` was accepted by an earlier field-editor draft. Read it for
944
- # old definitions, but keep the product wire canonical as ``color``.
945
- 'color': f.get('color') or f.get('colour') or CHECKBOX_COLOR_DEFAULT}
946
-
947
-
948
- def rating_symbol(field):
949
- """The symbol a rating column draws. Absence means `RATING_SYMBOL_DEFAULT`, same rule."""
950
- return (field if isinstance(field, dict) else {}).get('symbol') or RATING_SYMBOL_DEFAULT
951
-
952
-
953
- def _default_cell_text(value):
954
- """A validated `defaultValue` → the STORED CELL string, in the store's own vocabularies.
955
-
956
- ⛔ THE CONTRACTS ARE THE STORE'S, NOT THIS FUNCTION'S INVENTION. A checkbox cell is `'1'` or
957
- empty (`aios_grid.py:133`, `cells.ts:10`, `display.ts::checkboxOn`), and a multiselect cell is
958
- a COMMA-JOINED set (`cells.ts:789`). Written as a bare `str(value)` a checkbox default would
959
- store the text `'True'`, which `checkboxOn` reads as unchecked: a default that saves, reads
960
- back, and renders as off. That is the "a default that is not applied is not a default" failure
961
- arriving one layer lower down than expected.
962
- """
963
- if value is True:
964
- return '1'
965
- if value is False:
966
- return ''
967
- if isinstance(value, (list, tuple)):
968
- return ', '.join(str(v) for v in value)
969
- return str(value)
970
-
971
-
972
- def row_defaults(fields):
973
- """`{field key: stored cell text}` for every column declaring a default. ⛔ ONE DERIVATION.
974
-
975
- ⭐⭐ W42-T32 — **A DEFAULT THAT IS NOT APPLIED IS NOT A DEFAULT.** Storing the setting and
976
- stopping there is a key with no importer, which is the shape this repo has shipped repeatedly:
977
- the pane saves, the request succeeds, and every new row is still blank. Both row-create doors
978
- (`add_row`, `add_rows`) read this.
979
-
980
- ⛔ A COMPUTED CELL IS SKIPPED. `is_computed_cell` is the module's own predicate for "the server
981
- owns this number"; seeding one is an invented value the next compute pass overwrites, with
982
- nothing anywhere to notice. `DEFAULT_VALUE_TYPES` already excludes the computed TYPES, so this
983
- catches the remaining case: a `metric` bag sitting on an `int` column.
984
- """
985
- out = {}
986
- for f in fields or []:
987
- if not isinstance(f, dict) or 'defaultValue' not in f:
988
- continue
989
- if is_computed_cell(f):
990
- continue
991
- key = str(f.get('key') or '')
992
- if key:
993
- out[key] = _default_cell_text(f['defaultValue'])
994
- return out
995
-
996
-
997
- def option_cap_refusal(raw_options):
998
- """Why this option list cannot be stored, NAMING THE COUNT, or None if it fits.
999
-
1000
- ⭐⭐ W42-T36 — **STANDING RULE 1'S SECOND HALF, WHICH IS THE HALF THAT GETS DROPPED.** A limit
1001
- that cannot be removed must be REPORTED with its cause, never silently enforced. Both option
1002
- doors were bare `[:50]` slices: they dropped the tail with no error, so the only way to learn
1003
- the cap existed was to count the column afterwards. Raising 50 to `MAX_OPTIONS` without this
1004
- would have moved where the silence happens and changed nothing about the silence.
1005
-
1006
- ⚠ THIS FUNCTION IS THE WORDS; the WALL is in `_clean_field` and `clean_fields`, which refuse.
1007
- They are separate because a validator that returns `None` cannot carry a sentence, and the
1008
- route that answers the browser (`routes_tables._refusal_sentence`) is outside this module. A
1009
- surface wanting the sentence calls this; nothing here depends on it having been called.
1010
- """
1011
- n = len([o for o in (raw_options or []) if str(o).strip()])
1012
- if n <= MAX_OPTIONS:
1013
- return None
1014
- return (f'That column declares {n} options and the limit is {MAX_OPTIONS}. '
1015
- f'Remove {n - MAX_OPTIONS} of them, or split the vocabulary across two columns.')
1016
 
1017
 
1018
  def _clean_option_colors(raw, options):
@@ -1046,28 +843,57 @@ def _clean_option_colors(raw, options):
1046
  return out
1047
 
1048
 
1049
- #: ⭐⭐ W42-T33 — THE CURRENCY SYMBOL VOCABULARY, DELIBERATELY CLOSED.
1050
- #:
1051
- #: ⚠ REFERENCE DIVERGENCE, RECORDED SO A LATER READER DOES NOT THINK WE MATCHED IT. Airtable's own
1052
- #: create-field panel offers the currency symbol as a FREE TEXT INPUT
1053
- #: (`reference/airtable-field-docs/9701435990-number-based-fields-in-airtable__1.png`). We are
1054
- #: keeping a closed list ON PURPOSE: a validator that admits arbitrary text into a symbol that then
1055
- #: prefixes every number in a rendered money column is the worse trade, and this module's whole
1056
- #: posture is refuse-do-not-coerce. Widening the list is a one-line change; narrowing it after
1057
- #: arbitrary text has been stored is a migration.
1058
- FORMAT_CURRENCY_SYMBOLS = ('$', '€', '£', '¥', '₩', '₹', 'CHF', 'C$', 'A$', 'S$', 'HK$', 'R$')
1059
-
1060
- #: ⭐⭐ W42-T33 — the DURATION kinds, on `int` columns only. These name a DISPLAY shape and nothing
1061
- #: else: the stored value stays a plain integer count of seconds, which is the entire point (see
1062
- #: `_clean_format`'s note). Vocabulary matches Airtable's duration formats, which is what any
1063
- #: importer or exporter will already speak.
1064
- FORMAT_DURATION_KINDS = ('h:mm', 'h:mm:ss', 'h:mm:ss.s', 'h:mm:ss.ss', 'h:mm:ss.sss')
1065
-
1066
- #: The kinds `allowNegative` can speak about at all. A text or date column has no sign.
1067
- _FORMAT_SIGNED_TYPES = ('int', 'currency', 'pct')
1068
-
1069
-
1070
- def _clean_format(raw, ftype=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1071
  """One `format` bag → the stored shape, or None.
1072
 
1073
  ⛔⛔ THIS FUNCTION EXISTS BECAUSE THE BAG HAD NO STORAGE AT ALL. The column menu has shipped a
@@ -1099,39 +925,6 @@ def _clean_format(raw, ftype=None):
1099
  tz = str(raw.get('tz') or '').strip().lower()
1100
  if tz in FORMAT_TZ:
1101
  out['tz'] = tz
1102
- # ⭐⭐ W42-T33 — A NUMBER COLUMN SAYS WHAT IT MEANS.
1103
- #
1104
- # ⛔ THE SIGNATURE GREW A TYPE, AND IT HAD TO. "a `duration` format on `int`" is not a
1105
- # question this function could answer as written: it took one bag and no field type, so the
1106
- # rule would have had to be re-stated wherever the type IS known, which is two more copies of
1107
- # a validator ([[one-evaluator-per-question]]). `ftype` is in scope at BOTH in-tree call sites
1108
- # (`clean_fields`, `_clean_field`) and both now pass it — changing only one would have left
1109
- # the rule holding on the CREATE door and not the PATCH door, or the reverse, which is D-91's
1110
- # exact class. ⚠ The sibling `aios_grid._clean_format(raw, ftype)` has taken a type since
1111
- # wave 5; this is the two validators converging, not diverging.
1112
- # ⚠ `ftype=None` KEEPS THE CALL SHAPE VALID for a caller with no type context, and then judges
1113
- # the type-guarded keys on SHAPE alone. Both in-tree callers pass a real type.
1114
- symbol = str(raw.get('symbol') or '').strip()
1115
- if symbol in FORMAT_CURRENCY_SYMBOLS and ftype in (None, 'currency'):
1116
- out['symbol'] = symbol
1117
- # ⚠ `bool` IS AN `int` SUBCLASS and this bag is mostly booleans, so the guard runs the other
1118
- # way here: `allowNegative` must be a REAL bool, which `isinstance(x, bool)` already gives.
1119
- # ⛔ ABSENT MEANS ALLOWED, and that is what makes this safe to ship. Every number column in
1120
- # every user database has no `allowNegative` today; a default of False would start refusing
1121
- # values those columns already hold. Only an EXPLICIT `False` is a wall.
1122
- allow_negative = raw.get('allowNegative')
1123
- if isinstance(allow_negative, bool) and ftype in (None,) + _FORMAT_SIGNED_TYPES:
1124
- out['allowNegative'] = allow_negative
1125
- duration = str(raw.get('duration') or '').strip().lower()
1126
- if duration in FORMAT_DURATION_KINDS and ftype in (None, 'int'):
1127
- out['duration'] = duration
1128
- # ⛔ `duration` AND `time` CANNOT BOTH STAND, and the resolution is to keep `duration`
1129
- # rather than to refuse the bag. `time` means "this DATE also shows a clock" and is read
1130
- # by the date renderer; a duration is an elapsed count on an `int` column. Both set is a
1131
- # contradiction, but returning None for it would silently discard the user's UNRELATED
1132
- # format choices in the same bag (decimals, thousands, the lot) to punish one stray key.
1133
- # The narrower key wins and the contradiction is dropped, not the document.
1134
- out.pop('time', None)
1135
  return out or None
1136
 
1137
 
@@ -1155,10 +948,7 @@ def clean_fields(raw):
1155
  # ⭐ 2026-08-10 — the DISPLAY format, carried through the CREATE door. See `_clean_format`:
1156
  # this is the fifth time an entry built key-by-key has silently dropped a bag the editor
1157
  # sends, and the fourth of those was `agg` on this very line one wave ago.
1158
- # ⚠ W42-T33 — `ftype` is passed HERE TOO, not only on the patch door. A currency symbol or
1159
- # a duration kind that survived one door and not the other is the crossed-validator shape
1160
- # this file keeps paying for.
1161
- fmt = _clean_format(f.get('format'), ftype)
1162
  if fmt:
1163
  entry['format'] = fmt
1164
  description = ' '.join(str(f.get('description') or '').split())[:300]
@@ -1174,46 +964,9 @@ def clean_fields(raw):
1174
  if note:
1175
  entry['note'] = note
1176
  if ftype in ('select', 'multiselect'):
1177
- # ⭐⭐ W42-T36 — ONE declared cap, and it REFUSES rather than truncating. See
1178
- # `MAX_OPTIONS`. ⚠ This door DROPS the field rather than returning None for the whole
1179
- # list, which is `clean_fields`' existing posture for every other refusal here (an
1180
- # unknown type, a duplicate key): one bad column must not cost the caller the other
1181
- # fifty-nine. `option_cap_refusal` names the count for the surface that asks.
1182
  opts = [' '.join(str(o).split())[:60] for o in (f.get('options') or [])
1183
- if str(o).strip()]
1184
- if len(opts) > MAX_OPTIONS:
1185
- continue
1186
- if opts:
1187
- entry['options'] = opts
1188
- # ⭐⭐ W42-T32 — THE FIVE CONFIGURATION KEYS, ON THIS DOOR TOO, IN THE SAME CHANGE.
1189
- #
1190
- # ⛔ THIS FUNCTION BUILDS ITS ENTRY KEY-BY-KEY, and the module's own note twenty lines up
1191
- # says what that costs: *"this is the fifth time an entry built key-by-key has silently
1192
- # dropped a bag the editor sends"*. `create()` (:1371) and `set_fields` (:1479) both come
1193
- # through here, and `create` IS a user door, so a column authored with a default at table
1194
- # creation would have arrived without it while the very same column patched a second later
1195
- # kept it. One validator's answer, two doors, or it is D-91 again.
1196
- # ⚠ DROP, DO NOT REFUSE, which is this door's posture for every other refusal it makes
1197
- # (an unknown type, a duplicate key, an over-cap option list): one unusable setting must
1198
- # not cost the caller the column. `_clean_field` refuses instead, because it is handed ONE
1199
- # field and `None` is the only refusal it has.
1200
- if 'defaultValue' in f:
1201
- dv = _clean_default_value(f.get('defaultValue'), ftype, entry.get('options') or [])
1202
- if dv is not None and dv is not _DEFAULT_REFUSED:
1203
- entry['defaultValue'] = dv
1204
- if ftype == 'user' and f.get('single') is True:
1205
- entry['single'] = True
1206
- if ftype == 'rating':
1207
- sym = str(f.get('symbol') or '').strip().lower()
1208
- if sym in RATING_SYMBOLS:
1209
- entry['symbol'] = sym
1210
- if ftype == 'checkbox':
1211
- icon = str(f.get('icon') or '').strip().lower()
1212
- if icon in CHECKBOX_ICONS:
1213
- entry['icon'] = icon
1214
- cb_color = str(f.get('color') or f.get('colour') or '').strip().upper()
1215
- if _OPTION_COLOR_RE.fullmatch(cb_color):
1216
- entry['color'] = cb_color
1217
  if f.get('default') is True:
1218
  entry['default'] = True
1219
  # ⭐ WAVE-27 item 19 (R15) + D-80 — THE PRIMARY COLUMN, CARRIED THROUGH THE CREATE DOOR.
@@ -1259,16 +1012,6 @@ def clean_fields(raw):
1259
  # ⛔ THE TYPE/BAG PAIRING IS ENFORCED BOTH WAYS, as it is in `_clean_field`: a `link` with
1260
  # no bag can never resolve a row, and a bag on a column of another type is a declaration
1261
  # nothing reads. Either half alone is the silent kind of broken.
1262
- # ⚠ W42-T35 — AND THIS DOOR STAYS SHAPE-ONLY FOR A LINK'S RECORD FILTER, DECLINED WITH
1263
- # ITS REASON RATHER THAN OVERLOOKED. `_clean_link` validates a filter's COLUMN NAMES only
1264
- # when a caller hands it the target's column set, and this function has no `st` to
1265
- # resolve one from: `clean_fields` is reached from `create()`/`set_fields()`, neither of
1266
- # which carries a store handle at the point the field list is cleaned. `add_field` and
1267
- # `patch_field` both do, and both check there (`link_filter_refusal`). The gap is LATENT,
1268
- # not live, for the reason the paragraph above already gives: no API route calls
1269
- # `set_fields`, and `odoo_relational` writes its definitions directly. It stops being
1270
- # latent the moment a route does, and closing it means plumbing `st` through this
1271
- # signature, which is a caller-visible change outside one ticket's fence.
1272
  for bag_key, cleaner in (('link', _clean_link), ('rollup', _clean_rollup)):
1273
  bag = cleaner(f.get(bag_key)) if f.get(bag_key) is not None else None
1274
  if ftype == bag_key and bag is None:
@@ -1312,6 +1055,13 @@ def clean_fields(raw):
1312
  geo = (_ag_geocode(f.get('geocode')) if f.get('geocode') is not None else None)
1313
  if geo and ftype == 'text':
1314
  entry['geocode'] = geo
 
 
 
 
 
 
 
1315
  if entry is None:
1316
  seen.discard(key)
1317
  continue
@@ -1385,6 +1135,203 @@ def get(table_key, st=None):
1385
  return all_tables(st).get(str(table_key))
1386
 
1387
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1388
  def is_user_table(table_key, st=None):
1389
  """THE permission predicate for row writes. Cheap and total: a key that is not in this store
1390
  is not a user table, so it cannot accept invented rows."""
@@ -1456,6 +1403,15 @@ def delete(table_key, st=None):
1456
  return cur
1457
  s.update(STORE_KEY, _drop, flush='sync')
1458
 
 
 
 
 
 
 
 
 
 
1459
  ws_key = f'{key}_table_workspace'
1460
  view_ids = set()
1461
  try:
@@ -1568,15 +1524,6 @@ def add_row(table_key, values=None, username=None, st=None, rid=None):
1568
  rid = str(max((int(r) for r in rows if str(r).isdigit()), default=0) + 1)
1569
  valid = {f['key'] for f in (defn.get('fields') or [])}
1570
  clean = {k: str(v) for k, v in (values or {}).items() if k in valid}
1571
- # ⭐⭐ W42-T32 — THE COLUMN DEFAULTS, APPLIED. A stored `defaultValue` that no writer reads is
1572
- # a setting the pane saves and nothing honours; `row_defaults` is the one derivation and this
1573
- # is one of its two callers.
1574
- # ⚠ ONLY WHERE THE CALLER SAID NOTHING. An explicit value always wins, including an explicit
1575
- # BLANK — clearing a cell on the way in is a thing a caller may mean, and a default that
1576
- # overrode it would make the column impossible to leave empty.
1577
- for _dk, _dv in row_defaults(defn.get('fields') or []).items():
1578
- if _dk in valid and _dk not in clean:
1579
- clean[_dk] = _dv
1580
  # C3 (wave 25): a PROFILE cell is validated and normalised on the insert door too, not only
1581
  # on the edit door. A row born with `https://instagram.com/p/Cxyz` in its handle column is a
1582
  # row the enrich action can never answer, and the failure would otherwise surface as an
@@ -1592,6 +1539,7 @@ def add_row(table_key, values=None, username=None, st=None, rid=None):
1592
  t = cur.get(str(table_key))
1593
  if t is not None:
1594
  t.setdefault('rows', {})[rid] = clean
 
1595
  return cur
1596
 
1597
  _st(st).update(STORE_KEY, _add, flush='async')
@@ -1639,17 +1587,9 @@ def add_rows(table_key, rows_in, username=None, st=None):
1639
  valid = {f['key'] for f in (defn.get('fields') or [])}
1640
  pf = _profile_of(defn.get('fields') or [])
1641
  next_id = max((int(r) for r in rows if str(r).isdigit()), default=0)
1642
- # ⭐⭐ W42-T32 — the same defaults as `add_row`, DERIVED ONCE for the whole batch. Both doors
1643
- # read one function, so an imported row and a typed row cannot disagree about what a column's
1644
- # default is; computing it per row would also be a full field scan per line of a 2,000-row
1645
- # import, which is the shape this function exists to avoid.
1646
- row_default_cells = row_defaults(defn.get('fields') or [])
1647
  made = []
1648
  for values in batch:
1649
  clean = {k: str(v) for k, v in values.items() if k in valid}
1650
- for _dk, _dv in row_default_cells.items():
1651
- if _dk in valid and _dk not in clean:
1652
- clean[_dk] = _dv
1653
  if pf and pf['key'] in clean:
1654
  handle, ok = normalize_profile(clean[pf['key']], pf['profile'].get('source'))
1655
  if not ok:
@@ -1664,6 +1604,7 @@ def add_rows(table_key, rows_in, username=None, st=None):
1664
  bucket = t.setdefault('rows', {})
1665
  for rid, clean in made:
1666
  bucket[rid] = clean
 
1667
  return cur
1668
 
1669
  _st(st).update(STORE_KEY, _add, flush='sync')
@@ -1909,340 +1850,7 @@ def is_linkable_target(table_key):
1909
  return key.startswith(KEY_PREFIX) and len(key) > len(KEY_PREFIX)
1910
 
1911
 
1912
- #: ⭐⭐ W42-T03 / RULING R1 / CONTRACT C1 (2026-08-25) — THE NINE KEYS OF THE `via` HOP BAG.
1913
- #:
1914
- #: R1: *"a user-created link field may take TWO HOPS, the user configures the hop with the existing
1915
- #: filter UI, capped structurally at one `via`"*. `via` is OPTIONAL; absent means today's one-hop
1916
- #: join, unchanged to the byte. Present, it names the MIDDLE topic the join travels through:
1917
- #: `customer -> (sales_lines) -> product`, which is what RETIRES `routes_grid._PIVOT_ROUTES`, a
1918
- #: hand-written table of exactly one route.
1919
- #:
1920
- #: ⚠ RETIRES, NOT YET DELETES, and the distinction is load-bearing (A23, 2026-08-25, corrected
1921
- #: after this paragraph shipped saying "dissolves"). `_PIVOT_ROUTES` is still on disk as a DATED
1922
- #: SINGLE-PAIR TOMBSTONE, because no user-created link field can exist on a topic grid yet:
1923
- #: `aios_grid.FIELDS` holds zero entries of type `link` and `add_field` refuses non-`ut_` keys, so
1924
- #: deleting the table outright would have taken the customer-to-product pivot off the public live
1925
- #: domain. `routes_grid._pivot_route` tries THIS bag first and reaches the tombstone only when the
1926
- #: strict door refuses, so the tombstone expires by itself the moment a real `via` exists on that
1927
- #: pair. Wave 43's storage ticket deletes it, and `verify_pivot.py` section 13 is the proof it may.
1928
- #:
1929
- #: ⛔ `target_key` AND `scope_key` ARE REQUIRED AND ARE NOT DIM NAMES. This is the trap the
1930
- #: contract names by hand, because both LOOK like the two dims sitting beside them. `target_dim`
1931
- #: is a dim of the TOPIC (`product_code` on `sales_lines`); `target_key` is the column the TARGET
1932
- #: GRID joins on (`code` on `product_data`), and `scope_key` is the cohort bucket (`customer`).
1933
- #: Validating either as a dim refuses every legal bag; omitting either is worse — the target-row
1934
- #: filter then matches nothing and the reply is a 200 with `rows: []` and NO refusal, the silent
1935
- #: lie `_pivot_reply` exists to forbid. So both are required and neither is checked against dims.
1936
- #:
1937
- #: ⚠ `source_key` IS DELIBERATELY ABSENT, and it is the seventh key of the route table rather than
1938
- #: a forgotten one. `grid_pivot` only ever self-checked it (`!= "pid"` -> 500) and never passed it
1939
- #: downstream, so it dies WHEN THE TOMBSTONE DOES, not before. Do not add it: `_clean_via` refuses it by name
1940
- #: through this very allowlist, and `verify_pivot.py` asserts that refusal.
1941
- #:
1942
- #: ⛔ THE ORDER OF THESE NAMES IS NOT DECORATIVE — `verify_pivot.py` extracts the keys
1943
- #: `_clean_via` actually reads FROM ITS AST and asserts they are exactly this tuple. A key added
1944
- #: here with no `raw.get('<key>')` beside it (or read through a `for key in (...)` loop, which the
1945
- #: extractor cannot see) turns that gate red rather than shipping a key the client can send and
1946
- #: the server silently drops.
1947
- LINK_VIA_KEYS = ('topic', 'source_dim', 'target_dim', 'target_key', 'scope_key', 'measure',
1948
- 'filter', 'filterConj', 'window')
1949
-
1950
- #: The conjunctions the hop filter may name. Mirrors `clean_filter_tree`'s own two.
1951
- LINK_VIA_CONJ = ('and', 'or')
1952
-
1953
- #: The date-window kinds the hop may name. ⛔ IT IS `ROLLUP_SOURCE_WINDOWS` ITSELF, BOUND TO A
1954
- #: SECOND NAME RATHER THAN COPIED, so the two bags cannot drift into different calendars: this
1955
- #: module already keeps that tuple as the local mirror of `harness/windows.py::WINDOW_KINDS`, it
1956
- #: is what `GET /tables/rollup-sources` serves, and it is what the field editor's existing rollup
1957
- #: branch already emits.
1958
- #:
1959
- #: ⛔⛔ THERE IS NO BARE `'all'`, AND THE NEAR-MISS IS WORTH KEEPING (wave 42 amendment A5). C1's
1960
- #: first draft wrote `"window": "all"` while the client shipped `all_time`. Had the server
1961
- #: accepted the alias, every hop a user built would have failed at the window WITH BOTH LANES'
1962
- #: GATES GREEN — a parity gate that compares key NAMES sees a key-set match and is blind to a
1963
- #: value mismatch. That is why `verify_pivot.py` asserts the accepted VALUE set for `window` too,
1964
- #: and why this validator names the shared constant instead of a literal anybody could retype.
1965
- LINK_VIA_WINDOWS = ROLLUP_SOURCE_WINDOWS
1966
-
1967
-
1968
- def _topic_dims(topic):
1969
- """The dim names declared by a topic, or None when nothing declares that topic.
1970
-
1971
- ⛔ THE MODEL FILES, NEVER THE STORE. `harness.semantic.topics()` is a cached read of
1972
- `platform/model/topics/*.yml` and touches no DuckDB connection at all. That is the whole
1973
- reason this helper exists rather than a `store_columns` call: a validator that needed the
1974
- store to say yes would refuse every legal link the moment the file was locked by a
1975
- `validate.py` run or cold after a restart, and the user would see a correctly configured
1976
- column refused for reasons nothing on screen could explain.
1977
-
1978
- ⚠ The import is function-local for the reason `_ag_formula` states two hundred lines up:
1979
- `core` must stay importable without the layers above it, and one module-level `import
1980
- harness...` here is how the API's boot path grows a cycle.
1981
- """
1982
- if not topic:
1983
- return None
1984
- try:
1985
- from harness import semantic as _sem
1986
- t = (_sem.topics() or {}).get(topic)
1987
- except Exception:
1988
- # ⛔ FAIL CLOSED. An unreadable model is not a licence to accept an unvalidated topic;
1989
- # it is a reason to refuse until somebody can say what the topic means.
1990
- return None
1991
- if not t:
1992
- return None
1993
- dims = ((t.get('store') or {}).get('dims')) or {}
1994
- return frozenset(dims) or None
1995
-
1996
-
1997
- def _clean_via_filter(raw, depth=1, budget=None):
1998
- """The hop's condition tree, SHAPE-validated, or None (refuse the field).
1999
-
2000
- ⛔ SHAPE ONLY, AND THAT IS THE DIVISION OF LABOUR C1 DRAWS. Whether `category` is a real
2001
- column of `sales_lines` is answered by `harness/semantic.py::_clean_tree(tree,
2002
- store_columns(topic))` on the way to the engine (W42-T06's ticket), never here and NEVER by
2003
- `_clean_rollup`, whose source-backed branch returns before it reads a filter at all. What
2004
- this function guarantees is that what got stored is a `FilterNode[]` at all: a list of
2005
- objects, nested no deeper than the shared cap, with JSON-shaped values.
2006
-
2007
- ⛔ IT REFUSES RATHER THAN TRUNCATES, matching `_clean_tree` and departing from
2008
- `clean_filter_tree` on purpose. Dropping an AND-condition WIDENS the set the hop measures
2009
- while the column keeps its name, which is the silent-different-answer failure
2010
- [[no-unverifiable-aggregates]] forbids. The client's cap is a per-render DoS guard where a
2011
- dropped leaf is the lesser evil; a stored one is not.
2012
- """
2013
- import aios_grid as _agv
2014
- if budget is None:
2015
- budget = [_agv.MAX_FILTER_NODES]
2016
- if not isinstance(raw, list):
2017
- return None
2018
- if len(raw) > _agv.MAX_FILTER_SIBLINGS:
2019
- return None
2020
- out = []
2021
- for node in raw:
2022
- if not isinstance(node, dict):
2023
- return None
2024
- budget[0] -= 1
2025
- if budget[0] < 0:
2026
- return None
2027
- children = node.get('children')
2028
- if isinstance(children, list):
2029
- if depth >= _agv.MAX_FILTER_DEPTH:
2030
- return None
2031
- kids = _clean_via_filter(children, depth + 1, budget)
2032
- if kids is None:
2033
- return None
2034
- out.append({'conj': 'or' if node.get('conj') == 'or' else 'and', 'children': kids})
2035
- continue
2036
- leaf = {}
2037
- for k, v in node.items():
2038
- if not isinstance(k, str):
2039
- return None
2040
- if isinstance(v, str):
2041
- leaf[k] = v[:500]
2042
- elif isinstance(v, (int, float, bool)) or v is None:
2043
- leaf[k] = v
2044
- elif isinstance(v, (list, dict)):
2045
- # A CG-8 measure condition carries a nested `window` object, so a leaf may hold
2046
- # structure. It is passed on untouched for the engine's own validator to judge;
2047
- # what is refused is anything that is not JSON at all.
2048
- leaf[k] = v
2049
- else:
2050
- return None
2051
- out.append(leaf)
2052
- return out
2053
-
2054
-
2055
- def _clean_via(raw):
2056
- """One `via` hop bag → the stored shape, or None (REFUSE THE WHOLE FIELD).
2057
-
2058
- ⛔⛔ THE ONE-HOP CAP IS THE FIRST LINE OF THIS FUNCTION AND IT IS HAND-WRITTEN. `_clean_link`
2059
- is flat and reads six named keys, silently dropping every other key on the bag — so a `via`
2060
- nested inside a `via` would be DROPPED, not refused, and the field would store a two-hop
2061
- configuration wearing a one-hop shape. Recursing into the sub-bag would be exactly as blind.
2062
- The check is `'via' in raw`, MEMBERSHIP AND NOT TRUTHINESS: `{'via': None}` and `{'via': {}}`
2063
- are both falsy, and a `.get()` test would wave both through and drop the key, which is the
2064
- silent failure this cap exists to make impossible.
2065
-
2066
- ⚠ The allowlist below would also catch a nested `via` (it is not one of the nine names). That
2067
- redundancy is deliberate and the order is load-bearing: C1 requires the cap to be a check
2068
- somebody WROTE, not a side effect of an allowlist that a later ticket might loosen to admit a
2069
- tenth key.
2070
-
2071
- ⛔ THE ALLOWLIST IS INSIDE THE `via` BAG ONLY, never on the outer `link` bag. W42-T35 adds a
2072
- SECOND and different filter to the outer bag — a condition tree over the TARGET database's own
2073
- columns, restricting which records a person may pick — and a strict outer allowlist would
2074
- refuse it before it could land. `via.filter` filters the middle TOPIC; they are two keys, two
2075
- validators and two tickets.
2076
- """
2077
- if not isinstance(raw, dict):
2078
- return None
2079
- if 'via' in raw:
2080
- return None # the cap. Membership, not truthiness. See the docstring.
2081
- for key in raw:
2082
- if key not in LINK_VIA_KEYS:
2083
- return None
2084
- # ⛔ Each key is read by a LITERAL `raw.get('<name>')`. A `for key in (...)` loop would be
2085
- # shorter and would make `verify_pivot.py`'s AST extraction blind to every key in it, so the
2086
- # gate would assert parity over a set that quietly excluded them.
2087
- topic = str(raw.get('topic') or '').strip()
2088
- dims = _topic_dims(topic)
2089
- if not dims:
2090
- return None
2091
- source_dim = str(raw.get('source_dim') or '').strip()
2092
- target_dim = str(raw.get('target_dim') or '').strip()
2093
- if source_dim not in dims or target_dim not in dims:
2094
- return None
2095
- # ⛔ NOT DIMS, AND NOT DEFAULTED FROM `on`. `target_key` and C1's example `on` both read
2096
- # `code` here, which makes a fallback look free; it is not, because then a bag that omits
2097
- # `target_key` would be silently repaired instead of refused, and the refusal is the whole
2098
- # point of requiring it.
2099
- target_key = _field_key(raw.get('target_key'))
2100
- scope_key = _field_key(raw.get('scope_key'))
2101
- measure = _field_key(raw.get('measure'))
2102
- if not target_key or not scope_key or not measure:
2103
- return None
2104
- out = {'topic': topic, 'source_dim': source_dim, 'target_dim': target_dim,
2105
- 'target_key': target_key, 'scope_key': scope_key, 'measure': measure}
2106
- raw_filter = raw.get('filter')
2107
- if raw_filter is not None:
2108
- nodes = _clean_via_filter(raw_filter)
2109
- if nodes is None:
2110
- return None
2111
- out['filter'] = nodes
2112
- raw_conj = raw.get('filterConj')
2113
- if raw_conj is not None:
2114
- conj = str(raw_conj).strip().lower()
2115
- if conj not in LINK_VIA_CONJ:
2116
- return None
2117
- out['filterConj'] = conj
2118
- raw_window = raw.get('window')
2119
- if raw_window is not None:
2120
- window = str(raw_window).strip().lower()
2121
- if window not in LINK_VIA_WINDOWS:
2122
- return None
2123
- out['window'] = window
2124
- return out
2125
-
2126
-
2127
- #: ⭐⭐ W42-T35 / AMENDMENT A34 (2026-08-25) — THE LEAF KEYS A RECORD-SELECTION RULE MAY CARRY.
2128
- #:
2129
- #: The feature: *"a link field can restrict which records are selectable"*. Airtable badges it
2130
- #: *Filter record selection by a condition*, a THIRD toggle beside *Allow linking to multiple
2131
- #: records* (this bag's `single`) and *Limit record selection to a view* (a curated row set, a
2132
- #: different feature that is not built here).
2133
- #:
2134
- #: ⛔⛔ IT IS AN ALLOWLIST, AND THAT IS THE ENTIRE SAFETY ARGUMENT. Airtable's condition row
2135
- #: carries a gear offering STATIC (*"filter all records by the same condition"*) or DYNAMIC
2136
- #: (*"filter records based on a field in this table"*), and DYNAMIC IS CHECKED BY DEFAULT in its
2137
- #: own documentation. `ROLLUP_CONDITION_OPS`' vocabulary has LITERAL right-hand sides only, so it
2138
- #: cannot express the dynamic mode at all: there is nowhere for "the value of a column on the ROW
2139
- #: BEING EDITED" to live. Meanwhile `_clean_link` builds its bag key by key and drops everything
2140
- #: else in silence, with no unknown-key rejection on the outer bag. Put those two facts together
2141
- #: and a dynamic leaf would be STORED AS THOUGH IT WERE STATIC, and the picker would offer the
2142
- #: WRONG RECORD SET with nothing red anywhere. A filter resolving against the wrong operand is
2143
- #: worse than no filter.
2144
- #:
2145
- #: So the refusal cannot be a blocklist of marker names somebody guessed: a marker not on the
2146
- #: guess list ships as static, which is the exact failure. This is `_clean_via`'s discipline
2147
- #: (`if key not in LINK_VIA_KEYS`) applied one level out, so `mode`, `dynamic`, `sourceField`,
2148
- #: `fromField` and whatever the client calls it next quarter are all refused BY NAME for free,
2149
- #: and `ref`/`sigmas` go with them (see `_clean_link_conditions`). The dynamic half is wave 43's,
2150
- #: booked as D-568.
2151
- LINK_FILTER_LEAF_KEYS = ('field', 'op', 'value')
2152
-
2153
-
2154
- def _clean_link_conditions(raw, columns=None):
2155
- """The `conditions` / `conditionConj` half of a `link` bag.
2156
-
2157
- Returns `(the keys to store, None)` or `(None, the sentence the refusal owes the user)`.
2158
-
2159
- ⛔⛔ THIS IS NOT `via.filter`, AND CONFUSING THE TWO SHIPS ONE FEATURE TWICE. `via.filter`
2160
- (`_clean_via_filter`, one screen up) lives INSIDE the `via` bag, is a `FilterNode[]` in
2161
- `aios_grid`'s client vocabulary, is validated against `store_columns(topic)` by
2162
- `harness/semantic.py` on the way to the engine, and filters the MIDDLE TOPIC of a two-hop
2163
- pivot. This one lives on the link bag's TOP LEVEL, speaks `_clean_rollup`'s vocabulary, is
2164
- validated against the TARGET DATABASE's own columns, and decides WHICH RECORDS A PERSON MAY
2165
- PICK IN A CELL. Two keys, two validators, two consumers.
2166
-
2167
- ⚠ AND THE KEY NAMES ARE `_clean_rollup`'s TOO, DELIBERATELY. A repo-wide grep for
2168
- `conditionConj` now answers from two bags, exactly as the `single` note at `_clean_field`'s
2169
- `user` arm describes for its own word. There is no collision to fix: these live in
2170
- `field['link']`, the twin lives in `field['rollup']`, a field carries one bag or the other and
2171
- the type/bag pairing is enforced both ways. Reusing the names is what says the two speak the
2172
- SAME vocabulary; inventing a synonym would have implied they might not.
2173
-
2174
- ⭐ THE VOCABULARY IS `_clean_rollup`'s, BY SYMBOL AND NEVER BY COPY: `ROLLUP_CONDITION_OPS`,
2175
- `ROLLUP_CONDITION_CONJ`, `ROLLUP_MAX_CONDITIONS`. A second copy of an operator list is how two
2176
- validators start disagreeing about what a filter means, and the disagreement is silent on both
2177
- sides.
2178
-
2179
- ⛔ FLAT, NOT NESTED, mirroring `_clean_rollup`'s own loop rather than `_clean_via_filter`'s
2180
- recursion. A nested tree would drag in `aios_grid`'s depth/sibling/budget caps and with them
2181
- the second vocabulary this docstring exists to keep out. One list plus one conjunction is what
2182
- the ops above can express; deeper grouping lands when the ops do.
2183
-
2184
- ⛔ `ref` / `sigmas` ARE REFUSED, and it is `_clean_rollup`'s OWN decision reused rather than a
2185
- new one: its `where` branch passes `allow_ref=False` because a set-statistic threshold needs a
2186
- FOLDED SET to be a statistic OF. A record picker folds nothing, so `mean + k*stdev` here has
2187
- no set to compute over and would freeze into whatever the first read happened to see. The leaf
2188
- allowlist above refuses both names without a branch of their own.
2189
-
2190
- ⚠ `columns=None` MEANS NOT CHECKED; `frozenset()` MEANS THE TARGET HAS NO COLUMNS. Collapsing
2191
- the two would make an unresolvable target refuse every legal rule with a sentence that reads
2192
- like the user typed the column name wrong. `_clean_link` passes `None` so that
2193
- `_clean_field(f) == f` still round-trips a stored field with no store in reach; the write
2194
- doors pass the real set in through `link_filter_refusal`.
2195
- """
2196
- raw_conditions = raw.get('conditions')
2197
- if raw_conditions is None:
2198
- return {}, None
2199
- if not isinstance(raw_conditions, list):
2200
- return None, 'A record filter has to be a list of rules.'
2201
- if len(raw_conditions) > ROLLUP_MAX_CONDITIONS:
2202
- return None, (f'A link may carry at most {ROLLUP_MAX_CONDITIONS} record filter rules, '
2203
- f'and this one carries {len(raw_conditions)}.')
2204
- conditions = []
2205
- for condition in raw_conditions:
2206
- if not isinstance(condition, dict):
2207
- return None, 'Every record filter rule has to be an object.'
2208
- # ⛔⛔ A34, AND IT IS THE FIRST THING THE LOOP DOES. Naming the offending key before the
2209
- # rule is read at all is what makes a dynamic leaf a REFUSAL WITH AN ADDRESS instead of a
2210
- # silent coercion to static.
2211
- for key in condition:
2212
- if key not in LINK_FILTER_LEAF_KEYS:
2213
- return None, (f'A record filter rule cannot carry "{key}". This link filters by '
2214
- f'a fixed value only. A rule that reads a field on the row being '
2215
- f'edited is refused rather than saved as a fixed one, because a '
2216
- f'filter resolved against the wrong column offers the wrong '
2217
- f'records with nothing to notice.')
2218
- condition_field = _field_key(condition.get('field'))
2219
- op = str(condition.get('op') or '').strip().lower()
2220
- if not condition_field:
2221
- return None, 'Every record filter rule has to name a column of the linked database.'
2222
- if op not in ROLLUP_CONDITION_OPS:
2223
- return None, f'"{op}" is not a comparison a record filter understands.'
2224
- # ⭐ THE LEFT OPERAND IS A COLUMN OF THE TARGET, which is what Airtable's own picker
2225
- # caption says in as many words: *"Choose a field from the people in the linked table"*.
2226
- if columns is not None and condition_field not in columns:
2227
- return None, (f'The linked database has no column named "{condition_field}". Pick a '
2228
- f'column it has, or drop that rule.')
2229
- item = {'field': condition_field, 'op': op}
2230
- if op not in ('is_empty', 'is_not_empty'):
2231
- value = condition.get('value')
2232
- if not isinstance(value, (str, int, float, bool)):
2233
- return None, (f'The rule on "{condition_field}" needs a value to compare '
2234
- f'against.')
2235
- item['value'] = str(value)[:1000]
2236
- conditions.append(item)
2237
- if not conditions:
2238
- return {}, None
2239
- conj = str(raw.get('conditionConj') or 'and').strip().lower()
2240
- if conj not in ROLLUP_CONDITION_CONJ:
2241
- return None, f'"{conj}" is not a way record filter rules can be joined.'
2242
- return {'conditions': conditions, 'conditionConj': conj}, None
2243
-
2244
-
2245
- def _clean_link(raw, columns=None):
2246
  """One `link` bag → the stored shape, or None (refused).
2247
 
2248
  Same posture as `_clean_metric`: a mis-shaped bag REFUSES THE FIELD. A link column stored
@@ -2268,6 +1876,17 @@ def _clean_link(raw, columns=None):
2268
  if not is_linkable_target(table):
2269
  return None
2270
  out = {'table': table}
 
 
 
 
 
 
 
 
 
 
 
2271
  on = _field_key(raw.get('on'))
2272
  frm = _field_key(raw.get('from'))
2273
  inverse = _field_key(raw.get('inverse'))
@@ -2290,126 +1909,13 @@ def _clean_link(raw, columns=None):
2290
  # than dropped: a bag half of which is silently ignored is [[wrong-parent-not-broken-control]]
2291
  # with the control still on screen.
2292
  return None
2293
- # ⭐⭐ W42-T03 / R1 / C1 — THE SECOND HOP. Absent, this block does nothing and the bag above is
2294
- # byte-identical to what it has always been.
2295
- #
2296
- # ⛔ IT RIDES THE `on` BRANCH AND NOWHERE ELSE, and that is a decision rather than an
2297
- # oversight. A hop needs a first join to hop FROM. An `inverse` link is computed from the far
2298
- # side and has no `on` at all, so a `via` on one stores a promise nothing can resolve — the
2299
- # same thing this function already refuses for a `from` with no `on`, two branches up. A
2300
- # `via` arriving on an inverse or on an unconfigured bag therefore refuses the whole field
2301
- # rather than being dropped into a column that would silently answer a one-hop question.
2302
- if raw.get('via') is not None:
2303
- if 'on' not in out:
2304
- return None
2305
- via = _clean_via(raw.get('via'))
2306
- if via is None:
2307
- return None
2308
- out['via'] = via
2309
  if reciprocal:
2310
  out['reciprocal'] = reciprocal
2311
  if raw.get('single') is True:
2312
  out['single'] = True
2313
- # ⭐⭐ W42-T35 — WHICH RECORDS A PERSON MAY PICK. Absent, this block does nothing and the bag
2314
- # above is byte-identical to what it has always been.
2315
- #
2316
- # ⛔ IT RIDES THE PICKABLE BRANCH AND NOWHERE ELSE. A restriction on a picker needs a picker,
2317
- # and `is_derived_link` is the one definition of which links have none: an `on` join or an
2318
- # `inverse` backlink is computed by the engine, so `patch_link_cell` already refuses to take
2319
- # a human write on either. Storing a record filter there would be a control the editor shows
2320
- # and nothing can ever apply, which is the same silence this function refuses two branches up
2321
- # for a `from` with no `on`. The whole field is refused rather than the key dropped.
2322
- #
2323
- # ⛔ AND IT IS A DEFINITION FLAG, NOT A RETROACTIVE DELETE, exactly as the `user` column's
2324
- # `single` note says of its own. Records linked before the filter existed stay linked and
2325
- # visible because NOTHING here or in any reader touches a cell: `compute_relation_cells`,
2326
- # `patch_link_cell`'s `valid` set and every rollup fold read the target's rows, never this
2327
- # key. Applying it on read would delete links nobody asked to remove, invisibly, on a store
2328
- # with no history to undo it ([[a-cleanup-deletes-what-it-did-not-create]]).
2329
- if raw.get('conditions') is not None:
2330
- if out.get('on') or out.get('inverse'):
2331
- return None
2332
- picked, _sentence = _clean_link_conditions(raw, columns)
2333
- if picked is None:
2334
- return None
2335
- out.update(picked)
2336
  return out
2337
 
2338
 
2339
- def link_target_columns(table_key, st=None):
2340
- """The column keys a link TARGET database actually has, or None when nothing can answer.
2341
-
2342
- ⛔ `None` IS NOT AN EMPTY SET, and collapsing the two is the failure this signature exists to
2343
- prevent. `frozenset()` says "this database has no columns" and correctly refuses every rule;
2344
- `None` says "nobody here can say", which is a reason to refuse the FILTER naming that reason,
2345
- not to refuse each column with a sentence that reads like the user typed the name wrong.
2346
-
2347
- ⚠ TWO NAMESPACES, the same two `is_linkable_target` allows. A `ut_*` database answers from
2348
- its own stored `fields`; the two registry modules answer from `aios_grid`, which is where
2349
- `routes_tables::_module_link_targets` already reads their column lists for the field editor's
2350
- own dropdown, so the offer and the check cannot disagree about what a column is.
2351
-
2352
- ⚠ The import is function-local for the reason `_topic_dims` states: `core` must stay
2353
- importable without the layers above it.
2354
- """
2355
- key = str(table_key or '')
2356
- if key in LINKABLE_MODULE_KEYS:
2357
- try:
2358
- import aios_grid as _agl
2359
- fields = _agl.FIELDS if key == 'customer_data' else _agl.product_fields()
2360
- except Exception:
2361
- return None # fail closed: an unreadable grid answers nothing
2362
- cols = frozenset(str(f.get('key') or '') for f in (fields or [])
2363
- if isinstance(f, dict) and f.get('key'))
2364
- return cols or None
2365
- if not is_linkable_target(key):
2366
- return None
2367
- defn = get(key, st)
2368
- if not isinstance(defn, dict):
2369
- return None
2370
- return frozenset(str(f.get('key') or '') for f in (defn.get('fields') or [])
2371
- if isinstance(f, dict) and f.get('key'))
2372
-
2373
-
2374
- def link_filter_refusal(raw_bag, st=None):
2375
- """The sentence a refused record filter owes the user, or None when the filter is acceptable.
2376
-
2377
- ⛔⛔ IT EXISTS BECAUSE `_clean_link` HAS NO ERROR CHANNEL, and `verify_pivot.py` section 18
2378
- booked that gap by name: *"the refusal NAMES the missing key ... cannot be observed from
2379
- here: `_clean_via` returns a bare None, `_clean_link` returns None ... The naming half belongs
2380
- to a user_tables ticket."* This is that ticket, and this is that half. The shape is
2381
- `ai_enrich_dropped_keys`': a SEPARATE reporting function reading the SAME validator, never a
2382
- second copy of the rules.
2383
-
2384
- ⛔ IT READS THE RAW BAG, NEVER THE STORED ONE. A dynamic leaf cannot survive `_clean_link`, so
2385
- a function handed the cleaned bag would have nothing left to name.
2386
-
2387
- ⚠ THE LAW IS `_clean_link`; THIS IS THE SENTENCE. Same split `add_field`'s one-profile-column
2388
- rule already uses ("the route names the existing column in its refusal; the LAW is here"), so
2389
- a route that forgets to print this still cannot store a filter the target cannot satisfy.
2390
- """
2391
- if not isinstance(raw_bag, dict) or raw_bag.get('conditions') is None:
2392
- return None
2393
- if raw_bag.get('on') or raw_bag.get('inverse'):
2394
- return ('A record filter belongs on a link whose records a person picks. This link is '
2395
- 'computed by the server, so there is no picker to restrict.')
2396
- # ⛔⛔ THE SHAPE PASS RUNS FIRST, AND THE ORDER IS THE A34 CLAUSE. A dynamic leaf is refused
2397
- # BY NAME whether or not the target's columns can be read: resolving columns first would
2398
- # answer a bag carrying `mode: "dynamic"` with "the columns cannot be read", which names the
2399
- # wrong thing and points the user at the wrong fix. Caught by this ticket's own probe, which
2400
- # went 37/55 with the two calls the other way round.
2401
- _shape, sentence = _clean_link_conditions(raw_bag, None)
2402
- if sentence:
2403
- return sentence
2404
- table = _field_key(raw_bag.get('table'))
2405
- columns = link_target_columns(table, st)
2406
- if columns is None:
2407
- return (f'The columns of the linked database "{table}" cannot be read right now, so a '
2408
- f'record filter on it cannot be checked. Remove the filter, or try again.')
2409
- _picked, sentence = _clean_link_conditions(raw_bag, columns)
2410
- return sentence
2411
-
2412
-
2413
  def _clean_rollup(raw):
2414
  """One `rollup` bag → the stored shape, or None (refused).
2415
 
@@ -2891,7 +2397,7 @@ def _clean_field(raw, previous=None):
2891
  # `raw.get('format')`, exactly like `description` below: an explicit `{}`/None CLEARS the
2892
  # format, while omitting the key keeps what is stored. A PATCH that sends only a label must not
2893
  # silently strip a formatting choice — that is how `agg` stopped totalling a money column.
2894
- fmt = _clean_format(raw.get('format') if 'format' in raw else prev.get('format'), ftype)
2895
  if fmt:
2896
  out['format'] = fmt
2897
  # Canonical descriptions are schema metadata, not the user's per-view note. Preserve them
@@ -2934,17 +2440,12 @@ def _clean_field(raw, previous=None):
2934
  out['note'] = note
2935
  opts_raw = raw.get('options') if 'options' in raw else prev.get('options')
2936
  if ftype in ('select', 'multiselect'):
2937
- # ⭐⭐ W42-T36 — the SAME declared cap as `clean_fields`, and the same refuse-do-not-truncate
2938
- # posture. ⛔ THE DOORS DIFFER IN WHAT THEY REFUSE, deliberately: this validator is handed
2939
- # ONE field and its only refusal is `None`, which is `metric`/`profile`/`link`'s posture
2940
- # and what `add_field`/`patch_field` turn into a 400. A silent `[:MAX_OPTIONS]` here would
2941
- # be the 51st option vanishing under a 200 response, which is the exact behaviour the cap
2942
- # was raised to stop being invisible.
2943
- opts = [' '.join(str(o).split())[:60] for o in (opts_raw or []) if str(o).strip()]
2944
- if len(opts) > MAX_OPTIONS:
2945
- return None
2946
- if opts:
2947
- out['options'] = opts
2948
  # ⭐⭐ WAVE-29 CONTRACT C1 (owner item 13) — **THE OPTION COLOURS, WHICH THIS DOOR DROPPED.**
2949
  #
2950
  # The client has carried `optionColors`/`colorCodeOptions` since wave 14 (`types.ts`, the
@@ -2984,51 +2485,6 @@ def _clean_field(raw, previous=None):
2984
  else prev.get('colorCodeOptions'))
2985
  if isinstance(color_code, bool):
2986
  out['colorCodeOptions'] = color_code
2987
- # ⭐⭐ W42-T32 — THE COLUMN'S OWN DEFAULT VALUE, VALIDATED AGAINST WHAT THE COLUMN MEANS.
2988
- #
2989
- # ⚠ PLACED AFTER THE OPTIONS BLOCK ON PURPOSE. A select's default is checked against
2990
- # `out['options']`, which is computed twenty lines up; validated before that it would compare
2991
- # against an empty list and pass vacuously for every value — a leg that iterates the RESULT
2992
- # rather than the REQUIREMENT.
2993
- #
2994
- # ⚠ `'defaultValue' in raw` — the `format`/`description`/`agg` idiom, and the done-when's
2995
- # "clearing is distinguishable from never having set one" clause IS this idiom. Written the
2996
- # loose way (`raw.get(...) or prev.get(...)`) an explicit `None` from the pane's "no default"
2997
- # row would inherit the stored value and the control would be a no-op with the menu cheerfully
2998
- # showing the change. It also settles the falsy question: `0` and `False` are real defaults and
2999
- # survive, because presence is asked with `in` and emptiness with `is None`.
3000
- #
3001
- # ⛔ INHERITANCE IS GUARDED ON `prev_type == ftype`, exactly like `link`/`rollup`/`formula`.
3002
- # Retyping a select column to `int` must not resurrect the old select default through `prev`,
3003
- # fail its new vocabulary and REFUSE THE WHOLE PATCH — that is the bug those guards record,
3004
- # and here it would make a select column impossible to retype at all.
3005
- _prev_type_dv = str(prev.get('type') or '').strip().lower()
3006
- if 'defaultValue' in raw or (_prev_type_dv == ftype and 'defaultValue' in prev):
3007
- dv_raw = (raw.get('defaultValue') if 'defaultValue' in raw
3008
- else prev.get('defaultValue'))
3009
- dv = _clean_default_value(dv_raw, ftype, out.get('options') or [])
3010
- if dv is _DEFAULT_REFUSED:
3011
- return None
3012
- if dv is not None:
3013
- out['defaultValue'] = dv
3014
- # ⭐ W42-T32 — ONE PERSON, NOT MANY, on a `user` column.
3015
- #
3016
- # ⛔⛔ NAME COLLISION, AND THE TWO KEYS LIVE AT DIFFERENT LEVELS. `_clean_link` already stores a
3017
- # `single` (:1859) meaning "this LINK holds one record" — but it stores it INSIDE the link bag
3018
- # (`field['link']['single']`), while this one is a top-level key on a `user` column meaning
3019
- # "one person". Two keys, one word, two meanings; the `ftype == 'user'` guard is what stops
3020
- # either validator answering for the other, and it must not be relaxed into a generic arm.
3021
- #
3022
- # ⚠ IT IS A DEFINITION FLAG, NOT A READ-TIME TRUNCATION. Switching an existing multi-value
3023
- # `user` column to single must leave the stored cells exactly as they are until somebody next
3024
- # edits one: truncating on read would delete names nobody asked to remove, and would do it
3025
- # invisibly, on a store with no history to undo it ([[a-cleanup-deletes-what-it-did-not-create]]).
3026
- # Nothing here or in any reader touches a cell, which is how that clause is satisfied.
3027
- if ftype == 'user':
3028
- single_raw = (raw.get('single') if 'single' in raw
3029
- else (prev.get('single') if _prev_type_dv == 'user' else None))
3030
- if single_raw is True:
3031
- out['single'] = True
3032
  # ⭐ WAVE-29 T22's own repair: a `rating` column's star count. Grid-created columns on a `ut_*`
3033
  # database now come through this door rather than the per-user overlay, and this validator had
3034
  # no `max` — so a 3-star or 10-star column silently became 5-star on the way in. Bounded rather
@@ -3041,44 +2497,6 @@ def _clean_field(raw, previous=None):
3041
  out['max'] = max(2, min(int(max_raw), 10))
3042
  except (TypeError, ValueError):
3043
  pass
3044
- # ⭐ W42-T32 — the SHAPE those 1..max marks are drawn as. Bounded by `RATING_SYMBOLS`,
3045
- # whose note explains why that tuple has one member and what a wave-43 ticket must extend
3046
- # FIRST. An unknown name is DROPPED rather than refusing the field, `max`'s posture and
3047
- # `code`'s reasoning: a symbol chooses a GLYPH over a rating the column already holds, so
3048
- # an unusable value is a default and never a lost column.
3049
- # ⛔ OMIT-WHEN-ABSENT. Stamping `symbol: 'star'` on every rating column would break the
3050
- # `_clean_field(f) == f` identity two gates assert over every engine-seeded field list;
3051
- # `rating_symbol()` is the reader that resolves absence to the default.
3052
- sym = str((raw.get('symbol') if 'symbol' in raw else prev.get('symbol'))
3053
- or '').strip().lower()
3054
- if sym in RATING_SYMBOLS:
3055
- out['symbol'] = sym
3056
- # ⭐ W42-T32 — THE CHECKBOX'S MARK: which glyph, and in what colour.
3057
- #
3058
- # ✅ A HEX IS VALIDATED; BRAND MEMBERSHIP IS NOT, and this is not a new policy — it is the one
3059
- # `_clean_option_colors` twenty screens up already states, with its reasons. The client maps a
3060
- # stored colour to its nearest brand swatch at DISPLAY time (`choiceColors.brandedTint`),
3061
- # keeping the stored value byte-stable, so refusing a non-brand hex here would refuse values
3062
- # the sibling validator accepts on the same UI and would break a column that moved between the
3063
- # two. "From the brand swatches" describes the PICKER, not the wall.
3064
- # ⚠ A MALFORMED HEX IS DROPPED, matching `_clean_option_colors` exactly: same question, same
3065
- # answer, or the two doors start disagreeing about what a colour is.
3066
- if ftype == 'checkbox':
3067
- icon = str((raw.get('icon') if 'icon' in raw else prev.get('icon'))
3068
- or '').strip().lower()
3069
- if icon in CHECKBOX_ICONS:
3070
- out['icon'] = icon
3071
- # Accept the editor's British-spelling draft key as input as well as the
3072
- # established API spelling, then persist one canonical ``color`` key.
3073
- if 'color' in raw:
3074
- color_raw = raw.get('color')
3075
- elif 'colour' in raw:
3076
- color_raw = raw.get('colour')
3077
- else:
3078
- color_raw = prev.get('color') or prev.get('colour')
3079
- color = str(color_raw or '').strip().upper()
3080
- if _OPTION_COLOR_RE.fullmatch(color):
3081
- out['color'] = color
3082
  role = str(raw.get('editRole') or prev.get('editRole') or 'admins').strip().lower()
3083
  out['editRole'] = role if role in FIELD_EDIT_ROLES else 'admins'
3084
  if prev.get('default') is True or raw.get('default') is True:
@@ -3269,6 +2687,14 @@ def _clean_field(raw, previous=None):
3269
  geo = _ag_geocode(geocode_raw)
3270
  if geo and ftype == 'text':
3271
  out['geocode'] = geo
 
 
 
 
 
 
 
 
3272
  return out
3273
 
3274
 
@@ -3354,23 +2780,9 @@ def cell_type_refusal(field, value):
3354
  label = f.get('label') or f.get('key') or 'that column'
3355
  if ftype in _NUMERIC_CELL_TYPES:
3356
  try:
3357
- number = float(text.replace('$', '').replace(',', '')
3358
- .replace('%', '').replace(' ', ''))
3359
  except (TypeError, ValueError):
3360
  return f'{text[:40]!r} is not a number, and {label!r} holds numbers'
3361
- # ⭐⭐ W42-T33 — **A COLUMN THAT REFUSES NEGATIVES SAYS SO, IN A SENTENCE.**
3362
- #
3363
- # ⛔ THE WALL COULD NOT LIVE IN `_clean_format`, AND THAT IS THE WHOLE PLACEMENT NOTE.
3364
- # That function validates a SETTING; it never sees a cell and cannot decline one. This is
3365
- # the module's only evaluator that answers "why can this value not go in this column" with
3366
- # words, so a rule about VALUES belongs here or it is unbuilt: the setting would store,
3367
- # the pane would save, and a negative number would land anyway.
3368
- # ⚠ ABSENT MEANS ALLOWED (see `_clean_format`), so this is silent for every column that
3369
- # existed before this ticket and for every column that never opts in.
3370
- fmt = f.get('format')
3371
- if isinstance(fmt, dict) and fmt.get('allowNegative') is False and number < 0:
3372
- return (f'{label!r} does not take negative numbers, and {text[:40]!r} '
3373
- f'is below zero')
3374
  return None
3375
  if ftype == 'rating':
3376
  try:
@@ -3850,14 +3262,6 @@ def add_field(table_key, raw, st=None):
3850
  # the existing column in its refusal (`_refusal_sentence`); the LAW is here.
3851
  if field.get('profile') and _profile_of(have):
3852
  return None
3853
- # ⭐⭐ W42-T35 — THE RECORD FILTER IS CHECKED AGAINST THE TARGET'S OWN COLUMNS, HERE, because
3854
- # here is the first door that holds a store. `_clean_field` cannot do it: it is also the
3855
- # machine's validator and two gates assert `_clean_field(f) == f` over engine-seeded field
3856
- # lists with no store in reach, so a column check inside it would refuse every legal field
3857
- # the moment the store was cold. The RAW bag is passed, not the cleaned one, so a dynamic
3858
- # leaf is still there to be named.
3859
- if field.get('type') == 'link' and link_filter_refusal((raw or {}).get('link'), st):
3860
- return None
3861
 
3862
  def _add(cur):
3863
  t = cur.get(str(table_key))
@@ -3887,44 +3291,6 @@ def _reciprocal_link_key(table_key, field_key):
3887
  return f'linked_{digest}'
3888
 
3889
 
3890
- #: The suffix a SELF-LINK's reciprocal column wears, and the room it needs inside the 80-char
3891
- #: label ceiling `_clean_field` enforces. Declared as a pair so the budget can never drift from
3892
- #: the string: a suffix appended without reserving room truncates straight back to the field
3893
- #: label, and the two columns collide again with nothing anywhere going red.
3894
- _SELF_LINK_SUFFIX = ' (backlink)'
3895
- _SELF_LINK_LABEL_ROOM = 80 - len(_SELF_LINK_SUFFIX)
3896
-
3897
-
3898
- def _reciprocal_label(source, source_field, table_key, target_key):
3899
- """The label the backlink column carries. ⛔ TWO CASES, AND THE SPLIT IS THE WHOLE POINT.
3900
-
3901
- ⭐⭐ W42-T31 — A SELF-LINK'S RECIPROCAL WAS AN UNREADABLE TWIN. For a CROSS-TABLE link the
3902
- backlink lands on the OTHER database, where naming the SOURCE DATABASE is exactly the useful
3903
- thing: on "Orders" a backlink from "Customers.Primary contact" reads "Customers", which is
3904
- what Airtable shows and what a person expects. That case is UNCHANGED here, deliberately.
3905
-
3906
- ⛔ A SELF-LINK IS THE CASE THAT BREAKS. Target IS source, so the generated column lands on the
3907
- same grid as the field the user just built, and `source.label` names the database BOTH columns
3908
- already live on: "Tasks" sitting beside "Tasks", one of them inert. The user cannot tell which
3909
- is which without opening either, and the inert one is the derived twin (`inverse` in its bag)
3910
- that is permanently read-only and opens on zero rows.
3911
-
3912
- ⛔ AND THE OBVIOUS FIX IS ALSO WRONG: stamping the FIELD's label verbatim gives two columns
3913
- both reading "Parent task", which is the same indistinguishability wearing a better name. The
3914
- label must be DERIVED from the field label, never equal to it — so the mirror names what it
3915
- mirrors AND is legible as the mirror.
3916
-
3917
- ⚠ The field label is truncated to leave room for the suffix. Without that reservation an
3918
- 80-char field label truncates back to exactly the field label inside `_clean_field`, and the
3919
- collision returns silently for precisely the columns whose names were already hard to read.
3920
- """
3921
- if target_key and str(target_key) == str(table_key):
3922
- flabel = ' '.join(str((source_field or {}).get('label') or '').split())
3923
- if flabel:
3924
- return f'{flabel[:_SELF_LINK_LABEL_ROOM]}{_SELF_LINK_SUFFIX}'
3925
- return str((source or {}).get('label') or table_key)[:80]
3926
-
3927
-
3928
  def sync_reciprocal_link(table_key, field_key, st=None):
3929
  """Create/repair Airtable's reciprocal link field for one ordinary link.
3930
 
@@ -4033,7 +3399,7 @@ def sync_reciprocal_link(table_key, field_key, st=None):
4033
  reciprocal_key = _reciprocal_link_key(table_key, field_key)
4034
  reciprocal = _clean_field({
4035
  'key': reciprocal_key,
4036
- 'label': _reciprocal_label(source, source_field, table_key, target_key),
4037
  'type': 'link',
4038
  'link': {'table': table_key, 'inverse': field_key,
4039
  'reciprocal': field_key},
@@ -4058,106 +3424,9 @@ def sync_reciprocal_link(table_key, field_key, st=None):
4058
  return result
4059
 
4060
 
4061
- #: ⭐⭐ W42-T34 — **THE ONE DECLARED COERCION TABLE.** What happens to a stored cell when its
4062
- #: column changes type, keyed by the TARGET type and by nothing else.
4063
- #:
4064
- #: ⛔ IT IS A TABLE, NOT A CHAIN OF `if`s SPREAD THROUGH THE WRITER, and that is the whole shape of
4065
- #: the ticket. A second copy of "what does a retype mean" is how two surfaces start disagreeing
4066
- #: about it, which this module has paid for with `agg`, `format`, `optionColors` and `note`.
4067
- #:
4068
- #: ⛔ KEYED ON TYPE, NEVER ON FORMAT. A `duration`-formatted `int` and a plain `int` must coerce
4069
- #: identically, because a duration's stored value IS a plain integer (W42-T33) and every existing
4070
- #: `sum`/`average` fold over that column depends on it staying one. Reading `format` here is how
4071
- #: that guarantee would quietly stop holding.
4072
- #:
4073
- #: The four rules, and why each:
4074
- #: 'meanable' — keep the cell iff `cell_type_refusal` says the value can BE this kind. That
4075
- #: function is the module's existing evaluator for exactly this question; asking it
4076
- #: again in different words is [[one-evaluator-per-question]]'s failure mode.
4077
- #: 'boolish' — the checkbox contract is `'1'` or empty (`aios_grid.py:133`). Anything else is a
4078
- #: string a BooleanCell renders as unchecked while the store says otherwise.
4079
- #: 'keep' — the target renders any string, so clearing would DELETE DATA for no gain.
4080
- #: 'clear' — the SERVER owns this cell now (`is_computed_cell`'s family). A human string left
4081
- #: under a rollup is a fossil that no reader agrees with and the next compute pass
4082
- #: overwrites anyway.
4083
- #:
4084
- #: ⛔ `select`/`multiselect` ARE `keep`, AND THE NARROWING IS DELIBERATE. Clearing on option
4085
- #: membership was the obvious reading and it is the wrong one: `cell_type_refusal`'s own note says
4086
- #: choice vocabularies stay out of the wall because *"their options change under a stored row, and
4087
- #: refusing an import against a vocabulary edited yesterday would reject data that is merely out of
4088
- #: date"*. Clearing here would DELETE that same merely-stale data, on a store with no history to
4089
- #: undo it ([[a-cleanup-deletes-what-it-did-not-create]]). We clear what the new kind cannot
4090
- #: RENDER, not what its current vocabulary does not list.
4091
- RETYPE_COERCIONS = {
4092
- 'int': 'meanable', 'currency': 'meanable', 'pct': 'meanable',
4093
- 'date': 'meanable', 'rating': 'meanable',
4094
- 'checkbox': 'boolish',
4095
- 'text': 'keep', 'phone': 'keep', 'email': 'keep', 'url': 'keep',
4096
- 'json': 'keep', 'code': 'keep', 'image': 'keep', 'user': 'keep',
4097
- 'select': 'keep', 'multiselect': 'keep', 'automation': 'keep',
4098
- 'rollup': 'clear', 'formula': 'clear', 'link': 'clear', 'ai_enrich': 'clear',
4099
- }
4100
-
4101
- #: The checkbox cell vocabulary, named once so `boolish` and any later reader cannot drift.
4102
- _CHECKBOX_CELL_VALUES = ('1', '')
4103
-
4104
-
4105
- def _retype_survives(value, new_field):
4106
- """Can this stored cell stay, under the new column's kind? ⛔ Reads `RETYPE_COERCIONS` only."""
4107
- rule = RETYPE_COERCIONS.get(str((new_field or {}).get('type') or ''), 'keep')
4108
- if rule == 'keep':
4109
- return True
4110
- if rule == 'clear':
4111
- return False
4112
- text = '' if value is None else str(value).strip()
4113
- if not text:
4114
- return True # ⚠ a blank cell is a blank cell in every column
4115
- if rule == 'boolish':
4116
- return str(value) in _CHECKBOX_CELL_VALUES
4117
- return cell_type_refusal(new_field, value) is None
4118
-
4119
-
4120
- def retype_plan(table_key, fkey, new_field, st=None):
4121
- """What a type change WOULD clear, computed without writing anything.
4122
-
4123
- ⭐⭐ W42-T34 (as amended by A28) — **THE PREVIEW PAYLOAD A DIALOG WOULD NEED.** `patch_field`
4124
- cannot warn anybody: it is a store writer with no surface. What it CAN do is compute the count
4125
- and the column before it writes and hand them out through a channel, which is what this is and
4126
- what `patch_field(preview=...)` fills. No ticket this wave owns the dialog itself (D-558).
4127
-
4128
- ⛔ IT IS A SEPARATE PUBLIC FUNCTION so a future dialog can ask the question WITHOUT writing.
4129
- A preview only reachable by performing the act it previews is not a preview.
4130
-
4131
- Returns `{'column', 'label', 'from', 'to', 'rows', 'clearing', 'rowIds'}`.
4132
- """
4133
- defn = get(table_key, st) or {}
4134
- prev_field = next((f for f in (defn.get('fields') or [])
4135
- if f.get('key') == str(fkey)), None) or {}
4136
- rows = defn.get('rows') or {}
4137
- hits = [str(rid) for rid, cells in rows.items()
4138
- if isinstance(cells, dict) and str(fkey) in cells
4139
- and not _retype_survives(cells.get(str(fkey)), new_field)]
4140
- return {'column': str(fkey),
4141
- 'label': str((new_field or {}).get('label') or prev_field.get('label') or ''),
4142
- 'from': str(prev_field.get('type') or ''),
4143
- 'to': str((new_field or {}).get('type') or ''),
4144
- 'rows': len(rows), 'clearing': len(hits), 'rowIds': hits}
4145
-
4146
-
4147
- def patch_field(table_key, fkey, raw, st=None, preview=None):
4148
  """Edit one column's definition IN PLACE. Returns the stored field, or None if refused.
4149
 
4150
- ⭐⭐ W42-T34 — **A RETYPE NOW DOES SOMETHING HONEST TO THE CELLS.** Until this ticket `_set`
4151
- replaced the field dict and never touched `rows` at all, so a text column retyped to `int`
4152
- kept every cell as a string and the grid rendered whatever that does. The rewrite runs through
4153
- `RETYPE_COERCIONS`, the ONE declared table.
4154
-
4155
- ⚠ `preview` IS AN OUT-PARAM, NOT A CHANGED RETURN TYPE, and that is load-bearing. This
4156
- function's return value is what `routes_tables` echoes to the client; wrapping it in a tuple or
4157
- stuffing a preview into the field dict would break a caller outside this module's fence and
4158
- the failure would read like a regression somewhere else. The pattern is
4159
- `sync_reciprocal_link`'s `result` dict, one screen up: report what happened through a channel,
4160
- leave the wall's signature alone. Pass a dict and it is filled BEFORE the store write.
4161
  ⚠ THE KEY NEVER MOVES. A field's key is what every stored cell is filed under, so accepting
4162
  a new one here would orphan every value in the column while looking like a rename. The
4163
  LABEL is the renameable thing; the key is identity.
@@ -4194,10 +3463,6 @@ def patch_field(table_key, fkey, raw, st=None, preview=None):
4194
  # as adding one. `exclude=fkey` so re-saving the profile column does not collide with itself.
4195
  if field.get('profile') and _profile_of(fields, exclude=str(fkey)):
4196
  return None
4197
- # W42-T35 — the column check rides the EDIT door too, for the reason the profile rule above
4198
- # names: a law taught to only one of the two doors is a law the other silently permits.
4199
- if field.get('type') == 'link' and link_filter_refusal(merged.get('link'), st):
4200
- return None
4201
  # ⭐⭐ 2026-08-09 — THE CUSTODY STAMP IS WRITTEN HERE, at the ONE door a human reaches.
4202
  #
4203
  # `USER_EDITED_KEY`'s note has the why. It is written here rather than inside `_clean_field`
@@ -4235,18 +3500,6 @@ def patch_field(table_key, fkey, raw, st=None, preview=None):
4235
  and not description_edited(field) and not user_edited(field):
4236
  field.pop('note', None)
4237
 
4238
- # ⭐⭐ W42-T34 — THE PLAN IS COMPUTED BEFORE THE WRITE, and only for a genuine TYPE CHANGE.
4239
- # ⛔ `prev['type'] != field['type']` IS THE WHOLE TRIGGER. Anything looser reprocesses every
4240
- # cell on every rename, which on a 28.6 MB store is a silent full-document rewrite for a
4241
- # header edit. It is also what protects W42-T32's preservation clause: flipping a `user`
4242
- # column's `single` is not a type change, so its multi-value cells are never walked.
4243
- plan = None
4244
- if str(fields[idx].get('type') or '').strip().lower() != field['type']:
4245
- plan = retype_plan(table_key, fkey, field, st)
4246
- if isinstance(preview, dict):
4247
- preview.update({k: v for k, v in plan.items() if k != 'rowIds'})
4248
- preview['rewrote'] = False
4249
-
4250
  def _set(cur):
4251
  t = cur.get(str(table_key))
4252
  if t is not None:
@@ -4254,20 +3507,6 @@ def patch_field(table_key, fkey, raw, st=None, preview=None):
4254
  if f.get('key') == str(fkey):
4255
  t['fields'][i] = field
4256
  break
4257
- # ⭐⭐ THE BYTE-IDENTITY CLAUSE LIVES IN THIS `if`. A retype that clears nothing must
4258
- # leave the rows EXACTLY as they were, and the way to guarantee that is not to compare
4259
- # afterwards but never to enter the branch: a loop that rewrites every cell to the
4260
- # same value passes a hash check and is still the full-document write this guard
4261
- # exists to prevent. `rewrote` records which happened, so the two are distinguishable
4262
- # from outside.
4263
- if plan and plan['clearing']:
4264
- bucket = t.get('rows') or {}
4265
- for rid in plan['rowIds']:
4266
- cells = bucket.get(rid)
4267
- if isinstance(cells, dict):
4268
- cells.pop(str(fkey), None)
4269
- if isinstance(preview, dict):
4270
- preview['rewrote'] = True
4271
  return cur
4272
 
4273
  _st(st).update(STORE_KEY, _set, flush='sync')
@@ -4404,8 +3643,9 @@ def patch_cells(table_key, row_id, values, st=None):
4404
  def _set(cur):
4405
  t = cur.get(str(table_key))
4406
  if t is not None:
4407
- t.setdefault('rows', {}).setdefault(str(row_id), {}).update(
4408
- {str(k): str(v) for k, v in (values or {}).items()})
 
4409
  return cur
4410
 
4411
  _st(st).update(STORE_KEY, _set, flush='sync')
@@ -4441,6 +3681,7 @@ def patch_many_cells(table_key, updates, st=None):
4441
  for rid, cells in clean.items():
4442
  if rid in rows:
4443
  rows[rid].update(cells)
 
4444
  return cur
4445
 
4446
  _st(st).update(STORE_KEY, _set, flush='sync')
 
47
  import datetime as _dt
48
  import hashlib
49
  import json as _json
50
+ import math
51
  import re
52
+ import uuid as _uuid
53
 
54
  import core.store as store
55
 
56
  STORE_KEY = 'user_tables'
57
+ ZONE_STORE_KEY = 'table_zones'
58
  MAX_TABLES = 40
59
  MAX_LABEL = 60
60
 
 
358
  }
359
 
360
 
361
+ MAX_FIELDS = 60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
  #: the badge the nav paints for a table with no connector behind it
363
  BLANK_SOURCE = 'Blank'
364
  #: automation-created tables carry their maker instead (wave 18 C4-AUTO)
 
777
  return _agg._clean_geocode(raw)
778
 
779
 
780
+ def _ag_recurrence(raw):
781
+ """The single Date-recurrence normaliser, shared by both user-table field doors."""
782
+ import aios_grid as _agr
783
+ return _agr.clean_date_recurrence(raw)
784
+
785
+
786
  #: Display formats a field may declare. ⛔ DISPLAY ONLY — none of these touches the stored value,
787
  #: which stays the scalar the fold or the mapper wrote. That separation is the whole safety of the
788
  #: feature: a `thousands` setting can never make a number wrong, only easier to read.
 
808
  #: A choice colour, as the client's editor spells one. `#RRGGBB`, upper-cased on the way in so a
809
  #: stored value has exactly ONE spelling and two fields cannot disagree about `#ebf6ef`.
810
  _OPTION_COLOR_RE = re.compile(r'#[0-9A-F]{6}')
811
+ _MAX_CHOICE_OPTIONS = 50
812
+ _MAX_CHOICE_LABEL = 60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
813
 
814
 
815
  def _clean_option_colors(raw, options):
 
843
  return out
844
 
845
 
846
+ def _choice_values(field, value):
847
+ """The option labels represented by one stored choice-cell value.
848
+
849
+ A single-select cell is one label verbatim; a multiselect cell is a comma-joined set. This
850
+ is intentionally the shared-row writer's vocabulary, rather than a client courtesy, so a
851
+ paste, import, API write, and ordinary grid edit cannot disagree about which choices exist.
852
+ """
853
+ if not isinstance(field, dict) or field.get('type') not in ('select', 'multiselect'):
854
+ return []
855
+ parts = str(value or '').split(',') if field.get('type') == 'multiselect' else [value]
856
+ out = []
857
+ for raw in parts:
858
+ label = ' '.join(str(raw or '').split())[:_MAX_CHOICE_LABEL]
859
+ if label:
860
+ out.append(label)
861
+ return out
862
+
863
+
864
+ def _hydrate_choice_options(fields, value_maps):
865
+ """Extend each select field's vocabulary with values being written in this transaction.
866
+
867
+ Values remain the source of truth for a pasted/imported choice: this helper adds the exact
868
+ normalised label to the schema atomically with that write. Existing spellings stay intact;
869
+ case-insensitive matching merely prevents an import from minting ``Done`` and ``done`` as
870
+ two visibly indistinguishable options.
871
+ """
872
+ rows = [row for row in (value_maps or []) if isinstance(row, dict)]
873
+ for field in fields or []:
874
+ if not isinstance(field, dict) or field.get('type') not in ('select', 'multiselect'):
875
+ continue
876
+ key = field.get('key')
877
+ if not key:
878
+ continue
879
+ options = list(field.get('options') or [])
880
+ known = {str(option).casefold() for option in options}
881
+ changed = False
882
+ for values in rows:
883
+ if key not in values:
884
+ continue
885
+ for option in _choice_values(field, values[key]):
886
+ folded = option.casefold()
887
+ if folded in known or len(options) >= _MAX_CHOICE_OPTIONS:
888
+ continue
889
+ options.append(option)
890
+ known.add(folded)
891
+ changed = True
892
+ if changed:
893
+ field['options'] = options
894
+
895
+
896
+ def _clean_format(raw):
897
  """One `format` bag → the stored shape, or None.
898
 
899
  ⛔⛔ THIS FUNCTION EXISTS BECAUSE THE BAG HAD NO STORAGE AT ALL. The column menu has shipped a
 
925
  tz = str(raw.get('tz') or '').strip().lower()
926
  if tz in FORMAT_TZ:
927
  out['tz'] = tz
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
928
  return out or None
929
 
930
 
 
948
  # ⭐ 2026-08-10 — the DISPLAY format, carried through the CREATE door. See `_clean_format`:
949
  # this is the fifth time an entry built key-by-key has silently dropped a bag the editor
950
  # sends, and the fourth of those was `agg` on this very line one wave ago.
951
+ fmt = _clean_format(f.get('format'))
 
 
 
952
  if fmt:
953
  entry['format'] = fmt
954
  description = ' '.join(str(f.get('description') or '').split())[:300]
 
964
  if note:
965
  entry['note'] = note
966
  if ftype in ('select', 'multiselect'):
 
 
 
 
 
967
  opts = [' '.join(str(o).split())[:60] for o in (f.get('options') or [])
968
+ if str(o).strip()][:50]
969
+ entry['options'] = opts
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
970
  if f.get('default') is True:
971
  entry['default'] = True
972
  # ⭐ WAVE-27 item 19 (R15) + D-80 — THE PRIMARY COLUMN, CARRIED THROUGH THE CREATE DOOR.
 
1012
  # ⛔ THE TYPE/BAG PAIRING IS ENFORCED BOTH WAYS, as it is in `_clean_field`: a `link` with
1013
  # no bag can never resolve a row, and a bag on a column of another type is a declaration
1014
  # nothing reads. Either half alone is the silent kind of broken.
 
 
 
 
 
 
 
 
 
 
1015
  for bag_key, cleaner in (('link', _clean_link), ('rollup', _clean_rollup)):
1016
  bag = cleaner(f.get(bag_key)) if f.get(bag_key) is not None else None
1017
  if ftype == bag_key and bag is None:
 
1055
  geo = (_ag_geocode(f.get('geocode')) if f.get('geocode') is not None else None)
1056
  if geo and ftype == 'text':
1057
  entry['geocode'] = geo
1058
+ # W43C C2: a recurrence is valid only on a scalar Date field. It is not a new cell
1059
+ # type: the row still stores ``YYYY-MM-DD`` while this durable bag lets the server project
1060
+ # the next date and preview consistently for every reader.
1061
+ if entry is not None and ftype == 'date' and f.get('recurrence') is not None:
1062
+ recurrence = _ag_recurrence(f.get('recurrence'))
1063
+ if recurrence:
1064
+ entry['recurrence'] = recurrence
1065
  if entry is None:
1066
  seen.discard(key)
1067
  continue
 
1135
  return all_tables(st).get(str(table_key))
1136
 
1137
 
1138
+ # --- DURABLE MAP ZONES -------------------------------------------------------
1139
+ # Zones intentionally do not live in a view config: a view is a person's presentation of rows,
1140
+ # while a named geographic boundary is tenant data used by several views and routes. Keeping a
1141
+ # separate keyed bucket also lets the Map route attach zones to connector-backed grids whose rows
1142
+ # do not live in ``user_tables`` at all.
1143
+ _ZONE_ID_RE = re.compile(r'^[A-Za-z0-9_-]{1,96}$')
1144
+ _ZONE_FIELD_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_]{0,79}$')
1145
+ _ZONE_COLOR_RE = re.compile(r'^#[0-9A-Fa-f]{6}$')
1146
+ _ZONE_GEOMETRIES = frozenset({'Polygon', 'MultiPolygon'})
1147
+
1148
+
1149
+ def _zone_position(raw):
1150
+ if not isinstance(raw, (list, tuple)) or len(raw) not in (2, 3):
1151
+ return None
1152
+ out = []
1153
+ for index, value in enumerate(raw):
1154
+ if isinstance(value, bool):
1155
+ return None
1156
+ try:
1157
+ number = float(value)
1158
+ except (TypeError, ValueError):
1159
+ return None
1160
+ if not math.isfinite(number) or (abs(number) > (180 if index == 0 else 90)):
1161
+ return None
1162
+ out.append(number)
1163
+ return out
1164
+
1165
+
1166
+ def _zone_ring(raw):
1167
+ if not isinstance(raw, (list, tuple)) or len(raw) < 4:
1168
+ return None
1169
+ points = [_zone_position(point) for point in raw]
1170
+ if any(point is None for point in points) or points[0] != points[-1]:
1171
+ return None
1172
+ return points
1173
+
1174
+
1175
+ def _clean_zone_geometry(raw):
1176
+ """A bounded GeoJSON Polygon/MultiPolygon geometry, with no executable/foreign members."""
1177
+ if not isinstance(raw, dict) or raw.get('type') not in _ZONE_GEOMETRIES:
1178
+ return None
1179
+ kind, coords = raw['type'], raw.get('coordinates')
1180
+ if kind == 'Polygon':
1181
+ rings = [_zone_ring(ring) for ring in (coords if isinstance(coords, list) else [])]
1182
+ if not rings or any(ring is None for ring in rings):
1183
+ return None
1184
+ clean = rings
1185
+ else:
1186
+ clean = []
1187
+ for polygon in (coords if isinstance(coords, list) else []):
1188
+ rings = [_zone_ring(ring) for ring in (polygon if isinstance(polygon, list) else [])]
1189
+ if not rings or any(ring is None for ring in rings):
1190
+ return None
1191
+ clean.append(rings)
1192
+ if not clean:
1193
+ return None
1194
+ return {'type': kind, 'coordinates': clean}
1195
+
1196
+
1197
+ def clean_zone(raw, field_keys=None, allowed_row_ids=None):
1198
+ """One exact durable Zone shape, or ``None``. Unknown keys never reach the store."""
1199
+ if not isinstance(raw, dict):
1200
+ return None
1201
+ name = ' '.join(str(raw.get('name') or '').split())[:120]
1202
+ geometry = _clean_zone_geometry(raw.get('geometryGeoJson'))
1203
+ if not name or geometry is None:
1204
+ return None
1205
+ out = {'name': name,
1206
+ 'color': (str(raw.get('color') or '#1F4E78').upper()),
1207
+ 'geometryGeoJson': geometry,
1208
+ 'visible': raw.get('visible') is not False}
1209
+ if not _ZONE_COLOR_RE.fullmatch(out['color']):
1210
+ return None
1211
+ zone_id = str(raw.get('id') or '').strip()
1212
+ if zone_id:
1213
+ if not _ZONE_ID_RE.fullmatch(zone_id):
1214
+ return None
1215
+ out['id'] = zone_id
1216
+ geographic = str(raw.get('geographicField') or '').strip()[:80]
1217
+ if geographic:
1218
+ if not _ZONE_FIELD_RE.fullmatch(geographic):
1219
+ return None
1220
+ if field_keys is not None and geographic not in set(field_keys):
1221
+ return None
1222
+ out['geographicField'] = geographic or None
1223
+ memberships, seen = [], set()
1224
+ allowed = ({str(pid) for pid in allowed_row_ids} if allowed_row_ids is not None else None)
1225
+ for raw_pid in list(raw.get('memberships') or [])[:100000]:
1226
+ pid = str(raw_pid).strip()
1227
+ if not pid or pid in seen or (allowed is not None and pid not in allowed):
1228
+ continue
1229
+ seen.add(pid)
1230
+ memberships.append(pid)
1231
+ out['memberships'] = memberships
1232
+ return out
1233
+
1234
+
1235
+ def zones(table_key, st=None):
1236
+ """All valid zones for one table, in persisted order; malformed historical entries hide."""
1237
+ key = str(table_key or '').strip()
1238
+ if not key:
1239
+ return []
1240
+ try:
1241
+ raw = (_st(st).get(ZONE_STORE_KEY) or {}).get(key) or []
1242
+ except Exception:
1243
+ return []
1244
+ out = []
1245
+ for zone in raw:
1246
+ clean = clean_zone(zone)
1247
+ if clean and clean.get('id'):
1248
+ out.append(clean)
1249
+ return out
1250
+
1251
+
1252
+ def upsert_zone(table_key, raw, field_keys=None, allowed_row_ids=None, st=None):
1253
+ """Create/update a zone by id; the returned object is the exact persisted wire shape."""
1254
+ key = str(table_key or '').strip()
1255
+ if not key:
1256
+ return None
1257
+ clean = clean_zone(raw, field_keys=field_keys, allowed_row_ids=allowed_row_ids)
1258
+ if clean is None:
1259
+ return None
1260
+ clean.setdefault('id', 'zone_' + _uuid.uuid4().hex)
1261
+ result = {}
1262
+
1263
+ def _save(current):
1264
+ bucket = dict(current or {})
1265
+ existing = list(bucket.get(key) or [])
1266
+ replaced = False
1267
+ next_zones = []
1268
+ for zone in existing[:200]:
1269
+ if isinstance(zone, dict) and zone.get('id') == clean['id']:
1270
+ next_zones.append(dict(clean))
1271
+ replaced = True
1272
+ else:
1273
+ next_zones.append(zone)
1274
+ if not replaced:
1275
+ if len(next_zones) >= 200:
1276
+ return current
1277
+ next_zones.append(dict(clean))
1278
+ bucket[key] = next_zones
1279
+ result.update(clean)
1280
+ return bucket
1281
+
1282
+ _st(st).update(ZONE_STORE_KEY, _save, flush='sync')
1283
+ return result or None
1284
+
1285
+
1286
+ def delete_zone(table_key, zone_id, st=None):
1287
+ """Delete only this named zone; no prefix/glob deletion exists in this contract."""
1288
+ key, zid = str(table_key or '').strip(), str(zone_id or '').strip()
1289
+ if not key or not _ZONE_ID_RE.fullmatch(zid):
1290
+ return False
1291
+ removed = []
1292
+
1293
+ def _drop(current):
1294
+ bucket = dict(current or {})
1295
+ before = list(bucket.get(key) or [])
1296
+ after = [zone for zone in before if not (isinstance(zone, dict) and zone.get('id') == zid)]
1297
+ if len(after) != len(before):
1298
+ removed.append(True)
1299
+ if after:
1300
+ bucket[key] = after
1301
+ else:
1302
+ bucket.pop(key, None)
1303
+ return bucket
1304
+
1305
+ _st(st).update(ZONE_STORE_KEY, _drop, flush='sync')
1306
+ return bool(removed)
1307
+
1308
+
1309
+ def legacy_route_census(tenant, fields, exact_legacy_names):
1310
+ """Census exact, tenant-declared legacy route columns without selecting by prefix/pattern.
1311
+
1312
+ This is intentionally a reporting primitive, not a deletion API. A caller must supply the
1313
+ exact legacy names confirmed for this tenant; ``route_*`` and arbitrary columns merely
1314
+ containing the word "route" cannot enter this result. The unified route-order fields stay
1315
+ explicit in the report so retirement code can prove its replacement before it writes.
1316
+ """
1317
+ tenant = str(tenant or '').strip()
1318
+ names = (exact_legacy_names.get(tenant, ()) if isinstance(exact_legacy_names, dict)
1319
+ else exact_legacy_names)
1320
+ exact = {str(name).strip().casefold() for name in (names or ()) if str(name).strip()}
1321
+ candidates, unified = [], []
1322
+ for field in fields or ():
1323
+ if not isinstance(field, dict):
1324
+ continue
1325
+ key, label = str(field.get('key') or ''), str(field.get('label') or '')
1326
+ if field.get('kind') == 'route_order':
1327
+ unified.append(key)
1328
+ if exact and (key.casefold() in exact or label.casefold() in exact):
1329
+ candidates.append(key)
1330
+ return {'tenant': tenant, 'exactNames': sorted(exact),
1331
+ 'candidates': candidates, 'unifiedRouteFields': unified,
1332
+ 'retirementReady': bool(candidates and unified)}
1333
+
1334
+
1335
  def is_user_table(table_key, st=None):
1336
  """THE permission predicate for row writes. Cheap and total: a key that is not in this store
1337
  is not a user table, so it cannot accept invented rows."""
 
1403
  return cur
1404
  s.update(STORE_KEY, _drop, flush='sync')
1405
 
1406
+ # A zone is tenant data attached to this table's row-id namespace. Leaving it behind would
1407
+ # let a newly-created table with the same key inherit somebody else's geographic boundary.
1408
+ try:
1409
+ s.update(ZONE_STORE_KEY,
1410
+ lambda cur: {k: v for k, v in (cur or {}).items() if k != key},
1411
+ flush='async')
1412
+ except Exception:
1413
+ pass
1414
+
1415
  ws_key = f'{key}_table_workspace'
1416
  view_ids = set()
1417
  try:
 
1524
  rid = str(max((int(r) for r in rows if str(r).isdigit()), default=0) + 1)
1525
  valid = {f['key'] for f in (defn.get('fields') or [])}
1526
  clean = {k: str(v) for k, v in (values or {}).items() if k in valid}
 
 
 
 
 
 
 
 
 
1527
  # C3 (wave 25): a PROFILE cell is validated and normalised on the insert door too, not only
1528
  # on the edit door. A row born with `https://instagram.com/p/Cxyz` in its handle column is a
1529
  # row the enrich action can never answer, and the failure would otherwise surface as an
 
1539
  t = cur.get(str(table_key))
1540
  if t is not None:
1541
  t.setdefault('rows', {})[rid] = clean
1542
+ _hydrate_choice_options(t.get('fields') or [], [clean])
1543
  return cur
1544
 
1545
  _st(st).update(STORE_KEY, _add, flush='async')
 
1587
  valid = {f['key'] for f in (defn.get('fields') or [])}
1588
  pf = _profile_of(defn.get('fields') or [])
1589
  next_id = max((int(r) for r in rows if str(r).isdigit()), default=0)
 
 
 
 
 
1590
  made = []
1591
  for values in batch:
1592
  clean = {k: str(v) for k, v in values.items() if k in valid}
 
 
 
1593
  if pf and pf['key'] in clean:
1594
  handle, ok = normalize_profile(clean[pf['key']], pf['profile'].get('source'))
1595
  if not ok:
 
1604
  bucket = t.setdefault('rows', {})
1605
  for rid, clean in made:
1606
  bucket[rid] = clean
1607
+ _hydrate_choice_options(t.get('fields') or [], [clean for _, clean in made])
1608
  return cur
1609
 
1610
  _st(st).update(STORE_KEY, _add, flush='sync')
 
1850
  return key.startswith(KEY_PREFIX) and len(key) > len(KEY_PREFIX)
1851
 
1852
 
1853
+ def _clean_link(raw):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1854
  """One `link` bag → the stored shape, or None (refused).
1855
 
1856
  Same posture as `_clean_metric`: a mis-shaped bag REFUSES THE FIELD. A link column stored
 
1876
  if not is_linkable_target(table):
1877
  return None
1878
  out = {'table': table}
1879
+ # W43C R9: the choice of how a link is populated is schema, not a one-off picker state.
1880
+ # Existing bags which pre-date the setting stay byte-compatible; an explicit manual choice
1881
+ # persists as ``selectionMode: 'manual'`` and can be PATCHed to automatic later.
1882
+ selection = raw.get('selectionMode', raw.get('pickerMode', raw.get('mode')))
1883
+ if selection is not None:
1884
+ selection = str(selection).strip().lower()
1885
+ selection = {'pick': 'manual', 'none': 'manual', 'auto': 'automatic'}.get(selection,
1886
+ selection)
1887
+ if selection not in ('manual', 'automatic'):
1888
+ return None
1889
+ out['selectionMode'] = selection
1890
  on = _field_key(raw.get('on'))
1891
  frm = _field_key(raw.get('from'))
1892
  inverse = _field_key(raw.get('inverse'))
 
1909
  # than dropped: a bag half of which is silently ignored is [[wrong-parent-not-broken-control]]
1910
  # with the control still on screen.
1911
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1912
  if reciprocal:
1913
  out['reciprocal'] = reciprocal
1914
  if raw.get('single') is True:
1915
  out['single'] = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1916
  return out
1917
 
1918
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1919
  def _clean_rollup(raw):
1920
  """One `rollup` bag → the stored shape, or None (refused).
1921
 
 
2397
  # `raw.get('format')`, exactly like `description` below: an explicit `{}`/None CLEARS the
2398
  # format, while omitting the key keeps what is stored. A PATCH that sends only a label must not
2399
  # silently strip a formatting choice — that is how `agg` stopped totalling a money column.
2400
+ fmt = _clean_format(raw.get('format') if 'format' in raw else prev.get('format'))
2401
  if fmt:
2402
  out['format'] = fmt
2403
  # Canonical descriptions are schema metadata, not the user's per-view note. Preserve them
 
2440
  out['note'] = note
2441
  opts_raw = raw.get('options') if 'options' in raw else prev.get('options')
2442
  if ftype in ('select', 'multiselect'):
2443
+ # A vocabulary starts empty and is learned from actual writes. Omitting this key made
2444
+ # a valid, new select indistinguishable from a malformed text field on its read path.
2445
+ # Keep the empty list deliberately: the type is the contract; options are its current
2446
+ # vocabulary, not a prerequisite for the column to exist.
2447
+ opts = [' '.join(str(o).split())[:60] for o in (opts_raw or []) if str(o).strip()][:50]
2448
+ out['options'] = opts
 
 
 
 
 
2449
  # ⭐⭐ WAVE-29 CONTRACT C1 (owner item 13) — **THE OPTION COLOURS, WHICH THIS DOOR DROPPED.**
2450
  #
2451
  # The client has carried `optionColors`/`colorCodeOptions` since wave 14 (`types.ts`, the
 
2485
  else prev.get('colorCodeOptions'))
2486
  if isinstance(color_code, bool):
2487
  out['colorCodeOptions'] = color_code
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2488
  # ⭐ WAVE-29 T22's own repair: a `rating` column's star count. Grid-created columns on a `ut_*`
2489
  # database now come through this door rather than the per-user overlay, and this validator had
2490
  # no `max` — so a 3-star or 10-star column silently became 5-star on the way in. Bounded rather
 
2497
  out['max'] = max(2, min(int(max_raw), 10))
2498
  except (TypeError, ValueError):
2499
  pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2500
  role = str(raw.get('editRole') or prev.get('editRole') or 'admins').strip().lower()
2501
  out['editRole'] = role if role in FIELD_EDIT_ROLES else 'admins'
2502
  if prev.get('default') is True or raw.get('default') is True:
 
2687
  geo = _ag_geocode(geocode_raw)
2688
  if geo and ftype == 'text':
2689
  out['geocode'] = geo
2690
+ # Date recurrence follows the same PATCH law as format/geocode: an explicit null/invalid
2691
+ # value clears the optional config, omission preserves it only while the field remains date.
2692
+ recurrence_raw = (raw.get('recurrence') if 'recurrence' in raw
2693
+ else (prev.get('recurrence') if ftype == 'date' else None))
2694
+ if recurrence_raw is not None:
2695
+ recurrence = _ag_recurrence(recurrence_raw)
2696
+ if recurrence and ftype == 'date':
2697
+ out['recurrence'] = recurrence
2698
  return out
2699
 
2700
 
 
2780
  label = f.get('label') or f.get('key') or 'that column'
2781
  if ftype in _NUMERIC_CELL_TYPES:
2782
  try:
2783
+ float(text.replace('$', '').replace(',', '').replace('%', '').replace(' ', ''))
 
2784
  except (TypeError, ValueError):
2785
  return f'{text[:40]!r} is not a number, and {label!r} holds numbers'
 
 
 
 
 
 
 
 
 
 
 
 
 
2786
  return None
2787
  if ftype == 'rating':
2788
  try:
 
3262
  # the existing column in its refusal (`_refusal_sentence`); the LAW is here.
3263
  if field.get('profile') and _profile_of(have):
3264
  return None
 
 
 
 
 
 
 
 
3265
 
3266
  def _add(cur):
3267
  t = cur.get(str(table_key))
 
3291
  return f'linked_{digest}'
3292
 
3293
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3294
  def sync_reciprocal_link(table_key, field_key, st=None):
3295
  """Create/repair Airtable's reciprocal link field for one ordinary link.
3296
 
 
3399
  reciprocal_key = _reciprocal_link_key(table_key, field_key)
3400
  reciprocal = _clean_field({
3401
  'key': reciprocal_key,
3402
+ 'label': str(source.get('label') or table_key)[:80],
3403
  'type': 'link',
3404
  'link': {'table': table_key, 'inverse': field_key,
3405
  'reciprocal': field_key},
 
3424
  return result
3425
 
3426
 
3427
+ def patch_field(table_key, fkey, raw, st=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3428
  """Edit one column's definition IN PLACE. Returns the stored field, or None if refused.
3429
 
 
 
 
 
 
 
 
 
 
 
 
3430
  ⚠ THE KEY NEVER MOVES. A field's key is what every stored cell is filed under, so accepting
3431
  a new one here would orphan every value in the column while looking like a rename. The
3432
  LABEL is the renameable thing; the key is identity.
 
3463
  # as adding one. `exclude=fkey` so re-saving the profile column does not collide with itself.
3464
  if field.get('profile') and _profile_of(fields, exclude=str(fkey)):
3465
  return None
 
 
 
 
3466
  # ⭐⭐ 2026-08-09 — THE CUSTODY STAMP IS WRITTEN HERE, at the ONE door a human reaches.
3467
  #
3468
  # `USER_EDITED_KEY`'s note has the why. It is written here rather than inside `_clean_field`
 
3500
  and not description_edited(field) and not user_edited(field):
3501
  field.pop('note', None)
3502
 
 
 
 
 
 
 
 
 
 
 
 
 
3503
  def _set(cur):
3504
  t = cur.get(str(table_key))
3505
  if t is not None:
 
3507
  if f.get('key') == str(fkey):
3508
  t['fields'][i] = field
3509
  break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3510
  return cur
3511
 
3512
  _st(st).update(STORE_KEY, _set, flush='sync')
 
3643
  def _set(cur):
3644
  t = cur.get(str(table_key))
3645
  if t is not None:
3646
+ clean = {str(k): str(v) for k, v in (values or {}).items()}
3647
+ t.setdefault('rows', {}).setdefault(str(row_id), {}).update(clean)
3648
+ _hydrate_choice_options(t.get('fields') or [], [clean])
3649
  return cur
3650
 
3651
  _st(st).update(STORE_KEY, _set, flush='sync')
 
3681
  for rid, cells in clean.items():
3682
  if rid in rows:
3683
  rows[rid].update(cells)
3684
+ _hydrate_choice_options(t.get('fields') or [], clean.values())
3685
  return cur
3686
 
3687
  _st(st).update(STORE_KEY, _set, flush='sync')
platform/harness/filter_eval.py CHANGED
@@ -47,6 +47,9 @@ all already exist in `filter_sql.py` and `windows.py`, and are already held agai
47
  laziness — a second copy of "what counts as an active rule" is precisely the drift those gates
48
  exist to catch, and it would be a copy the gates do not cover.
49
  """
 
 
 
50
  from harness.filter_sql import ( # noqa: F401 (COHORT_OPS re-exported for callers)
51
  COHORT_FIELD, COHORT_OPS, COHORT_OP_ALIASES, FILTER_OPS, RANK_OPS,
52
  is_rule_active, parse_cohort_ids, to_num, _resolve_anchor, _window_bounds,
@@ -366,7 +369,12 @@ def _eval(node, row, columns, ctx, strict):
366
  # prior pass over the other rows. No set = REFUSE, never "ignore" and never "true" — both of
367
  # those SHOW rows.
368
  if node.get('op') in RANK_OPS:
 
 
 
369
  s = ctx.rank_sets.get(_rank_key(node))
 
 
370
  return (row.get('pid') in s) if s is not None else False
371
 
372
  # An operator in NO vocabulary at all. The comparators end in `default: True`, right for an
@@ -382,10 +390,208 @@ def _rank_key(node):
382
  """The client keys `rankSets` by leaf IDENTITY (a Map keyed on the node object). Python
383
  dicts cannot key on a dict, so the caller that resolves rank sets and this evaluator agree
384
  on a derived key. Kept in ONE place so the two cannot drift apart."""
 
 
 
 
 
385
  return (node.get('id') or '', node.get('colId') or '', node.get('op') or '',
386
  str(node.get('value') if node.get('value') is not None else ''))
387
 
388
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
  def _columns_map(fields):
390
  """`[{key,type,…}]` -> `{key: field}`. Accepts a mapping unchanged, so callers holding
391
  either shape need no adapter."""
@@ -430,7 +636,7 @@ def matches(tree, row, fields, ctx=None):
430
  return True if v is None else bool(v)
431
 
432
 
433
- def visible_pids(tree, rows, fields, ctx=None, member_pids=None):
434
  """The client's whole row pipeline for one tree, member union included — the shape a caller
435
  should reach for instead of assembling `matches` in a loop.
436
 
@@ -439,6 +645,16 @@ def visible_pids(tree, rows, fields, ctx=None, member_pids=None):
439
  matches UNION the hand-picked members.
440
  """
441
  ctx = ctx or _EMPTY_CTX
 
 
 
 
 
 
 
 
 
 
442
  members = set(member_pids or ())
443
  out, active = [], False
444
  verdicts = []
 
47
  laziness — a second copy of "what counts as an active rule" is precisely the drift those gates
48
  exist to catch, and it would be a copy the gates do not cover.
49
  """
50
+ import math
51
+ from collections import namedtuple
52
+
53
  from harness.filter_sql import ( # noqa: F401 (COHORT_OPS re-exported for callers)
54
  COHORT_FIELD, COHORT_OPS, COHORT_OP_ALIASES, FILTER_OPS, RANK_OPS,
55
  is_rule_active, parse_cohort_ids, to_num, _resolve_anchor, _window_bounds,
 
369
  # prior pass over the other rows. No set = REFUSE, never "ignore" and never "true" — both of
370
  # those SHOW rows.
371
  if node.get('op') in RANK_OPS:
372
+ # ``_rank_key`` gained an explicit scope in Wave 43. Accept the old four-part key
373
+ # for callers which resolved their own set before that addition; a missing answer is
374
+ # still a refusal, never a permissive fallback.
375
  s = ctx.rank_sets.get(_rank_key(node))
376
+ if s is None:
377
+ s = ctx.rank_sets.get(_legacy_rank_key(node))
378
  return (row.get('pid') in s) if s is not None else False
379
 
380
  # An operator in NO vocabulary at all. The comparators end in `default: True`, right for an
 
390
  """The client keys `rankSets` by leaf IDENTITY (a Map keyed on the node object). Python
391
  dicts cannot key on a dict, so the caller that resolves rank sets and this evaluator agree
392
  on a derived key. Kept in ONE place so the two cannot drift apart."""
393
+ return (_legacy_rank_key(node) + (_rank_scope_token(node),))
394
+
395
+
396
+ def _legacy_rank_key(node):
397
+ """The Wave-42 four-part resolver key, retained for supplied membership sets."""
398
  return (node.get('id') or '', node.get('colId') or '', node.get('op') or '',
399
  str(node.get('value') if node.get('value') is not None else ''))
400
 
401
 
402
+ def _rank_scope_token(node):
403
+ """A stable, serialisable identity for one rank leaf's scope configuration.
404
+
405
+ ``rankScope`` is deliberately optional: old views keep their global meaning. A grouped
406
+ rank may name its group field explicitly (``{mode:'group', field:'agent'}``) or defer to
407
+ the view's ``groupBy`` through the concise ``'group'`` shape. The resolver below refuses
408
+ the latter when no group field was supplied, rather than silently widening it to global.
409
+ """
410
+ raw = node.get('rankScope') if isinstance(node, dict) else None
411
+ if isinstance(raw, dict):
412
+ mode = raw.get('mode', raw.get('scope'))
413
+ field = raw.get('field', raw.get('groupBy'))
414
+ if mode == 'group':
415
+ return 'group:' + (str(field).strip()[:80] if field is not None else '')
416
+ return 'global'
417
+ return 'group:' if raw == 'group' else 'global'
418
+
419
+
420
+ def _rank_scope(node, group_by):
421
+ """``('global' | 'group', field | None)`` for a cleaned or directly-posted rank leaf."""
422
+ raw = node.get('rankScope') if isinstance(node, dict) else None
423
+ if raw == 'group':
424
+ field = group_by
425
+ elif isinstance(raw, dict) and raw.get('mode', raw.get('scope')) == 'group':
426
+ field = raw.get('field', raw.get('groupBy', group_by))
427
+ else:
428
+ return 'global', None
429
+ field = str(field or '').strip()[:80]
430
+ return ('group', field or None)
431
+
432
+
433
+ def _rank_leaves(nodes, columns):
434
+ """ACTIVE rank leaves in tree order; measure leaves are not rank questions."""
435
+ out = []
436
+ for node in nodes or ():
437
+ if _is_group(node):
438
+ out.extend(_rank_leaves(node.get('children'), columns))
439
+ elif (isinstance(node, dict) and node.get('op') in RANK_OPS
440
+ and not _is_measure(node) and is_rule_active(node, columns)):
441
+ out.append(node)
442
+ return out
443
+
444
+
445
+ def _strip_rank_leaves(nodes):
446
+ """The residue that defines the ranking domain (the client performs the same pass)."""
447
+ out = []
448
+ for node in nodes or ():
449
+ if _is_group(node):
450
+ children = _strip_rank_leaves(node.get('children'))
451
+ if children:
452
+ out.append({'conj': 'or' if node.get('conj') == 'or' else 'and',
453
+ 'children': children})
454
+ elif not (isinstance(node, dict) and node.get('op') in RANK_OPS
455
+ and not _is_measure(node)):
456
+ out.append(node)
457
+ return out
458
+
459
+
460
+ def _rank_number(raw):
461
+ """A rank value, where blank/unparseable is ABSENT rather than numeric zero."""
462
+ if raw is None or raw == '':
463
+ return None
464
+ if isinstance(raw, bool):
465
+ return float(raw) # JavaScript ``Number(true)`` parity.
466
+ try:
467
+ value = float(raw)
468
+ except (TypeError, ValueError):
469
+ return None
470
+ return value if math.isfinite(value) else None
471
+
472
+
473
+ def _rank_bound(value, lo, hi):
474
+ """The exact whole-number bounds the rank builder writes; junk remains unanswerable."""
475
+ try:
476
+ number = float(value)
477
+ except (TypeError, ValueError):
478
+ return None
479
+ if not math.isfinite(number) or int(number) != number:
480
+ return None
481
+ number = int(number)
482
+ return number if lo <= number <= hi else None
483
+
484
+
485
+ def _pid_order(pid):
486
+ """Stable ascending pid order even for mixed legacy string/integer wire ids."""
487
+ try:
488
+ return 0, int(pid)
489
+ except (TypeError, ValueError):
490
+ return 1, str(pid)
491
+
492
+
493
+ def _group_value(row, key):
494
+ """A hashable, deterministic grouping value; list/dict cells remain one visible group."""
495
+ value = row.get(key)
496
+ if isinstance(value, (list, dict, set)):
497
+ return repr(value)
498
+ try:
499
+ hash(value)
500
+ except TypeError:
501
+ return repr(value)
502
+ return value
503
+
504
+
505
+ RankResolution = namedtuple('RankResolution', 'sets unanswerable')
506
+
507
+
508
+ def resolve_rank_sets(tree, rows, fields, ctx=None, group_by=None):
509
+ """Resolve top/bottom/percentile/average slices over the server's filtered row domain.
510
+
511
+ Rank filters cannot be compiled as a row-level SQL ``WHERE`` clause, but they *can* and must
512
+ be answered before an in-memory API/host payload is filtered. The residue (all non-rank
513
+ conditions) defines the domain, ties are selected by ascending ``pid`` in both directions,
514
+ and ``rankScope: 'group'`` independently ranks every ``group_by`` bucket. A grouped request
515
+ without an actual group key is unanswerable and gets an empty membership set; it never falls
516
+ back to a global rank.
517
+ """
518
+ columns = _columns_map(fields)
519
+ nodes, conj = tree_parts(tree)
520
+ leaves = _rank_leaves(nodes, columns)
521
+ if not leaves:
522
+ return RankResolution({}, 0)
523
+
524
+ base_ctx = ctx or _EMPTY_CTX
525
+ residue = _strip_rank_leaves(nodes)
526
+ residue_tree = {'nodes': residue, 'conj': conj}
527
+ domain = [row for row in (rows or ())
528
+ if matches(residue_tree, row, columns, base_ctx)]
529
+ sets, unanswerable = {}, 0
530
+
531
+ for leaf in leaves:
532
+ key = _rank_key(leaf)
533
+ field = columns.get(leaf.get('colId')) or {}
534
+ if field.get('type') not in NUMERIC_TYPES:
535
+ sets[key] = set()
536
+ unanswerable += 1
537
+ continue
538
+ scope, scoped_by = _rank_scope(leaf, group_by)
539
+ if scope == 'group' and scoped_by not in columns:
540
+ sets[key] = set()
541
+ unanswerable += 1
542
+ continue
543
+ groups = {}
544
+ for row in domain:
545
+ group_key = _group_value(row, scoped_by) if scope == 'group' else None
546
+ groups.setdefault(group_key, []).append(row)
547
+
548
+ selected, answered = set(), False
549
+ for group_rows in groups.values():
550
+ ranked = []
551
+ for row in group_rows:
552
+ value = _rank_number(row.get(leaf.get('colId')))
553
+ if value is not None:
554
+ ranked.append((value, row.get('pid')))
555
+ if not ranked:
556
+ continue
557
+ answered = True
558
+ asc = sorted(ranked, key=lambda item: (item[0], _pid_order(item[1])))
559
+ desc = sorted(ranked, key=lambda item: (-item[0], _pid_order(item[1])))
560
+ count = len(asc)
561
+ op = leaf.get('op')
562
+ keep = None
563
+ if op == 'topN':
564
+ bound = _rank_bound(leaf.get('value'), 1, 10000)
565
+ keep = desc[:bound] if bound is not None else None
566
+ elif op == 'bottomN':
567
+ bound = _rank_bound(leaf.get('value'), 1, 10000)
568
+ keep = asc[:bound] if bound is not None else None
569
+ elif op in ('inTopPct', 'inBottomPct'):
570
+ pct = _rank_bound(leaf.get('value'), 1, 100)
571
+ take = min(count, max(1, math.ceil(count * pct / 100))) if pct else None
572
+ order = desc if op == 'inTopPct' else asc
573
+ keep = order[:take] if take is not None else None
574
+ elif op in ('aboveAvg', 'belowAvg'):
575
+ mean = sum(value for value, _ in asc) / count
576
+ keep = [(value, pid) for value, pid in asc
577
+ if (value > mean if op == 'aboveAvg' else value < mean)]
578
+ elif op in ('inQuartile', 'inDecile'):
579
+ buckets = 4 if op == 'inQuartile' else 10
580
+ wanted = _rank_bound(leaf.get('value'), 1, buckets)
581
+ if wanted is not None and count >= buckets:
582
+ keep = [item for index, item in enumerate(asc)
583
+ if min(buckets, (index * buckets) // count + 1) == wanted]
584
+ if keep is None:
585
+ selected = set()
586
+ answered = False
587
+ break
588
+ selected.update(pid for _, pid in keep)
589
+ sets[key] = selected
590
+ if domain and not answered:
591
+ unanswerable += 1
592
+ return RankResolution(sets, unanswerable)
593
+
594
+
595
  def _columns_map(fields):
596
  """`[{key,type,…}]` -> `{key: field}`. Accepts a mapping unchanged, so callers holding
597
  either shape need no adapter."""
 
636
  return True if v is None else bool(v)
637
 
638
 
639
+ def visible_pids(tree, rows, fields, ctx=None, member_pids=None, group_by=None):
640
  """The client's whole row pipeline for one tree, member union included — the shape a caller
641
  should reach for instead of assembling `matches` in a loop.
642
 
 
645
  matches UNION the hand-picked members.
646
  """
647
  ctx = ctx or _EMPTY_CTX
648
+ # This is the whole-payload entry point, so it is the one place a server can answer a rank
649
+ # filter without trusting a browser to have done a prior pass. Preserve supplied cohort /
650
+ # measure answers, but replace rank memberships with this payload's authoritative answer.
651
+ # Direct ``evaluate`` intentionally stays a one-row primitive and therefore stays
652
+ # fail-closed when a caller has not supplied a membership set.
653
+ resolved = resolve_rank_sets(tree, rows, fields, ctx, group_by=group_by)
654
+ if resolved.sets:
655
+ rank_sets = dict(ctx.rank_sets)
656
+ rank_sets.update(resolved.sets)
657
+ ctx = EvalCtx(ctx.cohort_sets, ctx.measure_sets, rank_sets, ctx.today)
658
  members = set(member_pids or ())
659
  out, active = [], False
660
  verdicts = []
platform/harness/measure_filter.py CHANGED
@@ -559,12 +559,6 @@ def resolve_pair(rule, today, team_id=None, allowed_pids=None):
559
  f"question, and both look like they work.")
560
  cmp = _CMP[op]
561
 
562
- # Validate BOTH windows before touching the store. Otherwise a malformed right-hand
563
- # condition can be hidden by an unrelated cache-warming error from the left-hand query,
564
- # leaving the caller with neither its refusal nor a safe answer.
565
- _query_parts(lkey, rule.get('window'), today, team_id)
566
- _query_parts(rkey, rhs.get('window'), today, team_id)
567
-
568
  pool = _pool_of(allowed_pids)
569
  con = _sem._store_con()
570
  try:
 
559
  f"question, and both look like they work.")
560
  cmp = _CMP[op]
561
 
 
 
 
 
 
 
562
  pool = _pool_of(allowed_pids)
563
  con = _sem._store_con()
564
  try:
platform/harness/runtime.py CHANGED
@@ -267,11 +267,7 @@ class TenantRuntime:
267
  first_odoo = next((e["id"] for e in entries if e.get("type") == "odoo"), None)
268
  if first_odoo and keychain.unlocked():
269
  return first_odoo
270
- # Tenant #0's compiled connector is the ENV fallback. Its presence is the
271
- # capability contract for the system card; consulting ODOO_URL here instead
272
- # makes the card (and its pause address) depend on the host process rather
273
- # than the same source that odoo_source() resolves.
274
- if self.key == "royal-imports" and self.odoo_source() is not None:
275
  return ENV_ODOO_FLAG_KEY
276
  return None
277
 
 
267
  first_odoo = next((e["id"] for e in entries if e.get("type") == "odoo"), None)
268
  if first_odoo and keychain.unlocked():
269
  return first_odoo
270
+ if self.key == "royal-imports" and os.environ.get("ODOO_URL"):
 
 
 
 
271
  return ENV_ODOO_FLAG_KEY
272
  return None
273
 
platform/harness/semantic.py CHANGED
@@ -47,7 +47,7 @@ def _customer_move_domain(move_type):
47
  def build(date_from=None, date_to=None, team_id=None, **kw):
48
  if team_id:
49
  raise ModelError(
50
- f"customer {move_type} documents are COMPANY-LEVEL: credit notes and invoices "
51
  f"carry no trustworthy business-unit tag, so a team-scoped total cannot be "
52
  f"produced. Refusing rather than returning the company number.")
53
  dom = [("move_type", "=", move_type), ("state", "=", "posted")]
@@ -71,26 +71,6 @@ class ModelError(Exception):
71
  """A model-file problem (unknown key, bad reference, unparseable expr)."""
72
 
73
 
74
- class UnknownColumnError(ModelError):
75
- """A request named a COLUMN (dim / filter key / group key) the topic does not have.
76
-
77
- W42-T06 / amendment A8. A SUBCLASS of ModelError so every existing `except ModelError`
78
- stays byte-identical, and so the route layer can tell "you asked for a column that is not
79
- there" (a 400 naming the column) apart from "this topic has no store binding" (a 503).
80
-
81
- The offending name is the `column` ATTRIBUTE, not merely a substring of the message.
82
- A caller that had to match the sentence would break the moment somebody reworded it, and
83
- the sentence is copy that reaches a screen, so it WILL be reworded (standing rule 2).
84
- `columns` carries the full sorted set when a tree named several, so the message stays short
85
- while nothing is hidden.
86
- """
87
-
88
- def __init__(self, message, column, columns=None):
89
- super().__init__(message)
90
- self.column = str(column)
91
- self.columns = sorted({str(c) for c in (columns or [column])})
92
-
93
-
94
  # ---------------------------------------------------------------- loading
95
 
96
  @functools.lru_cache(maxsize=1)
@@ -184,7 +164,7 @@ def describe(key):
184
  def _domain(topic_def, date_from, date_to, team_id):
185
  b = topic_def.get("domain_builder")
186
  if not b:
187
- raise ModelError(f"topic {topic_def['key']!r} is store-only, so use store_query() "
188
  f"(no live-path domain builder bound yet)")
189
  return _BUILDERS[b](date_from, date_to, team_id=team_id)
190
 
@@ -410,7 +390,7 @@ def _store_con():
410
  import harness.datastore as DS
411
  if not DS.ready(): # a mid-backfill store returns PARTIAL totals silently
412
  raise ModelError("the data cache is still warming up after a restart (a one-time first "
413
- "sync). The dashboards work now from live data; ask me again in a "
414
  "moment and I'll have it")
415
  return DS.ro_cursor() # cursor on the shared instance — no sync-writer contention
416
 
@@ -476,7 +456,7 @@ def _post_compute(row, key):
476
  _FORMAT_TYPE = {"usd": "currency", "int": "int", "pct": "pct"}
477
 
478
 
479
- def _clean_tree(tree, cols, tolerate=()):
480
  """Run a filter tree through the SAME validator the client's view state goes through.
481
 
482
  `filter_sql`'s documented input contract is "feed me CLEANED trees" — it is faithful to the
@@ -490,9 +470,6 @@ def _clean_tree(tree, cols, tolerate=()):
490
  module with zero imports of its own, so this cannot cycle.
491
  """
492
  from aios_grid import (clean_filter_tree, COHORT_FIELD as _COHORT_FIELD,
493
- VIEW_FIELD as _VIEW_FIELD, FILTER_OPS as _FILTER_OPS,
494
- COHORT_OPS as _COHORT_OPS, COHORT_OP_ALIASES as _COHORT_ALIASES,
495
- VIEW_OPS as _VIEW_OPS,
496
  MAX_FILTER_DEPTH, MAX_FILTER_NODES, MAX_FILTER_SIBLINGS)
497
 
498
  # REFUSE an over-large tree rather than TRUNCATE it. clean_filter_tree caps siblings per
@@ -558,92 +535,15 @@ def _clean_tree(tree, cols, tolerate=()):
558
  # it here, the fix is to pass the membership in, not to let it fall through.
559
  if cohorts:
560
  raise ModelError(
561
- f"filter tree carries cohort-membership condition(s) {sorted(set(cohorts))}, but "
562
  f"cohort membership is host state, not a column of this topic. Refusing rather than "
563
  f"dropping it, which would silently widen the result under an authoritative count.")
564
  if windowed:
565
  raise ModelError(
566
  f"filter tree carries measure condition(s) over a date window {sorted(set(windowed))}"
567
- f". Those are resolved to a set of ids by harness.measure_filter, not compiled into "
568
  f"this query. Refusing rather than dropping or mis-compiling them, either of which "
569
  f"would silently answer a different question under an authoritative count.")
570
- # ⭐ W42-T06 — AN UNKNOWN COLUMN IS REFUSED BY NAME, and this is the LAST check before the
571
- # validator because `clean_filter_tree` DROPS an unrecognised `colId` (its documented
572
- # fail-closed-per-node contract, correct on a saved view where one bad rule must not cost a
573
- # user the whole view). On THIS path it is the same silent widening the caps above refuse:
574
- # a hop whose `via.filter` names a column the middle topic does not have would return the
575
- # UNFILTERED set under a count that looks authoritative. So the server names it instead.
576
- # - a leaf with no `colId` is MALFORMED, not "a column this topic lacks" - left to the
577
- # validator, which drops it as it always has;
578
- # - `__cohort__` / `__view__` are HOST STATE, not columns of any topic; the cohort arm
579
- # above already refuses its own leaf, and a view leaf keeps today's drop;
580
- # - `tolerate` is for a caller whose `cols` is deliberately NARROWER than the topic's
581
- # vocabulary (store_rows at row grain drops count-style metrics). Those keys keep
582
- # today's silent drop rather than becoming a 400 that misnames a metric as a typo.
583
- tolerated = {str(c) for c in (tolerate or ())}
584
- known = set(cols) | tolerated | {_COHORT_FIELD, _VIEW_FIELD}
585
- unknown = []
586
- bad_ops = []
587
-
588
- def _cols(nodes):
589
- for node in nodes or []:
590
- if not isinstance(node, dict):
591
- continue
592
- if isinstance(node.get('children'), list):
593
- _cols(node['children'])
594
- continue
595
- col = node.get('colId')
596
- if col in (None, ''):
597
- continue
598
- col = str(col)
599
- if col not in known:
600
- unknown.append(col)
601
- continue
602
- # ⭐ THE SAME HOLE ONE KEY OVER, ruled into this ticket 2026-08-25 and INHERITED, not
603
- # introduced: `clean_filter_tree` drops a leaf whose `op` it does not know, by the
604
- # same fail-closed-per-node contract, and the result is identical. A `via.filter`
605
- # authored with `op: "is"` returned the WHOLE unfiltered topic (measured on
606
- # sales_lines: 16,779,678.21 instead of 14,763,400.38) under an authoritative count.
607
- # This is an AUTHORING error, not an unknown column, so it stays a plain ModelError:
608
- # `UnknownColumnError` has to keep meaning "unknown column" or the 400 it produces
609
- # would name a column that is perfectly fine.
610
- # - the three vocabularies are DISJOINT ON PURPOSE (aios_grid says so), so this is
611
- # per-leaf-KIND, never one union;
612
- # - a cohort leaf may carry `eq`/`neq`, which are PERMANENT aliases of
613
- # `anyOf`/`noneOf`; checking COHORT_OPS alone would 400 every saved view written
614
- # before the alias rewrite;
615
- # - the RANK ops are in FILTER_OPS and PASS here even though `filter_sql` cannot
616
- # compile them to row SQL. That refusal already exists downstream with its own
617
- # message; restating it here would change which error a caller sees;
618
- # - a leaf with NO `op` is MALFORMED, not a bad operator: left to the validator's
619
- # existing drop, exactly as a leaf with no `colId` is;
620
- # - a `tolerate`d key keeps its long-standing silent drop end to end, op included.
621
- if tolerated and col in tolerated and col not in cols:
622
- continue
623
- op = node.get('op')
624
- if op in (None, ''):
625
- continue
626
- legal = (_COHORT_OPS | set(_COHORT_ALIASES) if col == _COHORT_FIELD
627
- else _VIEW_OPS if col == _VIEW_FIELD
628
- else _FILTER_OPS)
629
- if str(op) not in legal:
630
- bad_ops.append((col, str(op), sorted(legal)))
631
-
632
- _cols(tree)
633
- if unknown:
634
- bad = sorted(set(unknown))
635
- extra = f" (and {bad[1:]})" if len(bad) > 1 else ""
636
- raise UnknownColumnError(
637
- f"filter rule names column {bad[0]!r}{extra}, which this topic does not have. "
638
- f"Refusing rather than dropping the rule, which would silently widen the result.",
639
- column=bad[0], columns=bad)
640
- if bad_ops:
641
- col, op, legal = bad_ops[0]
642
- raise ModelError(
643
- f"filter rule on column {col!r} carries operator {op!r}, which is not one this "
644
- f"filter understands (use: {legal}). Refusing rather than dropping the rule, which "
645
- f"would silently widen the result.")
646
-
647
  return clean_filter_tree(tree, set(cols))
648
 
649
 
@@ -788,7 +688,7 @@ def _channel_sql(channel):
788
  tid = names.get(channel)
789
  if tid is None:
790
  raise ModelError(
791
- f"channel {channel!r} is not a team this tenant names. `tenant.yml::team_names` "
792
  f"carries {sorted(names)}, so the channel cannot be resolved to a team id")
793
  return f"o.team_id = {int(tid)} AND l.order_partner_id NOT IN " \
794
  f"(SELECT id FROM res_partner WHERE name LIKE {_sql_value(excl)})"
@@ -866,7 +766,7 @@ def store_query(topic, measures, group_by=None, grain=None, date_from=None, date
866
  # never count(*) on the wrong table); in a GROUPED query they are refused (split the request).
867
  foreign = [k for k in base_keys if _model()["metrics"][k]["topic"] != topic]
868
  if foreign and (group_by or grain):
869
- raise ModelError(f"metrics {foreign} belong to another topic. Cross-topic measures are "
870
  f"scalar-only; run them against their own topic when grouping")
871
  base_keys = [k for k in base_keys if k not in foreign]
872
  foreign_vals = {}
@@ -882,8 +782,7 @@ def store_query(topic, measures, group_by=None, grain=None, date_from=None, date
882
  gb = [g for g in (group_by or []) if g]
883
  for g in gb:
884
  if g not in dims:
885
- raise UnknownColumnError(
886
- f"group_by {g!r} not a dim of {topic!r} (allowed: {list(dims)})", column=g)
887
  d = dims[g]
888
  select.append(f"{d['col']} AS {g}_id" if d.get("name_col") else f"{d['col']} AS {g}")
889
  group_cols.append(d["col"])
@@ -916,14 +815,13 @@ def store_query(topic, measures, group_by=None, grain=None, date_from=None, date
916
  # cell that reads as "this SKU sold nothing on Amazon" — a FALSE number, not a narrower one.
917
  if team_id and scope_variant is None:
918
  if not s.get("team_col"):
919
- raise ModelError(f"topic {topic!r} is company-level, so it has no business-unit filter")
920
  where.append(f"{s['team_col']} = ?"); params.append(int(team_id))
921
  if exclude_services and s.get("service_filter"):
922
  where.append(render_scope(s["service_filter"]))
923
  for dim_key, vals in (filters or {}).items():
924
  if dim_key not in dims:
925
- raise UnknownColumnError(
926
- f"filter dim {dim_key!r} not allowed (use: {list(dims)})", column=dim_key)
927
  # id dims filter by int; TEXT dims (e.g. city) filter by the value itself — either way
928
  # every VALUE stays parameterized (the whitelist covers identifiers only)
929
  def _coerce(v):
@@ -949,7 +847,7 @@ def store_query(topic, measures, group_by=None, grain=None, date_from=None, date
949
  if pred.uses_aggregate:
950
  bad = sorted(c for c in pred.columns_used if cols[c].get("aggregate"))
951
  raise ModelError(
952
- f"filter_tree references measure(s) {bad}. A measure filter has to land in "
953
  f"HAVING, and that path is deliberately NOT built: CG-1 ships the WHERE path "
954
  f"because its consumer (CG-2, the line-grain sales table) does not aggregate. "
955
  f"Filter on dims, or aggregate first and filter the result.")
@@ -1047,7 +945,7 @@ def store_rows(topic, date_from=None, date_to=None, team_id=None, filter_tree=No
1047
  scope_params.append(f"{date_to} 23:59:59")
1048
  if team_id:
1049
  if not s.get("team_col"):
1050
- raise ModelError(f"topic {topic!r} is company-level, so it has no business-unit filter")
1051
  scope.append(f"{s['team_col']} = ?")
1052
  scope_params.append(int(team_id))
1053
  if exclude_services and s.get("service_filter"):
@@ -1055,12 +953,7 @@ def store_rows(topic, date_from=None, date_to=None, team_id=None, filter_tree=No
1055
 
1056
  # --- the user's narrowing, on top of the scope --------------------------------------
1057
  narrow, narrow_params = [], []
1058
- # ⚠ `cols` here is the ROW-grain projection, which drops count-style metrics on purpose.
1059
- # Tolerate the aggregate-grain vocabulary so such a key keeps its long-standing silent drop
1060
- # instead of being refused as an unknown COLUMN, which would name a real metric a typo.
1061
- pred = _fs.compile_filter_tree(_clean_tree(filter_tree or [], cols,
1062
- tolerate=store_columns(topic)),
1063
- filter_conj, cols,
1064
  today=today,
1065
  member_ids=member_ids or None, id_sql=id_sql)
1066
  if pred is not None:
@@ -1134,7 +1027,7 @@ def store_field_values(topic, dim, search=None, limit=25):
1134
  raise ModelError(f"topic {topic!r} has no store binding")
1135
  d = (t["store"].get("dims") or {}).get(dim)
1136
  if not d:
1137
- raise UnknownColumnError(f"unknown dim {dim!r} for topic {topic!r}", column=dim)
1138
  if not d.get("name_col"):
1139
  raise ModelError(f"dim {dim!r} has no name column (filter by id)")
1140
  s = t["store"]
@@ -1427,7 +1320,7 @@ def _one_binding_offer(topic, b, strict=False, ready=None):
1427
  # user did not get rather than a base metric they never asked for.
1428
  key = key + _suffix
1429
  if strict:
1430
- raise _EntityMeasureError(f"{topic}: measure {key!r} refused, because {reason}")
1431
  refused.append({"key": key, "reason": reason})
1432
 
1433
  for key in b["keys"]:
@@ -1579,7 +1472,7 @@ def entity_measure_values(topic, keys, date_from=None, date_to=None, team_id=Non
1579
  # `rollup_sql.group_values` makes, for the same reason. Never write cells from one.
1580
  if res.get("truncated"):
1581
  raise _EntityMeasureError(
1582
- f"{topic}: {src} grouped by {dim} exceeded {MAX_GROUPS} groups, so refusing to write "
1583
  f"cells from a truncated result")
1584
  # `store_query` emits the bare dim name when the dim has no `name_col`, `<dim>_id` when it
1585
  # does. Both shapes are live in the model, so read whichever arrived.
 
47
  def build(date_from=None, date_to=None, team_id=None, **kw):
48
  if team_id:
49
  raise ModelError(
50
+ f"customer {move_type} documents are COMPANY-LEVEL — credit notes and invoices "
51
  f"carry no trustworthy business-unit tag, so a team-scoped total cannot be "
52
  f"produced. Refusing rather than returning the company number.")
53
  dom = [("move_type", "=", move_type), ("state", "=", "posted")]
 
71
  """A model-file problem (unknown key, bad reference, unparseable expr)."""
72
 
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  # ---------------------------------------------------------------- loading
75
 
76
  @functools.lru_cache(maxsize=1)
 
164
  def _domain(topic_def, date_from, date_to, team_id):
165
  b = topic_def.get("domain_builder")
166
  if not b:
167
+ raise ModelError(f"topic {topic_def['key']!r} is store-only — use store_query() "
168
  f"(no live-path domain builder bound yet)")
169
  return _BUILDERS[b](date_from, date_to, team_id=team_id)
170
 
 
390
  import harness.datastore as DS
391
  if not DS.ready(): # a mid-backfill store returns PARTIAL totals silently
392
  raise ModelError("the data cache is still warming up after a restart (a one-time first "
393
+ "sync) — the dashboards work now from live data; ask me again in a "
394
  "moment and I'll have it")
395
  return DS.ro_cursor() # cursor on the shared instance — no sync-writer contention
396
 
 
456
  _FORMAT_TYPE = {"usd": "currency", "int": "int", "pct": "pct"}
457
 
458
 
459
+ def _clean_tree(tree, cols):
460
  """Run a filter tree through the SAME validator the client's view state goes through.
461
 
462
  `filter_sql`'s documented input contract is "feed me CLEANED trees" — it is faithful to the
 
470
  module with zero imports of its own, so this cannot cycle.
471
  """
472
  from aios_grid import (clean_filter_tree, COHORT_FIELD as _COHORT_FIELD,
 
 
 
473
  MAX_FILTER_DEPTH, MAX_FILTER_NODES, MAX_FILTER_SIBLINGS)
474
 
475
  # REFUSE an over-large tree rather than TRUNCATE it. clean_filter_tree caps siblings per
 
535
  # it here, the fix is to pass the membership in, not to let it fall through.
536
  if cohorts:
537
  raise ModelError(
538
+ f"filter tree carries cohort-membership condition(s) {sorted(set(cohorts))} — "
539
  f"cohort membership is host state, not a column of this topic. Refusing rather than "
540
  f"dropping it, which would silently widen the result under an authoritative count.")
541
  if windowed:
542
  raise ModelError(
543
  f"filter tree carries measure condition(s) over a date window {sorted(set(windowed))}"
544
+ f" — those are resolved to a set of ids by harness.measure_filter, not compiled into "
545
  f"this query. Refusing rather than dropping or mis-compiling them, either of which "
546
  f"would silently answer a different question under an authoritative count.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547
  return clean_filter_tree(tree, set(cols))
548
 
549
 
 
688
  tid = names.get(channel)
689
  if tid is None:
690
  raise ModelError(
691
+ f"channel {channel!r} is not a team this tenant names — `tenant.yml::team_names` "
692
  f"carries {sorted(names)}, so the channel cannot be resolved to a team id")
693
  return f"o.team_id = {int(tid)} AND l.order_partner_id NOT IN " \
694
  f"(SELECT id FROM res_partner WHERE name LIKE {_sql_value(excl)})"
 
766
  # never count(*) on the wrong table); in a GROUPED query they are refused (split the request).
767
  foreign = [k for k in base_keys if _model()["metrics"][k]["topic"] != topic]
768
  if foreign and (group_by or grain):
769
+ raise ModelError(f"metrics {foreign} belong to another topic — cross-topic measures are "
770
  f"scalar-only; run them against their own topic when grouping")
771
  base_keys = [k for k in base_keys if k not in foreign]
772
  foreign_vals = {}
 
782
  gb = [g for g in (group_by or []) if g]
783
  for g in gb:
784
  if g not in dims:
785
+ raise ModelError(f"group_by {g!r} not a dim of {topic!r} (allowed: {list(dims)})")
 
786
  d = dims[g]
787
  select.append(f"{d['col']} AS {g}_id" if d.get("name_col") else f"{d['col']} AS {g}")
788
  group_cols.append(d["col"])
 
815
  # cell that reads as "this SKU sold nothing on Amazon" — a FALSE number, not a narrower one.
816
  if team_id and scope_variant is None:
817
  if not s.get("team_col"):
818
+ raise ModelError(f"topic {topic!r} is company-level — it has no business-unit filter")
819
  where.append(f"{s['team_col']} = ?"); params.append(int(team_id))
820
  if exclude_services and s.get("service_filter"):
821
  where.append(render_scope(s["service_filter"]))
822
  for dim_key, vals in (filters or {}).items():
823
  if dim_key not in dims:
824
+ raise ModelError(f"filter dim {dim_key!r} not allowed (use: {list(dims)})")
 
825
  # id dims filter by int; TEXT dims (e.g. city) filter by the value itself — either way
826
  # every VALUE stays parameterized (the whitelist covers identifiers only)
827
  def _coerce(v):
 
847
  if pred.uses_aggregate:
848
  bad = sorted(c for c in pred.columns_used if cols[c].get("aggregate"))
849
  raise ModelError(
850
+ f"filter_tree references measure(s) {bad} — a measure filter has to land in "
851
  f"HAVING, and that path is deliberately NOT built: CG-1 ships the WHERE path "
852
  f"because its consumer (CG-2, the line-grain sales table) does not aggregate. "
853
  f"Filter on dims, or aggregate first and filter the result.")
 
945
  scope_params.append(f"{date_to} 23:59:59")
946
  if team_id:
947
  if not s.get("team_col"):
948
+ raise ModelError(f"topic {topic!r} is company-level — it has no business-unit filter")
949
  scope.append(f"{s['team_col']} = ?")
950
  scope_params.append(int(team_id))
951
  if exclude_services and s.get("service_filter"):
 
953
 
954
  # --- the user's narrowing, on top of the scope --------------------------------------
955
  narrow, narrow_params = [], []
956
+ pred = _fs.compile_filter_tree(_clean_tree(filter_tree or [], cols), filter_conj, cols,
 
 
 
 
 
957
  today=today,
958
  member_ids=member_ids or None, id_sql=id_sql)
959
  if pred is not None:
 
1027
  raise ModelError(f"topic {topic!r} has no store binding")
1028
  d = (t["store"].get("dims") or {}).get(dim)
1029
  if not d:
1030
+ raise ModelError(f"unknown dim {dim!r} for topic {topic!r}")
1031
  if not d.get("name_col"):
1032
  raise ModelError(f"dim {dim!r} has no name column (filter by id)")
1033
  s = t["store"]
 
1320
  # user did not get rather than a base metric they never asked for.
1321
  key = key + _suffix
1322
  if strict:
1323
+ raise _EntityMeasureError(f"{topic}: measure {key!r} refused — {reason}")
1324
  refused.append({"key": key, "reason": reason})
1325
 
1326
  for key in b["keys"]:
 
1472
  # `rollup_sql.group_values` makes, for the same reason. Never write cells from one.
1473
  if res.get("truncated"):
1474
  raise _EntityMeasureError(
1475
+ f"{topic}: {src} grouped by {dim} exceeded {MAX_GROUPS} groups — refusing to write "
1476
  f"cells from a truncated result")
1477
  # `store_query` emits the bare dim name when the dim has no `name_col`, `<dim>_id` when it
1478
  # does. Both shapes are live in the model, so read whichever arrived.
platform/model/topics/odoo_products.yml CHANGED
@@ -190,11 +190,36 @@ fields:
190
  type: currency
191
  kind: data
192
  means: "Quoted unit cost at origin, before freight and duty. Editable and shared with everyone."
193
- - key: price_fisch
194
- label: "Fisch price"
195
  type: currency
196
  kind: data
197
- means: "Fisch pricelist price for this SKU. Blank when that list prices it nowhere."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  - key: price_fisch_t1
199
  label: "Fisch tier 1 price"
200
  type: currency
 
190
  type: currency
191
  kind: data
192
  means: "Quoted unit cost at origin, before freight and duty. Editable and shared with everyone."
193
+ - key: price_1
194
+ label: "Price 1"
195
  type: currency
196
  kind: data
197
+ means: "Cheapest live package price for this SKU pooled across ALL active pricelists and unattributed. Ask the per-list tier fields for what a named list charges."
198
+ - key: unit_1
199
+ label: "Unit 1"
200
+ type: text
201
+ kind: data
202
+ means: "Package label for Price 1; blank means Odoo has no package reference for that price."
203
+ - key: price_2
204
+ label: "Price 2"
205
+ type: currency
206
+ kind: data
207
+ means: "Second-cheapest live package price pooled across ALL pricelists, unattributed."
208
+ - key: unit_2
209
+ label: "Unit 2"
210
+ type: text
211
+ kind: data
212
+ means: "Package label for Price 2."
213
+ - key: price_3
214
+ label: "Price 3"
215
+ type: currency
216
+ kind: data
217
+ means: "Third-cheapest live package price pooled across ALL pricelists, unattributed."
218
+ - key: unit_3
219
+ label: "Unit 3"
220
+ type: text
221
+ kind: data
222
+ means: "Package label for Price 3."
223
  - key: price_fisch_t1
224
  label: "Fisch tier 1 price"
225
  type: currency
platform/model/topics/sales_lines.yml CHANGED
@@ -74,32 +74,6 @@ store:
74
  # 2,056 customers have a non-agent as agent_ids[0]. Do NOT "fix" it by reading the commission
75
  # table, which mixes agents and salespeople.
76
  agent: {col: "rp.agent_id", name_col: "ag.name", label: "Agent"}
77
- # ⭐⭐ W42-T01 (ruling R6) — THE ORDER-STATUS DIMS. R1's owner sentence is "where
78
- # `sale.order.line` is Invoiced", and until now the topic declared nothing to filter that on.
79
- # Both live on the PARENT order, which the `o` join already reaches; neither widens the scope.
80
- #
81
- # ⚠ `name_col` is DELIBERATELY THE SAME EXPRESSION AS `col`, the `city` pattern above. These
82
- # are text status codes, not m2o ids: give them a DIFFERENT name_col and `store_columns`
83
- # publishes an `<dim>_id` column typed `int` over a VARCHAR, and a numeric filter on it
84
- # quietly compares 0 against 0 for every row. Keeping them equal suppresses that id column
85
- # while still giving `store_field_values` a name column to resolve values with — a dim with
86
- # `name_col: null` raises "no name column (filter by id)" there (semantic.py, store_field_values),
87
- # so null is not an option either. ⚠ THOSE ARE TWO SEPARATE HAZARDS, and a third one is the
88
- # `receivables.payment_state` scar recorded in verify_odoo_relational: THAT one raised nothing
89
- # at all — `group_values` read a `<dim>_id` column the dim never emitted, so every cell came
90
- # back blank with no exception anywhere. Keeping name_col == col avoids all three: the id
91
- # column IS emitted (store_query always emits `<dim>_id` when name_col is set) and it holds
92
- # the same text value the user filters on.
93
- #
94
- # ⚠ VALUES ARE THE RAW ODOO STATES, not display words: invoice_status is one of
95
- # 'invoiced' / 'to invoice' / 'no' / 'upselling'; order_state is 'sale' / 'done'.
96
- invoice_status: {col: "o.invoice_status", name_col: "o.invoice_status",
97
- label: "Invoice status"}
98
- # ⛔ TRAP, AND IT IS NOT A BUG: `scope_sql` already pins o.state IN ('sale','done'), so this
99
- # dim can only ever return those two buckets. It exists to name the distinction inside the
100
- # confirmed scope (Confirmed vs Locked), NOT to reach quotes or cancellations. Do NOT "fix"
101
- # it by widening `scope_sql` — that would change what every metric on this topic means.
102
- order_state: {col: "o.state", name_col: "o.state", label: "Order state"}
103
 
104
  ai_context: >
105
  The wholesale sales dataset of Royal Imports / Fisch Floral Supply, at order-LINE grain.
@@ -143,14 +117,3 @@ ai_context: >
143
  has no address on file — present it as "no state on file", keep it in totals) and duplicate
144
  state records exist (two ids can share one name, e.g. New Jersey twice) — list them as the
145
  data shows and note the duplication rather than silently merging.
146
- INVOICING questions ("which confirmed sales are invoiced", "what is still to invoice") use the
147
- `invoice_status` dim, which carries the PARENT ORDER's status: an order is the unit Odoo
148
- invoices, so a line inherits its order's status rather than having one of its own. Its values
149
- are the raw Odoo codes, so say them in plain words: 'invoiced' is fully invoiced, 'to invoice'
150
- is awaiting an invoice, 'no' means nothing to invoice, and 'upselling' means delivered above
151
- the ordered quantity. The `order_state` dim is 'sale' (confirmed) or 'done' (locked) and can
152
- never be anything else here, because this topic's scope is confirmed orders only; quotes and
153
- cancelled orders are outside it, so never read a missing bucket as "we have no quotes".
154
- DATA CAVEAT, measured 2026-08-25: 'done' (locked) is reachable under this scope but has NO rows
155
- in this tenant's store today, so grouping by `order_state` returns the single bucket 'sale' and
156
- that is the whole confirmed population, not a filtered slice of it.
 
74
  # 2,056 customers have a non-agent as agent_ids[0]. Do NOT "fix" it by reading the commission
75
  # table, which mixes agents and salespeople.
76
  agent: {col: "rp.agent_id", name_col: "ag.name", label: "Agent"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
  ai_context: >
79
  The wholesale sales dataset of Royal Imports / Fisch Floral Supply, at order-LINE grain.
 
117
  has no address on file — present it as "no state on file", keep it in totals) and duplicate
118
  state records exist (two ids can share one name, e.g. New Jersey twice) — list them as the
119
  data shows and note the duplication rather than silently merging.
 
 
 
 
 
 
 
 
 
 
 
platform/modules/product_data.py CHANGED
@@ -558,20 +558,6 @@ def _catalogue_by_code():
558
  return products.catalogue()
559
 
560
 
561
- def _pricelist_by_code():
562
- """`({code: {price_*: price}}, report)` from `products.pricelist_by_code`, or `({}, …)`.
563
-
564
- A SEAM for the same two reasons `_inventory_by_code` is one: it degrades rather than raises
565
- (these are columns, not the row set), and `verify_perm_scope`'s section H stubs it to build a
566
- pool without Odoo. ⛔ Unstubbed there, section H would reach live Odoo through the back door
567
- and the whole file would stop being runnable offline.
568
- """
569
- try:
570
- return products.pricelist_by_code()
571
- except Exception as e:
572
- return {}, {"error": f"{type(e).__name__}: {str(e)[:200]}"}
573
-
574
-
575
  def pool(team_id=None, t=None):
576
  """One row per ACTIVE product — the PRODUCT analogue of `customer_data.pool`.
577
 
@@ -591,12 +577,11 @@ def pool(team_id=None, t=None):
591
  inv = _inventory_by_code(t)
592
  bu_share = {} if consolidated else _bu_ltm_share(t, team_id)
593
  sup = supplier_master()
594
- prices, _price_report = _pricelist_by_code()
595
  # ⭐ W37-T14 / T15. ⚠ MEASURED COST, stated because it lands on a scope's FIRST build:
596
  # tier prices 15.1 s + packagings 8.1 s on top of the ~44 s consolidated build. Only the
597
  # first build for a scope blocks (`routes_products._pool_for`'s stale-while-refresh), and
598
- # both degrade to `{}` on a read failure rather than taking the grid down — the same
599
- # asymmetry `pricelist_by_code` documents: a column is not the ROW SET.
600
  try:
601
  _prods = products.active_products() # ONE read, shared by both (see its docstring)
602
  except Exception: # noqa: BLE001
@@ -676,50 +661,29 @@ def pool(team_id=None, t=None):
676
  "qty_ytd": r.get("qty_ytd", 0.0) if r else None,
677
  "orders_ytd": r.get("orders_ytd", 0) if r else None,
678
  }
679
- # ⭐ WAVE 30 W30-T34 — the PRICELIST stratum, one column per declared list. Catalogue
680
- # data like the supplier block, so it rides every pull, scoped or not: a price book is
681
- # not a thing a business unit owns a slice of, and a Fisch reader who cannot see the
682
- # Fisch price is exactly who this column is for.
683
- #
684
- # ⛔ `None`, NEVER 0 AND NEVER A FALLBACK, for the 1,883 SKUs no list prices. That is
685
- # W29-T52's own negative control: the single `3_global` rule computes over `list_price`,
686
- # which is 1.00 on 5,817 of 5,871 products, so the fallback is not a cheaper answer —
687
- # it is a wrong one wearing a currency sign.
688
- # ⛔ `PRICELIST_GRID_COLUMNS`, NOT `PRICELIST_COLUMNS` — W42-T56 / R26. `prices` still
689
- # resolves all three declared lists; only Fisch still gets a BASE grid column, because
690
- # the per-list tier block supersedes the two Royal ones. The wider tuple stays the
691
- # PRICELIST IDENTITY registry that `PRICELIST_TIER_COLUMNS` is derived from, so reading
692
- # it here would write two cells the contract no longer declares — and `rows_from_pool`
693
- # projects STRICTLY, so those two would be dropped on the wire with no error at all.
694
- p = prices.get(code) or {}
695
- for _col, _name in products.PRICELIST_GRID_COLUMNS:
696
- row[_col] = p.get(_col)
697
- # ⭐⭐ W37-T14 / T15 — THE HONEST SETS, beside the three declared columns rather than
698
- # instead of them. The columns above answer "what does Fisch charge"; these answer "how
699
- # many prices/units does this SKU actually have", which the columns structurally cannot:
700
- # they are named after THIS tenant's lists, so a price on any other list is invisible.
701
  # ⚠ A `json` cell is a STRING on the wire (the type's own contract), so these are dumped
702
  # here rather than handed over as lists — a bare list would round-trip through the overlay
703
  # as something `grid_events` refuses to re-parse.
704
  # ⚠ BLANK, NOT "[]" — an empty cell reads as "sold in one unit / not priced on any list",
705
  # and an empty JSON array on screen reads as a bug.
706
  _tiers = tiers.get(code) or []
707
- # ⭐⭐ W40-T09 / RULING R6 (owner I25) — THE PRICES, ATTRIBUTED TO THE LIST THAT CHARGES
708
- # THEM: three (price, unit) pairs each for Fisch, Royal 1 and Royal 2.
 
 
 
 
709
  #
710
- # ⛔⛔ W42-T56 / R26 — THE POOLED `price_1..3` / `unit_1..3` WRITE THAT USED TO STAND
711
- # HERE IS GONE, NOT DEMOTED. W40-T09 left it in place with a comment promising the six
712
- # "stay DECLARED and stay WRITTEN ... demoted to `default: false`"; R26 reverses that
713
- # sentence and the write had to go with the declaration. The pooled six were the cheapest
714
- # three prices POOLED ACROSS EVERY LIST with no attribution, so on the 1,854 SKUs priced
715
- # on all three lists they answered a question nobody asked — not "what does Fisch charge"
716
- # but "what are the three lowest numbers anyone charges" — and carrying both blocks made
717
- # the grid state the same facts in two competing vocabularies.
718
- #
719
- # ⚠ DELETING THE CONTRACT ENTRY ALONE WOULD NOT HAVE BEEN ENOUGH, and that is why this
720
- # loop is deleted rather than left harmlessly writing: `rows_from_pool` projects STRICTLY
721
- # through `aios_grid_fields.json`, so an undeclared pool key is never iterated and there
722
- # is NO CELL, silently and with no exception. Six dead writes, every gate green.
723
  #
724
  # ⚠ NO SECOND ODOO READ. `tiers` already carries the pricelist name on every entry;
725
  # `per_list_tier_cells` is a group-by over the list this loop is already holding.
@@ -1053,143 +1017,6 @@ def validate(team_id=None, t=None):
1053
  "ours": still_active, "theirs": 0, "ok": still_active == 0,
1054
  "detail": {"codes": coded_outside[:10], "n_codes": len(outside)},
1055
  })
1056
- # ── ⭐⭐ WAVE 30 W30-T34 — THE PRICELIST COLUMNS, AGAINST ORACLES THAT CANNOT SEE OUR JOIN ──
1057
- #
1058
- # Three legs, because the column can fail in three different ways and only one of them is a
1059
- # count. `products.pricelist_by_code` builds a `{code: {col: price}}` map by expanding each
1060
- # rule over the products it names, IN PYTHON — that expansion is the fragile part, so every
1061
- # leg below re-asks ODOO instead of re-reading the map.
1062
- price_report = _pricelist_by_code()[1]
1063
- _pl_rows = O.search_read('product.pricelist', [], ['id', 'name'])
1064
- _pl_id = {}
1065
- for _p in _pl_rows:
1066
- _pl_id.setdefault(str(_p.get('name') or '').strip(), _p['id'])
1067
- _today = P.today().isoformat()
1068
-
1069
- _targets_memo = {}
1070
-
1071
- def _rule_targets(list_name):
1072
- """(variant_ids, template_ids) a pricelist prices today — read FRESH from Odoo.
1073
-
1074
- Memoised for the LIFE OF THIS CALL only: legs 1 and 2 both need all three lists, and
1075
- without this `validate()` makes six identical round trips instead of three (measured:
1076
- ~48s of the run). Deliberately NOT an `lru_cache` — an oracle that survives the process
1077
- is an oracle reading yesterday's Odoo.
1078
- """
1079
- if list_name in _targets_memo:
1080
- return _targets_memo[list_name]
1081
- var, tmpl = set(), set()
1082
- plid = _pl_id.get(list_name)
1083
- if plid is None:
1084
- return var, tmpl
1085
- for r in O.search_read(
1086
- 'product.pricelist.item',
1087
- [('pricelist_id', '=', plid), ('compute_price', '=', 'fixed'),
1088
- ('applied_on', 'in', ['0_product_variant', '1_product'])],
1089
- ['product_id', 'product_tmpl_id', 'applied_on', 'fixed_price',
1090
- 'date_start', 'date_end']):
1091
- ds, de = str(r.get('date_start') or '')[:10], str(r.get('date_end') or '')[:10]
1092
- if (ds and ds > _today) or (de and de < _today):
1093
- continue
1094
- fp = r.get('fixed_price')
1095
- if not isinstance(fp, (int, float)) or fp <= 0:
1096
- continue
1097
- if r.get('applied_on') == '0_product_variant' and r.get('product_id'):
1098
- var.add(O.m2o_id(r['product_id']))
1099
- elif r.get('product_tmpl_id'):
1100
- tmpl.add(O.m2o_id(r['product_tmpl_id']))
1101
- _targets_memo[list_name] = (var, tmpl)
1102
- return var, tmpl
1103
-
1104
- # LEG 1 — COVERAGE PER LIST. Ours: cells we filled. Theirs: a bare Odoo `search_count` of
1105
- # ACTIVE products a fresh read of that list's rules reaches. The rule set is shared (it IS
1106
- # the data) but the EXPANSION is not, and the expansion is what breaks.
1107
- # ⛔ GRID SUBSET — W42-T56 / R26. `ours` counts CELLS THAT WERE WRITTEN, so this leg must
1108
- # enumerate the columns the grid still carries. Left at the full `PRICELIST_COLUMNS` it asks
1109
- # Odoo for a live `search_count` on Royal 1 and Royal 2, gets a non-zero `theirs`, and counts
1110
- # `ours = 0` because nothing writes those cells any more — a coverage FAILURE that is really
1111
- # just a deleted column. The pricelists themselves are unchanged; only the grid narrowed.
1112
- for _col, _name in products.PRICELIST_GRID_COLUMNS:
1113
- _var, _tmpl = _rule_targets(_name)
1114
- _dom = [('active', '=', True), '|', ('id', 'in', sorted(_var)),
1115
- ('product_tmpl_id', 'in', sorted(_tmpl))]
1116
- theirs = O.get_odoo().search_count('product.product', _dom) if (_var or _tmpl) else 0
1117
- ours = sum(1 for r in rows if isinstance(r.get(_col), (int, float)))
1118
- checks.append({
1119
- "check": f"{_name} pricelist: SKUs priced in the grid == an INDEPENDENT Odoo count "
1120
- f"of ACTIVE products its date-valid fixed rules reach",
1121
- "ours": ours, "theirs": theirs, "ok": ours == theirs,
1122
- "detail": {"column": _col, "variant_rules": len(_var), "template_rules": len(_tmpl)},
1123
- })
1124
-
1125
- # LEG 2 — ⛔ THE TICKET'S OWN NEGATIVE CONTROL, AS A LEG. A SKU with no specific item must
1126
- # render BLANK. Asked of ODOO, never of the map that produced the blank — "everything I left
1127
- # empty was genuinely unpriced" is trivially true when checked against the dict that emptied
1128
- # it, which is the self-sealing shape the population leg above exists to end.
1129
- #
1130
- # ⛔ BOTH HALVES OF THIS LEG NARROW TOGETHER, AND SPLITTING THEM IS THE SILENT RED — W42-T56.
1131
- # `_unpriced` asks "which rows render a BLANK cell" (a GRID question, so the grid subset) and
1132
- # `_stray` asks "does Odoo in fact price them" (also the grid subset, because it must ask
1133
- # about the SAME lists). Narrow only the first and every SKU blank on Fisch but priced on
1134
- # Royal 1 counts as a stray: the check goes red on a perfectly correct build.
1135
- _unpriced = [r for r in rows
1136
- if not any(isinstance(r.get(c), (int, float))
1137
- for c, _n in products.PRICELIST_GRID_COLUMNS)]
1138
- _codes = {r["code"] for r in _unpriced}
1139
- _stray = 0
1140
- if _codes:
1141
- # Resolve those codes back to Odoo ids and ask whether ANY declared list prices them.
1142
- _ids, _tmpls = set(), set()
1143
- for _p in O.search_read('product.product',
1144
- [('active', '=', True),
1145
- ('default_code', 'in', sorted(c for c in _codes
1146
- if not c.startswith("pid:")))],
1147
- ['id', 'product_tmpl_id']):
1148
- _ids.add(_p['id'])
1149
- _tmpls.add(O.m2o_id(_p.get('product_tmpl_id')))
1150
- for _col, _name in products.PRICELIST_GRID_COLUMNS:
1151
- _v, _t = _rule_targets(_name)
1152
- _stray += len((_v & _ids) | ({t for t in _tmpls if t in _t}))
1153
- checks.append({
1154
- "check": "every SKU rendering a BLANK price is genuinely unpriced on every declared list "
1155
- "that still carries a BASE grid column (W29-T52's NC: no fallback dressed as a "
1156
- "price) — asked of Odoo. ⚠ NARROWED FROM 'all three' BY W42-T56/R26: Royal 1 "
1157
- "and Royal 2 no longer have a base cell to render blank, and their per-list "
1158
- "tier cells carry their own no-borrow NC in validate_price_and_unit_cells",
1159
- "ours": _stray, "theirs": 0, "ok": _stray == 0,
1160
- "detail": {"blank_skus": len(_unpriced), "priced_skus": len(rows) - len(_unpriced)},
1161
- })
1162
-
1163
- # LEG 3 — ⭐ R6's SECOND SENTENCE, AS A NUMBER. *"If there is lag or it can't be done, you
1164
- # need to explicitly tell me why and recommend a fix."* Everything the reader cannot see is
1165
- # counted here rather than dropped. The ASSERTION is the one thing that must never be true —
1166
- # a price cell that is present and not a positive number, i.e. a "free" SKU — while the
1167
- # rest rides `detail` so it is reported without reddening an honest day's data.
1168
- # ⛔ GRID SUBSET (W42-T56/R26) — all three counters below read GRID CELLS (`r.get(c)`), so
1169
- # they enumerate the columns the grid still writes. Behaviour is IDENTICAL either way today
1170
- # (an undeclared key returns None and every branch skips it), which is exactly why this is
1171
- # worth naming: left wide, these read two keys that can never be present and would report a
1172
- # narrowing rounding population as though it still covered three lists.
1173
- _bad = [r["code"] for r in rows
1174
- for c, _n in products.PRICELIST_GRID_COLUMNS
1175
- if r.get(c) is not None and not (isinstance(r.get(c), (int, float)) and r[c] > 0)]
1176
- # ⛔ MEASURED 2026-08-12 AND NOT FIXABLE FROM THIS FENCE: `aios_grid.rows_from_pool` sends
1177
- # every non-text field through `_round(v)` = `round(v)` with no ndigits, i.e. to a whole
1178
- # dollar. 52.1% of fixed prices carry cents and the median relative error is 5.26%, so this
1179
- # column ties to the cent HERE and ships rounded. Reported, never silently enforced.
1180
- _cents = sum(1 for r in rows for c, _n in products.PRICELIST_GRID_COLUMNS
1181
- if isinstance(r.get(c), (int, float)) and abs(r[c] - round(r[c])) > 1e-9)
1182
- _to_zero = sum(1 for r in rows for c, _n in products.PRICELIST_GRID_COLUMNS
1183
- if isinstance(r.get(c), (int, float)) and round(r[c]) == 0)
1184
- checks.append({
1185
- "check": "no price cell is present-but-not-a-positive-number (a 0 would read as FREE; "
1186
- "an unset rule must be blank), and what the reader cannot see is COUNTED",
1187
- "ours": len(_bad), "theirs": 0, "ok": not _bad,
1188
- "detail": {"bad_cells": _bad[:10], "reader_report": price_report,
1189
- "wire_rounding_loses_cents_on": _cents,
1190
- "wire_rounding_to_zero_dollars": _to_zero},
1191
- })
1192
-
1193
  # WAVE 17 R3 — the BUY SIGNAL must be a total, exact partition of the catalogue, and every
1194
  # member of it must be re-derivable from the two columns beside it. A signal somebody buys
1195
  # stock on cannot be "mostly right": the failure that matters is a row that says OK because
@@ -1513,40 +1340,39 @@ def validate_stock_measures(t=None, days=90, sample=4):
1513
 
1514
 
1515
  def validate_price_and_unit_cells(rows, sample=6):
1516
- """Reconcile the typed PER-LIST tier cells to a fresh, per-SKU Odoo read.
1517
 
1518
  The pool groups price rules in bulk. This asks Odoo per SKU so a wrong grouping, a lost
1519
  package price, or a missing unit has an oracle which cannot agree by reusing that grouping.
1520
- Duplicate SKU codes may make the pool a legitimate superset of a single product's rules,
1521
- so every comparison below is a SUPERSET test and never an equality.
1522
-
1523
- ⚠ W42-T56 / R26 — THE POOLED `price_1..3` / `unit_1..3` LEG IS GONE, THE TIER LEG STAYS.
1524
- This function used to validate BOTH vocabularies; R26 removed the pooled six from the grid,
1525
- so their legs went with them. Deleting the whole function would have silently dropped live
1526
- validation of the eighteen per-list tier columns, which are the half being KEPT and the half
1527
- that now carries the entire burden of proving the price cells are right.
1528
  """
1529
  checks = []
 
 
 
 
 
 
 
 
 
 
 
 
1530
 
1531
- # ── W40-T09 / R6 — the PER-LIST cells, the only price vocabulary the grid now speaks ──────
1532
  _tier_keys = [k for t in products.PRICELIST_TIER_COLUMNS for k in t[:2]]
1533
  _typed = [r for r in rows if all(k in r for k in _tier_keys)]
1534
- _json_cells = sum(1 for r in rows if "tier_prices" in r or "units" in r)
1535
  _per_list = {}
1536
  for _p, _u, _name, _n in products.PRICELIST_TIER_COLUMNS:
1537
  _per_list.setdefault(_name, {})[f"t{_n}"] = sum(1 for r in rows if r.get(_p) is not None)
1538
  checks.append({
1539
  "check": "the product grid serves all 18 per-list tier cells (price and unit 1..3 for "
1540
- "each declared pricelist), TYPED and on every row — never JSON cells",
1541
- "ours": {"rows_with_all_18": len(_typed), "rows": len(rows), "cells": len(_tier_keys),
1542
- "rows_with_json_cells": _json_cells},
1543
- "theirs": {"rows_with_all_18": len(rows), "cells": 18, "rows_with_json_cells": 0},
1544
- # ⚠ THE `tier_prices`/`units` CLAUSE IS INHERITED, NOT NEW. It rode the pooled
1545
- # "typed, not JSON cells" check that W42-T56/R26 deleted with the pooled columns, and it
1546
- # is a different assertion from the one that check was named for: it guards against the
1547
- # grid regressing to a JSON blob column instead of real typed cells. Rehomed here rather
1548
- # than dropped, because removing a vocabulary must not quietly remove a guard.
1549
- "ok": len(_typed) == len(rows) and len(_tier_keys) == 18 and not _json_cells,
1550
  "detail": {"skus_priced_per_list": _per_list},
1551
  })
1552
  # ⛔ CHEAPEST-FIRST PACKS FROM THE TOP, so a hole is the signature of a misaligned write:
@@ -1584,17 +1410,6 @@ def validate_price_and_unit_cells(rows, sample=6):
1584
  "detail": {"sku_list_pairs_over_cap": sum(len(v) for v in _over.values())},
1585
  })
1586
 
1587
- # ⛔ THE POPULATION IS RE-BASED ON THE TIER CELLS — W42-T56. It used to be
1588
- # `r.get("price_1") is not None`, a column that no longer exists; left alone it is falsy on
1589
- # every row, this function returns early, and the two live-Odoo tier oracles below (the per-list
1590
- # superset check and the no-borrow NC) STOP RUNNING while `validate()` still reports a full
1591
- # green — [[gate-that-never-ran-reads-as-failure]] at its quietest.
1592
- # ⚠ THE NEW POPULATION IS A SUBSET OF THE OLD, deliberately: a SKU priced only on a list the
1593
- # contract does not declare (Public Pricelist) had a pooled cell but has no tier cell, so it
1594
- # drops out of the sample. That also means `cand` samples different SKUs than it used to.
1595
- priced = [r for r in rows
1596
- if any(r.get(_p) is not None
1597
- for _p, _u, _n2, _n in products.PRICELIST_TIER_COLUMNS)]
1598
  if not priced:
1599
  return checks
1600
  o = O.get_odoo()
@@ -1603,7 +1418,7 @@ def validate_price_and_unit_cells(rows, sample=6):
1603
  # red gate on a correct build before it was written down. MEASURED 2026-08-24:
1604
  # `product.pricelist.name` is 'Fisch', but the m2o that arrives on a `product.pricelist.item`
1605
  # renders **'Fisch (USD)'** — Odoo appends the currency to the display name. Keying this
1606
- # oracle on `m2o_name(pricelist_id)` therefore matches NOTHING in `PRICELIST_COLUMNS`, every
1607
  # declared list reads as "this SKU is not priced here", and the no-borrow NC below reports
1608
  # all 18 sampled SKU/list pairs as violations while the shipped cells are perfect.
1609
  # `products.tier_prices_by_code` reads the field by id for exactly this reason, which is why
@@ -1611,14 +1426,13 @@ def validate_price_and_unit_cells(rows, sample=6):
1611
  _plname = {p["id"]: str(p.get("name") or "").strip()
1612
  for p in o.search_read("product.pricelist", [], ["id", "name"])}
1613
  # Prefer SKUs that carry more than one price, the ticket's own subject.
1614
- # Prefer SKUs carrying the most tier prices — the richest rows are the ticket's own subject
1615
- # and the ones a mis-grouped write is most likely to get wrong.
1616
  cand = sorted(priced,
1617
- key=lambda r: -sum(r.get(_p) is not None
1618
- for _p, _u, _n2, _n in products.PRICELIST_TIER_COLUMNS)
1619
- )[:sample]
1620
  bad_list, borrowed = [], [] # W40-T09: the per-list oracle and its no-borrow NC
1621
  for r in cand:
 
 
1622
  pid = r.get("product_id")
1623
  tmpl = None
1624
  if pid:
@@ -1642,8 +1456,16 @@ def validate_price_and_unit_cells(rows, sample=6):
1642
  by_template.setdefault(plid, []).append(it)
1643
  picked = [it for plid in sorted(set(by_variant) | set(by_template))
1644
  for it in (by_variant.get(plid) or by_template.get(plid) or [])]
1645
- # ── W40-T09 / R6 — THE ORACLE, ASKED PER LIST ──────────────────────────────
1646
- # ⚠ SUPERSET, NOT EQUALITY, for the same D-309 reason the deleted pooled leg had: a code
 
 
 
 
 
 
 
 
1647
  # carried by two active products merges here, so one list can legitimately hold more
1648
  # pairs than a single product's rules. Equality would go red on a working build.
1649
  theirs_by_list = {}
@@ -1655,9 +1477,8 @@ def validate_price_and_unit_cells(rows, sample=6):
1655
  # ⚠ AN EMPTY ORACLE IS NOT EVIDENCE OF BORROWING. If the per-SKU read came back with no
1656
  # rules at all, there is nothing to compare and firing the NC would report a broken
1657
  # oracle as a data defect — the failure mode the display-name bug above actually
1658
- # produced. The pooled leg that used to sit above was immune by construction (an
1659
- # empty oracle is trivially a subset) and W42-T56/R26 deleted it with the pooled
1660
- # columns, so this is now the ONLY place that says it.
1661
  for _name in (_declared_names if picked else []):
1662
  mine_l = sorted(
1663
  (round(float(r[_price_key[(_name, n)]]), 2),
@@ -1674,6 +1495,13 @@ def validate_price_and_unit_cells(rows, sample=6):
1674
  # prints another list's price under this list's heading.
1675
  if not theirs_by_list.get(_name) and mine_l:
1676
  borrowed.append({"sku": r.get("code"), "list": _name, "ours": mine_l})
 
 
 
 
 
 
 
1677
  checks.append({
1678
  "check": f"each sampled SKU's PER-LIST tier cells contain every live Odoo pair ON THAT "
1679
  f"LIST ({len(cand)} SKUs x {len(_declared_names)} declared pricelists)",
 
558
  return products.catalogue()
559
 
560
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
561
  def pool(team_id=None, t=None):
562
  """One row per ACTIVE product — the PRODUCT analogue of `customer_data.pool`.
563
 
 
577
  inv = _inventory_by_code(t)
578
  bu_share = {} if consolidated else _bu_ltm_share(t, team_id)
579
  sup = supplier_master()
 
580
  # ⭐ W37-T14 / T15. ⚠ MEASURED COST, stated because it lands on a scope's FIRST build:
581
  # tier prices 15.1 s + packagings 8.1 s on top of the ~44 s consolidated build. Only the
582
  # first build for a scope blocks (`routes_products._pool_for`'s stale-while-refresh), and
583
+ # both degrade to `{}` on a read failure rather than taking the grid down: they are columns,
584
+ # not the row set.
585
  try:
586
  _prods = products.active_products() # ONE read, shared by both (see its docstring)
587
  except Exception: # noqa: BLE001
 
661
  "qty_ytd": r.get("qty_ytd", 0.0) if r else None,
662
  "orders_ytd": r.get("orders_ytd", 0) if r else None,
663
  }
664
+ # ⭐⭐ W37-T14 / T15 — THE HONEST SETS. These answer "how many prices/units does this SKU
665
+ # actually have" across every list. The numbered per-list cells below select Fisch,
666
+ # Royal 1, and Royal 2 without rebuilding a legacy base-price payload.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
667
  # ⚠ A `json` cell is a STRING on the wire (the type's own contract), so these are dumped
668
  # here rather than handed over as lists — a bare list would round-trip through the overlay
669
  # as something `grid_events` refuses to re-parse.
670
  # ⚠ BLANK, NOT "[]" — an empty cell reads as "sold in one unit / not priced on any list",
671
  # and an empty JSON array on screen reads as a bug.
672
  _tiers = tiers.get(code) or []
673
+ for _n in range(1, 4):
674
+ _tier = _tiers[_n - 1] if len(_tiers) >= _n else None
675
+ row[f"price_{_n}"] = _tier.get("unit_price") if _tier else None
676
+ row[f"unit_{_n}"] = _tier.get("unit") if _tier else None
677
+ # ⭐⭐ W40-T09 / RULING R6 (owner I25) — THE SAME PRICES, ATTRIBUTED TO THE LIST THAT
678
+ # CHARGES THEM: three (price, unit) pairs each for Fisch, Royal 1 and Royal 2.
679
  #
680
+ # ⛔ THIS SUPERSEDES THE SIX LINES ABOVE RATHER THAN EXTENDING THEM, and the difference
681
+ # is the whole ticket. `price_1..3` are the cheapest three POOLED ACROSS EVERY LIST and
682
+ # carry no attribution, so on the 1,854 SKUs priced on all three lists they answer a
683
+ # question nobody asked: not "what does Fisch charge" but "what are the three lowest
684
+ # numbers anyone charges". The pooled six stay DECLARED and stay WRITTEN — a saved view
685
+ # or a stored permission wall naming one must keep working — but they are demoted to
686
+ # `default: false` in the contract so the default view stops offering the approximation.
 
 
 
 
 
 
687
  #
688
  # ⚠ NO SECOND ODOO READ. `tiers` already carries the pricelist name on every entry;
689
  # `per_list_tier_cells` is a group-by over the list this loop is already holding.
 
1017
  "ours": still_active, "theirs": 0, "ok": still_active == 0,
1018
  "detail": {"codes": coded_outside[:10], "n_codes": len(outside)},
1019
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1020
  # WAVE 17 R3 — the BUY SIGNAL must be a total, exact partition of the catalogue, and every
1021
  # member of it must be re-derivable from the two columns beside it. A signal somebody buys
1022
  # stock on cannot be "mostly right": the failure that matters is a row that says OK because
 
1340
 
1341
 
1342
  def validate_price_and_unit_cells(rows, sample=6):
1343
+ """Reconcile typed Price 1..3 / Unit 1..3 cells to a fresh, per-SKU Odoo read.
1344
 
1345
  The pool groups price rules in bulk. This asks Odoo per SKU so a wrong grouping, a lost
1346
  package price, or a missing unit has an oracle which cannot agree by reusing that grouping.
1347
+ The contract ships only the cheapest three pairs; duplicate SKU codes may make the pool a
1348
+ legitimate superset of a single product's rules.
 
 
 
 
 
 
1349
  """
1350
  checks = []
1351
+ priced = [r for r in rows if r.get("price_1") is not None]
1352
+ with_first_pair = [r for r in rows if "price_1" in r and "unit_1" in r]
1353
+ checks.append({
1354
+ "check": "the product grid serves typed Price 1..3 and Unit 1..3 cells, not JSON cells",
1355
+ "ours": {"with_price_1": len(priced), "with_first_pair": len(with_first_pair),
1356
+ "rows": len(rows)},
1357
+ "theirs": {"price_1": ">0", "typed_first_pair": len(rows)},
1358
+ "ok": bool(priced) and len(with_first_pair) == len(rows)
1359
+ and not any("tier_prices" in r or "units" in r for r in rows),
1360
+ "detail": {"two_or_more_prices": sum(1 for r in rows if r.get("price_2") is not None),
1361
+ "three_prices": sum(1 for r in rows if r.get("price_3") is not None)},
1362
+ })
1363
 
1364
+ # ── W40-T09 / R6 — the PER-LIST cells, which is what the pooled three above are not ──────
1365
  _tier_keys = [k for t in products.PRICELIST_TIER_COLUMNS for k in t[:2]]
1366
  _typed = [r for r in rows if all(k in r for k in _tier_keys)]
 
1367
  _per_list = {}
1368
  for _p, _u, _name, _n in products.PRICELIST_TIER_COLUMNS:
1369
  _per_list.setdefault(_name, {})[f"t{_n}"] = sum(1 for r in rows if r.get(_p) is not None)
1370
  checks.append({
1371
  "check": "the product grid serves all 18 per-list tier cells (price and unit 1..3 for "
1372
+ "each declared pricelist), typed and on every row",
1373
+ "ours": {"rows_with_all_18": len(_typed), "rows": len(rows), "cells": len(_tier_keys)},
1374
+ "theirs": {"rows_with_all_18": len(rows), "cells": 18},
1375
+ "ok": len(_typed) == len(rows) and len(_tier_keys) == 18,
 
 
 
 
 
 
1376
  "detail": {"skus_priced_per_list": _per_list},
1377
  })
1378
  # ⛔ CHEAPEST-FIRST PACKS FROM THE TOP, so a hole is the signature of a misaligned write:
 
1410
  "detail": {"sku_list_pairs_over_cap": sum(len(v) for v in _over.values())},
1411
  })
1412
 
 
 
 
 
 
 
 
 
 
 
 
1413
  if not priced:
1414
  return checks
1415
  o = O.get_odoo()
 
1418
  # red gate on a correct build before it was written down. MEASURED 2026-08-24:
1419
  # `product.pricelist.name` is 'Fisch', but the m2o that arrives on a `product.pricelist.item`
1420
  # renders **'Fisch (USD)'** — Odoo appends the currency to the display name. Keying this
1421
+ # oracle on `m2o_name(pricelist_id)` therefore matches NOTHING in `PRICELIST_TIER_LISTS`, every
1422
  # declared list reads as "this SKU is not priced here", and the no-borrow NC below reports
1423
  # all 18 sampled SKU/list pairs as violations while the shipped cells are perfect.
1424
  # `products.tier_prices_by_code` reads the field by id for exactly this reason, which is why
 
1426
  _plname = {p["id"]: str(p.get("name") or "").strip()
1427
  for p in o.search_read("product.pricelist", [], ["id", "name"])}
1428
  # Prefer SKUs that carry more than one price, the ticket's own subject.
 
 
1429
  cand = sorted(priced,
1430
+ key=lambda r: -sum(r.get(f"price_{n}") is not None for n in range(1, 4)))[:sample]
1431
+ bad = []
 
1432
  bad_list, borrowed = [], [] # W40-T09: the per-list oracle and its no-borrow NC
1433
  for r in cand:
1434
+ mine = sorted((round(float(r[f"price_{n}"]), 2), str(r.get(f"unit_{n}") or "").strip())
1435
+ for n in range(1, 4) if r.get(f"price_{n}") is not None)
1436
  pid = r.get("product_id")
1437
  tmpl = None
1438
  if pid:
 
1456
  by_template.setdefault(plid, []).append(it)
1457
  picked = [it for plid in sorted(set(by_variant) | set(by_template))
1458
  for it in (by_variant.get(plid) or by_template.get(plid) or [])]
1459
+ theirs = sorted((round(float(it.get("packaging_price") or it.get("fixed_price") or 0.0), 2),
1460
+ str(O.m2o_name(it.get("packaging_id")) or "").strip())
1461
+ for it in picked)[:3]
1462
+ # ⚠ A code carried by TWO active products legitimately holds MORE entries than a single
1463
+ # product's rules (D-309 / `2112-12`), so ours is a SUPERSET, never an equality.
1464
+ if not set(theirs) <= set(mine):
1465
+ bad.append({"sku": r.get("code"), "ours": mine, "odoo": theirs})
1466
+
1467
+ # ── W40-T09 / R6 — the SAME oracle, now asked PER LIST ──────────────────────────────
1468
+ # ⚠ SUPERSET, NOT EQUALITY, for the same D-309 reason as the pooled leg above: a code
1469
  # carried by two active products merges here, so one list can legitimately hold more
1470
  # pairs than a single product's rules. Equality would go red on a working build.
1471
  theirs_by_list = {}
 
1477
  # ⚠ AN EMPTY ORACLE IS NOT EVIDENCE OF BORROWING. If the per-SKU read came back with no
1478
  # rules at all, there is nothing to compare and firing the NC would report a broken
1479
  # oracle as a data defect — the failure mode the display-name bug above actually
1480
+ # produced. The pooled leg is immune by construction (`set() <= set(mine)` passes); this
1481
+ # one has to say so.
 
1482
  for _name in (_declared_names if picked else []):
1483
  mine_l = sorted(
1484
  (round(float(r[_price_key[(_name, n)]]), 2),
 
1495
  # prints another list's price under this list's heading.
1496
  if not theirs_by_list.get(_name) and mine_l:
1497
  borrowed.append({"sku": r.get("code"), "list": _name, "ours": mine_l})
1498
+ checks.append({
1499
+ "check": f"each sampled SKU's typed Price/Unit pairs contain every live Odoo pair "
1500
+ f"({len(cand)} SKUs, chosen for the most prices)",
1501
+ "ours": len(bad), "theirs": 0, "ok": not bad,
1502
+ "detail": {"mismatches": bad[:3],
1503
+ "sampled": [r.get("code") for r in cand]},
1504
+ })
1505
  checks.append({
1506
  "check": f"each sampled SKU's PER-LIST tier cells contain every live Odoo pair ON THAT "
1507
  f"LIST ({len(cand)} SKUs x {len(_declared_names)} declared pricelists)",
platform/modules/products.py CHANGED
@@ -405,7 +405,7 @@ DISCONTINUED_TAG = 'Discontinued'
405
  def discontinued_tag_id():
406
  """The `product.tag` id for `DISCONTINUED_TAG`, or `None` if the tag is not there.
407
 
408
- ⚠ RESOLVED BY NAME, NOT BY ID, for the reason `PRICELIST_COLUMNS` gives: an id hard-coded here
409
  keeps pointing at whatever inherits it if the tag is deleted and re-made, and every product
410
  would be silently mislabelled. A missing tag yields `None`, which marks the whole catalogue
411
  `No` — so `validate()` reconciles the count against Odoo rather than trusting this, and goes
@@ -462,66 +462,6 @@ def incoming_from_po(prods=None):
462
  'units_on_archived_products': round(off_catalogue, 1)}
463
 
464
 
465
- #: ⭐⭐ WAVE 30 / W30-T34 (the carried W29-T52) — THE PRICELIST STRATUM, PER LIST.
466
- #:
467
- #: MEASURED LIVE 2026-08-12, and every one of these numbers shaped the design rather than
468
- #: decorating it:
469
- #:
470
- #: · **Five pricelists, three of them material.** Date-valid fixed rules: Fisch 5,139,
471
- #: Royal 1 2,702, Royal 2 2,605, Public Pricelist 17, Giftware Deals 1. At SKU level that
472
- #: is Fisch 3,971 · Royal 1 1,920 · Royal 2 1,857 · Public 6 · Giftware 0.
473
- #: · **3,988 of 5,871 active products carry a usable fixed rule; 1,883 carry NONE.**
474
- #: · **1,853 SKUs are priced on all three lists AND THE LISTS DISAGREE** — median relative
475
- #: spread 16%, max 82%. That is why this is three columns rather than one "the price" or a
476
- #: low/high pair: neither can tell a Fisch rep what Fisch sells the SKU for, which is the
477
- #: only question the column exists to answer.
478
- #: · ⛔ **`list_price` is 1.00 on 5,817 of the 5,871** — so the single `3_global` rule
479
- #: computed over it is meaningless, exactly as W29-T52 said. **This reader never falls
480
- #: through to it**, and that is the ticket's own negative control: a SKU with no specific
481
- #: item renders BLANK, never a fallback dressed as a price.
482
- #:
483
- #: ⚠ RESOLVED BY NAME, NOT BY ID. A pricelist renamed or deleted in Odoo makes its column go
484
- #: blank and makes `report["lists_missing"]` name it — a hard-coded id would keep pointing at
485
- #: whatever inherited it and mislabel every cell silently.
486
- PRICELIST_COLUMNS = (
487
- ("price_fisch", "Fisch"),
488
- ("price_royal_1", "Royal 1"),
489
- ("price_royal_2", "Royal 2"),
490
- )
491
-
492
- #: ⛔⛔ THE PRICELIST COLUMNS THAT STILL GET A **BASE GRID COLUMN** OF THEIR OWN — W42-T56 / R26,
493
- #: and this constant exists because the two jobs above were one name doing two things.
494
- #:
495
- #: `PRICELIST_COLUMNS` wears TWO HATS: it is a GRID FIELD LIST *and* it is this tenant's
496
- #: PRICELIST IDENTITY REGISTRY. R26 took `price_royal_1` / `price_royal_2` off the grid — the
497
- #: per-list tier block (`price_royal1_t1..t3`) supersedes them, and carrying both vocabularies
498
- #: made the product grid answer the same question twice in two different dialects.
499
- #:
500
- #: ⛔ THEY STAY IN `PRICELIST_COLUMNS` ABOVE, AND DELETING THEM THERE IS THE ONE EDIT THAT
501
- #: DESTROYS THIS TICKET. `PRICELIST_TIER_COLUMNS` is DERIVED from that tuple by running
502
- #: `_pricelist_slug` over it — `price_royal_1` -> `royal1` -> `price_royal1_t1..t3`. Remove the
503
- #: two entries and the six tier columns R26 explicitly PRESERVES vanish with them, silently and
504
- #: with every gate green, because every remaining check would then agree about a smaller world.
505
- #:
506
- #: THE RULE, stated once: reach for THIS tuple when you are writing or counting a GRID CELL;
507
- #: reach for `PRICELIST_COLUMNS` when you are asking about a PRICELIST (which lists exist, what
508
- #: Odoo charges on them, what `pricelist_by_code` returns).
509
- #:
510
- #: ⚠ DERIVED BY FILTERING `PRICELIST_COLUMNS`, NOT RETYPED, so the label can never drift from the
511
- #: list it names — and the filter is ASSERTED rather than left to yield quietly. A bare
512
- #: comprehension would return an EMPTY tuple if `price_fisch` were ever renamed above, which
513
- #: stops every base price cell being written and reddens nothing at import.
514
- _GRID_PRICELIST_KEYS = ("price_fisch",)
515
- PRICELIST_GRID_COLUMNS = tuple(
516
- (col, name) for col, name in PRICELIST_COLUMNS if col in _GRID_PRICELIST_KEYS
517
- )
518
- if len(PRICELIST_GRID_COLUMNS) != len(_GRID_PRICELIST_KEYS):
519
- raise RuntimeError(
520
- f"PRICELIST_GRID_COLUMNS names {_GRID_PRICELIST_KEYS} but PRICELIST_COLUMNS only "
521
- f"offers {[c for c, _n in PRICELIST_COLUMNS]} — a pricelist was renamed without "
522
- f"updating the grid subset, and the silent result is a base price column that is "
523
- f"never written")
524
-
525
  #: ⭐⭐ W40-T09 / RULING R6 (owner I25: *"Fisch price and Royal price each have 3 units and 3
526
  #: prices. Separate them and put all of them in the Odoo fields."*) — HOW MANY (price, unit)
527
  #: PAIRS EACH DECLARED LIST SHOWS.
@@ -535,24 +475,23 @@ if len(PRICELIST_GRID_COLUMNS) != len(_GRID_PRICELIST_KEYS):
535
  #: observed per list: Fisch 4, Royal 1 3, Royal 2 3, Public Pricelist 1.
536
  PRICELIST_TIER_DEPTH = 3
537
 
 
 
 
 
538
 
539
- def _pricelist_slug(col):
540
- """`price_royal_1` -> `royal1`, the token the per-list tier keys are built on.
541
 
542
- ⛔ THE UNDERSCORE IS REMOVED DELIBERATELY, and it is not cosmetic. `price_royal_1` ALREADY
543
- EXISTS and means "the Royal 1 list's base price", so a tier key of `price_royal_1_t1` shares
544
- a prefix with a different column and is ambiguous to anyone diffing the contract by eye.
545
- `price_royal1_t1` cannot be mistaken for a suffix of it.
546
- """
547
- return col[len("price_"):].replace("_", "")
548
 
549
 
550
  #: `[(price_key, unit_key, pricelist_name, tier_no)]` — the 18 columns R6 declares, DERIVED from
551
- #: `PRICELIST_COLUMNS` so this tenant's list names live in exactly one place. A fourth pricelist
552
- #: added above becomes six more tier columns here with no second edit.
553
  PRICELIST_TIER_COLUMNS = tuple(
554
- (f"price_{_pricelist_slug(col)}_t{n}", f"unit_{_pricelist_slug(col)}_t{n}", name, n)
555
- for col, name in PRICELIST_COLUMNS
556
  for n in range(1, PRICELIST_TIER_DEPTH + 1)
557
  )
558
 
@@ -578,7 +517,7 @@ def per_list_tier_cells(tiers):
578
  cells. Sorting the group is one line and makes the guarantee local to the function that
579
  makes it. The tiebreak matches the reader's: unit name, then list name.
580
 
581
- ⚠ A LIST NOT IN `PRICELIST_COLUMNS` IS INVISIBLE HERE BY DESIGN — the columns are named
582
  after the three lists the contract declares. MEASURED: 3 active SKUs are priced ONLY on
583
  Public Pricelist, so they carry all eighteen cells empty. `tier_prices_by_code` still sees
584
  those prices; nothing is lost from the honest set, only from these named columns.
@@ -615,150 +554,6 @@ def tier_cap_overflow(tiers):
615
  if name in declared and n > PRICELIST_TIER_DEPTH}
616
 
617
 
618
- def pricelist_by_code():
619
- """`({code: {column_key: price}}, report)` — the date-valid FIXED base-tier price for each
620
- declared pricelist, keyed EXACTLY as `catalogue()` keys its rows.
621
-
622
- ⛔ THE KEYING IS LOAD-BEARING, not a detail. `catalogue()` keys on `default_code` with a
623
- `pid:{id}` fallback for the ~33 active records that carry none. Keying this map any other
624
- way would leave those SKUs permanently blank while an oracle counting active products
625
- counted them — a red gate on a working build, or worse, a silent hole nobody counts.
626
-
627
- **The base tier, deliberately.** `pricecomp._tier_for` picks the highest `min_quantity` at
628
- or below an order's quantity, because it is pricing a LINE that has one. A catalogue column
629
- has no quantity in hand, so it takes the LOWEST `min_quantity` — the price at qty 1. Rules
630
- above that break are a bulk price, and `report["qty_break_only"]` counts the SKUs whose only
631
- rule sits on one (MEASURED: 10 rules of 10,464 carry a break at all).
632
-
633
- **Variant rules beat template rules**, matching `pricecomp._tier_for`: a `0_product_variant`
634
- rule is the more specific statement about this exact SKU.
635
-
636
- ⚠ DEGRADES TO `({}, report)` on a read failure, matching `_inventory_by_code` rather than
637
- `catalogue()`: these are COLUMNS, and a product grid that will not render because pricing is
638
- momentarily unreachable is a worse failure than one with blank price columns. The blanks are
639
- not silent — `product_data.validate()`'s coverage leg reconciles each column against a fresh
640
- Odoo count and goes red at zero.
641
-
642
- ⭐ **The report exists because R6's second sentence is law** (*"if it can't be done, you need
643
- to explicitly tell me why and recommend a fix"*). Everything this reader CANNOT see is
644
- counted rather than dropped: rules on pricelists the contract does not declare, non-fixed
645
- (`formula`/`percent`) rules, the `3_global` fallback, and prices that only exist above a
646
- quantity break.
647
- """
648
- # ⚠ THE COUNTERS ARE DISJOINT AND ORDER-DEPENDENT, and saying so is the difference between a
649
- # report and a misleading one. A rule is classified ONCE, by the first reason it is skipped:
650
- # undeclared list → out of date → not fixed → global → zero price. So `rules_not_fixed: 0`
651
- # means "no formula rule on a list we declare", NOT "this Odoo has no formula rules"
652
- # (MEASURED 2026-08-12: it has exactly one, and it sits on Public Pricelist, which the
653
- # contract does not declare — so it lands in `rules_undeclared_list`).
654
- report = {"lists_missing": [], "rules_total": 0, "rules_undeclared_list": 0,
655
- "rules_not_fixed": 0, "rules_global": 0, "rules_out_of_date": 0,
656
- "rules_zero_price": 0, "qty_break_only": 0}
657
- try:
658
- pl_rows = O.search_read('product.pricelist', [], ['id', 'name'])
659
- by_name = {}
660
- for p in pl_rows:
661
- by_name.setdefault(str(p.get('name') or '').strip(), p['id'])
662
- wanted = {}
663
- for col, name in PRICELIST_COLUMNS:
664
- pid = by_name.get(name)
665
- if pid is None:
666
- report["lists_missing"].append(name)
667
- else:
668
- wanted[pid] = col
669
-
670
- # ⭐⭐ FILTERED SERVER-SIDE, AND THE REASON IS A MEASUREMENT, NOT A STYLE PREFERENCE.
671
- # Reading all 10,464 rules with 9 fields and sorting them in Python costs **30.1s** on
672
- # this connection; the same rules under a server-side domain with 6 fields cost
673
- # **13.6s** (measured 2026-08-12, back to back). `pool()` runs this on a scope's
674
- # first-ever build, so that 16.5s is 16.5s of somebody's page load.
675
- #
676
- # ⚠ The domain reproduces the Python predicate EXACTLY, and the null legs are the part
677
- # that is easy to get wrong: an absent `date_start` is `False`, not a past date, so
678
- # `('date_start','<=',today)` ALONE would drop every open-ended rule — which is almost
679
- # all of them.
680
- today = P.today().isoformat()
681
- _declared = sorted(wanted)
682
- _kinds = ['0_product_variant', '1_product']
683
- _live = [('pricelist_id', 'in', _declared), ('compute_price', '=', 'fixed'),
684
- ('applied_on', 'in', _kinds),
685
- '|', ('date_start', '=', False), ('date_start', '<=', today),
686
- '|', ('date_end', '=', False), ('date_end', '>=', today),
687
- ('fixed_price', '>', 0)]
688
- rules = O.search_read(
689
- 'product.pricelist.item', _live,
690
- ['pricelist_id', 'product_id', 'product_tmpl_id', 'applied_on', 'fixed_price',
691
- 'min_quantity']) if _declared else []
692
-
693
- # ⭐ R6's SECOND SENTENCE, PAID FOR WITH `search_count` RATHER THAN A WIDER READ. Six
694
- # counts cost ~1.2s together; the rules they count would cost 16s to read. What this
695
- # reader cannot see is still REPORTED — it is just no longer transferred.
696
- def _n(extra):
697
- try:
698
- return O.get_odoo().search_count('product.pricelist.item', extra)
699
- except Exception:
700
- return -1 # -1 reads as "not measured", never as zero
701
- _dated = ['|', ('date_start', '=', False), ('date_start', '<=', today),
702
- '|', ('date_end', '=', False), ('date_end', '>=', today)]
703
- report["rules_total"] = _n([])
704
- report["rules_undeclared_list"] = _n([('pricelist_id', 'not in', _declared)]) \
705
- if _declared else report["rules_total"]
706
- if _declared:
707
- _on = [('pricelist_id', 'in', _declared)]
708
- # `percent_price` and formula rules are read NOWHERE in this repo. A rule we cannot
709
- # price is one the operator is TOLD about, never one that quietly becomes a blank.
710
- report["rules_not_fixed"] = _n(_on + [('compute_price', '!=', 'fixed')])
711
- report["rules_global"] = _n(_on + [('compute_price', '=', 'fixed'),
712
- ('applied_on', 'not in', _kinds)])
713
- report["rules_out_of_date"] = (
714
- _n(_on + [('compute_price', '=', 'fixed'), ('applied_on', 'in', _kinds)])
715
- - _n(_on + [('compute_price', '=', 'fixed'),
716
- ('applied_on', 'in', _kinds)] + _dated))
717
- # A zero price is not "free" — it is an unset rule. Blank says so; 0 does not.
718
- report["rules_zero_price"] = _n(
719
- _on + [('compute_price', '=', 'fixed'), ('applied_on', 'in', _kinds)]
720
- + _dated + [('fixed_price', '<=', 0)])
721
-
722
- by_var, by_tmpl = {}, {}
723
- for r in rules:
724
- col = wanted[O.m2o_id(r.get('pricelist_id'))]
725
- if r.get('applied_on') == '0_product_variant' and r.get('product_id'):
726
- by_var.setdefault((col, O.m2o_id(r['product_id'])), []).append(r)
727
- elif r.get('product_tmpl_id'):
728
- by_tmpl.setdefault((col, O.m2o_id(r['product_tmpl_id'])), []).append(r)
729
-
730
- dom = [('active', '=', True)]
731
- prods = O.search_read('product.product', dom,
732
- ['id', 'default_code', 'product_tmpl_id'], limit=50000)
733
- n = O.get_odoo().search_count('product.product', dom)
734
- if len(prods) != n:
735
- # Same guard, same reason as `catalogue()`: a short pull renders as a plausible
736
- # smaller set of priced SKUs with nothing reporting it.
737
- raise ValueError(
738
- f"products.pricelist_by_code: the product pull is TRUNCATED — read {len(prods)} "
739
- f"rows against a search_count of {n}.")
740
- except Exception as e:
741
- report["error"] = f"{type(e).__name__}: {str(e)[:200]}"
742
- return {}, report
743
-
744
- out = {}
745
- for p in prods:
746
- code = (str(p['default_code']).strip() if p.get('default_code') else f"pid:{p['id']}")
747
- tmpl = O.m2o_id(p.get('product_tmpl_id'))
748
- cells = {}
749
- for col, _name in PRICELIST_COLUMNS:
750
- cands = by_var.get((col, p['id'])) or by_tmpl.get((col, tmpl))
751
- if not cands:
752
- continue
753
- base = min(cands, key=lambda r: r.get('min_quantity') or 0.0)
754
- if (base.get('min_quantity') or 0.0) > 1.0:
755
- report["qty_break_only"] += 1
756
- cells[col] = base.get('fixed_price')
757
- if cells:
758
- out.setdefault(code, {}).update(cells)
759
- return out, report
760
-
761
-
762
  def active_products(limit=50000):
763
  """`[{id, default_code, product_tmpl_id}]` for every ACTIVE product — read ONCE and shared.
764
 
@@ -781,28 +576,19 @@ def active_products(limit=50000):
781
  def tier_prices_by_code(prods=None):
782
  """`({code: [{pricelist, unit_price, unit}]}, report)` — EVERY live price a SKU really has.
783
 
784
- ⭐⭐ W37-T14 (owner: multiple prices per SKU). `pricelist_by_code` above answers a DIFFERENT
785
- question and both are needed: it resolves a base price for all three DECLARED lists
786
- (`price_fisch`, `price_royal_1`, `price_royal_2`) and therefore cannot show a price on a list
787
- the contract does not name.
788
-
789
- ⚠ ONLY ONE OF THOSE THREE IS STILL A GRID COLUMN. W42-T56 / R26 took `price_royal_1` and
790
- `price_royal_2` off the product grid — the per-list tier block supersedes them — so
791
- `pricelist_by_code` still RESOLVES all three (the key is its pricelist identity, and
792
- `PRICELIST_TIER_COLUMNS` is derived from those very names) while only
793
- `PRICELIST_GRID_COLUMNS` is written into a cell. Two hats; see that constant. This
794
- one is the honest set — one entry per PRICE RULE that actually prices this SKU today. One
795
- pricelist can carry Pack, Sleeve and Master rows for the same SKU; collapsing those rows to
796
- a single base price loses the unit-specific prices the catalogue needs to show.
797
 
798
- ⛔ IT READS EVERY LIVE PRICELIST, not `PRICELIST_COLUMNS`. Hardcoding this tenant's three list
799
- names into "how many prices does a SKU have" is exactly what the ticket forbids, and it is what
800
- would make the answer wrong for tenant #1 on the day they are onboarded.
801
 
802
  ⛔ ROWS ARE TEMPLATE-SCOPED (`proto/P2-pricing-uom.md`): joining on `product_id` drops 99.9% of
803
  price rows, because `applied_on` is `1_product` on 10,454 of 10,468 items and `1_product` means
804
  the TEMPLATE. A variant rule (`0_product_variant`, 13 rows) is the more specific statement and
805
- wins, matching `pricecomp._tier_for` and `pricelist_by_code`.
806
 
807
  ⛔ FILTER BY `pricelist_id`, NEVER BY `active`: the default `product.pricelist.item` count hides
808
  2,580 archived items, so an `active` filter reads as a smaller, plausible, wrong set.
 
405
  def discontinued_tag_id():
406
  """The `product.tag` id for `DISCONTINUED_TAG`, or `None` if the tag is not there.
407
 
408
+ ⚠ RESOLVED BY NAME, NOT BY ID, for the same reason as the per-list tier metadata: an id hard-coded here
409
  keeps pointing at whatever inherits it if the tag is deleted and re-made, and every product
410
  would be silently mislabelled. A missing tag yields `None`, which marks the whole catalogue
411
  `No` — so `validate()` reconciles the count against Odoo rather than trusting this, and goes
 
462
  'units_on_archived_products': round(off_catalogue, 1)}
463
 
464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
  #: ⭐⭐ W40-T09 / RULING R6 (owner I25: *"Fisch price and Royal price each have 3 units and 3
466
  #: prices. Separate them and put all of them in the Odoo fields."*) — HOW MANY (price, unit)
467
  #: PAIRS EACH DECLARED LIST SHOWS.
 
475
  #: observed per list: Fisch 4, Royal 1 3, Royal 2 3, Public Pricelist 1.
476
  PRICELIST_TIER_DEPTH = 3
477
 
478
+ #: W43-T01 / R17 — the three lists are metadata for the numbered tier contract ONLY. Keeping
479
+ #: this distinct from the retired base-price reader prevents a future base field from being
480
+ #: recreated merely because tier cells still need their list names.
481
+ PRICELIST_TIER_LISTS = ("Fisch", "Royal 1", "Royal 2")
482
 
 
 
483
 
484
+ def _pricelist_slug(name):
485
+ """`Royal 1` -> `royal1`, the stable token used by a numbered tier key."""
486
+ return "".join(ch.lower() for ch in str(name) if ch.isalnum())
 
 
 
487
 
488
 
489
  #: `[(price_key, unit_key, pricelist_name, tier_no)]` — the 18 columns R6 declares, DERIVED from
490
+ #: `PRICELIST_TIER_LISTS` so tier-list metadata lives in exactly one place. A fourth pricelist
491
+ #: added above becomes six more tier columns here with no base-price field or reader.
492
  PRICELIST_TIER_COLUMNS = tuple(
493
+ (f"price_{_pricelist_slug(name)}_t{n}", f"unit_{_pricelist_slug(name)}_t{n}", name, n)
494
+ for name in PRICELIST_TIER_LISTS
495
  for n in range(1, PRICELIST_TIER_DEPTH + 1)
496
  )
497
 
 
517
  cells. Sorting the group is one line and makes the guarantee local to the function that
518
  makes it. The tiebreak matches the reader's: unit name, then list name.
519
 
520
+ ⚠ A LIST NOT IN `PRICELIST_TIER_LISTS` IS INVISIBLE HERE BY DESIGN — the columns are named
521
  after the three lists the contract declares. MEASURED: 3 active SKUs are priced ONLY on
522
  Public Pricelist, so they carry all eighteen cells empty. `tier_prices_by_code` still sees
523
  those prices; nothing is lost from the honest set, only from these named columns.
 
554
  if name in declared and n > PRICELIST_TIER_DEPTH}
555
 
556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557
  def active_products(limit=50000):
558
  """`[{id, default_code, product_tmpl_id}]` for every ACTIVE product — read ONCE and shared.
559
 
 
576
  def tier_prices_by_code(prods=None):
577
  """`({code: [{pricelist, unit_price, unit}]}, report)` — EVERY live price a SKU really has.
578
 
579
+ ⭐⭐ W37-T14 (owner: multiple prices per SKU). This is the honest set — one entry per PRICE
580
+ RULE that actually prices this SKU today. One pricelist can carry Pack, Sleeve and Master
581
+ rows for the same SKU; collapsing those rows loses the unit-specific prices the catalogue
582
+ needs to show.
 
 
 
 
 
 
 
 
 
583
 
584
+ ⛔ IT READS EVERY LIVE PRICELIST. `per_list_tier_cells` later selects the three list names the
585
+ product contract declares; that selection must never narrow this source reader, or a future
586
+ tenant's additional list will quietly disappear from the honest price set.
587
 
588
  ⛔ ROWS ARE TEMPLATE-SCOPED (`proto/P2-pricing-uom.md`): joining on `product_id` drops 99.9% of
589
  price rows, because `applied_on` is `1_product` on 10,454 of 10,468 items and `1_product` means
590
  the TEMPLATE. A variant rule (`0_product_variant`, 13 rows) is the more specific statement and
591
+ wins, matching `pricecomp._tier_for`.
592
 
593
  ⛔ FILTER BY `pricelist_id`, NEVER BY `active`: the default `product.pricelist.item` count hides
594
  2,580 archived items, so an `active` filter reads as a smaller, plausible, wrong set.
web/src/customer-grid/ColumnMenu.tsx CHANGED
@@ -6,7 +6,7 @@ import { FieldAgentChat } from "./FieldAgentChat";
6
  import type { FieldProposal } from "./fieldAgent";
7
  import { AnchoredOverlay } from "./OverlaySurface";
8
  import type { AnchorRect } from "./OverlaySurface";
9
- import { FieldTypeIcon, InfoMark, MenuLabel } from "./icons";
10
  import { FieldSelectButton } from "./FieldSelect";
11
  // ⭐⭐ W40-T24 — the pre-set definition lock. It lives in `display.ts` rather than here because a
12
  // rule stated inside JSX cannot be LOADED by a node gate; `display.ts`'s header carries the full
@@ -18,18 +18,14 @@ import { columnDefinitionOffer } from "./display";
18
  // that must be runnable rather than read back to itself as source text.
19
  import { CODE_LANGUAGE_LABELS, CODE_LANGUAGES, CREATABLE_TYPES, choiceOptions, choiceRenames,
20
  codeLanguageOf, directionLabel, groupTypePickerRows, isDerivedLink, isMachineOwned,
21
- isProfileField, offerableCreateKind, parseOptions, ratingMax, ROLLUP_FN_LABELS, ROLLUP_FNS,
22
- ROLLUP_PRESET_FNS, ROLLUP_PRESETS, ROLLUP_REF_OPS, rollupPresetOf, TYPE_DESCRIPTIONS,
23
- mayEditFieldDefinition } from "./types";
24
- import { ROUTE_PROJECTION_KEY, ROUTE_SORT_REFUSAL_TEXT, filterTreeConj, filterTreeNodes,
25
- offerableFields } from "./types";
26
- import type { AggName, Conjunction, Field, FieldFormat, FieldScope, FieldType, FilterNode,
27
- Measure, RollupCondition, RollupFn, RollupPreset,
28
  RollupRefOp, RollupSource, Viewer } from "./types";
29
  import type { LinkTarget, RollupSourceOffer } from "./apiBridge";
30
  import type { WindowSpec } from "./windows";
31
  import { normalizeWindow, windowLabel } from "./windows";
32
- import { FilterBuilderPanel, WindowPicker } from "../filter-kit";
33
  // ⭐⭐ W41-T29 (R6, contract C2) — the ONE pair of rights predicates plus the copy that says what
34
  // they refused, read from the same module the Fields manager reads. C2: no surface re-implements
35
  // either test, so this menu asks rather than deriving a second answer of its own.
@@ -104,15 +100,7 @@ interface FieldConfigExtra {
104
  geocode?: { addressField: string; country?: string };
105
  /** ⭐ 2026-08-07 — a `link` column's target. REQUIRED for the type: `_clean_field` returns
106
  * None for a link with no bag, so a create without this is a column that never appears. */
107
- /** ⭐⭐ W42-T08 (R1, C1) — plus, OPTIONALLY, the two-hop `via`. Absent is today's one-hop
108
- * join, byte-identical to what this menu emitted before the hop existed. */
109
- link?: {
110
- table: string;
111
- single?: boolean;
112
- via?: HopViaBag;
113
- conditions?: RollupCondition[];
114
- conditionConj?: "and" | "or";
115
- };
116
  /** ⭐ 2026-08-07 — a `rollup` column's aggregate. Same requirement, same reason.
117
  * ⭐ 2026-08-09 — or, INSTEAD, a `source` binding: the read-through kind, which summarises
118
  * rows that were never copied into the workspace. The host's `_clean_rollup` reads `source`
@@ -174,28 +162,6 @@ interface ColumnMenuProps {
174
  * as it was before this existed. So this prop is what turns the second kind ON, not a flag.
175
  */
176
  rollupSourceOffer?: RollupSourceOffer;
177
- /**
178
- * ⭐⭐ W42-T08 (R1, contract C2) — the topics a Link field's HOP may travel through, each
179
- * carrying its dims already shaped as `Field[]` so the existing condition builder can take
180
- * them as its `fields` prop with no adapter in between. Fetched by the host from
181
- * `GET /grid/hop-topics`.
182
- *
183
- * ⚠ EMPTY RENDERS THE QUESTION AND SAYS SO rather than hiding it. An unwired surface that
184
- * simply vanishes is indistinguishable from a feature that was never built, and this file's
185
- * fence could not make the prop required at this boundary. W42-T09 wires it.
186
- */
187
- hopTopics?: HopTopic[];
188
- /**
189
- * ⭐⭐ W42-T08 (contract C1 `scope_key`) — the cohort scope of THIS database: `customer`,
190
- * `product`, or a `ut_*` key. `CustomerGrid` already holds it as `scope` at this mount.
191
- *
192
- * ⛔ IT IS NOT `tableKey`. That prop is `payload.workspace.storageKey`
193
- * (`product_table_workspace` for a registry topic), and deriving one from the other by
194
- * stripping a suffix is the near-miss class this menu already carries a warning about. Absent
195
- * means no `via` may be emitted at all, because a bag missing `scope_key` loses every cohort
196
- * leaf without a word.
197
- */
198
- hopScopeKey?: string;
199
  locked: boolean;
200
  /** Product-owned preset fields may still drive view actions, but their schema is immutable. */
201
  schemaLocked?: boolean;
@@ -221,6 +187,9 @@ interface ColumnMenuProps {
221
  onClose: () => void;
222
  onNote: (note: string) => void;
223
  onHide: () => void;
 
 
 
224
  onCreate: (
225
  label: string,
226
  type: FieldType,
@@ -330,10 +299,11 @@ interface ColumnMenuProps {
330
  * DIFFERENT ACT from `onDelete`, and therefore a different door: it destroys no definition and
331
  * no values, and pointing "Remove from my fields" at the delete handler would be a benign word
332
  * on a destructive action.
333
- * The grid's dedicated `DELETE /share/field/{oid}/mine` door removes only the current direct
334
- * grantee, so both mounted menus can call a real, non-destructive action.
 
335
  */
336
- onRemoveFromMine: () => void;
337
  /** ⭐⭐ Wave-34 (R13) — run this AI enrichment column over many rows.
338
  * `scope` is `"blank"` (only cells still empty) or `"always"` (every row the AI
339
  * wrote). OPTIONAL for `onDelete`'s reason: a host that has not wired the door shows
@@ -713,15 +683,11 @@ function optionDrafts(
713
  function optionSettings(
714
  drafts: OptionDraft[],
715
  type: CreateKind
716
- ): { options: string[]; colors: Record<string, string>; capMessage: string | null } {
717
  const clean = drafts.map((draft) =>
718
  type === "multiselect" ? draft.label.replace(/,/g, " ") : draft.label
719
  );
720
- // ⭐⭐ W42-T37 (C8b) — THE CAP TRAVELS WITH THE LIST. `parseOptions` no longer slices the tail
721
- // off in silence, so its refusal has to reach both save doors and the pane that shows it; a
722
- // caller that took only `.options` would put the silence back here instead.
723
- const parsed = parseOptions(clean.join("\n"));
724
- const options = parsed.options;
725
  const firstByLabel = new Map<string, OptionDraft>();
726
  drafts.forEach((draft, index) => {
727
  const label = clean[index].trim();
@@ -737,7 +703,7 @@ function optionSettings(
737
  if (color && color !== normalizeOptionColor(defaultOptionColor(option)))
738
  colors[option] = color;
739
  }
740
- return { options, colors, capMessage: parsed.message };
741
  }
742
 
743
  function optionAppearanceSignature(
@@ -947,15 +913,6 @@ function OptionsEditor({
947
  {settings.options.length} option{settings.options.length === 1 ? "" : "s"}.
948
  {type === "multiselect" && " Commas inside an option are not supported."}
949
  </span>
950
- {/* ⭐⭐ W42-T37 (C8b) — THE CAP, SAID OUT LOUD, ON THE ONE PANE EVERY OPTION LIST MOUNTS.
951
- Standing rule 1's second half: the limit is reported with its cause and what to do,
952
- never applied behind the person's back. The save doors refuse alongside this, so the
953
- sentence explains a Create button that has stopped working rather than replacing it. */}
954
- {settings.capMessage ? (
955
- <span className="cg-field-hint" role="alert">
956
- {settings.capMessage}
957
- </span>
958
- ) : null}
959
  </div>
960
  );
961
  }
@@ -968,20 +925,6 @@ function OptionsEditor({
968
  */
969
  type CreateKind = FieldType | "measure" | "geocode";
970
 
971
- /**
972
- * ⭐⭐ W42-T37 (G3) — WHAT THE PICKER CAN OFFER, which is one row wider than what the create pane
973
- * can BUILD. A preset is a starting point for a `rollup`, not a kind: pick "Count" and `kind`
974
- * becomes `"rollup"` with its fold already chosen, so nothing downstream of the pick ever sees
975
- * either name. That is why this union stops at the picker and `CreateKind` is untouched: widening
976
- * `CreateKind` would push two words that are not types into every switch that renders a cell,
977
- * which is the failure `CreateKind`'s own comment describes for `measure`.
978
- */
979
- type PickerKind = CreateKind | RollupPreset;
980
-
981
- /** The two presets' rows. The nouns Airtable uses, because they are the words somebody migrating
982
- * types into the find box; the description under each says it is a rollup. */
983
- const PRESET_LABELS: Record<RollupPreset, string> = { count: "Count", lookup: "Lookup" };
984
-
985
  /**
986
  * ⭐⭐ W37-T22 (R4 / C7) — the geocode pseudo-kind's picker label, and the address-column families
987
  * it may read. Declared here beside `CreateKind` because three places consume them (the picker
@@ -1016,12 +959,10 @@ function TypePicker({
1016
  onPick,
1017
  offerMeasure,
1018
  offerGeocode,
1019
- offerPresets,
1020
- isUserTable,
1021
  only,
1022
  }: {
1023
- value: PickerKind;
1024
- onPick: (k: PickerKind) => void;
1025
  offerMeasure: boolean;
1026
  /**
1027
  * ⭐⭐ W37-T22 (R4 / C7) — offer the geocode pseudo-kind. REQUIRED, not optional: an optional
@@ -1039,47 +980,17 @@ function TypePicker({
1039
  * "has an address column", which is what W37-T22's `done-when` asks for.
1040
  */
1041
  offerGeocode: boolean;
1042
- /**
1043
- * ⭐⭐ W42-T37 (G3) — offer the Count and Lookup PRESETS. REQUIRED for `offerGeocode`'s exact
1044
- * reason, and false on the retype picker on purpose: a preset AUTHORS a rollup bag, and the
1045
- * retype pane changes a column's type without authoring anything (its own comment books that
1046
- * gap for the geocode row already).
1047
- */
1048
- offerPresets: boolean;
1049
- /**
1050
- * ⭐⭐ W42-T37 (D-497) — this grid is a `ut_*` runtime database, so the picker withholds the
1051
- * kinds `user_tables._clean_field` refuses. REQUIRED, not optional, for the third time in this
1052
- * signature: an optional flag defaults to "Odoo grid" at whichever mount forgets it, and the
1053
- * defect being fixed IS a menu offering a kind the server returns `None` for.
1054
- */
1055
- isUserTable: boolean;
1056
  /** Restrict the list (the Edit-field pane passes RETYPE_TYPES — the overlay-editable
1057
  * strata a created field may become). Absent = every creatable type. */
1058
  only?: readonly FieldType[];
1059
  }) {
1060
  const [q, setQ] = useState("");
1061
  const needle = q.trim().toLowerCase();
1062
- // ⭐⭐ W42-T37 (D-497) — THE WITHHOLDING HAPPENS HERE, ONCE, OVER THE WHOLE VOCABULARY, and it
1063
- // is a `types.ts` predicate rather than a `type !== "created_time"` written into this JSX: a
1064
- // rule stated inside a React file is a rule no node gate can run, and this one answers to the
1065
- // server's own `UT_FIELD_TYPES` through `verify_rollup_editor.py`.
1066
- const offerable = only
1067
  ? FIELD_TYPES.filter((r) => (only as readonly string[]).includes(r.value))
1068
  : FIELD_TYPES;
1069
- const base = offerable.filter((r) => offerableCreateKind(r.value, isUserTable));
1070
- const rows: { value: PickerKind; label: string }[] = [
1071
  ...base,
1072
- // ⭐⭐ W42-T37 (G3) — COUNT AND LOOKUP, the two rollups people arrive looking for by name.
1073
- // They are PRESETS: picking one selects the rollup kind and fixes its fold, so the editor
1074
- // below can ask only what is left. No new member of any type vocabulary (contract C8), and
1075
- // they sit in the ORDINARY group deliberately, which is the entire point of adding them: the
1076
- // rollup they are made of has just moved under Advanced.
1077
- ...(offerPresets
1078
- ? ROLLUP_PRESETS.map((preset) => ({
1079
- value: preset as PickerKind,
1080
- label: PRESET_LABELS[preset],
1081
- }))
1082
- : []),
1083
  // C-NAME (item 9, 2026-08-02): "Formula measure (over a period)" -> "Metric". Two words
1084
  // of jargon and a parenthetical, replaced by the word people already use for the thing.
1085
  // The internal key stays `measure` — see the C-NAME amendment in the wave doc.
@@ -1143,55 +1054,19 @@ function TypePicker({
1143
  type="button"
1144
  role="option"
1145
  aria-selected={value === r.value}
1146
- aria-label={r.label}
1147
- aria-describedby={`cg-type-description-${r.value}`}
1148
  className={"cg-type-row" + (value === r.value ? " is-on" : "")}
1149
  onClick={() => onPick(r.value)}
1150
  >
1151
  {/* Each row wears the mark its COLUMN will wear. A measure column's real type is
1152
  currency/int/pct and a geocode column's is `text`, so both pseudo-kinds borrow
1153
- rather than inventing a glyph no column ever shows (the iconShapes ruling).
1154
- ⭐ W42-T37: a Count or Lookup column's real type IS `rollup`, so the presets
1155
- borrow that mark for the same reason rather than earning a glyph of their own. */}
1156
  <FieldTypeIcon
1157
  type={
1158
- r.value === "measure" ? "currency" : r.value === "geocode" ? "text"
1159
- : r.value === "count" || r.value === "lookup" ? "rollup" : r.value
1160
  }
1161
  size={16}
1162
  />
1163
- {/* The type name is all this dense picker needs to scan. R24's load-bearing
1164
- explanation lives on the compact (i): native title makes it discoverable on
1165
- hover, while aria-describedby keeps it attached to the focused option. */}
1166
  <span className="cg-type-label">{r.label}</span>
1167
- <span
1168
- className="cg-type-info"
1169
- title={TYPE_DESCRIPTIONS[r.value]}
1170
- aria-hidden="true"
1171
- >
1172
- <InfoMark />
1173
- </span>
1174
- <span id={`cg-type-description-${r.value}`} className="cg-sr-only">
1175
- {TYPE_DESCRIPTIONS[r.value]}
1176
- </span>
1177
- {value === r.value && (
1178
- <svg
1179
- className="cg-type-check"
1180
- width="14"
1181
- height="14"
1182
- viewBox="0 0 16 16"
1183
- fill="none"
1184
- aria-hidden="true"
1185
- >
1186
- <path
1187
- d="m3.5 8.5 3 3 6-6.5"
1188
- stroke="currentColor"
1189
- strokeWidth="1.6"
1190
- strokeLinecap="round"
1191
- strokeLinejoin="round"
1192
- />
1193
- </svg>
1194
- )}
1195
  </button>
1196
  ))}
1197
  </Fragment>
@@ -1344,182 +1219,6 @@ const AI_ENRICH_OVERWRITE: ReadonlyArray<{ value: string; label: string }> = [
1344
  { value: "always", label: "Every row the AI wrote, every run" },
1345
  ];
1346
 
1347
- // ─────────────────────────────────────────────────────────────────────────────────────────────
1348
- // W42-T08 (ruling R1, contracts C1 + C2) — THE HOP.
1349
- //
1350
- // A user-created Link field may take TWO HOPS: instead of the user picking rows by hand, the
1351
- // column reaches the other database THROUGH a governed topic (the order lines that connect a
1352
- // customer to a product). The user declares that middle step here, at field-creation time, with
1353
- // the same condition builder every other filter on the product is authored in.
1354
- //
1355
- // ⛔ THE BAG'S KEY NAMES ARE C1, NOT A CHOICE. `aios-web/api/verify_pivot.py` asserts that the
1356
- // key set the server accepts and the key set THIS FILE emits are identical name-for-name, so
1357
- // `source_dim` is snake_case because the server spells it that way and `filterConj` is camelCase
1358
- // for the same reason. Rename one half and the join stops resolving with no error anywhere.
1359
- //
1360
- // ⛔ `target_key` AND `scope_key` ARE NOT DIM NAMES, and this is the trap the ideation record
1361
- // walked into. `target_key` is a column of the TARGET DATABASE (the value its rows join on) and
1362
- // `scope_key` is the cohort scope of the database the column is being created ON. Drop
1363
- // `target_key` and the server matches nothing and still answers 200 with an empty row list: no
1364
- // refusal, no error, a column of blanks. So both are required before a `via` is emitted at all.
1365
- //
1366
- // ⛔ `source_key` IS DELIBERATELY ABSENT (C1). It is the seventh key of the route table this
1367
- // ruling dissolves, and it does not travel onto `via`.
1368
- // ─────────────────────────────────────────────────────────────────────────────────────────────
1369
-
1370
- /**
1371
- * C2 — one topic as the hop question offers it.
1372
- *
1373
- * ⚠ `dims` IS A `Field[]`, NOT the `{key,label,keyedBy}` shape `apiBridge.RollupSourceTopic.dims`
1374
- * carries. `FilterBuilderPanel` fetches nothing and takes its whole vocabulary as a `fields`
1375
- * prop, so a topic whose dims already ARE fields can be filtered by the existing control with no
1376
- * adapter in between. That is the entire reason `GET /grid/hop-topics` exists beside
1377
- * `/tables/rollup-sources`, and deriving a `type` from `keyedBy` here instead would produce a
1378
- * plausible operand list with the wrong operators, which is worse than none.
1379
- */
1380
- export interface HopTopic {
1381
- key: string;
1382
- label: string;
1383
- dims: Field[];
1384
- measures: { key: string; label: string }[];
1385
- }
1386
-
1387
- /**
1388
- * C1's `via`, ON THE WIRE — nine keys, and the parity gate reads THIS declaration as the client's
1389
- * emitted key set. `source_dim` is snake_case and `filterConj` is camelCase because the server
1390
- * spells them that way; do not tidy either.
1391
- */
1392
- export interface HopViaBag {
1393
- topic: string;
1394
- source_dim: string;
1395
- target_dim: string;
1396
- target_key: string;
1397
- scope_key: string;
1398
- measure: string;
1399
- filter: FilterNode[];
1400
- filterConj: Conjunction;
1401
- window: string;
1402
- }
1403
-
1404
- /** The hop as the editor holds it while it is being authored. `topic: ""` means NO hop. */
1405
- export interface HopDraft {
1406
- topic: string;
1407
- sourceDim: string;
1408
- targetDim: string;
1409
- targetKey: string;
1410
- measure: string;
1411
- filter: FilterNode[];
1412
- filterConj: Conjunction;
1413
- window: string;
1414
- /**
1415
- * ⛔⛔ THE STORED `scope_key`, CARRIED RATHER THAN RE-DERIVED, and it is a scar not a style.
1416
- *
1417
- * The relational save is a REBUILD, and `hopVia` refuses to emit a bag with no scope. Derive
1418
- * the scope from the HOST prop alone and a field with a saved hop, opened on any surface that
1419
- * does not pass that prop, re-emits its link bag WITHOUT the hop: one rename click silently
1420
- * deletes a configured join. So a bag that already carries its scope keeps it, and the host's
1421
- * prop answers only for a hop being authored for the first time.
1422
- */
1423
- scopeKey: string;
1424
- }
1425
-
1426
- /** ⚠ A FRESH OBJECT PER CALL. `filter` is an array and a shared literal would let one draft's
1427
- * conditions surface in the next field the user creates. */
1428
- /**
1429
- * ⛔ THE NO-WINDOW KEY IS `all_time`, NOT `all`. `core.user_tables.ROLLUP_SOURCE_WINDOWS` is the
1430
- * validator's closed set and it spells the whole-history window `all_time`; it is also what
1431
- * `GET /tables/rollup-sources` offers, so a draft defaulted to anything outside that list would
1432
- * give a `<select>` whose value matches no option, which renders the FIRST option instead with no
1433
- * warning. The control would then read "Year to date" while the bag saved something else.
1434
- * ⚠ C1's example writes `"window": "all"`; that spelling is not in any live vocabulary and is
1435
- * reported in this ticket's handoff for the lane that owns the server half.
1436
- */
1437
- export const HOP_WINDOW_ALL = "all_time";
1438
-
1439
- export const emptyHopDraft = (): HopDraft => ({
1440
- topic: "", sourceDim: "", targetDim: "", targetKey: "",
1441
- measure: "", filter: [], filterConj: "and", window: HOP_WINDOW_ALL, scopeKey: "",
1442
- });
1443
-
1444
- /** What one mount of the hop question needs. `null` at a mount that cannot save a hop. */
1445
- export interface HopOffer {
1446
- topics: HopTopic[];
1447
- /** The window vocabulary of the topic being travelled through. */
1448
- windows: { key: string; label: string }[];
1449
- /** C1 `scope_key` — the cohort scope of the database this column is being created on. It is a
1450
- * fact about the HOST grid, never a question for the user, so it arrives rather than being
1451
- * picked. Empty means the host could not name it, and then no `via` may be emitted. */
1452
- scopeKey: string;
1453
- draft: HopDraft;
1454
- onDraft: (patch: Partial<HopDraft>) => void;
1455
- }
1456
-
1457
- /**
1458
- * C1's `via`, or `null` when the hop is blank OR half-declared.
1459
- *
1460
- * ⛔ HALF-DECLARED EMITS NOTHING, and the caller's Create door refuses instead. `_clean_link`
1461
- * refuses the WHOLE field on a bad `via`, so shipping an incomplete one produces a column that
1462
- * is named, configured and simply absent on the next read.
1463
- */
1464
- export function hopVia(
1465
- draft: HopDraft | null | undefined,
1466
- scopeKey: string
1467
- ): HopViaBag | null {
1468
- if (!draft) return null;
1469
- const topic = draft.topic.trim();
1470
- const sourceDim = draft.sourceDim.trim();
1471
- const targetDim = draft.targetDim.trim();
1472
- const targetKey = draft.targetKey.trim();
1473
- const measure = draft.measure.trim();
1474
- // ⛔ THE BAG'S OWN SCOPE WINS. See `HopDraft.scopeKey`: a stored hop must survive a rebuild on a
1475
- // surface that does not pass the host prop, and the prop answers only for a NEW hop.
1476
- const scope = (draft.scopeKey || scopeKey || "").trim();
1477
- if (!topic || !sourceDim || !targetDim || !targetKey || !measure || !scope) return null;
1478
- // Exactly C1's nine keys, in C1's spelling, and nothing else.
1479
- return {
1480
- topic,
1481
- source_dim: sourceDim,
1482
- target_dim: targetDim,
1483
- target_key: targetKey,
1484
- scope_key: scope,
1485
- measure,
1486
- filter: draft.filter,
1487
- filterConj: draft.filterConj,
1488
- window: draft.window || HOP_WINDOW_ALL,
1489
- };
1490
- }
1491
-
1492
- /** True when the user has begun a hop but has not finished it. The Create/Save door reads this. */
1493
- export const hopIncomplete = (draft: HopDraft | null | undefined, scopeKey: string): boolean =>
1494
- !!draft && draft.topic.trim() !== "" && hopVia(draft, scopeKey) === null;
1495
-
1496
- /**
1497
- * Seed a draft from a STORED bag.
1498
- *
1499
- * ⚠ THE CAST IS DELIBERATE AND IT IS OWED. `types.ts::Field.link` does not declare `via` yet;
1500
- * that file belongs to W42-T09 / W42-T37 in this lane, and this ticket's fence is two files.
1501
- * Reading the key through a narrow local shape is what lets the EDIT pane round-trip an existing
1502
- * hop instead of rebuilding the bag without it, which would silently delete a saved hop on the
1503
- * next rename. See the HANDOFF's PENDING line.
1504
- */
1505
- export function hopDraftFrom(link: unknown): HopDraft {
1506
- const via = (link as { via?: Record<string, unknown> } | null | undefined)?.via;
1507
- const draft = emptyHopDraft();
1508
- if (!via || typeof via !== "object") return draft;
1509
- const str = (v: unknown) => (typeof v === "string" ? v : "");
1510
- return {
1511
- topic: str(via.topic),
1512
- sourceDim: str(via.source_dim),
1513
- targetDim: str(via.target_dim),
1514
- targetKey: str(via.target_key),
1515
- measure: str(via.measure),
1516
- filter: Array.isArray(via.filter) ? (via.filter as FilterNode[]) : [],
1517
- filterConj: via.filterConj === "or" ? "or" : "and",
1518
- window: str(via.window) || HOP_WINDOW_ALL,
1519
- scopeKey: str(via.scope_key),
1520
- };
1521
- }
1522
-
1523
  function ExtraTypeEditor({
1524
  kind,
1525
  fields,
@@ -1543,12 +1242,6 @@ function ExtraTypeEditor({
1543
  onLinkTable,
1544
  linkSingle = false,
1545
  onLinkSingle,
1546
- linkConditions = [],
1547
- onLinkConditions,
1548
- linkConditionConj = "and",
1549
- onLinkConditionConj,
1550
- hop,
1551
- rollupPreset = null,
1552
  rollupMode = "link",
1553
  onRollupMode,
1554
  rollupSourceOffer = { topics: [], windows: [] },
@@ -1615,35 +1308,6 @@ function ExtraTypeEditor({
1615
  onLinkTable?: (v: string) => void;
1616
  linkSingle?: boolean;
1617
  onLinkSingle?: (v: boolean) => void;
1618
- linkConditions?: RollupCondition[];
1619
- onLinkConditions?: (v: RollupCondition[]) => void;
1620
- linkConditionConj?: "and" | "or";
1621
- onLinkConditionConj?: (v: "and" | "or") => void;
1622
- /**
1623
- * ⭐⭐ W42-T08 (R1, C1 + C2) — the HOP question, and it is REQUIRED at every mount on purpose.
1624
- *
1625
- * ⛔ OPTIONAL WOULD BE THE SAFE-LOOKING WRONG CHOICE (PRD "cross-feature wirings"): an omitted
1626
- * optional prop degrades to "the feature does not exist", which is indistinguishable from never
1627
- * built. Required makes `tsc` name every mount the day this lands.
1628
- *
1629
- * ⛔ `null` IS A STATEMENT, NOT AN OMISSION — "this mount cannot save a hop, so do not paint
1630
- * one". The automation, formula and swap mounts pass it: the swap form supplies no link
1631
- * plumbing at all, so a hop authored there would configure nothing, which this file's own
1632
- * rules call worse than no control.
1633
- */
1634
- hop: HopOffer | null;
1635
- /**
1636
- * ⭐⭐ W42-T37 (G3) — this rollup is a Count or a Lookup, so the editor asks ONLY what that
1637
- * preset still needs: the link column, plus the column to look up. The fold is already decided,
1638
- * and a "Fold" select showing one answer nobody may change is a control that configures
1639
- * nothing.
1640
- *
1641
- * ⚠ THE EDIT PANE PASSES IT TOO, computed from the STORED bag by `types.ts::rollupPresetOf` —
1642
- * that is what makes a Count re-open as a Count rather than as a rollup folded by "Count of
1643
- * records". `rollupPresetOf` is exact, so a bag carrying anything beyond the preset's own keys
1644
- * answers `null` and opens in the full editor with every value it holds visible.
1645
- */
1646
- rollupPreset?: RollupPreset | null;
1647
  /** ⭐ 2026-08-09 — which KIND of rollup is being built. `"link"` folds workspace rows;
1648
  * `"source"` reads through to a governed Odoo topic without copying a row into the store. */
1649
  rollupMode?: "link" | "source";
@@ -1677,11 +1341,7 @@ function ExtraTypeEditor({
1677
  if (kind === "formula") {
1678
  // 2026-07-31 (owner item 2): other FORMULA fields are referencable now — evaluation is
1679
  // topological and a cycle is refused at validation, so the old exclusion is gone.
1680
- // C11 (W42-T54) — a formula's reference picker is a field picker, so it offers the
1681
- // OFFERABLE columns. ⚠ The formula VALIDATION sets (`known` below, `knownKeys` further
1682
- // down) are deliberately NOT narrowed: they answer "does this column exist", and a
1683
- // formula already stored against a route column would start reporting an unknown field.
1684
- const referencable = offerableFields(fields).filter((f) => f.key !== "__proto__");
1685
  return (
1686
  <>
1687
  <label>
@@ -1938,10 +1598,7 @@ function ExtraTypeEditor({
1938
  // thing it reads. The schedule and the Run-now button are NOT here — they belong to the
1939
  // automation itself, on the Automation surface, because one job can fill a column across
1940
  // many records and its cadence is a property of the job, not of the column.
1941
- // C11 — a picker. Type-narrowed already, so today it can only have held the route
1942
- // PROJECTION column (text), which passes through by contract; filtered anyway so the
1943
- // rule does not depend on a route position staying numeric.
1944
- const urlish = offerableFields(fields).filter((f) => f.type === "url" || f.type === "text");
1945
  const chosen = AUTOMATION_KINDS.find((k) => k.key === automationKind)
1946
  ?? AUTOMATION_KINDS[0];
1947
  return (
@@ -1999,16 +1656,6 @@ function ExtraTypeEditor({
1999
  if (kind === "link") {
2000
  // ⭐ 2026-08-07 — Airtable's "Link to another record", and the whole editor is ONE question:
2001
  // which database. The relation itself is then the cell (a set of linked rows).
2002
- //
2003
- // ⭐⭐ W42-T08 (R1) — plus ONE added question, and the panel now reads as the sentence it
2004
- // always was: which database, then through what, then filtered how. It sits INLINE under the
2005
- // settings it belongs to, which is where the reference art puts a link field's own condition
2006
- // block; a wizard or a second modal is forbidden by this wave's design contract.
2007
- const hopTarget = linkTargets.find((t) => t.key === linkTable);
2008
- const hopTargetFields = hopTarget?.fields ?? [];
2009
- const hopTopic = hop?.topics.find((t) => t.key === hop.draft.topic);
2010
- const hopWindow = hop?.draft.window || HOP_WINDOW_ALL;
2011
- const hopWindowOffered = (hop?.windows ?? []).some((w) => w.key === hopWindow);
2012
  return (
2013
  <>
2014
  <label>
@@ -2040,209 +1687,10 @@ function ExtraTypeEditor({
2040
  />
2041
  <span>Allow only one linked record</span>
2042
  </label>
2043
- {linkTable ? (
2044
- <RollupConditionList
2045
- idPrefix={`${idPrefix}-link-condition`}
2046
- title="Offer only"
2047
- hint="Applied when choosing records. Links already saved in this column stay visible."
2048
- conditions={linkConditions}
2049
- onConditions={(value) => onLinkConditions?.(value)}
2050
- conj={linkConditionConj}
2051
- onConj={(value) => onLinkConditionConj?.(value)}
2052
- targetFields={hopTargetFields}
2053
- allowRef={false}
2054
- />
2055
- ) : null}
2056
- {/* ⛔⛔ THIS SENTENCE IS FALSE ONCE A HOP IS SET, so it is not shown then. With a hop the
2057
- cell does not hold "the records you pick": it holds the records the middle step
2058
- resolves, and a panel asserting otherwise beside the control that changed it is the
2059
- surface telling the user something untrue about their own column. It is also a
2060
- TERMINAL summary, and the hop question below has to follow the reading order the
2061
- design contract fixes: which database, then through what, then filtered how.
2062
- ⚠ NOTHING REPLACES IT. The hop's own controls already say what the column does; a
2063
- second paragraph here would be the app narrating itself (DESIGN.md §4). */}
2064
- {hop?.draft.topic ? null : (
2065
- <div className="cg-field-hint">
2066
- A cell here holds the records you pick. Add a Rollup column afterwards to summarise a
2067
- column of those records — an average, a total, a count.
2068
- </div>
2069
- )}
2070
- {hop ? (
2071
- <div className="cg-hop">
2072
- <label className="cg-hop-question">
2073
- <span>Through</span>
2074
- <select
2075
- id={`${idPrefix}-hop-topic`}
2076
- className="cg-input"
2077
- value={hop.draft.topic}
2078
- aria-label="Live data this link travels through"
2079
- onChange={(event) =>
2080
- // ⛔ CLEAR EVERY KEY THAT NAMES SOMETHING OF THE OLD TOPIC. Both dims, the
2081
- // measure and every filter leaf belong TO the topic, so carrying them across a
2082
- // topic change leaves a bag naming dims the new topic does not have, which the
2083
- // save door refuses on a form that looks complete. Same rule the source rollup
2084
- // above follows for its measure and its grouping.
2085
- hop.onDraft({
2086
- topic: event.target.value,
2087
- sourceDim: "", targetDim: "", measure: "", filter: [], filterConj: "and",
2088
- })
2089
- }
2090
- >
2091
- <option value="">Nothing, I will pick the records myself</option>
2092
- {hop.topics.map((t) => (
2093
- <option key={t.key} value={t.key}>{t.label}</option>
2094
- ))}
2095
- </select>
2096
- </label>
2097
- {hop.topics.length === 0 ? (
2098
- <div className="cg-field-hint">
2099
- No live data is offered for this workspace, so there is nothing to travel through.
2100
- </div>
2101
- ) : null}
2102
- {hopTopic ? (
2103
- <div className="cg-hop-body">
2104
- <label>
2105
- <span>Matched from</span>
2106
- <select
2107
- id={`${idPrefix}-hop-source-dim`}
2108
- className="cg-input"
2109
- value={hop.draft.sourceDim}
2110
- aria-label="What names a row of this database"
2111
- onChange={(event) => hop.onDraft({ sourceDim: event.target.value })}
2112
- >
2113
- <option value="">Choose what names a row here…</option>
2114
- {hopTopic.dims.map((d) => (
2115
- <option key={d.key} value={d.key}>{d.label}</option>
2116
- ))}
2117
- </select>
2118
- </label>
2119
- <label>
2120
- <span>Matched to</span>
2121
- <select
2122
- id={`${idPrefix}-hop-target-dim`}
2123
- className="cg-input"
2124
- value={hop.draft.targetDim}
2125
- aria-label="What names a row of the other database"
2126
- onChange={(event) => hop.onDraft({ targetDim: event.target.value })}
2127
- >
2128
- <option value="">Choose what names a row over there…</option>
2129
- {hopTopic.dims.map((d) => (
2130
- <option key={d.key} value={d.key}>{d.label}</option>
2131
- ))}
2132
- </select>
2133
- </label>
2134
- {hopTopic.dims.length === 0 ? (
2135
- <div className="cg-field-hint">
2136
- This data offers nothing to match on, so it cannot be travelled through.
2137
- </div>
2138
- ) : null}
2139
- {/* ⛔ C1 `target_key`, AND IT IS NOT A DIM. It is the column of the OTHER
2140
- database whose value the target dim equals. Leave it out and the server
2141
- matches nothing and still answers 200 with an empty row list: no refusal, no
2142
- error, a column of blanks. So the control is offered, and the Create door
2143
- below refuses without it. */}
2144
- <label>
2145
- <span>Column over there</span>
2146
- <select
2147
- id={`${idPrefix}-hop-target-key`}
2148
- className="cg-input"
2149
- value={hop.draft.targetKey}
2150
- aria-label="Column in the other database holding that value"
2151
- onChange={(event) => hop.onDraft({ targetKey: event.target.value })}
2152
- >
2153
- <option value="">Choose the other database's column…</option>
2154
- {hopTargetFields.map((f) => (
2155
- <option key={f.key} value={f.key}>{f.label}</option>
2156
- ))}
2157
- </select>
2158
- </label>
2159
- {linkTable === "" ? (
2160
- <div className="cg-field-hint">
2161
- Choose a database above first, so its columns can be listed here.
2162
- </div>
2163
- ) : hopTargetFields.length === 0 ? (
2164
- <div className="cg-field-hint">
2165
- The columns of <b>{linkTable}</b> cannot be listed here, so nothing can be
2166
- matched against them. Ask an admin to share that database with you, then
2167
- reopen this editor.
2168
- </div>
2169
- ) : null}
2170
- <label>
2171
- <span>Measure</span>
2172
- <select
2173
- id={`${idPrefix}-hop-measure`}
2174
- className="cg-input"
2175
- value={hop.draft.measure}
2176
- aria-label="Measure"
2177
- onChange={(event) => hop.onDraft({ measure: event.target.value })}
2178
- >
2179
- <option value="">Choose a measure…</option>
2180
- {hopTopic.measures.map((m) => (
2181
- <option key={m.key} value={m.key}>{m.label}</option>
2182
- ))}
2183
- </select>
2184
- </label>
2185
- {hopTopic.measures.length === 0 ? (
2186
- <div className="cg-field-hint">
2187
- This data offers no measure yet, so the hop cannot be completed.
2188
- </div>
2189
- ) : null}
2190
- {/* ⛔⛔ A `<select>` WHOSE VALUE MATCHES NO OPTION RENDERS THE FIRST ONE, SILENTLY.
2191
- A stored bag may carry a window spelling this offer does not list (C1's
2192
- example writes `all`, while the validator's closed set spells it `all_time`),
2193
- and without this row the control would show "Today" while the field saved
2194
- something else: the control and the saved value disagreeing on screen, which
2195
- is the exact class of lie this ticket exists to close. So an unlisted value is
2196
- OFFERED BACK, under its own key, and the user can leave it or replace it. */}
2197
- {hop.windows.length > 0 ? (
2198
- <label>
2199
- <span>Over</span>
2200
- <select
2201
- id={`${idPrefix}-hop-window`}
2202
- className="cg-input"
2203
- value={hopWindow}
2204
- aria-label="Date window"
2205
- onChange={(event) => hop.onDraft({ window: event.target.value })}
2206
- >
2207
- {hopWindowOffered ? null : (
2208
- <option value={hopWindow}>{hopWindow}</option>
2209
- )}
2210
- {hop.windows.map((w) => (
2211
- <option key={w.key} value={w.key}>{w.label}</option>
2212
- ))}
2213
- </select>
2214
- </label>
2215
- ) : null}
2216
- {/* ⭐⭐ C2 — THE FILTER IS THE CONTROL THAT ALREADY EXISTS. `FilterBuilderPanel`
2217
- fetches nothing and already mounts against a foreign field list in two
2218
- permission editors, so the hop reuses it verbatim rather than growing a second
2219
- condition builder.
2220
- ⛔ `fields` AND NOTHING ELSE. `via.filter` is validated server-side against
2221
- the TOPIC's own store columns, so a cohort, view or measure leaf authored here
2222
- would be a condition the server drops without saying so. */}
2223
- <div className="cg-hop-filter">
2224
- <span className="cg-type-title">Keep only</span>
2225
- <FilterBuilderPanel
2226
- fields={hopTopic.dims}
2227
- filters={{ conj: hop.draft.filterConj, nodes: hop.draft.filter }}
2228
- onChange={(next) =>
2229
- hop.onDraft({
2230
- filter: filterTreeNodes(next),
2231
- filterConj: filterTreeConj(next),
2232
- })
2233
- }
2234
- />
2235
- </div>
2236
- {(hop.draft.scopeKey || hop.scopeKey).trim() === "" ? (
2237
- <div className="cg-field-hint">
2238
- This database cannot be named as the starting point of a middle step yet, so
2239
- the hop cannot be saved.
2240
- </div>
2241
- ) : null}
2242
- </div>
2243
- ) : null}
2244
- </div>
2245
- ) : null}
2246
  </>
2247
  );
2248
  }
@@ -2253,10 +1701,7 @@ function ExtraTypeEditor({
2253
  // WHICH column, folded HOW, and across WHICH records. That last control is the owner's
2254
  // headline ("average Views over last N posts") and Airtable cannot express it — its rollup
2255
  // conditions filter by predicate, never by rank.
2256
- // C11 — a picker. `type === "link"` cannot hold a route column today; filtered for the
2257
- // same reason `urlish` is, so offerability is a property of PICKERS here and not a list
2258
- // of the types that happen to collide with routes this wave.
2259
- const linkFields = offerableFields(fields).filter((f) => f.type === "link");
2260
  const chosenLink = linkFields.find((f) => f.key === rollupLink);
2261
  const target = linkTargets.find((t) => t.key === chosenLink?.link?.table);
2262
  const targetFields = target?.fields ?? [];
@@ -2274,9 +1719,7 @@ function ExtraTypeEditor({
2274
  onRollupSource?.({ ...rollupSource, ...patch });
2275
  // ⚠ A join column must hold a SCALAR the group key can equal. Link and rollup columns hold a
2276
  // comma-joined id list and a computed value respectively, so neither can ever match.
2277
- // C11 — a picker, and the widest one in this file: every scalar column. This is the one
2278
- // that would have offered all ~64 route positions as join columns.
2279
- const joinable = offerableFields(fields).filter(
2280
  (f) => f.type !== "link" && f.type !== "rollup" && f.key !== "__proto__"
2281
  );
2282
  const sourceEditor = (
@@ -2389,12 +1832,6 @@ function ExtraTypeEditor({
2389
  );
2390
  const linkEditor = (
2391
  <>
2392
- {/* ⭐⭐ W42-T37 (G3) — A PRESET SAYS WHAT IT IS, IN THE PANE, IN THE SAME WORDS THE PICKER
2393
- USED. It is one rollup among sixteen folds, and a person who chose "Count" should be
2394
- able to see that without being asked to configure it again. */}
2395
- {rollupPreset ? (
2396
- <div className="cg-field-hint">{TYPE_DESCRIPTIONS[rollupPreset]}</div>
2397
- ) : null}
2398
  <label>
2399
  <span>Through</span>
2400
  <select
@@ -2416,10 +1853,6 @@ function ExtraTypeEditor({
2416
  link, so add one of those first.
2417
  </div>
2418
  ) : null}
2419
- {/* ⛔ W42-T37 — THE FOLD IS THE ONE QUESTION A PRESET HAS ALREADY ANSWERED, so the preset
2420
- editor does not ask it. Hidden rather than disabled: a greyed select showing "Count of
2421
- records" invites a click that can never do anything. */}
2422
- {rollupPreset ? null : (
2423
  <label>
2424
  <span>Fold</span>
2425
  <select
@@ -2434,7 +1867,6 @@ function ExtraTypeEditor({
2434
  ))}
2435
  </select>
2436
  </label>
2437
- )}
2438
  {needsField ? (
2439
  <label>
2440
  <span>Column</span>
@@ -2483,14 +1915,6 @@ function ExtraTypeEditor({
2483
  unavailable. Ask an admin to share that database with you, then reopen this editor.
2484
  </div>
2485
  ) : null}
2486
- {/* ⛔⛔ W42-T37 — EVERYTHING BELOW BELONGS TO THE FULL ROLLUP, AND A PRESET RENDERS NONE OF
2487
- IT. The window, the de-duplication and both condition lists are what makes our rollup a
2488
- superset of Airtable's fold; a Count is the ONE preset shape whose bag carries none of
2489
- them, and `rollupPresetOf` refuses to call any bag a preset once one is set. So hiding
2490
- them here can never hide a stored value: the two facts are the same rule, written once
2491
- on each side of the round trip. */}
2492
- {rollupPreset ? null : (
2493
- <>
2494
  {/*
2495
  ⭐⭐ 2026-08-09 (owner) — THE PRE-FILTER, ABOVE THE WINDOW, AND THE SCREEN ORDER IS THE
2496
  ORDER OF OPERATIONS. Owner: *"instead of last 12 posts, we also want to make it so its
@@ -2599,8 +2023,6 @@ function ExtraTypeEditor({
2599
  targetFields={targetFields}
2600
  allowRef
2601
  />
2602
- </>
2603
- )}
2604
  <div className="cg-field-hint">
2605
  Computed for you and refreshed as the linked records change — the cell cannot be typed
2606
  into.
@@ -2611,10 +2033,7 @@ function ExtraTypeEditor({
2611
  // connected source the offer is empty, and a two-way toggle whose second option can never
2612
  // work is a control that configures nothing ([[wrong-parent-not-broken-control]]). The link
2613
  // editor is then simply what a rollup is, exactly as it was before this existed.
2614
- // ⛔ AND A PRESET IS A LINK FOLD BY DEFINITION. Count and Lookup both count or list the
2615
- // records a LINK reaches, so the read-through mode is not a choice they have; showing the
2616
- // Summarise switch would offer a second answer that their own bag cannot express.
2617
- if (rollupPreset || !sourceTopics.length) return linkEditor;
2618
  return (
2619
  <>
2620
  <label>
@@ -2660,6 +2079,8 @@ export default function ColumnMenu({
2660
  onClose,
2661
  onNote,
2662
  onHide,
 
 
2663
  onCreate,
2664
  onChangeField,
2665
  onCreateAndSwap,
@@ -2689,8 +2110,6 @@ export default function ColumnMenu({
2689
  onClearGroup,
2690
  userOptions = [],
2691
  measures = [],
2692
- hopTopics = [],
2693
- hopScopeKey = "",
2694
  tableKey,
2695
  }: ColumnMenuProps) {
2696
  /**
@@ -2806,9 +2225,7 @@ export default function ColumnMenu({
2806
  /** C5-AUTOFIELD — the create form's automation config. */
2807
  const [automationKind, setAutomationKind] = useState(AUTOMATION_KINDS[0].key);
2808
  const [automationUrlField, setAutomationUrlField] = useState(
2809
- // C11 — the DEFAULT for the `urlish` picker above, narrowed with it: a default the
2810
- // picker does not list is a control that opens showing something it cannot re-select.
2811
- () => offerableFields(fields).find((f) => f.type === "url")?.key ?? ""
2812
  );
2813
  /**
2814
  * ⭐ 2026-08-07 — the create form's LINK and ROLLUP configuration.
@@ -2820,14 +2237,6 @@ export default function ColumnMenu({
2820
  */
2821
  const [linkTable, setLinkTable] = useState("");
2822
  const [linkSingle, setLinkSingle] = useState(false);
2823
- const [linkConditions, setLinkConditions] = useState<RollupCondition[]>([]);
2824
- const [linkConditionConj, setLinkConditionConj] = useState<"and" | "or">("and");
2825
- // ⭐⭐ W42-T08 (R1, C1) — the HOP draft for the create pane. `topic: ""` is "no hop", and it is
2826
- // the default, so a Link field created without touching this question emits exactly the bag it
2827
- // emitted before this existed.
2828
- const [hopDraft, setHopDraft] = useState<HopDraft>(emptyHopDraft);
2829
- const patchHopDraft = (patch: Partial<HopDraft>) =>
2830
- setHopDraft((prev) => ({ ...prev, ...patch }));
2831
  /** ⭐ 2026-08-09 — the read-through half. `rollupMode` decides which bag `extraFor` builds;
2832
  * the two are mutually exclusive because the host's `_clean_rollup` returns the `source`
2833
  * shape before it ever reads `link`. */
@@ -2846,46 +2255,6 @@ export default function ColumnMenu({
2846
  const [rollupWhereConj, setRollupWhereConj] = useState<"and" | "or">("and");
2847
  const [rollupConditions, setRollupConditions] = useState<RollupCondition[]>([]);
2848
  const [rollupConditionConj, setRollupConditionConj] = useState<"and" | "or">("and");
2849
- /**
2850
- * ⭐⭐ W42-T37 (G3) — WHICH PRESET THE CREATE PANE IS BUILDING, or `null` for a rollup authored
2851
- * in full. It is picker state, never payload: `extraFor` reads the same rollup drafts it always
2852
- * did, so a Count saves the bag `{link, fn: "countall"}` that `_clean_rollup` already accepts
2853
- * and returns unchanged, and re-opens through `rollupPresetOf` as a Count.
2854
- *
2855
- * ⛔ IT CANNOT BE DERIVED FROM `kind` AND MUST NOT BE. `kind` is `"rollup"` for all three, so a
2856
- * derived answer would show the reduced editor to somebody who chose Rollup outright and had
2857
- * not filled anything in yet.
2858
- */
2859
- const [rollupPreset, setRollupPreset] = useState<RollupPreset | null>(null);
2860
- /**
2861
- * The picker's one entry point. A preset row selects the rollup kind and FIXES its fold; every
2862
- * other row clears the preset, because leaving one set would open the reduced editor on a kind
2863
- * that is not a rollup at all.
2864
- *
2865
- * ⛔ THE WINDOW AND BOTH CONDITION LISTS ARE CLEARED WITH IT. A preset's editor does not render
2866
- * them, so a value left behind by an abandoned rollup draft would ride out on the bag from
2867
- * controls the person can no longer see: configuration nobody chose, on a column nobody could
2868
- * inspect. That is also what keeps the saved bag EXACTLY the preset shape `rollupPresetOf`
2869
- * recognises, which is the round trip this ticket asserts.
2870
- */
2871
- const pickKind = (picked: PickerKind) => {
2872
- const preset: RollupPreset | null =
2873
- picked === "count" || picked === "lookup" ? picked : null;
2874
- setRollupPreset(preset);
2875
- if (!preset) {
2876
- setKind(picked as CreateKind);
2877
- return;
2878
- }
2879
- setKind("rollup");
2880
- setRollupMode("link");
2881
- setRollupFn(ROLLUP_PRESET_FNS[preset]);
2882
- if (preset === "count") setRollupField("");
2883
- setRollupLimit(0);
2884
- setRollupSortBy("");
2885
- setRollupDistinctBy("");
2886
- setRollupWhere([]);
2887
- setRollupConditions([]);
2888
- };
2889
  const [swapTo, setSwapTo] = useState("");
2890
  /** The "New field" half of Change-field keeps its own name/options — a half-typed insert
2891
  * form must not leak into a swap and vice versa. */
@@ -2986,19 +2355,6 @@ export default function ColumnMenu({
2986
  });
2987
  const [editLinkTable, setEditLinkTable] = useState(() => field.link?.table ?? "");
2988
  const [editLinkSingle, setEditLinkSingle] = useState(() => field.link?.single === true);
2989
- const [editLinkConditions, setEditLinkConditions] = useState<RollupCondition[]>(
2990
- () => field.link?.conditions ?? []
2991
- );
2992
- const [editLinkConditionConj, setEditLinkConditionConj] = useState<"and" | "or">(
2993
- () => field.link?.conditionConj ?? "and"
2994
- );
2995
- // ⛔⛔ W42-T08 — SEEDED FROM THE STORED BAG, and this is not a nicety. The relational save
2996
- // below is a REBUILD: it re-emits the whole `link` bag, so a hop the pane never read would be
2997
- // DELETED by the one click meant to rename the column. Round-tripping it is what makes the
2998
- // rebuild safe.
2999
- const [editHopDraft, setEditHopDraft] = useState<HopDraft>(() => hopDraftFrom(field.link));
3000
- const patchEditHopDraft = (patch: Partial<HopDraft>) =>
3001
- setEditHopDraft((prev) => ({ ...prev, ...patch }));
3002
 
3003
  const swapToNewType = swapTo.startsWith(NEW_PREFIX)
3004
  ? (swapTo.slice(NEW_PREFIX.length) as FieldType)
@@ -3008,8 +2364,7 @@ export default function ColumnMenu({
3008
  const options = createChoice.options;
3009
  const swapChoice = swapToNewType
3010
  ? optionSettings(swapOptionDrafts, swapToNewType)
3011
- : { options: [] as string[], colors: {} as Record<string, string>,
3012
- capMessage: null as string | null };
3013
  const swapNewOptions = swapChoice.options;
3014
  /** Owner item 8 — the Edit pane's parsed choices for the drafted type. */
3015
  const editChoice = optionSettings(editOptionDrafts, editType);
@@ -3059,10 +2414,7 @@ export default function ColumnMenu({
3059
  * permanently unable to run.
3060
  */
3061
  const addressFields = useMemo(
3062
- // C11 — an offer, and the picker behind it.
3063
- () => offerableFields(fields).filter(
3064
- (f) => (GEOCODE_ADDRESS_TYPES as readonly string[]).includes(f.type)
3065
- ),
3066
  [fields]
3067
  );
3068
  const offerGeocode = geocodable && addressFields.length > 0;
@@ -3073,17 +2425,12 @@ export default function ColumnMenu({
3073
  const effectiveLabel =
3074
  kind === "measure" && !labelTouched && !label.trim() ? suggestedLabel : label;
3075
 
3076
- // A select with no choices is a column nothing can ever be put in, so creation is blocked
3077
- // until it has at least one. An assignee takes its choices from the host, not from here.
3078
- // A measure column needs a measure; a formula column needs a formula that PARSES — an
3079
  // unparseable formula would be a permanently blank column, refused here rather than shipped.
3080
  const canCreate =
3081
  effectiveLabel.trim() !== "" &&
3082
- (!needsOptions(kind) || options.length > 0) &&
3083
- // ⭐⭐ W42-T37 (C8b) — THE CAP REFUSES, IT DOES NOT TRUNCATE. The pane beside this button is
3084
- // already saying how many choices are over the line and how many to remove; Create stays shut
3085
- // until they are, so nothing is dropped on the way to the store.
3086
- createChoice.capMessage === null &&
3087
  (kind !== "measure" || !!chosenMeasure) &&
3088
  // ⭐⭐ W37-T22 (R4 / C7) — a geocode column with no address column to read is a column no run
3089
  // can ever fill: the identical argument the `automation` URL-column rule below makes, and the
@@ -3104,11 +2451,7 @@ export default function ColumnMenu({
3104
  // `ai_enrich` column with no prompt, so creating one without this gate produces a column that
3105
  // is named, configured and simply absent on the next read.
3106
  (kind !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
3107
- // ⛔⛔ W42-T08 (C1) — A HALF-DECLARED HOP IS REFUSED HERE, not shipped. `_clean_link` refuses
3108
- // the WHOLE field on a bad `via`, so a bag naming a topic with no `target_key` would produce
3109
- // a column that is named, configured and simply absent on the next read. A BLANK hop is not
3110
- // half-declared and passes untouched, which is the unchanged one-hop path.
3111
- (kind !== "link" || (linkTable !== "" && !hopIncomplete(hopDraft, hopScopeKey))) &&
3112
  (kind !== "rollup" || (rollupMode === "source"
3113
  // ⭐ 2026-08-09 — the read-through bag. ALL FOUR keys are required by `_clean_rollup`
3114
  // (`if not (topic and measure and group_by and on): return None`), and `on` is the one a
@@ -3127,18 +2470,7 @@ export default function ColumnMenu({
3127
  t: CreateKind,
3128
  src: string,
3129
  starCount: number,
3130
- lang: string,
3131
- /**
3132
- * ⛔⛔ W42-T08 — THE HOP IS PASSED IN, NOT READ FROM STATE, AND THAT IS THE WHOLE POINT.
3133
- *
3134
- * `hopDraft` is component-level state and this builder serves TWO forms: the create pane and
3135
- * the "change this column" swap form. The swap form is mounted with `hop={null}` so a hop
3136
- * cannot be AUTHORED there, but reading the draft off state anyway would let a hop configured
3137
- * in the create pane and abandoned ride out on a link field created by the swap form: a join
3138
- * the user never asked for, on a column they were only retyping. `null` here says which form
3139
- * is asking.
3140
- */
3141
- hopSource: HopDraft | null
3142
  ): FieldConfigExtra | undefined => {
3143
  if (t === "formula") return { formula: src.trim() };
3144
  if (t === "rating") return { max: starCount };
@@ -3180,22 +2512,7 @@ export default function ColumnMenu({
3180
  // picks records). The DERIVED mode is the automation's, spawned with its join declared —
3181
  // offering "join on a column of the other table" here would be a second, harder mental
3182
  // model for the same button.
3183
- // ⭐⭐ W42-T08 (R1, C1) — `via` TRAVELS ONLY WHEN IT IS COMPLETE, and its ABSENCE is the
3184
- // one-hop bag this menu has always emitted. `hopVia` answers null for a blank draft and for a
3185
- // half-filled one alike; `canCreate` above is what stops the second from reaching here.
3186
- if (t === "link") {
3187
- const via = hopVia(hopSource, hopScopeKey);
3188
- return {
3189
- link: {
3190
- table: linkTable,
3191
- ...(linkSingle ? { single: true } : {}),
3192
- ...(linkConditions.length
3193
- ? { conditions: linkConditions, conditionConj: linkConditionConj }
3194
- : {}),
3195
- ...(via ? { via } : {}),
3196
- },
3197
- };
3198
- }
3199
  if (t === "rollup" && rollupMode === "source")
3200
  // ⛔ THE SOURCE BAG TRAVELS ALONE. `_clean_rollup` reads `source` first and returns
3201
  // immediately, so sending `link`/`fn` alongside it would ship keys the store drops —
@@ -3290,7 +2607,7 @@ export default function ColumnMenu({
3290
  onCreate(clean, kind, position === "end" ? null : field.key, position,
3291
  needsOptions(kind) ? options : undefined, undefined,
3292
  withScope({
3293
- ...extraFor(kind, formulaText, maxValue, codeLanguage, hopDraft),
3294
  ...optionExtraFor(kind, createChoice.colors, createColorCode),
3295
  }));
3296
  onClose();
@@ -3299,11 +2616,6 @@ export default function ColumnMenu({
3299
  const canCreateSwap =
3300
  swapToNewType != null &&
3301
  swapLabel.trim() !== "" &&
3302
- (!needsOptions(swapToNewType) || swapNewOptions.length > 0) &&
3303
- // ⭐⭐ W42-T37 (C8b) — the option cap refuses at this door too. Unlike the completeness gates
3304
- // the comment below books as missing, this one costs nothing to state here: the swap form
3305
- // mounts the same options editor and therefore shows the same sentence.
3306
- swapChoice.capMessage === null &&
3307
  (swapToNewType !== "formula" || swapFormulaCheck.ok) &&
3308
  // ⭐⭐ Wave-34 (R13) — the SAME completeness gate `canCreate` carries, on this door too.
3309
  //
@@ -3326,8 +2638,7 @@ export default function ColumnMenu({
3326
  swapToNewType,
3327
  needsOptions(swapToNewType) ? swapNewOptions : undefined,
3328
  withScope({
3329
- // ⛔ `null`: the swap form offers no hop question, so it emits no hop. See `hopSource`.
3330
- ...extraFor(swapToNewType, swapFormulaText, swapMaxValue, swapCodeLanguage, null),
3331
  ...optionExtraFor(swapToNewType, swapChoice.colors, swapColorCode),
3332
  })
3333
  );
@@ -3369,8 +2680,7 @@ export default function ColumnMenu({
3369
  (editType !== field.type || editOptionsChanged || editAppearanceChanged ||
3370
  editStarsChanged || editAutomationChanged);
3371
  const editRetypeValid =
3372
- (!needsOptions(editType) || editOptions.length > 0) &&
3373
- (editType !== "automation" || editAutomationUrlField !== "");
3374
  const editFormulaCheck = useMemo(
3375
  () =>
3376
  editFormulaText.trim() === ""
@@ -3438,15 +2748,7 @@ export default function ColumnMenu({
3438
  (field.type === "rollup"
3439
  ? JSON.stringify(editRollup) !== JSON.stringify(field.rollup ?? {})
3440
  : editLinkTable !== (field.link?.table ?? "") ||
3441
- editLinkSingle !== (field.link?.single === true) ||
3442
- JSON.stringify(editLinkConditions) !== JSON.stringify(field.link?.conditions ?? []) ||
3443
- editLinkConditionConj !== (field.link?.conditionConj ?? "and") ||
3444
- // ⚠ COMPARED AS THE BAG, NOT AS THE DRAFT. `hopDraftFrom` normalises an absent `via` and
3445
- // an absent `window` to the same seeded draft the empty one produces, so comparing the
3446
- // drafts by `JSON.stringify` would report a hop change on a pane nobody touched, which is
3447
- // exactly the false-dirty class the description-only guard above exists to prevent.
3448
- JSON.stringify(hopVia(editHopDraft, hopScopeKey)) !==
3449
- JSON.stringify(hopVia(hopDraftFrom(field.link), hopScopeKey)));
3450
  const canSaveEdit =
3451
  /**
3452
  * ⭐ W41-T31 — THE DESCRIPTION-ONLY PANE'S WHOLE SAVE CONDITION, and it is one dirty flag
@@ -3470,16 +2772,9 @@ export default function ColumnMenu({
3470
  // is refused by the server, so Save is refused here instead: a 400 arriving after the click
3471
  // is the same "named, configured, gone" surprise one layer later.
3472
  (editType !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
3473
- // ⭐⭐ W42-T37 (C8b) — and the third door. An EDIT is where a long list actually arrives: a
3474
- // column already holding choices is where somebody pastes another two hundred in.
3475
- editChoice.capMessage === null &&
3476
  (editingRelational
3477
  ? (editRollupValid && (editRelationalTouched || editNameDirty || editNoteDirty) &&
3478
- // ⛔ W42-T08 — the same half-declared-hop refusal `canCreate` makes, at the second
3479
- // door. `_clean_link` refuses the WHOLE field on a bad `via`, so saving one here would
3480
- // not edit the column, it would remove it.
3481
- (field.type !== "link" ||
3482
- (editLinkTable !== "" && !hopIncomplete(editHopDraft, hopScopeKey))))
3483
  : (editNameDirty || editRetypeTouched || editFormulaTouched ||
3484
  (canPeriod && periodChanged) || editNoteDirty)));
3485
  /**
@@ -3525,19 +2820,8 @@ export default function ColumnMenu({
3525
  ...(editNameDirty ? { label: cleanRename } : {}),
3526
  ...(field.type === "rollup"
3527
  ? { rollup: editRollup as Record<string, unknown> }
3528
- // ⛔ W42-T08 — AND THE HOP RIDES THE REBUILD. This branch re-emits the whole bag, so
3529
- // omitting `via` would not mean "unchanged", it would DELETE a saved hop. `hopVia`
3530
- // answers null only for a blank or half-filled draft, and the Save door above already
3531
- // refuses the second.
3532
  : { link: { table: editLinkTable,
3533
- ...(editLinkSingle ? { single: true } : {}),
3534
- ...(editLinkConditions.length
3535
- ? { conditions: editLinkConditions,
3536
- conditionConj: editLinkConditionConj }
3537
- : {}),
3538
- ...(hopVia(editHopDraft, hopScopeKey)
3539
- ? { via: hopVia(editHopDraft, hopScopeKey)! }
3540
- : {}) } }),
3541
  });
3542
  if (editNoteDirty) onNote(note);
3543
  onClose();
@@ -3620,10 +2904,7 @@ export default function ColumnMenu({
3620
  * would contain; `swapOffered` is whether the picker exists at all, and it is read twice (the
3621
  * control itself, and the focus fallback that has to know whether the control is there).
3622
  */
3623
- // C11 (W42-T54) — "Change this column to…" is a picker, so `presetSwap` and `yourSwap`
3624
- // below are both narrowed by narrowing their source ONCE. ⚠ `swapOffered` reads this list's
3625
- // LENGTH, so a table whose only other columns were withheld correctly offers no swap at all.
3626
- const swapOptions = offerableFields(fields).filter((f) => f.key !== field.key);
3627
  const presetSwap = swapOptions.filter((f) => f.source === "odoo" && !f.custom);
3628
  const yourSwap = swapOptions.filter((f) => !(f.source === "odoo" && !f.custom));
3629
  const swapOffered = offer.swap && swapOptions.length > 0;
@@ -3792,12 +3073,10 @@ export default function ColumnMenu({
3792
  rows, Airtable-style. The measure row appears exactly when the host offers
3793
  measures — the same availability rule as the filter's measure conditions. */}
3794
  <TypePicker
3795
- value={rollupPreset ?? kind}
3796
- onPick={pickKind}
3797
  offerMeasure={measures.length > 0}
3798
  offerGeocode={offerGeocode}
3799
- offerPresets
3800
- isUserTable={isUserTable}
3801
  />
3802
  </div>
3803
  {kind === "measure" && (
@@ -3897,27 +3176,9 @@ export default function ColumnMenu({
3897
  onAutomationUrlField={setAutomationUrlField}
3898
  linkTargets={linkTargets}
3899
  linkTable={linkTable}
3900
- onLinkTable={(value) => {
3901
- setLinkTable(value);
3902
- setLinkConditions([]);
3903
- }}
3904
  linkSingle={linkSingle}
3905
  onLinkSingle={setLinkSingle}
3906
- linkConditions={linkConditions}
3907
- onLinkConditions={setLinkConditions}
3908
- linkConditionConj={linkConditionConj}
3909
- onLinkConditionConj={setLinkConditionConj}
3910
- hop={{
3911
- topics: hopTopics,
3912
- // The hop travels through a governed topic, so its window vocabulary is the one the
3913
- // read-through rollup already offers for the same topics. `all` when none is
3914
- // offered, which is what C1's default spells.
3915
- windows: rollupSourceOffer.windows,
3916
- scopeKey: hopScopeKey,
3917
- draft: hopDraft,
3918
- onDraft: patchHopDraft,
3919
- }}
3920
- rollupPreset={rollupPreset}
3921
  rollupMode={rollupMode}
3922
  onRollupMode={setRollupMode}
3923
  rollupSourceOffer={rollupSourceOffer}
@@ -4224,28 +3485,10 @@ export default function ColumnMenu({
4224
  onCodeLanguage={setEditCodeLanguage}
4225
  idPrefix="cg-edit"
4226
  linkTable={editLinkTable}
4227
- onLinkTable={(value) => {
4228
- setEditLinkTable(value);
4229
- setEditLinkConditions([]);
4230
- }}
4231
  linkSingle={editLinkSingle}
4232
  onLinkSingle={setEditLinkSingle}
4233
- linkConditions={editLinkConditions}
4234
- onLinkConditions={setEditLinkConditions}
4235
- linkConditionConj={editLinkConditionConj}
4236
- onLinkConditionConj={setEditLinkConditionConj}
4237
- hop={{
4238
- topics: hopTopics,
4239
- windows: rollupSourceOffer.windows,
4240
- scopeKey: hopScopeKey,
4241
- draft: editHopDraft,
4242
- onDraft: patchEditHopDraft,
4243
- }}
4244
  rollupSourceOffer={rollupSourceOffer}
4245
- // ⭐⭐ W42-T37 — THE RE-OPEN. Read from the STORED bag, so a Count comes back as a
4246
- // Count and a rollup that merely happens to fold by "Count of records" over a
4247
- // window does not.
4248
- rollupPreset={rollupPresetOf(editRollup)}
4249
  rollupMode={editRollup.source ? "source" : "link"}
4250
  // ⛔ A MODE SWITCH REPLACES THE BAG, it does not merge into it. `_clean_rollup`
4251
  // reads `source` first and returns before it ever looks at `link`, so a bag
@@ -4314,8 +3557,6 @@ export default function ColumnMenu({
4314
  codeLanguage={editCodeLanguage}
4315
  onCodeLanguage={setEditCodeLanguage}
4316
  idPrefix="cg-edit"
4317
- // This arm is `field.type === "automation"`, which can never be a link.
4318
- hop={null}
4319
  automationKind={editAutomationKind}
4320
  onAutomationKind={setEditAutomationKind}
4321
  automationUrlField={editAutomationUrlField}
@@ -4332,14 +3573,6 @@ export default function ColumnMenu({
4332
  value={editType}
4333
  onPick={(k) => setEditType(k as FieldType)}
4334
  offerMeasure={false}
4335
- offerPresets={
4336
- /* ⛔ FALSE FOR `offerGeocode`'s REASON, one line down. A preset AUTHORS a
4337
- rollup bag, and this pane retypes an existing column rather than authoring
4338
- one; a Count row here would set a kind whose configuration nothing on this
4339
- door writes. */
4340
- false
4341
- }
4342
- isUserTable={isUserTable}
4343
  offerGeocode={
4344
  /* ⛔ FALSE ON PURPOSE, and stated rather than omitted: this is the RETYPE
4345
  picker, and a geocode column is not a type an existing column can BECOME.
@@ -4482,8 +3715,6 @@ export default function ColumnMenu({
4482
  codeLanguage={editCodeLanguage}
4483
  onCodeLanguage={setEditCodeLanguage}
4484
  idPrefix="cg-edit"
4485
- // This arm is `field.type === "formula"`, which can never be a link.
4486
- hop={null}
4487
  showFormulaHelp={false}
4488
  />
4489
  )}
@@ -4600,11 +3831,6 @@ export default function ColumnMenu({
4600
  codeLanguage={swapCodeLanguage}
4601
  onCodeLanguage={setSwapCodeLanguage}
4602
  idPrefix="cg-swap"
4603
- // ⛔ NULL, AND IT IS A STATEMENT. The swap form passes no `linkTargets`,
4604
- // `onLinkTable` or `onLinkSingle` either, so a link built here already
4605
- // configures nothing; painting a hop question on top of that would be a
4606
- // second control that saves nothing rather than a feature.
4607
- hop={null}
4608
  />
4609
  {needsOptions(swapToNewType) && (
4610
  <OptionsEditor
@@ -5045,6 +4271,16 @@ export default function ColumnMenu({
5045
  <MenuLabel icon="duplicate" text="Duplicate field" />
5046
  </button>
5047
  )}
 
 
 
 
 
 
 
 
 
 
5048
  <button type="button" onClick={() => setPosition("left")}>
5049
  <MenuLabel icon="insertLeft" text="Insert field left" />
5050
  </button>
@@ -5081,30 +4317,18 @@ export default function ColumnMenu({
5081
  <div className="cg-menu-sep" role="separator" aria-hidden />
5082
 
5083
  {/* Group 3 — sort. Direction wording stays the shipped per-type directionLabel. */}
5084
- {/* ⛔⛔ WAVE-42 R22 — THE ROUTE PROJECTION COLUMN IS NOT SORTED FROM HERE. Its cell is
5085
- `Route A - 3, Route B - 7`, so an ordinary sort compares TEXT and puts
5086
- `Route A - 10` before `Route A - 2`. A stop position only orders records inside ONE
5087
- route, and this menu is not told what the view is filtered to, so it cannot know
5088
- whether it is. It says so instead of guessing in the permissive direction; the Sort
5089
- panel, which does hold the filter, is where the narrowed case is allowed. */}
5090
- {field.key === ROUTE_PROJECTION_KEY ? (
5091
- <div className="cg-field-hint">{ROUTE_SORT_REFUSAL_TEXT}</div>
5092
- ) : (
5093
- <>
5094
- <button type="button" onClick={() => { onSort("asc"); onClose(); }}>
5095
- <MenuLabel
5096
- icon="sortAsc"
5097
- text={`Sort ${directionLabel(field.type, "asc")}`}
5098
- />
5099
- </button>
5100
- <button type="button" onClick={() => { onSort("desc"); onClose(); }}>
5101
- <MenuLabel
5102
- icon="sortDesc"
5103
- text={`Sort ${directionLabel(field.type, "desc")}`}
5104
- />
5105
- </button>
5106
- </>
5107
- )}
5108
  {sortedDir != null && (
5109
  <button type="button" onClick={() => { onClearSort(); onClose(); }}>
5110
  <MenuLabel icon="off" text="Don't sort by this field" />
 
6
  import type { FieldProposal } from "./fieldAgent";
7
  import { AnchoredOverlay } from "./OverlaySurface";
8
  import type { AnchorRect } from "./OverlaySurface";
9
+ import { FieldTypeIcon, MenuLabel } from "./icons";
10
  import { FieldSelectButton } from "./FieldSelect";
11
  // ⭐⭐ W40-T24 — the pre-set definition lock. It lives in `display.ts` rather than here because a
12
  // rule stated inside JSX cannot be LOADED by a node gate; `display.ts`'s header carries the full
 
18
  // that must be runnable rather than read back to itself as source text.
19
  import { CODE_LANGUAGE_LABELS, CODE_LANGUAGES, CREATABLE_TYPES, choiceOptions, choiceRenames,
20
  codeLanguageOf, directionLabel, groupTypePickerRows, isDerivedLink, isMachineOwned,
21
+ isProfileField, parseOptions, ratingMax, ROLLUP_FN_LABELS, ROLLUP_FNS,
22
+ ROLLUP_REF_OPS, mayEditFieldDefinition } from "./types";
23
+ import type { AggName, Field, FieldFormat, FieldScope, FieldType, Measure, RollupCondition, RollupFn,
 
 
 
 
24
  RollupRefOp, RollupSource, Viewer } from "./types";
25
  import type { LinkTarget, RollupSourceOffer } from "./apiBridge";
26
  import type { WindowSpec } from "./windows";
27
  import { normalizeWindow, windowLabel } from "./windows";
28
+ import { WindowPicker } from "../filter-kit";
29
  // ⭐⭐ W41-T29 (R6, contract C2) — the ONE pair of rights predicates plus the copy that says what
30
  // they refused, read from the same module the Fields manager reads. C2: no surface re-implements
31
  // either test, so this menu asks rather than deriving a second answer of its own.
 
100
  geocode?: { addressField: string; country?: string };
101
  /** ⭐ 2026-08-07 — a `link` column's target. REQUIRED for the type: `_clean_field` returns
102
  * None for a link with no bag, so a create without this is a column that never appears. */
103
+ link?: { table: string; single?: boolean };
 
 
 
 
 
 
 
 
104
  /** ⭐ 2026-08-07 — a `rollup` column's aggregate. Same requirement, same reason.
105
  * ⭐ 2026-08-09 — or, INSTEAD, a `source` binding: the read-through kind, which summarises
106
  * rows that were never copied into the workspace. The host's `_clean_rollup` reads `source`
 
162
  * as it was before this existed. So this prop is what turns the second kind ON, not a flag.
163
  */
164
  rollupSourceOffer?: RollupSourceOffer;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  locked: boolean;
166
  /** Product-owned preset fields may still drive view actions, but their schema is immutable. */
167
  schemaLocked?: boolean;
 
187
  onClose: () => void;
188
  onNote: (note: string) => void;
189
  onHide: () => void;
190
+ /** Header drag has a keyboard-equivalent path in this same action surface. */
191
+ onMoveLeft?: () => void;
192
+ onMoveRight?: () => void;
193
  onCreate: (
194
  label: string,
195
  type: FieldType,
 
299
  * DIFFERENT ACT from `onDelete`, and therefore a different door: it destroys no definition and
300
  * no values, and pointing "Remove from my fields" at the delete handler would be a benign word
301
  * on a destructive action.
302
+ * ⚠ OPTIONAL for `onDelete`'s reason, and unwired today: `CustomerGrid.tsx` is another lane's
303
+ * file and no endpoint unshares a field yet. The half of R6(b) that holds without it is the
304
+ * REFUSAL: a shared-with-me column loses its Delete row whether or not this handler arrives.
305
  */
306
+ onRemoveFromMine?: () => void;
307
  /** ⭐⭐ Wave-34 (R13) — run this AI enrichment column over many rows.
308
  * `scope` is `"blank"` (only cells still empty) or `"always"` (every row the AI
309
  * wrote). OPTIONAL for `onDelete`'s reason: a host that has not wired the door shows
 
683
  function optionSettings(
684
  drafts: OptionDraft[],
685
  type: CreateKind
686
+ ): { options: string[]; colors: Record<string, string> } {
687
  const clean = drafts.map((draft) =>
688
  type === "multiselect" ? draft.label.replace(/,/g, " ") : draft.label
689
  );
690
+ const options = parseOptions(clean.join("\n"));
 
 
 
 
691
  const firstByLabel = new Map<string, OptionDraft>();
692
  drafts.forEach((draft, index) => {
693
  const label = clean[index].trim();
 
703
  if (color && color !== normalizeOptionColor(defaultOptionColor(option)))
704
  colors[option] = color;
705
  }
706
+ return { options, colors };
707
  }
708
 
709
  function optionAppearanceSignature(
 
913
  {settings.options.length} option{settings.options.length === 1 ? "" : "s"}.
914
  {type === "multiselect" && " Commas inside an option are not supported."}
915
  </span>
 
 
 
 
 
 
 
 
 
916
  </div>
917
  );
918
  }
 
925
  */
926
  type CreateKind = FieldType | "measure" | "geocode";
927
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
928
  /**
929
  * ⭐⭐ W37-T22 (R4 / C7) — the geocode pseudo-kind's picker label, and the address-column families
930
  * it may read. Declared here beside `CreateKind` because three places consume them (the picker
 
959
  onPick,
960
  offerMeasure,
961
  offerGeocode,
 
 
962
  only,
963
  }: {
964
+ value: CreateKind;
965
+ onPick: (k: CreateKind) => void;
966
  offerMeasure: boolean;
967
  /**
968
  * ⭐⭐ W37-T22 (R4 / C7) — offer the geocode pseudo-kind. REQUIRED, not optional: an optional
 
980
  * "has an address column", which is what W37-T22's `done-when` asks for.
981
  */
982
  offerGeocode: boolean;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
983
  /** Restrict the list (the Edit-field pane passes RETYPE_TYPES — the overlay-editable
984
  * strata a created field may become). Absent = every creatable type. */
985
  only?: readonly FieldType[];
986
  }) {
987
  const [q, setQ] = useState("");
988
  const needle = q.trim().toLowerCase();
989
+ const base = only
 
 
 
 
990
  ? FIELD_TYPES.filter((r) => (only as readonly string[]).includes(r.value))
991
  : FIELD_TYPES;
992
+ const rows: { value: CreateKind; label: string }[] = [
 
993
  ...base,
 
 
 
 
 
 
 
 
 
 
 
994
  // C-NAME (item 9, 2026-08-02): "Formula measure (over a period)" -> "Metric". Two words
995
  // of jargon and a parenthetical, replaced by the word people already use for the thing.
996
  // The internal key stays `measure` — see the C-NAME amendment in the wave doc.
 
1054
  type="button"
1055
  role="option"
1056
  aria-selected={value === r.value}
 
 
1057
  className={"cg-type-row" + (value === r.value ? " is-on" : "")}
1058
  onClick={() => onPick(r.value)}
1059
  >
1060
  {/* Each row wears the mark its COLUMN will wear. A measure column's real type is
1061
  currency/int/pct and a geocode column's is `text`, so both pseudo-kinds borrow
1062
+ rather than inventing a glyph no column ever shows (the iconShapes ruling). */}
 
 
1063
  <FieldTypeIcon
1064
  type={
1065
+ r.value === "measure" ? "currency" : r.value === "geocode" ? "text" : r.value
 
1066
  }
1067
  size={16}
1068
  />
 
 
 
1069
  <span className="cg-type-label">{r.label}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1070
  </button>
1071
  ))}
1072
  </Fragment>
 
1219
  { value: "always", label: "Every row the AI wrote, every run" },
1220
  ];
1221
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1222
  function ExtraTypeEditor({
1223
  kind,
1224
  fields,
 
1242
  onLinkTable,
1243
  linkSingle = false,
1244
  onLinkSingle,
 
 
 
 
 
 
1245
  rollupMode = "link",
1246
  onRollupMode,
1247
  rollupSourceOffer = { topics: [], windows: [] },
 
1308
  onLinkTable?: (v: string) => void;
1309
  linkSingle?: boolean;
1310
  onLinkSingle?: (v: boolean) => void;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1311
  /** ⭐ 2026-08-09 — which KIND of rollup is being built. `"link"` folds workspace rows;
1312
  * `"source"` reads through to a governed Odoo topic without copying a row into the store. */
1313
  rollupMode?: "link" | "source";
 
1341
  if (kind === "formula") {
1342
  // 2026-07-31 (owner item 2): other FORMULA fields are referencable now — evaluation is
1343
  // topological and a cycle is refused at validation, so the old exclusion is gone.
1344
+ const referencable = fields.filter((f) => f.key !== "__proto__");
 
 
 
 
1345
  return (
1346
  <>
1347
  <label>
 
1598
  // thing it reads. The schedule and the Run-now button are NOT here — they belong to the
1599
  // automation itself, on the Automation surface, because one job can fill a column across
1600
  // many records and its cadence is a property of the job, not of the column.
1601
+ const urlish = fields.filter((f) => f.type === "url" || f.type === "text");
 
 
 
1602
  const chosen = AUTOMATION_KINDS.find((k) => k.key === automationKind)
1603
  ?? AUTOMATION_KINDS[0];
1604
  return (
 
1656
  if (kind === "link") {
1657
  // ⭐ 2026-08-07 — Airtable's "Link to another record", and the whole editor is ONE question:
1658
  // which database. The relation itself is then the cell (a set of linked rows).
 
 
 
 
 
 
 
 
 
 
1659
  return (
1660
  <>
1661
  <label>
 
1687
  />
1688
  <span>Allow only one linked record</span>
1689
  </label>
1690
+ <div className="cg-field-hint">
1691
+ A cell here holds the records you pick. Add a Rollup column afterwards to summarise a
1692
+ column of those records — an average, a total, a count.
1693
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1694
  </>
1695
  );
1696
  }
 
1701
  // WHICH column, folded HOW, and across WHICH records. That last control is the owner's
1702
  // headline ("average Views over last N posts") and Airtable cannot express it — its rollup
1703
  // conditions filter by predicate, never by rank.
1704
+ const linkFields = fields.filter((f) => f.type === "link");
 
 
 
1705
  const chosenLink = linkFields.find((f) => f.key === rollupLink);
1706
  const target = linkTargets.find((t) => t.key === chosenLink?.link?.table);
1707
  const targetFields = target?.fields ?? [];
 
1719
  onRollupSource?.({ ...rollupSource, ...patch });
1720
  // ⚠ A join column must hold a SCALAR the group key can equal. Link and rollup columns hold a
1721
  // comma-joined id list and a computed value respectively, so neither can ever match.
1722
+ const joinable = fields.filter(
 
 
1723
  (f) => f.type !== "link" && f.type !== "rollup" && f.key !== "__proto__"
1724
  );
1725
  const sourceEditor = (
 
1832
  );
1833
  const linkEditor = (
1834
  <>
 
 
 
 
 
 
1835
  <label>
1836
  <span>Through</span>
1837
  <select
 
1853
  link, so add one of those first.
1854
  </div>
1855
  ) : null}
 
 
 
 
1856
  <label>
1857
  <span>Fold</span>
1858
  <select
 
1867
  ))}
1868
  </select>
1869
  </label>
 
1870
  {needsField ? (
1871
  <label>
1872
  <span>Column</span>
 
1915
  unavailable. Ask an admin to share that database with you, then reopen this editor.
1916
  </div>
1917
  ) : null}
 
 
 
 
 
 
 
 
1918
  {/*
1919
  ⭐⭐ 2026-08-09 (owner) — THE PRE-FILTER, ABOVE THE WINDOW, AND THE SCREEN ORDER IS THE
1920
  ORDER OF OPERATIONS. Owner: *"instead of last 12 posts, we also want to make it so its
 
2023
  targetFields={targetFields}
2024
  allowRef
2025
  />
 
 
2026
  <div className="cg-field-hint">
2027
  Computed for you and refreshed as the linked records change — the cell cannot be typed
2028
  into.
 
2033
  // connected source the offer is empty, and a two-way toggle whose second option can never
2034
  // work is a control that configures nothing ([[wrong-parent-not-broken-control]]). The link
2035
  // editor is then simply what a rollup is, exactly as it was before this existed.
2036
+ if (!sourceTopics.length) return linkEditor;
 
 
 
2037
  return (
2038
  <>
2039
  <label>
 
2079
  onClose,
2080
  onNote,
2081
  onHide,
2082
+ onMoveLeft,
2083
+ onMoveRight,
2084
  onCreate,
2085
  onChangeField,
2086
  onCreateAndSwap,
 
2110
  onClearGroup,
2111
  userOptions = [],
2112
  measures = [],
 
 
2113
  tableKey,
2114
  }: ColumnMenuProps) {
2115
  /**
 
2225
  /** C5-AUTOFIELD — the create form's automation config. */
2226
  const [automationKind, setAutomationKind] = useState(AUTOMATION_KINDS[0].key);
2227
  const [automationUrlField, setAutomationUrlField] = useState(
2228
+ () => fields.find((f) => f.type === "url")?.key ?? ""
 
 
2229
  );
2230
  /**
2231
  * ⭐ 2026-08-07 — the create form's LINK and ROLLUP configuration.
 
2237
  */
2238
  const [linkTable, setLinkTable] = useState("");
2239
  const [linkSingle, setLinkSingle] = useState(false);
 
 
 
 
 
 
 
 
2240
  /** ⭐ 2026-08-09 — the read-through half. `rollupMode` decides which bag `extraFor` builds;
2241
  * the two are mutually exclusive because the host's `_clean_rollup` returns the `source`
2242
  * shape before it ever reads `link`. */
 
2255
  const [rollupWhereConj, setRollupWhereConj] = useState<"and" | "or">("and");
2256
  const [rollupConditions, setRollupConditions] = useState<RollupCondition[]>([]);
2257
  const [rollupConditionConj, setRollupConditionConj] = useState<"and" | "or">("and");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2258
  const [swapTo, setSwapTo] = useState("");
2259
  /** The "New field" half of Change-field keeps its own name/options — a half-typed insert
2260
  * form must not leak into a swap and vice versa. */
 
2355
  });
2356
  const [editLinkTable, setEditLinkTable] = useState(() => field.link?.table ?? "");
2357
  const [editLinkSingle, setEditLinkSingle] = useState(() => field.link?.single === true);
 
 
 
 
 
 
 
 
 
 
 
 
 
2358
 
2359
  const swapToNewType = swapTo.startsWith(NEW_PREFIX)
2360
  ? (swapTo.slice(NEW_PREFIX.length) as FieldType)
 
2364
  const options = createChoice.options;
2365
  const swapChoice = swapToNewType
2366
  ? optionSettings(swapOptionDrafts, swapToNewType)
2367
+ : { options: [] as string[], colors: {} as Record<string, string> };
 
2368
  const swapNewOptions = swapChoice.options;
2369
  /** Owner item 8 — the Edit pane's parsed choices for the drafted type. */
2370
  const editChoice = optionSettings(editOptionDrafts, editType);
 
2414
  * permanently unable to run.
2415
  */
2416
  const addressFields = useMemo(
2417
+ () => fields.filter((f) => (GEOCODE_ADDRESS_TYPES as readonly string[]).includes(f.type)),
 
 
 
2418
  [fields]
2419
  );
2420
  const offerGeocode = geocodable && addressFields.length > 0;
 
2425
  const effectiveLabel =
2426
  kind === "measure" && !labelTouched && !label.trim() ? suggestedLabel : label;
2427
 
2428
+ // A select/multiselect starts with an empty vocabulary and learns values from the shared write
2429
+ // path, so creation and retyping never block on predeclared options. A measure column needs a
2430
+ // measure; a formula column needs a formula that PARSES — an
2431
  // unparseable formula would be a permanently blank column, refused here rather than shipped.
2432
  const canCreate =
2433
  effectiveLabel.trim() !== "" &&
 
 
 
 
 
2434
  (kind !== "measure" || !!chosenMeasure) &&
2435
  // ⭐⭐ W37-T22 (R4 / C7) — a geocode column with no address column to read is a column no run
2436
  // can ever fill: the identical argument the `automation` URL-column rule below makes, and the
 
2451
  // `ai_enrich` column with no prompt, so creating one without this gate produces a column that
2452
  // is named, configured and simply absent on the next read.
2453
  (kind !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
2454
+ (kind !== "link" || linkTable !== "") &&
 
 
 
 
2455
  (kind !== "rollup" || (rollupMode === "source"
2456
  // ⭐ 2026-08-09 — the read-through bag. ALL FOUR keys are required by `_clean_rollup`
2457
  // (`if not (topic and measure and group_by and on): return None`), and `on` is the one a
 
2470
  t: CreateKind,
2471
  src: string,
2472
  starCount: number,
2473
+ lang: string
 
 
 
 
 
 
 
 
 
 
 
2474
  ): FieldConfigExtra | undefined => {
2475
  if (t === "formula") return { formula: src.trim() };
2476
  if (t === "rating") return { max: starCount };
 
2512
  // picks records). The DERIVED mode is the automation's, spawned with its join declared —
2513
  // offering "join on a column of the other table" here would be a second, harder mental
2514
  // model for the same button.
2515
+ if (t === "link") return { link: { table: linkTable, ...(linkSingle ? { single: true } : {}) } };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2516
  if (t === "rollup" && rollupMode === "source")
2517
  // ⛔ THE SOURCE BAG TRAVELS ALONE. `_clean_rollup` reads `source` first and returns
2518
  // immediately, so sending `link`/`fn` alongside it would ship keys the store drops —
 
2607
  onCreate(clean, kind, position === "end" ? null : field.key, position,
2608
  needsOptions(kind) ? options : undefined, undefined,
2609
  withScope({
2610
+ ...extraFor(kind, formulaText, maxValue, codeLanguage),
2611
  ...optionExtraFor(kind, createChoice.colors, createColorCode),
2612
  }));
2613
  onClose();
 
2616
  const canCreateSwap =
2617
  swapToNewType != null &&
2618
  swapLabel.trim() !== "" &&
 
 
 
 
 
2619
  (swapToNewType !== "formula" || swapFormulaCheck.ok) &&
2620
  // ⭐⭐ Wave-34 (R13) — the SAME completeness gate `canCreate` carries, on this door too.
2621
  //
 
2638
  swapToNewType,
2639
  needsOptions(swapToNewType) ? swapNewOptions : undefined,
2640
  withScope({
2641
+ ...extraFor(swapToNewType, swapFormulaText, swapMaxValue, swapCodeLanguage),
 
2642
  ...optionExtraFor(swapToNewType, swapChoice.colors, swapColorCode),
2643
  })
2644
  );
 
2680
  (editType !== field.type || editOptionsChanged || editAppearanceChanged ||
2681
  editStarsChanged || editAutomationChanged);
2682
  const editRetypeValid =
2683
+ editType !== "automation" || editAutomationUrlField !== "";
 
2684
  const editFormulaCheck = useMemo(
2685
  () =>
2686
  editFormulaText.trim() === ""
 
2748
  (field.type === "rollup"
2749
  ? JSON.stringify(editRollup) !== JSON.stringify(field.rollup ?? {})
2750
  : editLinkTable !== (field.link?.table ?? "") ||
2751
+ editLinkSingle !== (field.link?.single === true));
 
 
 
 
 
 
 
 
2752
  const canSaveEdit =
2753
  /**
2754
  * ⭐ W41-T31 — THE DESCRIPTION-ONLY PANE'S WHOLE SAVE CONDITION, and it is one dirty flag
 
2772
  // is refused by the server, so Save is refused here instead: a 400 arriving after the click
2773
  // is the same "named, configured, gone" surprise one layer later.
2774
  (editType !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
 
 
 
2775
  (editingRelational
2776
  ? (editRollupValid && (editRelationalTouched || editNameDirty || editNoteDirty) &&
2777
+ (field.type !== "link" || editLinkTable !== ""))
 
 
 
 
2778
  : (editNameDirty || editRetypeTouched || editFormulaTouched ||
2779
  (canPeriod && periodChanged) || editNoteDirty)));
2780
  /**
 
2820
  ...(editNameDirty ? { label: cleanRename } : {}),
2821
  ...(field.type === "rollup"
2822
  ? { rollup: editRollup as Record<string, unknown> }
 
 
 
 
2823
  : { link: { table: editLinkTable,
2824
+ ...(editLinkSingle ? { single: true } : {}) } }),
 
 
 
 
 
 
 
2825
  });
2826
  if (editNoteDirty) onNote(note);
2827
  onClose();
 
2904
  * would contain; `swapOffered` is whether the picker exists at all, and it is read twice (the
2905
  * control itself, and the focus fallback that has to know whether the control is there).
2906
  */
2907
+ const swapOptions = fields.filter((f) => f.key !== field.key);
 
 
 
2908
  const presetSwap = swapOptions.filter((f) => f.source === "odoo" && !f.custom);
2909
  const yourSwap = swapOptions.filter((f) => !(f.source === "odoo" && !f.custom));
2910
  const swapOffered = offer.swap && swapOptions.length > 0;
 
3073
  rows, Airtable-style. The measure row appears exactly when the host offers
3074
  measures — the same availability rule as the filter's measure conditions. */}
3075
  <TypePicker
3076
+ value={kind}
3077
+ onPick={setKind}
3078
  offerMeasure={measures.length > 0}
3079
  offerGeocode={offerGeocode}
 
 
3080
  />
3081
  </div>
3082
  {kind === "measure" && (
 
3176
  onAutomationUrlField={setAutomationUrlField}
3177
  linkTargets={linkTargets}
3178
  linkTable={linkTable}
3179
+ onLinkTable={setLinkTable}
 
 
 
3180
  linkSingle={linkSingle}
3181
  onLinkSingle={setLinkSingle}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3182
  rollupMode={rollupMode}
3183
  onRollupMode={setRollupMode}
3184
  rollupSourceOffer={rollupSourceOffer}
 
3485
  onCodeLanguage={setEditCodeLanguage}
3486
  idPrefix="cg-edit"
3487
  linkTable={editLinkTable}
3488
+ onLinkTable={setEditLinkTable}
 
 
 
3489
  linkSingle={editLinkSingle}
3490
  onLinkSingle={setEditLinkSingle}
 
 
 
 
 
 
 
 
 
 
 
3491
  rollupSourceOffer={rollupSourceOffer}
 
 
 
 
3492
  rollupMode={editRollup.source ? "source" : "link"}
3493
  // ⛔ A MODE SWITCH REPLACES THE BAG, it does not merge into it. `_clean_rollup`
3494
  // reads `source` first and returns before it ever looks at `link`, so a bag
 
3557
  codeLanguage={editCodeLanguage}
3558
  onCodeLanguage={setEditCodeLanguage}
3559
  idPrefix="cg-edit"
 
 
3560
  automationKind={editAutomationKind}
3561
  onAutomationKind={setEditAutomationKind}
3562
  automationUrlField={editAutomationUrlField}
 
3573
  value={editType}
3574
  onPick={(k) => setEditType(k as FieldType)}
3575
  offerMeasure={false}
 
 
 
 
 
 
 
 
3576
  offerGeocode={
3577
  /* ⛔ FALSE ON PURPOSE, and stated rather than omitted: this is the RETYPE
3578
  picker, and a geocode column is not a type an existing column can BECOME.
 
3715
  codeLanguage={editCodeLanguage}
3716
  onCodeLanguage={setEditCodeLanguage}
3717
  idPrefix="cg-edit"
 
 
3718
  showFormulaHelp={false}
3719
  />
3720
  )}
 
3831
  codeLanguage={swapCodeLanguage}
3832
  onCodeLanguage={setSwapCodeLanguage}
3833
  idPrefix="cg-swap"
 
 
 
 
 
3834
  />
3835
  {needsOptions(swapToNewType) && (
3836
  <OptionsEditor
 
4271
  <MenuLabel icon="duplicate" text="Duplicate field" />
4272
  </button>
4273
  )}
4274
+ {onMoveLeft && (
4275
+ <button type="button" onClick={() => { onMoveLeft(); onClose(); }}>
4276
+ <MenuLabel icon="insertLeft" text="Move left" />
4277
+ </button>
4278
+ )}
4279
+ {onMoveRight && (
4280
+ <button type="button" onClick={() => { onMoveRight(); onClose(); }}>
4281
+ <MenuLabel icon="insertRight" text="Move right" />
4282
+ </button>
4283
+ )}
4284
  <button type="button" onClick={() => setPosition("left")}>
4285
  <MenuLabel icon="insertLeft" text="Insert field left" />
4286
  </button>
 
4317
  <div className="cg-menu-sep" role="separator" aria-hidden />
4318
 
4319
  {/* Group 3 — sort. Direction wording stays the shipped per-type directionLabel. */}
4320
+ <button type="button" onClick={() => { onSort("asc"); onClose(); }}>
4321
+ <MenuLabel
4322
+ icon="sortAsc"
4323
+ text={`Sort ${directionLabel(field.type, "asc")}`}
4324
+ />
4325
+ </button>
4326
+ <button type="button" onClick={() => { onSort("desc"); onClose(); }}>
4327
+ <MenuLabel
4328
+ icon="sortDesc"
4329
+ text={`Sort ${directionLabel(field.type, "desc")}`}
4330
+ />
4331
+ </button>
 
 
 
 
 
 
 
 
 
 
 
 
4332
  {sortedDir != null && (
4333
  <button type="button" onClick={() => { onClearSort(); onClose(); }}>
4334
  <MenuLabel icon="off" text="Don't sort by this field" />
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -70,21 +70,20 @@ import {
70
  } from "./scriptViews";
71
  import type { ScriptRun, ScriptView as ScriptViewRecord, ScriptViewRow } from "./scriptViews";
72
  import { defaultViewConfig, headerMarksFor, useGridColumns } from "./useGridColumns";
73
- import { activeMeasureRuleIds, matchFilterTree, pendingMeasures, runPipeline, sliceForDisplay,
74
- unresolvedConditionReasons, useVisibleRows } from "./useVisibleRows";
75
  import { computeAggs } from "./aggregations";
76
  import type { CohortSets } from "./useVisibleRows";
77
  import type { MeasureSets } from "./useVisibleRows";
78
  import { useGetCellContent } from "./useGetCellContent";
79
  import { useGridSelection } from "./useGridSelection";
80
  import Toolbar from "./Toolbar";
 
81
  import JsonViewer from "./JsonViewer";
82
  import RecordDetail from "./RecordDetail";
83
  import ViewSidebar from "./ViewSidebar";
84
  import ColumnMenu from "./ColumnMenu";
85
- import FieldBatchAccessDialog from "./FieldBatchAccessDialog";
86
- import type { FieldBatchAccessAction } from "./FieldBatchAccessDialog";
87
- import type { ColumnMenuState, HopTopic } from "./ColumnMenu";
88
  import { HEADER_ICONS } from "./iconShapes";
89
  import { emitHostEvent, eventId } from "./hostBridge";
90
  // ⭐ WAVE 27 item 21 (R14) — which of this table's views carry an alert. The SERVER's
@@ -95,10 +94,9 @@ import { API_V1, CREDENTIALS, NAV_MINIMIZE_EVENT, ROWS_STALE_EVENT, TOAST_EVENT,
95
  from "../apiContract";
96
  import type { ViewOpenDetail } from "../apiContract";
97
  import { addTableField, addTableRow, clearTopicRowsCache, deleteRouteOrderField, deleteTableField,
98
- deleteTableFields,
99
  deleteTableRow, fetchLinkTargets,
100
  fetchRollupSources, patchRouteOrderField, patchTableField, enrichField } from "./apiBridge";
101
- import type { FieldDeleteResult, LinkTarget, RollupSourceOffer } from "./apiBridge";
102
  import SelectFromFile from "./SelectFromFile";
103
  import ImportDialog from "./ImportDialog";
104
  import { FormInterface } from "./FormInterface";
@@ -175,12 +173,12 @@ import { ALL_VIEW_ID, MAX_CALENDAR_METRICS, allViewName,
175
  viewDisplayName,
176
  /* ⭐ W37-T26 (C4) — the view-membership leaf's two pure helpers. `viewRefsOf` is the ONE walk
177
  the resolver, the cycle detector and the gate share; `viewFilterCycle` is the refusal. */
178
- viewFilterCycle, viewRefsOf, linkPickerFilterNodes } from "./types";
179
  /* ⭐⭐ W41-T42 (owner instruction 23) — the pivot's whole vocabulary is DECLARED in `types.ts`
180
  and only consumed here, because W41-T43 (this file) and W41-T44 (`RecordDetail.tsx`) open the
181
  same feature through other doors and neither of them may edit `types.ts`. */
182
  import { buildPivotRequest, cleanSecondaryView, emptyViewConfig, PIVOT_PATH, PIVOT_WINDOW_LABELS,
183
- pivotRefusalFromBody, pivotResponse, relationalTargets } from "./types";
184
  import type {
185
  DisplayMode,
186
  DisplaySpec,
@@ -190,12 +188,10 @@ import type {
190
  FieldType,
191
  FilterNode,
192
  FilterRule,
193
- PivotRefusal,
194
  PivotResponse,
195
  PivotWindow,
196
  Row,
197
  RowHeightMode,
198
- RollupCondition,
199
  SavedView,
200
  ViewConfig,
201
  } from "./types";
@@ -447,21 +443,10 @@ function sameConfig(a: ViewConfig, b: ViewConfig): boolean {
447
  * and it renders a sentence rather than a grid. Collapsing it into `ok` with zero rows would
448
  * put "no related records" on screen as the answer to a question nobody has asked yet.
449
  */
450
- /**
451
- * ⭐⭐ W42-T09 — **`refused` IS THE FIFTH STATE, AND IT IS THE ONE THAT WAS MISSING.** A non-2xx
452
- * answer used to land in `absent` beside "the endpoint is not there", so a server that had
453
- * walled the reader out, refused the route, or found more related records than one answer can
454
- * carry printed the words *not available yet* — half of why D-484 read as "nothing works". The
455
- * server authored a reason every time; nothing read it.
456
- *
457
- * ⚠ It carries the SAME `PivotRefusal` a 200-with-a-refusal carries, so both arrive at one
458
- * renderer and there is one sentence about walls on this surface rather than two.
459
- */
460
  type PivotState =
461
  | { status: "idle" }
462
  | { status: "loading" }
463
  | { status: "absent" }
464
- | { status: "refused"; refusal: PivotRefusal }
465
  | { status: "ok"; answer: PivotResponse };
466
 
467
  /**
@@ -639,265 +624,6 @@ function withColorField(config: ViewConfig, key: string): ViewConfig {
639
  return { ...config, colorBy: key || null, display: cleanDisplay(display) };
640
  }
641
 
642
- /**
643
- * ⭐⭐ W42-T11 — THE ONE RECONCILER FOR COLUMNS THAT NO LONGER EXIST, AND IT TAKES A SET.
644
- *
645
- * Every delete on this surface has to scrub the same six members of the view config against the
646
- * key it just removed: `order`, `visible`, `widths`, `sorts`, `groupBy` and `colorBy`. Three
647
- * handlers below (`deleteField`, `deleteRouteField`, `deleteDefinitionField`) each spelled that
648
- * scrub out by hand, and a bulk delete needed a fourth copy — except a bulk delete cannot be
649
- * three copies run in a loop, because each rebuilds `config` from the SAME closed-over snapshot
650
- * and only the last survives. So the scrub becomes a pure function over a SET of removed keys,
651
- * and the plural act performs exactly ONE config write.
652
- *
653
- * ⛔ `groupBy` AND `colorBy` ARE SCALARS, AND NULL IS THE ONLY CORRECT ANSWER FOR THEM. The other
654
- * four are collections you filter; these two each name ONE column, and when that column goes the
655
- * view is grouped by nothing and coloured by nothing. Left dangling, `useVisibleRows::groupRows`
656
- * reads `r[groupBy]` as `undefined` on every row and pours the whole table into a single
657
- * "(empty)" bucket while the toolbar chip reads `Group: ?` — a config fault wearing the costume
658
- * of a data fault. `""` is not the answer either: the rest of this file tests `!config.groupBy`
659
- * and `config.colorBy` for truthiness, and an empty string only passes those by accident.
660
- *
661
- * ⛔ AND THE COLOUR IS TWO KEYS, NOT ONE. `withColorField` above is the ONE writer of a colour
662
- * choice precisely because two renderers read it — `config.colorBy` washes the grid rows and
663
- * `config.display.colorField` colours the map pins. A reconciler that nulled only the first
664
- * would leave the map painting by a column nobody can see, which is the same half-written state
665
- * that function exists to prevent. Both go, in this one call.
666
- *
667
- * ⚠ PURE, AND IT RETURNS THE ORIGINAL WHEN NOTHING WAS REMOVED. `viewEcho` compares whole config
668
- * objects, so manufacturing a new identity for a no-op delete would bill an autosave for nothing.
669
- */
670
- export function configWithoutFields(
671
- config: ViewConfig,
672
- removed: readonly string[]
673
- ): ViewConfig {
674
- const gone = new Set(removed.filter((key) => typeof key === "string" && key !== ""));
675
- if (gone.size === 0) return config;
676
- const widths = { ...(config.widths ?? {}) };
677
- for (const key of gone) delete widths[key];
678
- const next: ViewConfig = {
679
- ...config,
680
- order: (config.order ?? []).filter((key) => !gone.has(key)),
681
- visible: (config.visible ?? []).filter((key) => !gone.has(key)),
682
- widths,
683
- sorts: (config.sorts ?? []).filter((sort) => !gone.has(sort.colId)),
684
- groupBy: config.groupBy && gone.has(config.groupBy) ? null : config.groupBy,
685
- colorBy: config.colorBy && gone.has(config.colorBy) ? null : config.colorBy,
686
- };
687
- const spec = next.display;
688
- if (spec?.colorField && gone.has(spec.colorField)) {
689
- const display: DisplaySpec = { ...spec };
690
- delete display.colorField;
691
- next.display = cleanDisplay(display);
692
- }
693
- return next;
694
- }
695
-
696
- /**
697
- * ⭐⭐ W42-T11 — WHICH DOOR DELETES THIS COLUMN, ASKED ONCE.
698
- *
699
- * The column menu's `onDelete` already dispatches three strata, spelled inline across sixty lines
700
- * of prose. A bulk delete has to ask the SAME question of every key it was handed, and a second
701
- * copy of that test is how the two surfaces stop agreeing about what is deletable. So the test
702
- * moves here, pure and exported, and the menu's own branches keep their sentences.
703
- *
704
- * ⛔ `null` IS AN ANSWER AND IT MEANS "NO DOOR", not "try the nearest one". `deleteField`'s guard
705
- * (`if (!f?.custom …) return;`) makes a wrong guess look exactly like a successful delete that
706
- * paints nothing, which is the failure this ticket exists to close.
707
- */
708
- export type FieldDeleteDoor = "overlay" | "definition" | "route";
709
-
710
- export function fieldDeleteDoor(
711
- field: Field | undefined,
712
- opts: { isUserTable: boolean; lockedKey: string }
713
- ): FieldDeleteDoor | null {
714
- if (!field || field.key === opts.lockedKey) return null;
715
- if (field.custom && !field.shared) return "overlay";
716
- if (
717
- opts.isUserTable && !field.custom &&
718
- (field.type === "link" || field.type === "rollup" || field.type === "formula")
719
- ) return "definition";
720
- if (field.shared && field.kind === "route_order") return "route";
721
- return null;
722
- }
723
-
724
- /**
725
- * The five doors `filter-kit/FieldsHidePanel.tsx` needs a HOST to supply, built in one place.
726
- *
727
- * ⛔⛔ THE PANEL DOES NOT LOOP, AND NEITHER DOES ANY HANDLER BELOW. `runBulk` collects the fields
728
- * that passed contract C2's rights test into one `passed` array and fires ONE plural call per
729
- * act, because every per-key host handler on this surface rewrites the view config from a
730
- * closed-over snapshot: N of them in a tick all rebuild the SAME config and only the last write
731
- * survives. What that forbids is looping the HANDLER, and since W42-T58 (contract C4) the REQUEST
732
- * is not looped either: `deleteTableFields` posts every key to the plural door in one call and
733
- * hands back a per key verdict, and this hook then performs exactly ONE `updateConfig`. The per
734
- * key door it used to walk is still the only door a SINGLE column delete elsewhere in this file
735
- * has, and that is a call, not a loop.
736
- *
737
- * ⛔ A KEY THE SERVER REFUSED IS NOT RECONCILED OUT. Scrubbing it from `order` and `visible`
738
- * would take the column off the screen while it still exists in the store, so the refusal would
739
- * read as a success until the next workspace fetch put the column back.
740
- *
741
- * Share, reassign, and self-removal deliberately have no bulk door here. The first two APIs are
742
- * per field and require a person picker; the last has no safe server operation for a grantee.
743
- * Passing a toast callback would render a button that does not perform its named action, so the
744
- * Toolbar receives `null` for all three until their real contracts exist.
745
- */
746
- export interface FieldBulkDoorDeps {
747
- config: ViewConfig;
748
- updateConfig: (next: ViewConfig) => void;
749
- /** The RECONCILED sequence and set, which is what every delete on this surface writes back. */
750
- order: string[];
751
- visible: Set<string>;
752
- lockedKey: string;
753
- fieldByKey: Map<string, Field>;
754
- isUserTable: boolean;
755
- scope: string;
756
- rowsPath: string;
757
- setFields: (update: (current: Field[]) => Field[]) => void;
758
- stampFieldDelete: (key: string) => void;
759
- }
760
-
761
- export interface FieldBulkDoors {
762
- onSetFieldsHidden: (keys: string[], hidden: boolean) => void;
763
- onDeleteFields: (keys: string[]) => void;
764
- }
765
-
766
- /**
767
- * ⭐⭐ W42-T58 (contract C4) — THE SERVER'S OWN SENTENCE, ABOUT THE COLUMN IT IS ACTUALLY ABOUT.
768
- *
769
- * ⛔ D-485, WHICH THIS LANE ALREADY FOUGHT IN T12: widening a return type and leaving nothing
770
- * reading it is a control that degrades to nothing. C4 answers the plural delete door with a
771
- * status, a code and a reason PER KEY, and this is the thing that reads them. Before it, the
772
- * refusal was raised from inside the per key request, one toast per key, several of them racing
773
- * into one slot with nothing naming which column each sentence belonged to.
774
- *
775
- * ⚠ THE MACHINE CODE STAYS OFF THE SCREEN. It is carried on the type for a caller that wants to
776
- * branch on it; pasted into a sentence it is not an explanation to the person reading it. And a
777
- * refusal with no sentence at all still says so out loud, because a control that silently leaves
778
- * a column alone is the failure this whole surface was rewired to end.
779
- */
780
- function reportFieldDeleteRefusals(
781
- results: readonly FieldDeleteResult[],
782
- fieldByKey: Map<string, Field>
783
- ): void {
784
- const refused = results.filter((r) => r.status === "refused");
785
- if (refused.length === 0) return;
786
- const explained = refused.find((r) => typeof r.reason === "string" && r.reason.trim().length > 0);
787
- if (!explained) {
788
- signal(TOAST_EVENT, refused.length === 1
789
- ? "That column was left alone, and the server gave no reason."
790
- : `${refused.length} of those columns were left alone, and the server gave no reason.`);
791
- return;
792
- }
793
- const label = fieldByKey.get(explained.key)?.label ?? explained.key;
794
- signal(TOAST_EVENT, refused.length === 1
795
- ? `${label} was left alone. ${explained.reason}`
796
- : `${refused.length} of those columns were left alone. ${label}: ${explained.reason}`);
797
- }
798
-
799
- export function useFieldBulkDoors(deps: FieldBulkDoorDeps): FieldBulkDoors {
800
- const { config, updateConfig, order, visible, lockedKey, fieldByKey, isUserTable, scope,
801
- rowsPath, setFields, stampFieldDelete } = deps;
802
-
803
- /**
804
- * ⛔ AN ABSOLUTE SET, NOT A DELTA, because that is what the primitive underneath takes:
805
- * `onColumnsVisible` is called as `onColumnsVisible(fields.map(f => f.key))` for Show all and
806
- * `onColumnsVisible([lockedKey])` for Hide all. Handing it the keys being hidden would hide
807
- * everything else instead.
808
- * ⚠ THE LOCKED COLUMN NEVER LEAVES. `useGridColumns::setColumnVisible` already refuses to hide
809
- * it one key at a time; a plural door that forgot would hide the row identity of the grid.
810
- */
811
- const onSetFieldsHidden = useCallback(
812
- (keys: string[], hidden: boolean) => {
813
- const next = new Set(visible);
814
- for (const key of keys) {
815
- if (hidden) {
816
- if (key !== lockedKey) next.delete(key);
817
- } else {
818
- next.add(key);
819
- }
820
- }
821
- updateConfig({ ...config, visible: [...new Set([lockedKey, ...next])] });
822
- },
823
- [config, lockedKey, updateConfig, visible]
824
- );
825
-
826
- const onDeleteFields = useCallback(
827
- (keys: string[]) => {
828
- const overlay: string[] = [];
829
- const definition: string[] = [];
830
- const route: string[] = [];
831
- const noDoor: string[] = [];
832
- for (const key of keys) {
833
- const door = fieldDeleteDoor(fieldByKey.get(key), { isUserTable, lockedKey });
834
- if (door === "overlay") overlay.push(key);
835
- else if (door === "definition") definition.push(key);
836
- else if (door === "route") route.push(key);
837
- else noDoor.push(key);
838
- }
839
- void (async () => {
840
- const gone = [...overlay];
841
- let touchedServer = false;
842
- let unreadableAnswer = false;
843
- if (definition.length > 0) {
844
- const outcome = await deleteTableFields(scope, definition);
845
- gone.push(...outcome.deleted);
846
- touchedServer = touchedServer || outcome.deleted.length > 0;
847
- unreadableAnswer = unreadableAnswer || outcome.unreadable;
848
- reportFieldDeleteRefusals(outcome.results, fieldByKey);
849
- }
850
- for (const key of route) {
851
- // ⚠ SEQUENTIAL, AND THIS DOOR STATES ITS OWN REASON NOW (W42-T58 took the plural
852
- // delete off the per key door, so there is no longer a shared note to point at):
853
- // `deleteRouteOrderField` raises the server's refusal itself, one toast per key, and
854
- // fired in parallel several of them race into one slot.
855
- // eslint-disable-next-line no-await-in-loop
856
- const ok = await deleteRouteOrderField(key);
857
- if (ok) {
858
- gone.push(key);
859
- touchedServer = true;
860
- }
861
- }
862
- if (noDoor.length > 0) {
863
- signal(TOAST_EVENT,
864
- noDoor.length === 1
865
- ? "One of those columns cannot be deleted here, so it was left alone."
866
- : `${noDoor.length} of those columns cannot be deleted here, so they were left alone.`);
867
- }
868
- if (gone.length > 0) {
869
- const goneSet = new Set(gone);
870
- setFields((current) => current.filter((item) => !goneSet.has(item.key)));
871
- // ⛔ ONE CONFIG WRITE FOR THE WHOLE ACT. This is the line the panel's JSDoc protects,
872
- // and it is written over the keys that ACTUALLY WENT, never over the keys asked for.
873
- updateConfig(configWithoutFields({ ...config, order, visible: [...visible] }, gone));
874
- for (const key of overlay) {
875
- stampFieldDelete(key);
876
- emitHostEvent({ id: eventId("fielddel"), type: "field_delete", key });
877
- }
878
- }
879
- if (touchedServer || unreadableAnswer) {
880
- // The values went with the definitions, so the rows are a beat stale as well as the
881
- // schema — the same pair every singular definition delete signals.
882
- // ⚠ THE SECOND TERM IS THE ANSWER NOBODY COULD READ (C4). The view is left exactly as
883
- // it is, nothing above reconciled, and the truth is FETCHED rather than guessed at.
884
- // Without it the person is told the table is being read again and nothing reads it.
885
- clearTopicRowsCache(rowsPath);
886
- signal(WORKSPACE_STALE_EVENT);
887
- signal(ROWS_STALE_EVENT);
888
- }
889
- })();
890
- },
891
- [config, fieldByKey, isUserTable, lockedKey, order, rowsPath, scope, setFields,
892
- stampFieldDelete, updateConfig, visible]
893
- );
894
-
895
- return useMemo(
896
- () => ({ onSetFieldsHidden, onDeleteFields }),
897
- [onDeleteFields, onSetFieldsHidden]
898
- );
899
- }
900
-
901
  function readLocal(storageKey: string): LocalWorkspace | null {
902
  try {
903
  const raw = localStorage.getItem(`aios-grid:${storageKey}`);
@@ -1203,73 +929,20 @@ interface CustomerGridProps {
1203
  embeddedSelectable?: boolean;
1204
  embeddedSelectedIds?: readonly number[];
1205
  onEmbeddedSelectionChange?: (recordIds: number[]) => void;
1206
- /** W42-T29 — the SOURCE record, withheld from its own candidate list so a record cannot be
1207
- * offered as a link to itself. Applied on top of any projection above. */
1208
- embeddedExcludeRecordId?: number;
1209
- /** W42-T35 — static conditions narrow candidates only; saved links are never rewritten. */
1210
- embeddedLinkConditions?: readonly RollupCondition[];
1211
- embeddedLinkConditionConj?: "and" | "or";
1212
- }
1213
-
1214
- /**
1215
- * ⭐⭐ W42-T29 — WHICH TABLES A LINK COLUMN MAY POINT AT, mirroring the server's own predicate
1216
- * `core.user_tables.is_linkable_target` rather than guessing a second time.
1217
- *
1218
- * ⛔ THE CLIENT HAD ONE HALF OF IT. Every door into the linked-record picker tested the `ut_`
1219
- * prefix alone, so once the server learned to accept the two registry databases the client
1220
- * refused to open the picker for them at all: no chips, no typing, no candidate list, and no
1221
- * error either, because a click gate that falls through simply does nothing.
1222
- *
1223
- * ⛔ TWO NAMESPACES, ONE PREDICATE, and both halves are strict. A user database must reach
1224
- * BEYOND the prefix, so the bare three characters are not a table and never were. The module
1225
- * half is EXACT MEMBERSHIP, never a prefix test, which is what keeps it an allowlist rather
1226
- * than a hole a lookalike key can walk through.
1227
- */
1228
- const LINKABLE_MODULE_KEYS = ["customer_data", "product_data"] as const;
1229
-
1230
- export function isLinkableTarget(table: unknown): boolean {
1231
- if (typeof table !== "string") return false;
1232
- if (table.startsWith("ut_") && table.length > 3) return true;
1233
- return (LINKABLE_MODULE_KEYS as readonly string[]).includes(table);
1234
  }
1235
 
1236
- /**
1237
- * The SURFACE the picker mounts for an eligible link target.
1238
- *
1239
- * ⚠ A TARGET KEY IS NOT A SCOPE, and conflating them is how this half breaks silently: the
1240
- * registry names the two module databases with the `_data` suffix, while the renderer's scopes
1241
- * are the bare topic words. `topicForScope` falls back to the customer topic for anything it
1242
- * does not recognise, so an unmapped key opens a fully populated picker over the WRONG table.
1243
- * Unresolvable targets get `undefined`, which is the signal not to open anything.
1244
- */
1245
- export function scopeForLinkTable(table: unknown): SurfaceScope | undefined {
1246
- if (!isLinkableTarget(table)) return undefined;
1247
- if (table === "customer_data") return "customer";
1248
- if (table === "product_data") return "product";
1249
- return table as `ut_${string}`;
1250
- }
1251
-
1252
- /**
1253
- * W42-T35 — Link conditions deliberately use the server's Rollup vocabulary while the grid
1254
- * evaluator speaks the view vocabulary. This is the sole adapter: a picker condition is static,
1255
- * flat and has no rank, view, cohort or dynamic-field arm.
1256
- */
1257
  interface LinkGridModalProps {
1258
  label: string;
1259
  table: SurfaceScope;
1260
  recordIds: readonly number[];
1261
- conditions?: readonly RollupCondition[];
1262
- conditionConj?: "and" | "or";
1263
  editable?: boolean;
1264
  single?: boolean;
1265
- /** The source record, when this picker draws the source record's OWN database. */
1266
- excludeRecordId?: number;
1267
  onSave?: (recordIds: number[]) => void;
1268
  onClose: () => void;
1269
  }
1270
 
1271
- function LinkGridModal({ label, table, recordIds, conditions = [], conditionConj = "and",
1272
- editable = false, single = false, excludeRecordId, onSave, onClose }: LinkGridModalProps) {
1273
  const panelRef = useRef<HTMLDivElement>(null);
1274
  const [selectedIds, setSelectedIds] = useState<number[]>(() => [...recordIds]);
1275
  const changeSelectedIds = useCallback((ids: number[]) => {
@@ -1317,20 +990,10 @@ function LinkGridModal({ label, table, recordIds, conditions = [], conditionConj
1317
  </button>
1318
  </header>
1319
  <div className="cg-link-grid-body">
1320
- {/* ⛔ W42-T29 — the candidate list is every row of the target database, and when the
1321
- target IS this record's own database that list contained the record itself, so a
1322
- record could be linked to itself. The source is withheld only while the picker is
1323
- EDITABLE: a read-only mount is showing links that already exist, and hiding one
1324
- there would hide data rather than refuse an act. A self-link already stored
1325
- survives either way, because the selection is carried by pid and is not rebuilt
1326
- from the rows on screen. */}
1327
  <CustomerGrid
1328
  scope={table}
1329
  embedded
1330
  embeddedRecordIds={editable ? undefined : recordIds}
1331
- embeddedExcludeRecordId={editable ? excludeRecordId : undefined}
1332
- embeddedLinkConditions={editable ? conditions : undefined}
1333
- embeddedLinkConditionConj={conditionConj}
1334
  embeddedSelectable={editable}
1335
  embeddedSelectedIds={selectedIds}
1336
  onEmbeddedSelectionChange={changeSelectedIds}
@@ -1407,9 +1070,6 @@ function CustomerGridSurface({
1407
  embeddedSelectable = false,
1408
  embeddedSelectedIds = [],
1409
  onEmbeddedSelectionChange,
1410
- embeddedExcludeRecordId,
1411
- embeddedLinkConditions = [],
1412
- embeddedLinkConditionConj = "and",
1413
  }: CustomerGridProps = {}) {
1414
  const isQueryPreview = queryBinding !== undefined;
1415
  /**
@@ -1476,20 +1136,16 @@ function CustomerGridSurface({
1476
  */
1477
  const [pendingRows, setPendingRows] = useState<Row[]>([]);
1478
  const rawRows = useMemo(() => {
1479
- const projected = embeddedRecordIds
1480
  ? fetchedRows.filter((row) => new Set(embeddedRecordIds).has(row.pid))
1481
  : fetchedRows;
1482
- // W42-T29 — the source record is not a candidate for its own link column.
1483
- const base = embeddedExcludeRecordId
1484
- ? projected.filter((row) => row.pid !== embeddedExcludeRecordId)
1485
- : projected;
1486
  if (!pendingRows.length) return base;
1487
  const known = new Set(base.map((r) => r.pid));
1488
  const extra = pendingRows.filter((r) => !known.has(r.pid));
1489
  return extra.length ? [...base, ...extra] : base;
1490
  // The scalar key keeps this stable when a caller reconstructs the same id list.
1491
  // eslint-disable-next-line react-hooks/exhaustive-deps
1492
- }, [fetchedRows, embeddedIdsKey, embeddedExcludeRecordId, pendingRows]);
1493
  useEffect(() => {
1494
  // ⚠ PRUNED AGAINST THE FETCHED PAYLOAD, not against `rawRows` — `rawRows` contains the
1495
  // pending rows, so it can never report that one has been absorbed. Pruning against the
@@ -1634,6 +1290,7 @@ function CustomerGridSurface({
1634
  >(null);
1635
  const [detailPid, setDetailPid] = useState<number | null>(null);
1636
  const [columnMenu, setColumnMenu] = useState<ColumnMenuState | null>(null);
 
1637
  /** Open choice list for a `select` / `user` cell — see onCellClicked. */
1638
  const [picker, setPicker] = useState<{
1639
  pid: number;
@@ -1652,6 +1309,12 @@ function CustomerGridSurface({
1652
  */
1653
  seed?: string;
1654
  } | null>(null);
 
 
 
 
 
 
1655
  /** W40-T23 — what is typed in the picker's find box. Seeded by the keystroke that opened it
1656
  * (see `seed`), reset by every open and by `closePicker`, so a picker never inherits the
1657
  * previous one's query. */
@@ -1690,6 +1353,11 @@ function CustomerGridSurface({
1690
  /** Owner item 9 (wave 20) — its counterpart: "Remove from cohort…", in ORDINARY views. */
1691
  const [selRemoveOpen, setSelRemoveOpen] = useState(false);
1692
  const selRemoveRef = useRef<HTMLButtonElement>(null);
 
 
 
 
 
1693
  /** Owner item 4 / C-ADDROW — the pid the trailing "+" just created, so the cursor can land on
1694
  * it once the re-read actually brings it back (the row does not exist locally before that). */
1695
  const [newRowPid, setNewRowPid] = useState<number | null>(null);
@@ -1807,19 +1475,6 @@ function CustomerGridSurface({
1807
  ? `query:${queryBinding.workspaceBinding.key}`
1808
  : payload?.workspace?.storageKey ?? `${LOCAL_KEY_PREFIX}${scope}`;
1809
 
1810
- /** The field-share route speaks this durable surface key, never a browser cache key. */
1811
- const fieldGrantTableKey = isQueryPreview
1812
- ? null
1813
- : scope === "product"
1814
- ? "product_data"
1815
- : scope.startsWith("ut_")
1816
- ? scope
1817
- : "customer_data";
1818
- const [fieldBatchAccess, setFieldBatchAccess] = useState<{
1819
- action: FieldBatchAccessAction;
1820
- keys: string[];
1821
- } | null>(null);
1822
-
1823
  // Initialize once per permission/data scope. Host state wins; local state
1824
  // fills only missing objects and keeps the standalone path useful.
1825
  useEffect(() => {
@@ -2162,6 +1817,14 @@ function CustomerGridSurface({
2162
  },
2163
  [config.groupBy, isQueryPreview, queryBinding]
2164
  );
 
 
 
 
 
 
 
 
2165
 
2166
  const {
2167
  visibleCols,
@@ -2254,71 +1917,6 @@ function CustomerGridSurface({
2254
  const isUserTable = !embedded && scope.startsWith("ut_");
2255
  const recordsMutable = payload?.recordsMutable !== false;
2256
  const canMutateRecords = isUserTable && recordsMutable;
2257
- const batchAccessFields = useMemo(
2258
- () => (fieldBatchAccess?.keys ?? [])
2259
- .map((key) => fieldByKey.get(key))
2260
- .filter((field): field is Field => !!field)
2261
- .map((field) => ({ key: field.key, label: field.label })),
2262
- [fieldBatchAccess, fieldByKey]
2263
- );
2264
- const openFieldBatchAccess = useCallback((action: FieldBatchAccessAction, keys: string[]) => {
2265
- if (!fieldGrantTableKey) {
2266
- signal(TOAST_EVENT, "Field access is unavailable on this preview.");
2267
- return;
2268
- }
2269
- setFieldBatchAccess({ action, keys: [...new Set(keys)] });
2270
- }, [fieldGrantTableKey]);
2271
- const removeFieldFromMine = useCallback((field: Field) => {
2272
- if (!fieldGrantTableKey) return;
2273
- void (async () => {
2274
- const path = `${API_V1}/share/field/${encodeURIComponent(`${fieldGrantTableKey}:${field.key}`)}/mine`;
2275
- const res = await fetch(path, { method: "DELETE", credentials: CREDENTIALS }).catch(() => null);
2276
- if (!res) {
2277
- signal(TOAST_EVENT, "Cannot reach the server.");
2278
- return;
2279
- }
2280
- if (!res.ok) {
2281
- const body = (await res.json().catch(() => null)) as { error?: { message?: unknown } } | null;
2282
- const message = body?.error?.message;
2283
- signal(TOAST_EVENT, typeof message === "string" && message.trim()
2284
- ? message.trim()
2285
- : `The server answered ${res.status}.`);
2286
- return;
2287
- }
2288
- setFields((current) => current.filter((item) => item.key !== field.key));
2289
- updateConfig(configWithoutFields({ ...config, order, visible: [...visible] }, [field.key]));
2290
- clearTopicRowsCache(topic.rowsPath);
2291
- signal(WORKSPACE_STALE_EVENT);
2292
- signal(ROWS_STALE_EVENT);
2293
- signal(TOAST_EVENT, `${field.label} was removed from your fields.`);
2294
- })();
2295
- }, [config, fieldGrantTableKey, order, setFields, topic.rowsPath, updateConfig, visible]);
2296
- /**
2297
- * ⭐⭐ W42-T12 (D-485, amendment A20) — THE FIELD MANAGER'S FIVE DOORS, CALLED AT LAST.
2298
- *
2299
- * W42-T11 built and exported `useFieldBulkDoors` and stopped at the fence: the hook existed,
2300
- * nothing called it, and every bulk act in the Fields manager was a silent no-op. This call is
2301
- * the other half. Each door batches its whole selection into ONE config write, which is why
2302
- * none of them may be assembled at the toolbar out of the per-key props beside them — N calls
2303
- * to a per-key handler in one tick all rebuild from the same closed-over snapshot and only the
2304
- * last survives (see `FieldBulkDoors`' own note upstream).
2305
- *
2306
- * ⚠ IT SITS HERE, ABOVE the pivot and the main mount, because a hook may not be called
2307
- * conditionally and both `<Toolbar>` mounts render below.
2308
- */
2309
- const fieldBulkDoors = useFieldBulkDoors({
2310
- config,
2311
- updateConfig,
2312
- order,
2313
- visible,
2314
- lockedKey,
2315
- fieldByKey,
2316
- isUserTable,
2317
- scope,
2318
- rowsPath: topic.rowsPath,
2319
- setFields,
2320
- stampFieldDelete,
2321
- });
2322
  /**
2323
  * ⭐ 2026-08-07 — the databases a `link` column may point at, fetched when the column menu
2324
  * OPENS rather than on every render of the grid.
@@ -2392,61 +1990,6 @@ function CustomerGridSurface({
2392
  * carrying these same cells, or the row it paints locally fails the filter it was added under
2393
  * and disappears on the next read — the exact blip C2 exists to prevent.
2394
  */
2395
- /**
2396
- * ⭐⭐ W42-T09 (R1, contract C2) — THE HOP'S OPERAND LIST, FETCHED ONCE PER GRID.
2397
- *
2398
- * `GET /grid/hop-topics` hands back the governed topics a Link column's two-hop join may travel
2399
- * THROUGH, each carrying its dimensions already shaped as `Field[]` (`source: "topic"`) so the
2400
- * link editor can hand them straight to the condition builder as its `fields` prop. That is the
2401
- * entire reason this endpoint exists beside `/tables/rollup-sources`, whose `dims` are the bare
2402
- * `{key, label, keyedBy}` shape: deriving a `type` from `keyedBy` would produce a plausible
2403
- * operand list with the WRONG OPERATORS, which is worse than no list at all.
2404
- *
2405
- * ⛔⛔ THE SERVER HALF IS NOT IN THIS WORKTREE, AND AN EMPTY LIST IS THE CORRECT ANSWER TO
2406
- * THAT. A 404 here leaves `hopTopics` empty, the editor renders the Through question and says
2407
- * it has nothing to offer, and no `via` can be authored — which is exactly today's one-hop
2408
- * behaviour. Nothing is stubbed and nothing throws: a client that crashed on an unbuilt
2409
- * endpoint would take the whole column menu down with it.
2410
- *
2411
- * ⚠ THE GUARD IS AN `asked` REF, NOT `topics.length`, and gates on BOTH DOORS. Both reasons are
2412
- * the rollup offer's above, learned the hard way twice in this file: an empty offer is a common
2413
- * and correct answer, so a length guard re-asks on every menu open for exactly the workspaces
2414
- * where the answer can never change; and a fetch gated on `columnMenu` alone leaves the "+"
2415
- * create menu with an empty list while its twin is full.
2416
- */
2417
- const [hopTopics, setHopTopics] = useState<HopTopic[]>([]);
2418
- const hopTopicsAsked = useRef(false);
2419
- useEffect(() => {
2420
- if ((!columnMenu && !plusMenu) || hopTopicsAsked.current) return;
2421
- hopTopicsAsked.current = true;
2422
- let live = true;
2423
- (async () => {
2424
- try {
2425
- const res = await fetch(`${API_V1}/grid/hop-topics`, { credentials: CREDENTIALS });
2426
- if (!live || !res.ok) return;
2427
- const body = (await res.json().catch(() => null)) as { topics?: unknown } | null;
2428
- if (!live || !Array.isArray(body?.topics)) return;
2429
- /* ⚠ SHAPE-CHECKED, NOT TRUSTED. `key` and `label` are what the editor renders and `dims`
2430
- is what it filters by; a topic missing any of them would draw a nameless row that
2431
- cannot be picked. `measures` is tolerated as absent because a hop may legitimately
2432
- carry none, and the editor already defaults it. */
2433
- const clean = (body!.topics as unknown[]).filter(
2434
- (t): t is HopTopic =>
2435
- !!t && typeof t === "object" &&
2436
- typeof (t as HopTopic).key === "string" && !!(t as HopTopic).key &&
2437
- typeof (t as HopTopic).label === "string" &&
2438
- Array.isArray((t as HopTopic).dims)
2439
- ).map((t) => ({ ...t, measures: Array.isArray(t.measures) ? t.measures : [] }));
2440
- setHopTopics(clean);
2441
- } catch {
2442
- /* An unreachable endpoint and an unbuilt one are the same fact here, and the same
2443
- truthful answer: this database offers no hop today. */
2444
- }
2445
- })();
2446
- return () => {
2447
- live = false;
2448
- };
2449
- }, [columnMenu, plusMenu]);
2450
  const seedValues = useCallback(
2451
  () => filterSeedValues(config.filters, config.filterConj, fields, payload?.viewer),
2452
  [config.filters, config.filterConj, fields, payload?.viewer]
@@ -2627,24 +2170,6 @@ function CustomerGridSurface({
2627
  if (displayMode !== "map") setRoutePanelOpen(false);
2628
  }, [displayMode]);
2629
 
2630
- // W42-T35: the same static Link condition must reach the server when the target table is
2631
- // windowed. Filtering only the loaded page would make matching records outside that page
2632
- // unreachable. Existing selections remain exceptions so a new condition never erases a link.
2633
- const embeddedLinkFilterNodes = useMemo(
2634
- () => linkPickerFilterNodes(embeddedLinkConditions),
2635
- [embeddedLinkConditions]
2636
- );
2637
- const linkPickerFilters = embeddedSelectable && embeddedLinkFilterNodes.length > 0
2638
- ? embeddedLinkFilterNodes
2639
- : config.filters;
2640
- const linkPickerFilterConj = embeddedSelectable && embeddedLinkFilterNodes.length > 0
2641
- ? embeddedLinkConditionConj
2642
- : config.filterConj;
2643
- const embeddedLinkSelectionKey = embeddedSelectedIds.join(",");
2644
- const linkPickerPreservedIds = embeddedSelectable && embeddedLinkFilterNodes.length > 0
2645
- ? embeddedSelectedIds
2646
- : [];
2647
-
2648
  // ═══════════════════════════════════════════════════════════════════════════════════════
2649
  // ⭐⭐ WAVE 30 · W30-T42 (contract C2) — PAGING A READ-THROUGH GRID.
2650
  // ═══════════════════════════════════════════════════════════════════════════════════════
@@ -2656,22 +2181,20 @@ function CustomerGridSurface({
2656
  // question. So the predicate has to reach the evaluator that CAN answer it, which is SQL.
2657
  //
2658
  // ⛔ THE SAVED VIEW'S OWN OBJECTS GO ON THE WIRE, UNTRANSLATED (see `windowRowsPath`).
2659
- const windowPredicate = useMemo(() => {
2660
- const base = windowPredicateKey(linkPickerFilters, linkPickerFilterConj, config.sorts, search);
2661
- return linkPickerPreservedIds.length ? `${base}|link:${embeddedLinkSelectionKey}` : base;
2662
- }, [linkPickerFilters, linkPickerFilterConj, config.sorts, search, linkPickerPreservedIds,
2663
- embeddedLinkSelectionKey]);
2664
  const windowRequest = useCallback(
2665
  (offset: number) => ({
2666
  offset,
2667
  limit: WINDOW_ROWS,
2668
- filters: linkPickerFilters,
2669
- filterConj: linkPickerFilterConj,
2670
  sorts: config.sorts,
2671
  search,
2672
- includePids: linkPickerPreservedIds,
2673
  }),
2674
- [linkPickerFilters, linkPickerFilterConj, config.sorts, search, linkPickerPreservedIds]
2675
  );
2676
  const sentPredicate = useRef<string | null>(null);
2677
  useEffect(() => {
@@ -2832,23 +2355,6 @@ function CustomerGridSurface({
2832
  });
2833
  }, [rawRows, overlayEdits, formulaAsts, createdTimeKeys, payload?.today]);
2834
 
2835
- // W42-T35 — a link filter constrains the records an editor may ADD, not the relationships that
2836
- // already exist. The latter remain in the modal so a new rule cannot erase an older choice.
2837
- const embeddedLinkEligibleIds = useMemo(() => {
2838
- if (!embeddedSelectable || embeddedLinkFilterNodes.length === 0)
2839
- return new Set(computedRows.map((row) => row.pid));
2840
- return new Set(computedRows.filter((row) => matchFilterTree(
2841
- embeddedLinkFilterNodes, embeddedLinkConditionConj, row, fieldByKey, { today, strict: true }
2842
- )).map((row) => row.pid));
2843
- }, [computedRows, embeddedSelectable, embeddedLinkFilterNodes, embeddedLinkConditionConj,
2844
- fieldByKey, today]);
2845
- const linkCandidateRows = useMemo(() => {
2846
- if (!embeddedSelectable || embeddedLinkFilterNodes.length === 0) return computedRows;
2847
- const saved = new Set(embeddedSelectedIds);
2848
- return computedRows.filter((row) => saved.has(row.pid) || embeddedLinkEligibleIds.has(row.pid));
2849
- }, [computedRows, embeddedSelectable, embeddedLinkFilterNodes, embeddedLinkEligibleIds,
2850
- embeddedLinkSelectionKey]);
2851
-
2852
  /**
2853
  * ⭐⭐ W37-T26 / CONTRACT C4 — `view id -> the pids that view resolves to`, for the VIEW
2854
  * MEMBERSHIP leaf (`Where View is [some view]`).
@@ -2946,17 +2452,16 @@ function CustomerGridSurface({
2946
  [activeViewId, views, config, updateConfig]
2947
  );
2948
 
2949
- const unresolvedReasons = useMemo(
2950
  // ⭐ W37-T26 (C4) — `viewSets` rides this context too. Without it a view leaf would ALWAYS
2951
  // count as unresolved (the chip would cry wolf on a working filter) and, worse, a leaf naming
2952
  // a DELETED view would look identical to one naming a live one.
2953
  // ⭐⭐ D-229 — `fieldByKey` rides this context so a condition naming a column this table no
2954
  // longer has is COUNTED. `evalNode` ignores such a leaf (correctly), which means the grid was
2955
  // showing MORE rows than the filter panel claimed with nothing on screen saying so.
2956
- () => unresolvedConditionReasons(config.filters, { cohortSets, viewSets, fieldByKey, today }),
2957
  [config.filters, cohortSets, viewSets, fieldByKey, today]
2958
  );
2959
- const unresolvedCount = unresolvedReasons.length;
2960
 
2961
  // Wave-2 item 2c — COHORT MODE (the Cohort page). The host serves the WHOLE pool (rows +
2962
  // derived values over the pool); the ACTIVE cohort scopes the table to its pids CLIENT-side.
@@ -2980,18 +2485,11 @@ function CustomerGridSurface({
2980
  const scopedRows = useMemo(
2981
  () =>
2982
  cohortMode
2983
- ? linkCandidateRows.filter((r) => cohortMemberSet.has(r.pid))
2984
- : linkCandidateRows,
2985
- [cohortMode, linkCandidateRows, cohortMemberSet]
2986
  );
2987
 
2988
- // W42-T27 — display mode deliberately ignores an unresolved condition so an
2989
- // owner's existing view stays unchanged. A view granted to this reader is a
2990
- // permission boundary instead: an unavailable field must narrow the result,
2991
- // never make the shared view show extra rows.
2992
- const activeViewForPermissions = views.find((view) => view.id === activeViewId);
2993
- const receiverSharedView = activeViewForPermissions?.shared === true;
2994
-
2995
  const { visibleRows, pidToIndex } = useVisibleRows(
2996
  scopedRows,
2997
  fields,
@@ -3013,8 +2511,7 @@ function CustomerGridSurface({
3013
  // wave17 R1 / C-LOCKV: the view's SAVED lock is now the only source. A locked view is a
3014
  // saved view whose `config.cohortLock` names its own id, so opening it IS applying the
3015
  // lock — the wave-15 transient rail pick that used to outrank this is gone with its rail.
3016
- config.cohortLock,
3017
- receiverSharedView
3018
  );
3019
 
3020
  // Owner item 8 — the DISPLAY cap. The pipeline above still ran over the whole book (counts,
@@ -3090,20 +2587,10 @@ function CustomerGridSurface({
3090
  * grouped: subtotals appeared, the table's own total vanished, and nothing said why.
3091
  *
3092
  * ⛔ WHY A SECOND PREDICATE RATHER THAN A WIDER `showTotals`. `showTotals` still answers a
3093
- * NARROWER question that two other call sites need unchanged: the WINDOWED ARM of this very
3094
- * memo, and `foldNote` — the disclosure sentence. Both are about a fabricated aggregate over a
3095
- * partial window, which is a different question from "is a grand-total row appended at all",
3096
- * which is what THIS one answers.
3097
- *
3098
- * ⭐⭐ W42-T17 (D-494, owner ruling R7) — AND THE FROZEN-ROW COUNT READS THIS ONE, NOT
3099
- * `showTotals`. The earlier text here argued that pinning the grand total below the scroll
3100
- * region while group footers scroll past it was "the ungrouped layout, not the grouped one",
3101
- * and left the frozen-row count on `showTotals`. That split is the defect: `showTotals` carries
3102
- * `!config.groupBy`, so under grouping the row was APPENDED by this memo and then not pinned —
3103
- * it existed, it scrolled away with the rows, and it read as missing. R7 reverses the split.
3104
- * The frozen-row count is now this same predicate, so FREEZE ≡ APPEND by construction: exactly
3105
- * one trailing row is frozen whenever exactly one is appended, and zero when none is, which is
3106
- * what stops the last DATA record being pinned on a grid with no totals row.
3107
  *
3108
  * ⛔ THE WINDOWED ARM IS `showTotals` VERBATIM, AND THAT IS THE WHOLE SAFETY ARGUMENT. Over a
3109
  * `server-windowed` table the fold covers the LOADED WINDOW, and `foldNote` — the sentence that
@@ -3349,9 +2836,7 @@ function CustomerGridSurface({
3349
  const displayRows = useMemo(() => {
3350
  const shown = capped ? sliceForDisplay(visibleRows, displayCap) : visibleRows;
3351
  // ⚠ APPENDED AFTER THE SLICE, so the cap can never eat the totals row itself — and it is the
3352
- // LAST row, which is the one glide's frozen-trailing-row count pins.
3353
- // W42-T17 (R7) — that count is passed as `totalsRowShown ? 1 : 0`, i.e. THIS predicate, so a
3354
- // row appended here is always the row pinned there, and a grid with no totals row freezes 0.
3355
  // W41-T40 — `totalsRowShown`, not `showTotals`: a grouped table gets its grand total back,
3356
  // after the last group's footer. Still appended AFTER the slice, so the cap can never eat it.
3357
  return totalsRowShown
@@ -3359,6 +2844,10 @@ function CustomerGridSurface({
3359
  { kind: "group-footer" as const, groupKey: TOTAL_GROUP_KEY, aggs: totalsAggs }]
3360
  : shown;
3361
  }, [capped, visibleRows, displayCap, totalsRowShown, totalsAggs]);
 
 
 
 
3362
  const displayPidToIndex = useMemo(() => {
3363
  if (!capped) return pidToIndex;
3364
  const m = new Map<number, number>();
@@ -3483,7 +2972,7 @@ function CustomerGridSurface({
3483
  embeddedSelectable ? embeddedSelectedIds : [],
3484
  !embedded ? `aios:grid-selection:${scope}` : undefined
3485
  );
3486
- const embeddedSelectedKey = embeddedLinkSelectionKey;
3487
  const selectedPidKey = [...selectedPids].join(",");
3488
  useEffect(() => {
3489
  if (!embeddedSelectable) return;
@@ -3492,13 +2981,8 @@ function CustomerGridSurface({
3492
  }, [embeddedSelectable, embeddedSelectedKey, embeddedSelectedIds, selectedPidKey, selectPids]);
3493
  useEffect(() => {
3494
  if (!embeddedSelectable) return;
3495
- const previous = new Set(embeddedSelectedIds);
3496
- const next = [...selectedPids].filter((pid) =>
3497
- embeddedLinkFilterNodes.length === 0 || embeddedLinkEligibleIds.has(pid) || previous.has(pid)
3498
- );
3499
- onEmbeddedSelectionChange?.(next);
3500
- }, [embeddedSelectable, onEmbeddedSelectionChange, selectedPids, embeddedSelectedIds,
3501
- embeddedLinkFilterNodes, embeddedLinkEligibleIds]);
3502
  /* ════════════════════════ owner item 16 / R4 / C-UNDO ════════════════════════
3503
  THE RECORDING LAYER. `undoStack.ts` owns the stack and every inverse; this owns the one
3504
  thing it cannot: reading the value a cell held BEFORE the write, which only exists at the
@@ -3720,6 +3204,17 @@ function CustomerGridSurface({
3720
  },
3721
  [currentValue, patchOverlay, recordCells]
3722
  );
 
 
 
 
 
 
 
 
 
 
 
3723
 
3724
  /**
3725
  * Apply one stack entry in one direction. The INVERSE lives in `undoStack.directed` — this
@@ -4616,6 +4111,20 @@ function CustomerGridSurface({
4616
  // also where the noreferrer rule that protects every URL cell lives.
4617
  const column = visibleCols[cell[0]];
4618
  const field = column ? fieldByKey.get(column.id!) : undefined;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4619
  // A picked field (select / assignee) opens its choices where the cell is. It cannot use
4620
  // glide's text overlay — a free-text editor on a constrained column is how you end up
4621
  // with "Done", "done" and "DONE" as three different values — and glide's own dropdown
@@ -4648,12 +4157,7 @@ function CustomerGridSurface({
4648
  // The large modal mounts the same Grid surface over exactly these pids, so its standard
4649
  // search, Filters, Sort, Fields, and column menus keep working for every database kind.
4650
  if (row.kind === "data" && field?.type === "link" && field.link?.table) {
4651
- // ⛔ W42-T29 — THE ELIGIBILITY QUESTION IS THE SERVER'S, ASKED THROUGH ONE PREDICATE.
4652
- // The prefix test that stood here answered a narrower question than the store does, so
4653
- // a link pointed at either registry database fell through this branch with no `else`
4654
- // and the cell had no door at all: no picker on a click, and none on a keystroke either,
4655
- // since the cell carries no overlay.
4656
- if (isLinkableTarget(field.link.table)) {
4657
  event.preventDefault();
4658
  setActiveCell(cell[0], cell[1]);
4659
  setLinkAt({ pid: row.record.pid, fieldKey: field.key });
@@ -4769,7 +4273,8 @@ function CustomerGridSurface({
4769
  canEditField(field) &&
4770
  !isPickType(field.type) &&
4771
  field.type !== "rating" &&
4772
- field.type !== "status"
 
4773
  );
4774
  },
4775
  [displayRows, visibleCols, fieldByKey, canEditField]
@@ -4837,17 +4342,31 @@ function CustomerGridSurface({
4837
  // instruction 27) every resizable column is a real one, so `onColumnResize` is handed to the
4838
  // grid unwrapped. The two move guards below are kept as plain bounds checks: they never
4839
  // depended on the virtual column, and they still refuse an out-of-range index.
 
4840
  const onGridColumnMoved = useCallback(
4841
  (from: number, to: number) => {
4842
  if (from >= visibleCols.length || to >= visibleCols.length) return;
 
4843
  onColumnMoved(from, to);
4844
  },
4845
  [onColumnMoved, visibleCols.length]
4846
  );
4847
  const onGridColumnProposeMove = useCallback(
4848
- (from: number, to: number) =>
4849
- from < visibleCols.length && to < visibleCols.length && onColumnProposeMove(from, to),
4850
- [onColumnProposeMove, visibleCols.length]
 
 
 
 
 
 
 
 
 
 
 
 
4851
  );
4852
  const onHeaderClicked = useCallback(
4853
  (column: number, event: HeaderClickedEventArgs) => {
@@ -6492,11 +6011,17 @@ function CustomerGridSurface({
6492
  const f = fieldByKey.get(key);
6493
  if (!f?.custom || key === lockedKey) return;
6494
  setFields((current) => current.filter((item) => item.key !== key));
6495
- // ⭐ W42-T11 — the six-member scrub is `configWithoutFields` now, one copy for all
6496
- // four deletes on this surface, and it drops the map's `display.colorField` too.
6497
- // The RECONCILED `order`/`visible` are handed in, exactly as this line always
6498
- // wrote them back, so a delete still persists the healed column sequence.
6499
- updateConfig(configWithoutFields({ ...config, order, visible: [...visible] }, [key]));
 
 
 
 
 
 
6500
  stampFieldDelete(key);
6501
  emitHostEvent({ id: eventId("fielddel"), type: "field_delete", key });
6502
  },
@@ -6539,11 +6064,17 @@ function CustomerGridSurface({
6539
  void deleteRouteOrderField(key).then((ok) => {
6540
  if (!ok) return; // the bridge has already said why
6541
  setFields((current) => current.filter((item) => item.key !== key));
6542
- // ⭐ W42-T11 — the six-member scrub is `configWithoutFields` now, one copy for all
6543
- // four deletes on this surface, and it drops the map's `display.colorField` too.
6544
- // The RECONCILED `order`/`visible` are handed in, exactly as this line always
6545
- // wrote them back, so a delete still persists the healed column sequence.
6546
- updateConfig(configWithoutFields({ ...config, order, visible: [...visible] }, [key]));
 
 
 
 
 
 
6547
  // ⛔ AND THE ROWS CACHE, for the reason `revealRouteField` states above: the values went
6548
  // with the definition (`shared_overlay.drop_field` scrubs the cells), so a refetch served
6549
  // from the pre-delete window would repaint the numbers of a column that no longer exists.
@@ -6595,11 +6126,17 @@ function CustomerGridSurface({
6595
  void deleteTableField(scope, key).then((ok) => {
6596
  if (!ok) return; // the bridge has already said why
6597
  setFields((current) => current.filter((item) => item.key !== key));
6598
- // ⭐ W42-T11 — the six-member scrub is `configWithoutFields` now, one copy for all
6599
- // four deletes on this surface, and it drops the map's `display.colorField` too.
6600
- // The RECONCILED `order`/`visible` are handed in, exactly as this line always
6601
- // wrote them back, so a delete still persists the healed column sequence.
6602
- updateConfig(configWithoutFields({ ...config, order, visible: [...visible] }, [key]));
 
 
 
 
 
 
6603
  signal(WORKSPACE_STALE_EVENT);
6604
  signal(ROWS_STALE_EVENT);
6605
  });
@@ -7498,15 +7035,7 @@ function CustomerGridSurface({
7498
  });
7499
  if (!live) return;
7500
  if (!res.ok) {
7501
- /* ⛔⛔ W42-T09 — THE BODY IS READ BEFORE ANYTHING IS CONCLUDED FROM THE STATUS. Every
7502
- non-2xx used to collapse to `absent`, which prints "not available yet" — and the
7503
- server had already said which wall it hit (`no_pivot_route`, `pivot_unavailable`,
7504
- `pivot_truncated`, `forbidden`), each with a sentence a reader can act on. Falling
7505
- back to the generic line now means only what it says: the body carried no reason at
7506
- all, so this client has nothing of the server's to quote. */
7507
- const refusal = pivotRefusalFromBody(await res.json().catch(() => null));
7508
- if (!live) return;
7509
- setPivot(refusal ? { status: "refused", refusal } : { status: "absent" });
7510
  return;
7511
  }
7512
  const answer = pivotResponse(await res.json().catch(() => null));
@@ -7536,7 +7065,7 @@ function CustomerGridSurface({
7536
  );
7537
  }
7538
 
7539
- const activeView = activeViewForPermissions;
7540
  // Cohort mode's toolbar control (rendered by Toolbar via the `cohortAction` slot; the popover
7541
  // it opens is with the other overlays at the bottom). Disabled without an active cohort —
7542
  // zero cohorts is the host page's near-empty state, not this button's error to explain.
@@ -7593,6 +7122,17 @@ function CustomerGridSurface({
7593
  // Item 11c — is the menu's field the current frozen boundary (its Pin would be a no-op)?
7594
  const menuVisIndex = menuField ? visibleKeys.indexOf(menuField.key) : -1;
7595
  const menuPinnedTo = menuVisIndex >= 0 && frozenN > 1 && menuVisIndex + 1 === frozenN;
 
 
 
 
 
 
 
 
 
 
 
7596
  // Item 10 — the toolbar's mode switcher (grid-only on windowed tables, see displayMode).
7597
  const modeControl = serverWindowed || embedded || isQueryPreview ? undefined : (
7598
  <ModeSwitch
@@ -7647,18 +7187,17 @@ function CustomerGridSurface({
7647
  ?? (linkField && linkRow ? linkRow[linkField.key] : "")
7648
  ?? ""
7649
  );
7650
- // W42-T29 — the surface the picker will mount, or `undefined` when this column points at
7651
- // something no link may target. One resolution, shared by the render guard and the mount, so
7652
- // the modal cannot open onto a table the predicate did not authorise.
7653
- const linkTargetScope = linkField?.type === "link"
7654
- ? scopeForLinkTable(linkField.link?.table)
7655
- : undefined;
7656
  const linkedRecordIds = [...new Set(
7657
  linkValue.split(",").map((part) => Number(part.trim())).filter(
7658
  (pid) => Number.isInteger(pid) && pid > 0
7659
  )
7660
  )];
7661
  const pickerField = picker ? fieldByKey.get(picker.fieldKey) : undefined;
 
 
 
 
 
7662
  // A `user` field's choices come from the HOST's real user list, a `select`'s from its own
7663
  // definition — so an assignee is always someone who can log in, and a status is always one of
7664
  // the choices the column was created with.
@@ -7683,6 +7222,21 @@ function CustomerGridSurface({
7683
  * choices survive this query" has one definition rather than one per surface.
7684
  */
7685
  const pickerShown = matchChoices(pickerChoices, pickQuery);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7686
  /**
7687
  * ⭐ W40-T23 — WHETHER THE FIND BOX IS THERE: only when a KEYSTROKE opened this picker.
7688
  *
@@ -7704,7 +7258,7 @@ function CustomerGridSurface({
7704
  */
7705
  const pickerSearchOn =
7706
  pickerField?.type !== "rating" &&
7707
- pickerChoices.length > 0 &&
7708
  picker?.seed !== undefined;
7709
  /** Item 6 — which choice receives focus when the picker opens: the current value where it
7710
  * still exists in the list, else the first choice. Keyboard-only editing starts HERE.
@@ -7742,17 +7296,7 @@ function CustomerGridSurface({
7742
 
7743
  const pivotOn = !!secondary;
7744
  const pivotAnswer = pivot.status === "ok" ? pivot.answer : null;
7745
- /**
7746
- * ⭐⭐ W42-T09 — ONE REFUSAL, TWO DOORS INTO IT. A refusal reaches this client either as C10's
7747
- * `refusal` member on a 200 (`_pivot_reply`'s permission walls) or as a non-2xx body the fetch
7748
- * effect above has already turned into the same shape. Both land here, so the renderer below
7749
- * is untouched and there is exactly one sentence about walls on this surface.
7750
- *
7751
- * ⚠ `pivotServed` and `pivotColumnless` are unaffected on purpose: both gate on `pivotAnswer`,
7752
- * which is null in the `refused` state, so neither predicate moves.
7753
- */
7754
- const pivotRefusal =
7755
- pivotAnswer?.refusal ?? (pivot.status === "refused" ? pivot.refusal : null);
7756
  /**
7757
  * ⭐ W41-T43 — THE SAVED PIVOT NAMES A LINK COLUMN THIS READER WAS NOT SERVED. No request went
7758
  * out (`pivotRequestBody` is empty), so `pivot` stays `idle` and every other branch below is
@@ -7879,19 +7423,6 @@ function CustomerGridSurface({
7879
  relational={relationalState}
7880
  onRelational={setPivotVia}
7881
  onRelationalWindow={setPivotWindow}
7882
- /* ⭐⭐ W42-T12 — THE PIVOT ROW STATES `null` FIVE TIMES, AND STATING IT IS THE POINT.
7883
- `fieldBulkDoors` writes THIS view's `config` through `updateConfig`; the row below
7884
- edits `secondary.config` through `setPivotConfig`, so handing it the grid's doors would
7885
- mean a bulk hide on the related table silently rewriting the table you pivoted FROM.
7886
- There is no second bag to hand it, so each act is declared absent — and absent makes the
7887
- control not render at all, which is this panel's house posture. Required keys are what
7888
- force that decision to be written down instead of left out. */
7889
- viewer={viewer}
7890
- onSetFieldsHidden={null}
7891
- onShareFields={null}
7892
- onReassignFields={null}
7893
- onDeleteFields={null}
7894
- onRemoveField={null}
7895
  />
7896
  ) : null;
7897
 
@@ -7910,7 +7441,7 @@ function CustomerGridSurface({
7910
  // Streamlit rerun replaces it. An attribute survives the remount and is one `get_attribute`
7911
  // away from any harness, local or deployed.
7912
  <div
7913
- className="cg-shell"
7914
  data-today={today ?? ""}
7915
  data-measure-rules={measureRuleKeys}
7916
  data-measure-sets={measureSetKeys}
@@ -8269,6 +7800,8 @@ function CustomerGridSurface({
8269
  viewer={viewer}
8270
  onToggleLock={toggleViewLock}
8271
  onToggleImportant={toggleViewImportant}
 
 
8272
  />
8273
  )}
8274
  {/* ⭐⭐ W37-T29 / CONTRACT C6 (rulings R2, R10) — E's CHAT, DOCKED AND OPENABLE.
@@ -8346,21 +7879,16 @@ function CustomerGridSurface({
8346
  if (target && target.shared && target.kind === "route_order") deleteRouteField(key);
8347
  else deleteField(key);
8348
  }}
8349
- viewer={viewer}
8350
- onSetFieldsHidden={fieldBulkDoors.onSetFieldsHidden}
8351
- onShareFields={fieldGrantTableKey
8352
- ? (keys) => openFieldBatchAccess("share", keys)
8353
- : null}
8354
- onReassignFields={fieldGrantTableKey
8355
- ? (keys) => openFieldBatchAccess("reassign", keys)
8356
- : null}
8357
- onDeleteFields={fieldBulkDoors.onDeleteFields}
8358
- onRemoveField={fieldGrantTableKey
8359
- ? (key) => {
8360
- const field = fieldByKey.get(key);
8361
- if (field) removeFieldFromMine(field);
8362
- }
8363
- : null}
8364
  /* ⭐⭐ W38-T07 (owner instruction 12) — THE ONE COLOUR CONTROL. This was `colorOn` plus a
8365
  boolean toggle whose `true` arm guessed the column: `fields.find(type === "status")`,
8366
  so on a table with two status columns the person got the first one and had no way to
@@ -8386,7 +7914,6 @@ function CustomerGridSurface({
8386
  statusValues={statusValues}
8387
  measures={measures}
8388
  unresolvedCount={unresolvedCount}
8389
- unresolvedReasons={unresolvedReasons}
8390
  lists={lists}
8391
  /* ⭐⭐ W37-T26 (C4) — the views this database's conditions may name: every SAVED view
8392
  except the one being edited (a view naming itself is the cycle a person reaches most
@@ -8426,7 +7953,16 @@ function CustomerGridSurface({
8426
  onRelational={setPivotVia}
8427
  onRelationalWindow={setPivotWindow}
8428
  sourceLabel={topic.nouns}
 
8429
  />
 
 
 
 
 
 
 
 
8430
  {/* ⭐ R11's SECOND ROW — live, on the pivoted database. It renders only once the pivot has
8431
  actually been SERVED, which is the house posture for a control whose other half may
8432
  not be wired yet: absent beats present-and-inert. A control row over a database whose
@@ -8467,13 +8003,14 @@ function CustomerGridSurface({
8467
  read as an alert rather than as a label. It now sits under the view's name in the
8468
  rail (ViewSidebar), where it annotates the thing it describes. */}
8469
  <div
8470
- className="cg-grid-box"
8471
  ref={gridBoxRef}
8472
  // Item 19 — THE dismissal. Not glide's out-of-bounds hover: the button sits over the
8473
  // canvas, so reaching for it IS an out-of-bounds event and dismissing there would
8474
  // unmount the control under the arriving pointer. Leaving the whole grid box is the
8475
  // honest "you are done with this row".
8476
  onMouseLeave={() => {
 
8477
  setExpandAt((prev) => (prev === null ? prev : null));
8478
  // W35-T29: the star control is dismissed with the Expand, and it is HOVER-SCOPED —
8479
  // say so rather than implying otherwise. It is how you SET a star, and it shows
@@ -8483,7 +8020,15 @@ function CustomerGridSurface({
8483
  // `getBounds` per visible row on every repaint, for a fact the view already answers.
8484
  setStarHover((prev) => (prev === null ? prev : null));
8485
  }}
 
8486
  >
 
 
 
 
 
 
 
8487
  {secondary ? (
8488
  /* ⭐⭐ W41-T42 — THE PIVOT RENDERS IN PLACE (R11). It stands in the grid's own box, so
8489
  the swap happens where the reader is looking and the two control rows above it stay
@@ -8575,12 +8120,7 @@ function CustomerGridSurface({
8575
  {pivot.status === "absent" && (
8576
  /* ⛔⛔ NOTHING, PLUS ONE LINE. C10's endpoint is W41-T20 and it had not been built
8577
  when this shipped. An absent answer means "not built yet", never "false", and
8578
- never an empty grid.
8579
- ⭐⭐ W42-T09 — AND IT NOW MEANS ONLY THAT. Every non-2xx used to land here, so
8580
- this sentence was also being printed at readers the server had walled out and
8581
- at routes it had refused by name. A body carrying any reason at all is read
8582
- into `refused` above and quoted; this line is what is left when there is
8583
- genuinely nothing of the server's to say. */
8584
  <div className="cg-rel-note" role="status">
8585
  The related view is not available yet, so there is nothing to show.
8586
  </div>
@@ -8674,20 +8214,12 @@ function CustomerGridSurface({
8674
  * ⭐⭐ WAVE-29 T33 (owner item 17) — the totals row is glide's OWN frozen trailing
8675
  * row, which is why it is aligned to every column width for free.
8676
  *
8677
- * ⛔ A CONDITIONAL COUNT, never a bare `1`: with no totals row appended, freezing
8678
  * one trailing row would pin the LAST DATA RECORD to the bottom of the viewport —
8679
  * a record that then appears twice while scrolling, which reads as duplicated data
8680
  * rather than as a layout bug.
8681
- *
8682
- * ⭐⭐ W42-T17 (D-494, ruling R7) — THE CONDITION IS `totalsRowShown`, NOT
8683
- * `showTotals`. `displayRows` appends the grand-total row on `totalsRowShown`;
8684
- * `showTotals` additionally carries `!config.groupBy`. While the two differed, a
8685
- * GROUPED grid painted its grand total and then froze zero rows, so the total
8686
- * scrolled away with the body and read as missing. Reading the same predicate the
8687
- * append reads makes freeze ≡ append: one frozen row exactly when one is appended,
8688
- * zero otherwise, so the ungrouped case is unchanged and no data record is pinned.
8689
  */
8690
- freezeTrailingRows={totalsRowShown ? 1 : 0}
8691
  rowHeight={rowHeight}
8692
  headerHeight={36}
8693
  rowMarkers="both"
@@ -9273,6 +8805,29 @@ function CustomerGridSurface({
9273
  <span className="cg-selbar-count">
9274
  {selectedPids.size.toLocaleString()} selected
9275
  </span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9276
  {/* ⭐ 2026-08-06 (owner) — *"right now it only shows 'Add to cohort'"*. On a user
9277
  database the checked rows are RECORDS the reader owns, and there was no door to
9278
  remove one; the whole delete path existed server-side with nothing calling it.
@@ -9431,26 +8986,6 @@ function CustomerGridSurface({
9431
  state={columnMenu}
9432
  field={menuField}
9433
  fields={fields}
9434
- /**
9435
- * ⭐⭐ W42-T09 (R1, contracts C1 + C2) — THE TWO PROPS THAT LET A LINK COLUMN ASK THE
9436
- * "through what?" QUESTION. Without them T08's hop editor renders and offers nothing,
9437
- * which on screen is indistinguishable from a feature that was never built.
9438
- *
9439
- * ⛔⛔ PASSED AT BOTH `<ColumnMenu>` MOUNTS, and this file's own history is why the
9440
- * rule is written here rather than remembered: the note beside `linkTargets` below
9441
- * records the SAME defect landing twice, where the full column menu had a prop its "+"
9442
- * twin did not and a column created through one door came out different from the other.
9443
- * A hop alive at one door and dead at the other is that defect again.
9444
- *
9445
- * ⛔ `hopScopeKey` IS `scope`, NOT `storageKey`. It is contract C1's `scope_key`: the
9446
- * COHORT scope (`customer`, `product`, a `ut_*` key), which is what a hop's cohort
9447
- * leaves resolve against. `tableKey` is the workspace's storage key
9448
- * (`product_table_workspace`), and stripping a suffix off one to get the other is the
9449
- * near-miss this menu already carries a warning about. A bag missing `scope_key`
9450
- * loses every cohort leaf without a word, so the editor refuses to emit one.
9451
- */
9452
- hopTopics={hopTopics}
9453
- hopScopeKey={scope}
9454
  /**
9455
  * ⭐ 2026-08-10 — SELF-LINKING, and somebody asked for it (owner, D-113).
9456
  *
@@ -9689,14 +9224,20 @@ function CustomerGridSurface({
9689
  }
9690
  : undefined
9691
  }
9692
- onRemoveFromMine={() => {
9693
- removeFieldFromMine(menuField);
9694
- setColumnMenu(null);
9695
- }}
9696
  onDuplicate={
9697
  // Creatable strata only — a base Odoo field offers no Duplicate (contract).
9698
  menuField.custom && !menuField.shared ? () => duplicateField(menuField) : undefined
9699
  }
 
 
 
 
 
 
 
 
 
 
9700
  onFormat={(format) => saveField({ ...menuField, format })}
9701
  /**
9702
  * ⭐ WAVE-29 T33 (owner item 17) — the column summary, through whichever door owns this
@@ -9778,18 +9319,6 @@ function CustomerGridSurface({
9778
  field={fieldByKey.get(lockedKey)!}
9779
  fields={fields}
9780
  locked
9781
- /**
9782
- * ⛔⛔ W42-T37 (D-583) — THE THIRD TIME A PROP LANDED AT ONE OF THESE TWO MOUNTS.
9783
- * This is the "+" CREATE door, so it is the mount where `offerableCreateKind` actually
9784
- * decides anything: without this line the flag defaults to `false`, the picker offers
9785
- * Created time on a `ut_*` database, and `_clean_field` returns `None` for it.
9786
- * ⚠ `web_rollup_editor` is GREEN over that, because its leg reads `ColumnMenu.tsx`
9787
- * alone — a withheld kind proven at the component and never wired at the door is
9788
- * D-485 with a passing gate beside it. The three `PASSED AT BOTH MOUNTS` warnings in
9789
- * this file are about exactly this, and W42-T13's `onRemoveFromMine` was the same
9790
- * shape one ticket earlier.
9791
- */
9792
- isUserTable={isUserTable}
9793
  viewer={viewer}
9794
  sortedDir={null}
9795
  isFiltered={false}
@@ -9800,14 +9329,10 @@ function CustomerGridSurface({
9800
  onNote={() => undefined}
9801
  onHide={() => undefined}
9802
  onCreate={createField}
9803
- /* This create-only mount normally cannot expose the row, but it still receives the
9804
- same real self-removal door as the ordinary menu. Keeping both mounts wired makes
9805
- a future affordance change safe instead of silently inert. */
9806
- onRemoveFromMine={() => {
9807
- const field = fieldByKey.get(lockedKey);
9808
- if (field) removeFieldFromMine(field);
9809
- setPlusMenu(null);
9810
- }}
9811
  geocodable={true}
9812
  onChangeField={() => undefined}
9813
  onCreateAndSwap={() => undefined}
@@ -9835,26 +9360,6 @@ function CustomerGridSurface({
9835
  // either way. See the sibling's note for why self-links are offered now.
9836
  linkTargets={linkTargets}
9837
  rollupSourceOffer={rollupSourceOffer}
9838
- /**
9839
- * ⭐⭐ W42-T09 (R1, contracts C1 + C2) — THE TWO PROPS THAT LET A LINK COLUMN ASK THE
9840
- * "through what?" QUESTION. Without them T08's hop editor renders and offers nothing,
9841
- * which on screen is indistinguishable from a feature that was never built.
9842
- *
9843
- * ⛔⛔ PASSED AT BOTH `<ColumnMenu>` MOUNTS, and this file's own history is why the
9844
- * rule is written here rather than remembered: the note beside `linkTargets` below
9845
- * records the SAME defect landing twice, where the full column menu had a prop its "+"
9846
- * twin did not and a column created through one door came out different from the other.
9847
- * A hop alive at one door and dead at the other is that defect again.
9848
- *
9849
- * ⛔ `hopScopeKey` IS `scope`, NOT `storageKey`. It is contract C1's `scope_key`: the
9850
- * COHORT scope (`customer`, `product`, a `ut_*` key), which is what a hop's cohort
9851
- * leaves resolve against. `tableKey` is the workspace's storage key
9852
- * (`product_table_workspace`), and stripping a suffix off one to get the other is the
9853
- * near-miss this menu already carries a warning about. A bag missing `scope_key`
9854
- * loses every cohort leaf without a word, so the editor refuses to emit one.
9855
- */
9856
- hopTopics={hopTopics}
9857
- hopScopeKey={scope}
9858
  />
9859
  )}
9860
 
@@ -9951,6 +9456,35 @@ function CustomerGridSurface({
9951
  {/* ⭐ Owner item 9 — the remove picker. Every row states how many of the CHECKED rows it
9952
  would take out ("3 of 4"), because the selection and the cohort are two different sets
9953
  and the difference is the whole reason this needs a picker rather than a button. */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9954
  {selRemoveOpen && selRemoveRef.current && removableLists.length > 0 && (
9955
  <AnchoredOverlay
9956
  anchor={selRemoveRef.current}
@@ -10084,30 +9618,13 @@ function CustomerGridSurface({
10084
  onClose={closeJson}
10085
  />
10086
  )}
10087
- {fieldBatchAccess && fieldGrantTableKey && batchAccessFields.length > 0 ? (
10088
- <FieldBatchAccessDialog
10089
- action={fieldBatchAccess.action}
10090
- tableKey={fieldGrantTableKey}
10091
- fields={batchAccessFields}
10092
- onClose={() => setFieldBatchAccess(null)}
10093
- onComplete={(message) => {
10094
- clearTopicRowsCache(topic.rowsPath);
10095
- signal(WORKSPACE_STALE_EVENT);
10096
- signal(ROWS_STALE_EVENT);
10097
- signal(TOAST_EVENT, message);
10098
- }}
10099
- />
10100
- ) : null}
10101
- {linkField && linkTargetScope && linkAt && (
10102
  <LinkGridModal
10103
  label={linkField.label}
10104
- table={linkTargetScope}
10105
  recordIds={linkedRecordIds}
10106
- conditions={linkField.link?.conditions}
10107
- conditionConj={linkField.link?.conditionConj}
10108
  editable={canEditField(linkField) && !isDerivedLink(linkField)}
10109
- single={linkField.link?.single === true}
10110
- excludeRecordId={linkTargetScope === scope ? linkAt.pid : undefined}
10111
  onSave={(ids) => patchAndRecord(
10112
  linkAt.pid,
10113
  { [linkField.key]: ids.join(",") },
@@ -10116,6 +9633,20 @@ function CustomerGridSurface({
10116
  onClose={closeLink}
10117
  />
10118
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10119
  {pickerField && picker && (
10120
  <AnchoredOverlay
10121
  anchor={picker.anchor}
@@ -10146,8 +9677,8 @@ function CustomerGridSurface({
10146
  * `previous.focus()` — a selector that changed per keystroke would throw focus back to
10147
  * the grid and re-grab it on every letter. `pickerSearchOn` is frozen for the life of
10148
  * the picker, and it is the SAME predicate that renders the box, so the selector can
10149
- * never name a control that is not there (a choiceless field seeded by a keystroke
10150
- * would otherwise focus nothing at all).
10151
  */
10152
  initialFocus={pickerSearchOn ? ".cg-pick-search input" : "[data-overlay-autofocus]"}
10153
  onKeyDown={(e) => {
@@ -10219,7 +9750,7 @@ function CustomerGridSurface({
10219
  <div className="cg-pop-note">
10220
  {pickerField.type === "user"
10221
  ? "No assignable people were supplied for this workspace."
10222
- : "This field has no choices yet. Add them from the column menu."}
10223
  </div>
10224
  )}
10225
  {/* ⭐ W40-T23 — the find box, in the house search shape (`.cg-type-search`, the same
@@ -10343,12 +9874,41 @@ function CustomerGridSurface({
10343
  </button>
10344
  );
10345
  })}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10346
  </div>
10347
- {/* ⭐ W40-T23 — a query nothing answers. ONE line, in the slot the "no choices yet"
10348
- note already uses, and no advice about what to try instead: an empty result is a
10349
- fact, not something to apologise for. `pickerSearchOn` already implies the field
10350
- HAS choices, so this can never stand in for the empty-field note above. */}
10351
- {pickerSearchOn && pickerShown.length === 0 && (
10352
  <div className="cg-pop-note">No choice matches.</div>
10353
  )}
10354
  {pickerMulti && (
 
70
  } from "./scriptViews";
71
  import type { ScriptRun, ScriptView as ScriptViewRecord, ScriptViewRow } from "./scriptViews";
72
  import { defaultViewConfig, headerMarksFor, useGridColumns } from "./useGridColumns";
73
+ import { activeMeasureRuleIds, pendingMeasures, runPipeline, sliceForDisplay,
74
+ unresolvedConditions, useVisibleRows } from "./useVisibleRows";
75
  import { computeAggs } from "./aggregations";
76
  import type { CohortSets } from "./useVisibleRows";
77
  import type { MeasureSets } from "./useVisibleRows";
78
  import { useGetCellContent } from "./useGetCellContent";
79
  import { useGridSelection } from "./useGridSelection";
80
  import Toolbar from "./Toolbar";
81
+ import { DatePicker } from "./DatePicker";
82
  import JsonViewer from "./JsonViewer";
83
  import RecordDetail from "./RecordDetail";
84
  import ViewSidebar from "./ViewSidebar";
85
  import ColumnMenu from "./ColumnMenu";
86
+ import type { ColumnMenuState } from "./ColumnMenu";
 
 
87
  import { HEADER_ICONS } from "./iconShapes";
88
  import { emitHostEvent, eventId } from "./hostBridge";
89
  // ⭐ WAVE 27 item 21 (R14) — which of this table's views carry an alert. The SERVER's
 
94
  from "../apiContract";
95
  import type { ViewOpenDetail } from "../apiContract";
96
  import { addTableField, addTableRow, clearTopicRowsCache, deleteRouteOrderField, deleteTableField,
 
97
  deleteTableRow, fetchLinkTargets,
98
  fetchRollupSources, patchRouteOrderField, patchTableField, enrichField } from "./apiBridge";
99
+ import type { LinkTarget, RollupSourceOffer } from "./apiBridge";
100
  import SelectFromFile from "./SelectFromFile";
101
  import ImportDialog from "./ImportDialog";
102
  import { FormInterface } from "./FormInterface";
 
173
  viewDisplayName,
174
  /* ⭐ W37-T26 (C4) — the view-membership leaf's two pure helpers. `viewRefsOf` is the ONE walk
175
  the resolver, the cycle detector and the gate share; `viewFilterCycle` is the refusal. */
176
+ viewFilterCycle, viewRefsOf } from "./types";
177
  /* ⭐⭐ W41-T42 (owner instruction 23) — the pivot's whole vocabulary is DECLARED in `types.ts`
178
  and only consumed here, because W41-T43 (this file) and W41-T44 (`RecordDetail.tsx`) open the
179
  same feature through other doors and neither of them may edit `types.ts`. */
180
  import { buildPivotRequest, cleanSecondaryView, emptyViewConfig, PIVOT_PATH, PIVOT_WINDOW_LABELS,
181
+ pivotResponse, relationalTargets } from "./types";
182
  import type {
183
  DisplayMode,
184
  DisplaySpec,
 
188
  FieldType,
189
  FilterNode,
190
  FilterRule,
 
191
  PivotResponse,
192
  PivotWindow,
193
  Row,
194
  RowHeightMode,
 
195
  SavedView,
196
  ViewConfig,
197
  } from "./types";
 
443
  * and it renders a sentence rather than a grid. Collapsing it into `ok` with zero rows would
444
  * put "no related records" on screen as the answer to a question nobody has asked yet.
445
  */
 
 
 
 
 
 
 
 
 
 
446
  type PivotState =
447
  | { status: "idle" }
448
  | { status: "loading" }
449
  | { status: "absent" }
 
450
  | { status: "ok"; answer: PivotResponse };
451
 
452
  /**
 
624
  return { ...config, colorBy: key || null, display: cleanDisplay(display) };
625
  }
626
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
627
  function readLocal(storageKey: string): LocalWorkspace | null {
628
  try {
629
  const raw = localStorage.getItem(`aios-grid:${storageKey}`);
 
929
  embeddedSelectable?: boolean;
930
  embeddedSelectedIds?: readonly number[];
931
  onEmbeddedSelectionChange?: (recordIds: number[]) => void;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
932
  }
933
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
934
  interface LinkGridModalProps {
935
  label: string;
936
  table: SurfaceScope;
937
  recordIds: readonly number[];
 
 
938
  editable?: boolean;
939
  single?: boolean;
 
 
940
  onSave?: (recordIds: number[]) => void;
941
  onClose: () => void;
942
  }
943
 
944
+ function LinkGridModal({ label, table, recordIds, editable = false, single = false,
945
+ onSave, onClose }: LinkGridModalProps) {
946
  const panelRef = useRef<HTMLDivElement>(null);
947
  const [selectedIds, setSelectedIds] = useState<number[]>(() => [...recordIds]);
948
  const changeSelectedIds = useCallback((ids: number[]) => {
 
990
  </button>
991
  </header>
992
  <div className="cg-link-grid-body">
 
 
 
 
 
 
 
993
  <CustomerGrid
994
  scope={table}
995
  embedded
996
  embeddedRecordIds={editable ? undefined : recordIds}
 
 
 
997
  embeddedSelectable={editable}
998
  embeddedSelectedIds={selectedIds}
999
  onEmbeddedSelectionChange={changeSelectedIds}
 
1070
  embeddedSelectable = false,
1071
  embeddedSelectedIds = [],
1072
  onEmbeddedSelectionChange,
 
 
 
1073
  }: CustomerGridProps = {}) {
1074
  const isQueryPreview = queryBinding !== undefined;
1075
  /**
 
1136
  */
1137
  const [pendingRows, setPendingRows] = useState<Row[]>([]);
1138
  const rawRows = useMemo(() => {
1139
+ const base = embeddedRecordIds
1140
  ? fetchedRows.filter((row) => new Set(embeddedRecordIds).has(row.pid))
1141
  : fetchedRows;
 
 
 
 
1142
  if (!pendingRows.length) return base;
1143
  const known = new Set(base.map((r) => r.pid));
1144
  const extra = pendingRows.filter((r) => !known.has(r.pid));
1145
  return extra.length ? [...base, ...extra] : base;
1146
  // The scalar key keeps this stable when a caller reconstructs the same id list.
1147
  // eslint-disable-next-line react-hooks/exhaustive-deps
1148
+ }, [fetchedRows, embeddedIdsKey, pendingRows]);
1149
  useEffect(() => {
1150
  // ⚠ PRUNED AGAINST THE FETCHED PAYLOAD, not against `rawRows` — `rawRows` contains the
1151
  // pending rows, so it can never report that one has been absorbed. Pruning against the
 
1290
  >(null);
1291
  const [detailPid, setDetailPid] = useState<number | null>(null);
1292
  const [columnMenu, setColumnMenu] = useState<ColumnMenuState | null>(null);
1293
+ const [viewActionsAnchor, setViewActionsAnchor] = useState<HTMLElement | null>(null);
1294
  /** Open choice list for a `select` / `user` cell — see onCellClicked. */
1295
  const [picker, setPicker] = useState<{
1296
  pid: number;
 
1309
  */
1310
  seed?: string;
1311
  } | null>(null);
1312
+ /** Date cells use a calendar surface, never Glide's generic one-line text editor. */
1313
+ const [datePicker, setDatePicker] = useState<{
1314
+ pid: number;
1315
+ fieldKey: string;
1316
+ anchor: AnchorRect;
1317
+ } | null>(null);
1318
  /** W40-T23 — what is typed in the picker's find box. Seeded by the keystroke that opened it
1319
  * (see `seed`), reset by every open and by `closePicker`, so a picker never inherits the
1320
  * previous one's query. */
 
1353
  /** Owner item 9 (wave 20) — its counterpart: "Remove from cohort…", in ORDINARY views. */
1354
  const [selRemoveOpen, setSelRemoveOpen] = useState(false);
1355
  const selRemoveRef = useRef<HTMLButtonElement>(null);
1356
+ /** Bulk edits are intentionally scoped to the filtered view, never a display-cap page. */
1357
+ const [bulkUpdateOpen, setBulkUpdateOpen] = useState(false);
1358
+ const [bulkFieldKey, setBulkFieldKey] = useState("");
1359
+ const [bulkValue, setBulkValue] = useState("");
1360
+ const bulkUpdateRef = useRef<HTMLButtonElement>(null);
1361
  /** Owner item 4 / C-ADDROW — the pid the trailing "+" just created, so the cursor can land on
1362
  * it once the re-read actually brings it back (the row does not exist locally before that). */
1363
  const [newRowPid, setNewRowPid] = useState<number | null>(null);
 
1475
  ? `query:${queryBinding.workspaceBinding.key}`
1476
  : payload?.workspace?.storageKey ?? `${LOCAL_KEY_PREFIX}${scope}`;
1477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1478
  // Initialize once per permission/data scope. Host state wins; local state
1479
  // fills only missing objects and keeps the standalone path useful.
1480
  useEffect(() => {
 
1817
  },
1818
  [config.groupBy, isQueryPreview, queryBinding]
1819
  );
1820
+ useEffect(() => {
1821
+ if (!config.fullscreen) return;
1822
+ const onKey = (event: KeyboardEvent) => {
1823
+ if (event.key === "Escape") updateConfig({ ...config, fullscreen: false });
1824
+ };
1825
+ window.addEventListener("keydown", onKey);
1826
+ return () => window.removeEventListener("keydown", onKey);
1827
+ }, [config, updateConfig]);
1828
 
1829
  const {
1830
  visibleCols,
 
1917
  const isUserTable = !embedded && scope.startsWith("ut_");
1918
  const recordsMutable = payload?.recordsMutable !== false;
1919
  const canMutateRecords = isUserTable && recordsMutable;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1920
  /**
1921
  * ⭐ 2026-08-07 — the databases a `link` column may point at, fetched when the column menu
1922
  * OPENS rather than on every render of the grid.
 
1990
  * carrying these same cells, or the row it paints locally fails the filter it was added under
1991
  * and disappears on the next read — the exact blip C2 exists to prevent.
1992
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1993
  const seedValues = useCallback(
1994
  () => filterSeedValues(config.filters, config.filterConj, fields, payload?.viewer),
1995
  [config.filters, config.filterConj, fields, payload?.viewer]
 
2170
  if (displayMode !== "map") setRoutePanelOpen(false);
2171
  }, [displayMode]);
2172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2173
  // ═══════════════════════════════════════════════════════════════════════════════════════
2174
  // ⭐⭐ WAVE 30 · W30-T42 (contract C2) — PAGING A READ-THROUGH GRID.
2175
  // ═══════════════════════════════════════════════════════════════════════════════════════
 
2181
  // question. So the predicate has to reach the evaluator that CAN answer it, which is SQL.
2182
  //
2183
  // ⛔ THE SAVED VIEW'S OWN OBJECTS GO ON THE WIRE, UNTRANSLATED (see `windowRowsPath`).
2184
+ const windowPredicate = useMemo(
2185
+ () => windowPredicateKey(config.filters, config.filterConj, config.sorts, search),
2186
+ [config.filters, config.filterConj, config.sorts, search]
2187
+ );
 
2188
  const windowRequest = useCallback(
2189
  (offset: number) => ({
2190
  offset,
2191
  limit: WINDOW_ROWS,
2192
+ filters: config.filters,
2193
+ filterConj: config.filterConj,
2194
  sorts: config.sorts,
2195
  search,
 
2196
  }),
2197
+ [config.filters, config.filterConj, config.sorts, search]
2198
  );
2199
  const sentPredicate = useRef<string | null>(null);
2200
  useEffect(() => {
 
2355
  });
2356
  }, [rawRows, overlayEdits, formulaAsts, createdTimeKeys, payload?.today]);
2357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2358
  /**
2359
  * ⭐⭐ W37-T26 / CONTRACT C4 — `view id -> the pids that view resolves to`, for the VIEW
2360
  * MEMBERSHIP leaf (`Where View is [some view]`).
 
2452
  [activeViewId, views, config, updateConfig]
2453
  );
2454
 
2455
+ const unresolvedCount = useMemo(
2456
  // ⭐ W37-T26 (C4) — `viewSets` rides this context too. Without it a view leaf would ALWAYS
2457
  // count as unresolved (the chip would cry wolf on a working filter) and, worse, a leaf naming
2458
  // a DELETED view would look identical to one naming a live one.
2459
  // ⭐⭐ D-229 — `fieldByKey` rides this context so a condition naming a column this table no
2460
  // longer has is COUNTED. `evalNode` ignores such a leaf (correctly), which means the grid was
2461
  // showing MORE rows than the filter panel claimed with nothing on screen saying so.
2462
+ () => unresolvedConditions(config.filters, { cohortSets, viewSets, fieldByKey, today }),
2463
  [config.filters, cohortSets, viewSets, fieldByKey, today]
2464
  );
 
2465
 
2466
  // Wave-2 item 2c — COHORT MODE (the Cohort page). The host serves the WHOLE pool (rows +
2467
  // derived values over the pool); the ACTIVE cohort scopes the table to its pids CLIENT-side.
 
2485
  const scopedRows = useMemo(
2486
  () =>
2487
  cohortMode
2488
+ ? computedRows.filter((r) => cohortMemberSet.has(r.pid))
2489
+ : computedRows,
2490
+ [cohortMode, computedRows, cohortMemberSet]
2491
  );
2492
 
 
 
 
 
 
 
 
2493
  const { visibleRows, pidToIndex } = useVisibleRows(
2494
  scopedRows,
2495
  fields,
 
2511
  // wave17 R1 / C-LOCKV: the view's SAVED lock is now the only source. A locked view is a
2512
  // saved view whose `config.cohortLock` names its own id, so opening it IS applying the
2513
  // lock — the wave-15 transient rail pick that used to outrank this is gone with its rail.
2514
+ config.cohortLock
 
2515
  );
2516
 
2517
  // Owner item 8 — the DISPLAY cap. The pipeline above still ran over the whole book (counts,
 
2587
  * grouped: subtotals appeared, the table's own total vanished, and nothing said why.
2588
  *
2589
  * ⛔ WHY A SECOND PREDICATE RATHER THAN A WIDER `showTotals`. `showTotals` still answers a
2590
+ * NARROWER question that two other call sites need unchanged: `freezeTrailingRows` pins
2591
+ * exactly one trailing row, and glide's frozen trailing rows sit below the scroll region —
2592
+ * pinning the grand total there while group footers scroll past it is the ungrouped layout,
2593
+ * not the grouped one. This one answers "is a grand-total row appended at all".
 
 
 
 
 
 
 
 
 
 
2594
  *
2595
  * ⛔ THE WINDOWED ARM IS `showTotals` VERBATIM, AND THAT IS THE WHOLE SAFETY ARGUMENT. Over a
2596
  * `server-windowed` table the fold covers the LOADED WINDOW, and `foldNote` — the sentence that
 
2836
  const displayRows = useMemo(() => {
2837
  const shown = capped ? sliceForDisplay(visibleRows, displayCap) : visibleRows;
2838
  // ⚠ APPENDED AFTER THE SLICE, so the cap can never eat the totals row itself — and it is the
2839
+ // LAST row, which is what `freezeTrailingRows={1}` pins.
 
 
2840
  // W41-T40 — `totalsRowShown`, not `showTotals`: a grouped table gets its grand total back,
2841
  // after the last group's footer. Still appended AFTER the slice, so the cap can never eat it.
2842
  return totalsRowShown
 
2844
  { kind: "group-footer" as const, groupKey: TOTAL_GROUP_KEY, aggs: totalsAggs }]
2845
  : shown;
2846
  }, [capped, visibleRows, displayCap, totalsRowShown, totalsAggs]);
2847
+ const filteredPids = useMemo(
2848
+ () => visibleRows.flatMap((row) => row.kind === "data" ? [row.record.pid] : []),
2849
+ [visibleRows]
2850
+ );
2851
  const displayPidToIndex = useMemo(() => {
2852
  if (!capped) return pidToIndex;
2853
  const m = new Map<number, number>();
 
2972
  embeddedSelectable ? embeddedSelectedIds : [],
2973
  !embedded ? `aios:grid-selection:${scope}` : undefined
2974
  );
2975
+ const embeddedSelectedKey = embeddedSelectedIds.join(",");
2976
  const selectedPidKey = [...selectedPids].join(",");
2977
  useEffect(() => {
2978
  if (!embeddedSelectable) return;
 
2981
  }, [embeddedSelectable, embeddedSelectedKey, embeddedSelectedIds, selectedPidKey, selectPids]);
2982
  useEffect(() => {
2983
  if (!embeddedSelectable) return;
2984
+ onEmbeddedSelectionChange?.([...selectedPids]);
2985
+ }, [embeddedSelectable, onEmbeddedSelectionChange, selectedPids]);
 
 
 
 
 
2986
  /* ════════════════════════ owner item 16 / R4 / C-UNDO ════════════════════════
2987
  THE RECORDING LAYER. `undoStack.ts` owns the stack and every inverse; this owns the one
2988
  thing it cannot: reading the value a cell held BEFORE the write, which only exists at the
 
3204
  },
3205
  [currentValue, patchOverlay, recordCells]
3206
  );
3207
+ const bulkEditableFields = useMemo(
3208
+ () => fields.filter((field) => canEditField(field) && field.type !== "rating"),
3209
+ [fields, canEditField]
3210
+ );
3211
+ const bulkField = bulkEditableFields.find((field) => field.key === bulkFieldKey) ?? bulkEditableFields[0];
3212
+ const applyBulkUpdate = useCallback(() => {
3213
+ if (!bulkField || selectedPids.size === 0) return;
3214
+ const value = bulkField.type === "checkbox" ? (bulkValue === "1" ? "1" : "") : bulkValue;
3215
+ patchManyAndRecord([...selectedPids].map((pid) => ({ pid, updates: { [bulkField.key]: value } })), "a bulk update");
3216
+ setBulkUpdateOpen(false);
3217
+ }, [bulkField, bulkValue, patchManyAndRecord, selectedPids]);
3218
 
3219
  /**
3220
  * Apply one stack entry in one direction. The INVERSE lives in `undoStack.directed` — this
 
4111
  // also where the noreferrer rule that protects every URL cell lives.
4112
  const column = visibleCols[cell[0]];
4113
  const field = column ? fieldByKey.get(column.id!) : undefined;
4114
+ // A Date is chosen from a calendar. Keeping it ahead of the generic editor makes the
4115
+ // click and keyboard paths agree: no temporary free-text value can race the recurrence
4116
+ // settings the field owns.
4117
+ if (row.kind === "data" && field?.type === "date" && canEditField(field)) {
4118
+ event.preventDefault();
4119
+ setActiveCell(cell[0], cell[1]);
4120
+ const b = event.bounds;
4121
+ setDatePicker({
4122
+ pid: row.record.pid,
4123
+ fieldKey: field.key,
4124
+ anchor: { left: b.x, top: b.y, right: b.x + b.width, bottom: b.y + b.height, width: b.width, height: b.height },
4125
+ });
4126
+ return;
4127
+ }
4128
  // A picked field (select / assignee) opens its choices where the cell is. It cannot use
4129
  // glide's text overlay — a free-text editor on a constrained column is how you end up
4130
  // with "Done", "done" and "DONE" as three different values — and glide's own dropdown
 
4157
  // The large modal mounts the same Grid surface over exactly these pids, so its standard
4158
  // search, Filters, Sort, Fields, and column menus keep working for every database kind.
4159
  if (row.kind === "data" && field?.type === "link" && field.link?.table) {
4160
+ if (field.link.table.startsWith("ut_")) {
 
 
 
 
 
4161
  event.preventDefault();
4162
  setActiveCell(cell[0], cell[1]);
4163
  setLinkAt({ pid: row.record.pid, fieldKey: field.key });
 
4273
  canEditField(field) &&
4274
  !isPickType(field.type) &&
4275
  field.type !== "rating" &&
4276
+ field.type !== "status" &&
4277
+ field.type !== "date"
4278
  );
4279
  },
4280
  [displayRows, visibleCols, fieldByKey, canEditField]
 
4342
  // instruction 27) every resizable column is a real one, so `onColumnResize` is handed to the
4343
  // grid unwrapped. The two move guards below are kept as plain bounds checks: they never
4344
  // depended on the virtual column, and they still refuse an out-of-range index.
4345
+ const [columnDrag, setColumnDrag] = useState<{ direction: "left" | "right"; x: number } | null>(null);
4346
  const onGridColumnMoved = useCallback(
4347
  (from: number, to: number) => {
4348
  if (from >= visibleCols.length || to >= visibleCols.length) return;
4349
+ setColumnDrag(null);
4350
  onColumnMoved(from, to);
4351
  },
4352
  [onColumnMoved, visibleCols.length]
4353
  );
4354
  const onGridColumnProposeMove = useCallback(
4355
+ (from: number, to: number) => {
4356
+ const allowed = from >= 0 && to >= 0 && from < visibleCols.length && to < visibleCols.length
4357
+ && onColumnProposeMove(from, to);
4358
+ if (!allowed) return false;
4359
+ const x = visibleCols.slice(0, to).reduce(
4360
+ (sum, column) => {
4361
+ const width = (column as { width?: number }).width;
4362
+ return sum + (typeof width === "number" ? width : 0);
4363
+ },
4364
+ 0,
4365
+ );
4366
+ setColumnDrag({ direction: to < from ? "left" : "right", x });
4367
+ return true;
4368
+ },
4369
+ [onColumnProposeMove, visibleCols]
4370
  );
4371
  const onHeaderClicked = useCallback(
4372
  (column: number, event: HeaderClickedEventArgs) => {
 
6011
  const f = fieldByKey.get(key);
6012
  if (!f?.custom || key === lockedKey) return;
6013
  setFields((current) => current.filter((item) => item.key !== key));
6014
+ const nextWidths = { ...(config.widths ?? {}) };
6015
+ delete nextWidths[key];
6016
+ updateConfig({
6017
+ ...config,
6018
+ order: order.filter((k) => k !== key),
6019
+ visible: [...visible].filter((k) => k !== key),
6020
+ widths: nextWidths,
6021
+ sorts: (config.sorts ?? []).filter((s) => s.colId !== key),
6022
+ groupBy: config.groupBy === key ? null : config.groupBy,
6023
+ colorBy: config.colorBy === key ? null : config.colorBy,
6024
+ });
6025
  stampFieldDelete(key);
6026
  emitHostEvent({ id: eventId("fielddel"), type: "field_delete", key });
6027
  },
 
6064
  void deleteRouteOrderField(key).then((ok) => {
6065
  if (!ok) return; // the bridge has already said why
6066
  setFields((current) => current.filter((item) => item.key !== key));
6067
+ const nextWidths = { ...(config.widths ?? {}) };
6068
+ delete nextWidths[key];
6069
+ updateConfig({
6070
+ ...config,
6071
+ order: order.filter((k) => k !== key),
6072
+ visible: [...visible].filter((k) => k !== key),
6073
+ widths: nextWidths,
6074
+ sorts: (config.sorts ?? []).filter((s) => s.colId !== key),
6075
+ groupBy: config.groupBy === key ? null : config.groupBy,
6076
+ colorBy: config.colorBy === key ? null : config.colorBy,
6077
+ });
6078
  // ⛔ AND THE ROWS CACHE, for the reason `revealRouteField` states above: the values went
6079
  // with the definition (`shared_overlay.drop_field` scrubs the cells), so a refetch served
6080
  // from the pre-delete window would repaint the numbers of a column that no longer exists.
 
6126
  void deleteTableField(scope, key).then((ok) => {
6127
  if (!ok) return; // the bridge has already said why
6128
  setFields((current) => current.filter((item) => item.key !== key));
6129
+ const nextWidths = { ...(config.widths ?? {}) };
6130
+ delete nextWidths[key];
6131
+ updateConfig({
6132
+ ...config,
6133
+ order: order.filter((k) => k !== key),
6134
+ visible: [...visible].filter((k) => k !== key),
6135
+ widths: nextWidths,
6136
+ sorts: (config.sorts ?? []).filter((s) => s.colId !== key),
6137
+ groupBy: config.groupBy === key ? null : config.groupBy,
6138
+ colorBy: config.colorBy === key ? null : config.colorBy,
6139
+ });
6140
  signal(WORKSPACE_STALE_EVENT);
6141
  signal(ROWS_STALE_EVENT);
6142
  });
 
7035
  });
7036
  if (!live) return;
7037
  if (!res.ok) {
7038
+ setPivot({ status: "absent" });
 
 
 
 
 
 
 
 
7039
  return;
7040
  }
7041
  const answer = pivotResponse(await res.json().catch(() => null));
 
7065
  );
7066
  }
7067
 
7068
+ const activeView = views.find((view) => view.id === activeViewId);
7069
  // Cohort mode's toolbar control (rendered by Toolbar via the `cohortAction` slot; the popover
7070
  // it opens is with the other overlays at the bottom). Disabled without an active cohort —
7071
  // zero cohorts is the host page's near-empty state, not this button's error to explain.
 
7122
  // Item 11c — is the menu's field the current frozen boundary (its Pin would be a no-op)?
7123
  const menuVisIndex = menuField ? visibleKeys.indexOf(menuField.key) : -1;
7124
  const menuPinnedTo = menuVisIndex >= 0 && frozenN > 1 && menuVisIndex + 1 === frozenN;
7125
+ /** The menu moves across the visible header order, not across hidden fields between headers. */
7126
+ const moveVisibleColumn = (key: string, direction: -1 | 1) => {
7127
+ const from = visibleKeys.indexOf(key);
7128
+ const to = from + direction;
7129
+ if (from <= 0 || to <= 0 || to >= visibleKeys.length) return;
7130
+ const moved = visibleKeys.slice();
7131
+ [moved[from], moved[to]] = [moved[to], moved[from]];
7132
+ let index = 0;
7133
+ const nextOrder = order.map((candidate) => visible.has(candidate) ? moved[index++] : candidate);
7134
+ updateConfig({ ...config, order: nextOrder });
7135
+ };
7136
  // Item 10 — the toolbar's mode switcher (grid-only on windowed tables, see displayMode).
7137
  const modeControl = serverWindowed || embedded || isQueryPreview ? undefined : (
7138
  <ModeSwitch
 
7187
  ?? (linkField && linkRow ? linkRow[linkField.key] : "")
7188
  ?? ""
7189
  );
 
 
 
 
 
 
7190
  const linkedRecordIds = [...new Set(
7191
  linkValue.split(",").map((part) => Number(part.trim())).filter(
7192
  (pid) => Number.isInteger(pid) && pid > 0
7193
  )
7194
  )];
7195
  const pickerField = picker ? fieldByKey.get(picker.fieldKey) : undefined;
7196
+ const dateField = datePicker ? fieldByKey.get(datePicker.fieldKey) : undefined;
7197
+ const dateRow = datePicker ? rawRows.find((row) => row.pid === datePicker.pid) : undefined;
7198
+ const dateValue = datePicker && dateField && dateRow
7199
+ ? overlayEdits[datePicker.pid]?.[datePicker.fieldKey] ?? dateRow[dateField.key] ?? ""
7200
+ : "";
7201
  // A `user` field's choices come from the HOST's real user list, a `select`'s from its own
7202
  // definition — so an assignee is always someone who can log in, and a status is always one of
7203
  // the choices the column was created with.
 
7222
  * choices survive this query" has one definition rather than one per surface.
7223
  */
7224
  const pickerShown = matchChoices(pickerChoices, pickQuery);
7225
+ // A choice field may start empty. Typing an unlisted value is both the value write and the
7226
+ // vocabulary-creation gesture: the server hydrates the shared field definition atomically,
7227
+ // while this local candidate keeps the picker truthful before that response next refreshes it.
7228
+ // `user` remains a roster-backed picker and can never create a person from text.
7229
+ const pickerCanCreateChoice =
7230
+ pickerField?.type === "select" || pickerField?.type === "multiselect";
7231
+ const pickerAddChoice = (() => {
7232
+ if (!pickerCanCreateChoice) return "";
7233
+ // Mirrors the server's choice-label storage shape so the optimistic row is exactly what the
7234
+ // next field payload will contain, rather than a whitespace-only near duplicate.
7235
+ const candidate = pickQuery.trim().replace(/\s+/g, " ").slice(0, 60);
7236
+ return candidate && !pickerChoices.some((choice) => choice.toLowerCase() === candidate.toLowerCase())
7237
+ ? candidate
7238
+ : "";
7239
+ })();
7240
  /**
7241
  * ⭐ W40-T23 — WHETHER THE FIND BOX IS THERE: only when a KEYSTROKE opened this picker.
7242
  *
 
7258
  */
7259
  const pickerSearchOn =
7260
  pickerField?.type !== "rating" &&
7261
+ (pickerChoices.length > 0 || pickerCanCreateChoice) &&
7262
  picker?.seed !== undefined;
7263
  /** Item 6 — which choice receives focus when the picker opens: the current value where it
7264
  * still exists in the list, else the first choice. Keyboard-only editing starts HERE.
 
7296
 
7297
  const pivotOn = !!secondary;
7298
  const pivotAnswer = pivot.status === "ok" ? pivot.answer : null;
7299
+ const pivotRefusal = pivotAnswer?.refusal ?? null;
 
 
 
 
 
 
 
 
 
 
7300
  /**
7301
  * ⭐ W41-T43 — THE SAVED PIVOT NAMES A LINK COLUMN THIS READER WAS NOT SERVED. No request went
7302
  * out (`pivotRequestBody` is empty), so `pivot` stays `idle` and every other branch below is
 
7423
  relational={relationalState}
7424
  onRelational={setPivotVia}
7425
  onRelationalWindow={setPivotWindow}
 
 
 
 
 
 
 
 
 
 
 
 
 
7426
  />
7427
  ) : null;
7428
 
 
7441
  // Streamlit rerun replaces it. An attribute survives the remount and is one `get_attribute`
7442
  // away from any harness, local or deployed.
7443
  <div
7444
+ className={"cg-shell" + (config.fullscreen ? " is-view-fullscreen" : "")}
7445
  data-today={today ?? ""}
7446
  data-measure-rules={measureRuleKeys}
7447
  data-measure-sets={measureSetKeys}
 
7800
  viewer={viewer}
7801
  onToggleLock={toggleViewLock}
7802
  onToggleImportant={toggleViewImportant}
7803
+ actionAnchor={viewActionsAnchor}
7804
+ onActionAnchorConsumed={() => setViewActionsAnchor(null)}
7805
  />
7806
  )}
7807
  {/* ⭐⭐ W37-T29 / CONTRACT C6 (rulings R2, R10) — E's CHAT, DOCKED AND OPENABLE.
 
7879
  if (target && target.shared && target.kind === "route_order") deleteRouteField(key);
7880
  else deleteField(key);
7881
  }}
7882
+ onEditField={(fieldKey, rect) => {
7883
+ setColumnMenu({
7884
+ fieldKey,
7885
+ pane: "edit",
7886
+ anchor: {
7887
+ left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom,
7888
+ width: rect.width, height: rect.height,
7889
+ },
7890
+ });
7891
+ }}
 
 
 
 
 
7892
  /* ⭐⭐ W38-T07 (owner instruction 12) — THE ONE COLOUR CONTROL. This was `colorOn` plus a
7893
  boolean toggle whose `true` arm guessed the column: `fields.find(type === "status")`,
7894
  so on a table with two status columns the person got the first one and had no way to
 
7914
  statusValues={statusValues}
7915
  measures={measures}
7916
  unresolvedCount={unresolvedCount}
 
7917
  lists={lists}
7918
  /* ⭐⭐ W37-T26 (C4) — the views this database's conditions may name: every SAVED view
7919
  except the one being edited (a view naming itself is the cycle a person reaches most
 
7953
  onRelational={setPivotVia}
7954
  onRelationalWindow={setPivotWindow}
7955
  sourceLabel={topic.nouns}
7956
+ onViewActions={setViewActionsAnchor}
7957
  />
7958
+ <button
7959
+ type="button"
7960
+ className="cg-fullscreen-toggle"
7961
+ aria-pressed={!!config.fullscreen}
7962
+ onClick={() => updateConfig({ ...config, fullscreen: !config.fullscreen })}
7963
+ >
7964
+ {config.fullscreen ? "Exit fullscreen" : "Fullscreen"}
7965
+ </button>
7966
  {/* ⭐ R11's SECOND ROW — live, on the pivoted database. It renders only once the pivot has
7967
  actually been SERVED, which is the house posture for a control whose other half may
7968
  not be wired yet: absent beats present-and-inert. A control row over a database whose
 
8003
  read as an alert rather than as a label. It now sits under the view's name in the
8004
  rail (ViewSidebar), where it annotates the thing it describes. */}
8005
  <div
8006
+ className={"cg-grid-box" + (columnDrag ? ` is-column-dragging-${columnDrag.direction}` : "")}
8007
  ref={gridBoxRef}
8008
  // Item 19 — THE dismissal. Not glide's out-of-bounds hover: the button sits over the
8009
  // canvas, so reaching for it IS an out-of-bounds event and dismissing there would
8010
  // unmount the control under the arriving pointer. Leaving the whole grid box is the
8011
  // honest "you are done with this row".
8012
  onMouseLeave={() => {
8013
+ setColumnDrag(null);
8014
  setExpandAt((prev) => (prev === null ? prev : null));
8015
  // W35-T29: the star control is dismissed with the Expand, and it is HOVER-SCOPED —
8016
  // say so rather than implying otherwise. It is how you SET a star, and it shows
 
8020
  // `getBounds` per visible row on every repaint, for a fact the view already answers.
8021
  setStarHover((prev) => (prev === null ? prev : null));
8022
  }}
8023
+ onMouseUp={() => setColumnDrag(null)}
8024
  >
8025
+ {columnDrag && (
8026
+ <div
8027
+ className="cg-column-drop-shadow is-visible"
8028
+ aria-hidden
8029
+ style={{ left: columnDrag.x + rowMarkerPx(displayRows.length) }}
8030
+ />
8031
+ )}
8032
  {secondary ? (
8033
  /* ⭐⭐ W41-T42 — THE PIVOT RENDERS IN PLACE (R11). It stands in the grid's own box, so
8034
  the swap happens where the reader is looking and the two control rows above it stay
 
8120
  {pivot.status === "absent" && (
8121
  /* ⛔⛔ NOTHING, PLUS ONE LINE. C10's endpoint is W41-T20 and it had not been built
8122
  when this shipped. An absent answer means "not built yet", never "false", and
8123
+ never an empty grid. */
 
 
 
 
 
8124
  <div className="cg-rel-note" role="status">
8125
  The related view is not available yet, so there is nothing to show.
8126
  </div>
 
8214
  * ⭐⭐ WAVE-29 T33 (owner item 17) — the totals row is glide's OWN frozen trailing
8215
  * row, which is why it is aligned to every column width for free.
8216
  *
8217
+ * ⛔ `showTotals ? 1 : 0`, never a bare `1`: with no totals row appended, freezing
8218
  * one trailing row would pin the LAST DATA RECORD to the bottom of the viewport —
8219
  * a record that then appears twice while scrolling, which reads as duplicated data
8220
  * rather than as a layout bug.
 
 
 
 
 
 
 
 
8221
  */
8222
+ freezeTrailingRows={showTotals ? 1 : 0}
8223
  rowHeight={rowHeight}
8224
  headerHeight={36}
8225
  rowMarkers="both"
 
8805
  <span className="cg-selbar-count">
8806
  {selectedPids.size.toLocaleString()} selected
8807
  </span>
8808
+ {selectedPids.size !== filteredPids.length && filteredPids.length > 0 && (
8809
+ <button
8810
+ type="button"
8811
+ className="cg-btn cg-selbar-all"
8812
+ style={ONE_LINE}
8813
+ onClick={() => selectPids(filteredPids, "replace")}
8814
+ >
8815
+ Select all {filteredPids.length.toLocaleString()} filtered
8816
+ </button>
8817
+ )}
8818
+ {bulkEditableFields.length > 0 && (
8819
+ <button
8820
+ ref={bulkUpdateRef}
8821
+ type="button"
8822
+ className="cg-btn cg-selbar-update"
8823
+ style={ONE_LINE}
8824
+ aria-expanded={bulkUpdateOpen}
8825
+ aria-haspopup="dialog"
8826
+ onClick={() => setBulkUpdateOpen((open) => !open)}
8827
+ >
8828
+ Update field
8829
+ </button>
8830
+ )}
8831
  {/* ⭐ 2026-08-06 (owner) — *"right now it only shows 'Add to cohort'"*. On a user
8832
  database the checked rows are RECORDS the reader owns, and there was no door to
8833
  remove one; the whole delete path existed server-side with nothing calling it.
 
8986
  state={columnMenu}
8987
  field={menuField}
8988
  fields={fields}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8989
  /**
8990
  * ⭐ 2026-08-10 — SELF-LINKING, and somebody asked for it (owner, D-113).
8991
  *
 
9224
  }
9225
  : undefined
9226
  }
 
 
 
 
9227
  onDuplicate={
9228
  // Creatable strata only — a base Odoo field offers no Duplicate (contract).
9229
  menuField.custom && !menuField.shared ? () => duplicateField(menuField) : undefined
9230
  }
9231
+ onMoveLeft={
9232
+ menuVisIndex > 1
9233
+ ? () => moveVisibleColumn(menuField.key, -1)
9234
+ : undefined
9235
+ }
9236
+ onMoveRight={
9237
+ menuVisIndex >= 1 && menuVisIndex < visibleKeys.length - 1
9238
+ ? () => moveVisibleColumn(menuField.key, 1)
9239
+ : undefined
9240
+ }
9241
  onFormat={(format) => saveField({ ...menuField, format })}
9242
  /**
9243
  * ⭐ WAVE-29 T33 (owner item 17) — the column summary, through whichever door owns this
 
9319
  field={fieldByKey.get(lockedKey)!}
9320
  fields={fields}
9321
  locked
 
 
 
 
 
 
 
 
 
 
 
 
9322
  viewer={viewer}
9323
  sortedDir={null}
9324
  isFiltered={false}
 
9329
  onNote={() => undefined}
9330
  onHide={() => undefined}
9331
  onCreate={createField}
9332
+ /* The SAME answer as the sibling instance above, stated rather than defaulted: this is
9333
+ the "+" menu and it creates through the identical `createField`, so a different value
9334
+ here would mean one door offers the kind and its twin does not. The note above the
9335
+ other instance carries the reasoning, including why it is now unconditional. */
 
 
 
 
9336
  geocodable={true}
9337
  onChangeField={() => undefined}
9338
  onCreateAndSwap={() => undefined}
 
9360
  // either way. See the sibling's note for why self-links are offered now.
9361
  linkTargets={linkTargets}
9362
  rollupSourceOffer={rollupSourceOffer}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9363
  />
9364
  )}
9365
 
 
9456
  {/* ⭐ Owner item 9 — the remove picker. Every row states how many of the CHECKED rows it
9457
  would take out ("3 of 4"), because the selection and the cohort are two different sets
9458
  and the difference is the whole reason this needs a picker rather than a button. */}
9459
+ {bulkUpdateOpen && bulkUpdateRef.current && selectedPids.size > 0 && bulkField && (
9460
+ <AnchoredOverlay
9461
+ anchor={bulkUpdateRef.current}
9462
+ className="cg-pop cg-bulk-update-pop"
9463
+ placement="bottom-start"
9464
+ role="dialog"
9465
+ ariaLabel="Update selected records"
9466
+ onDismiss={() => setBulkUpdateOpen(false)}
9467
+ dataKind="filtered-bulk-update"
9468
+ >
9469
+ <div className="cg-pop-title">Update field</div>
9470
+ <div className="cg-pop-note">Updates all {selectedPids.size.toLocaleString()} selected records in this filtered view.</div>
9471
+ <select className="cg-select" aria-label="Field to update" value={bulkFieldKey || bulkField.key} onChange={(event) => { setBulkFieldKey(event.target.value); setBulkValue(""); }}>
9472
+ {bulkEditableFields.map((field) => <option key={field.key} value={field.key}>{field.label}</option>)}
9473
+ </select>
9474
+ {bulkField.type === "checkbox" ? (
9475
+ <select className="cg-select" aria-label="New value" value={bulkValue} onChange={(event) => setBulkValue(event.target.value)}><option value="">Unchecked</option><option value="1">Checked</option></select>
9476
+ ) : bulkField.type === "select" && bulkField.options?.length ? (
9477
+ <select className="cg-select" aria-label="New value" value={bulkValue} onChange={(event) => setBulkValue(event.target.value)}><option value="">(blank)</option>{bulkField.options.map((option) => <option key={option} value={option}>{option}</option>)}</select>
9478
+ ) : (
9479
+ <input className="cg-input" aria-label="New value" value={bulkValue} onChange={(event) => setBulkValue(event.target.value)} />
9480
+ )}
9481
+ <div className="cg-form-actions">
9482
+ <button type="button" className="cg-btn cg-btn--primary" style={ONE_LINE} onClick={applyBulkUpdate}>Update records</button>
9483
+ <button type="button" className="cg-btn" style={ONE_LINE} onClick={() => setBulkUpdateOpen(false)}>Cancel</button>
9484
+ </div>
9485
+ </AnchoredOverlay>
9486
+ )}
9487
+
9488
  {selRemoveOpen && selRemoveRef.current && removableLists.length > 0 && (
9489
  <AnchoredOverlay
9490
  anchor={selRemoveRef.current}
 
9618
  onClose={closeJson}
9619
  />
9620
  )}
9621
+ {linkField?.type === "link" && linkField.link?.table.startsWith("ut_") && linkAt && (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9622
  <LinkGridModal
9623
  label={linkField.label}
9624
+ table={linkField.link.table as SurfaceScope}
9625
  recordIds={linkedRecordIds}
 
 
9626
  editable={canEditField(linkField) && !isDerivedLink(linkField)}
9627
+ single={linkField.link.single === true}
 
9628
  onSave={(ids) => patchAndRecord(
9629
  linkAt.pid,
9630
  { [linkField.key]: ids.join(",") },
 
9633
  onClose={closeLink}
9634
  />
9635
  )}
9636
+ {datePicker && dateField?.type === "date" && (
9637
+ <DatePicker
9638
+ anchor={datePicker.anchor}
9639
+ field={dateField}
9640
+ value={dateValue}
9641
+ today={today}
9642
+ onChange={(value) => patchAndRecord(datePicker.pid, { [dateField.key]: value }, "a date")}
9643
+ onRecurrence={(recurrence, nextDate) => saveField({ ...dateField, recurrence, nextDate })}
9644
+ onClose={() => {
9645
+ setDatePicker(null);
9646
+ requestAnimationFrame(() => gridRef.current?.focus());
9647
+ }}
9648
+ />
9649
+ )}
9650
  {pickerField && picker && (
9651
  <AnchoredOverlay
9652
  anchor={picker.anchor}
 
9677
  * `previous.focus()` — a selector that changed per keystroke would throw focus back to
9678
  * the grid and re-grab it on every letter. `pickerSearchOn` is frozen for the life of
9679
  * the picker, and it is the SAME predicate that renders the box, so the selector can
9680
+ * never name a control that is not there (an empty roster picker is not creatable and
9681
+ * therefore has no find box to focus).
9682
  */
9683
  initialFocus={pickerSearchOn ? ".cg-pick-search input" : "[data-overlay-autofocus]"}
9684
  onKeyDown={(e) => {
 
9750
  <div className="cg-pop-note">
9751
  {pickerField.type === "user"
9752
  ? "No assignable people were supplied for this workspace."
9753
+ : "This field has no choices yet."}
9754
  </div>
9755
  )}
9756
  {/* ⭐ W40-T23 — the find box, in the house search shape (`.cg-type-search`, the same
 
9874
  </button>
9875
  );
9876
  })}
9877
+ {pickerAddChoice && (
9878
+ <button
9879
+ type="button"
9880
+ role="option"
9881
+ aria-selected={false}
9882
+ className="cg-pick-row cg-pick-add"
9883
+ data-overlay-autofocus={pickerShown.length === 0 ? true : undefined}
9884
+ onClick={() => {
9885
+ const choice = pickerAddChoice;
9886
+ // The same value goes through the ordinary record write. The server appends it
9887
+ // to the field vocabulary in that transaction; this optimistic definition
9888
+ // update means a person can select it again immediately, before any reload.
9889
+ setFields((current) => current.map((item) =>
9890
+ item.key === pickerField.key
9891
+ ? { ...item, options: [...choiceOptions(item), choice] }
9892
+ : item
9893
+ ));
9894
+ if (pickerMulti) {
9895
+ patchAndRecord(picker.pid, {
9896
+ [pickerField.key]: [...pickerParts, choice].join(","),
9897
+ }, "a new choice");
9898
+ return;
9899
+ }
9900
+ patchAndRecord(picker.pid, { [pickerField.key]: choice }, "a new choice");
9901
+ closePicker();
9902
+ }}
9903
+ >
9904
+ <span className="cg-pick-pill">Add option: {pickerAddChoice}</span>
9905
+ </button>
9906
+ )}
9907
  </div>
9908
+ {/* A query nothing answers only when its field cannot create a choice (the user roster).
9909
+ A select/multiselect renders its `Add option` row instead, so this never competes
9910
+ with the empty-vocabulary note or looks like a dead-end picker. */}
9911
+ {pickerSearchOn && pickerShown.length === 0 && !pickerAddChoice && (
 
9912
  <div className="cg-pop-note">No choice matches.</div>
9913
  )}
9914
  {pickerMulti && (
web/src/customer-grid/DatePicker.tsx ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useMemo, useState } from "react";
2
+ import type { Field } from "./types";
3
+ import { AnchoredOverlay } from "./OverlaySurface";
4
+ import type { AnchorRect } from "./OverlaySurface";
5
+
6
+ type Frequency = NonNullable<Field["recurrence"]>["frequency"];
7
+
8
+ const MONTHS = [
9
+ "January", "February", "March", "April", "May", "June",
10
+ "July", "August", "September", "October", "November", "December",
11
+ ];
12
+ const WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
13
+
14
+ function parseIso(value: unknown): Date | null {
15
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
16
+ const [year, month, day] = value.split("-").map(Number);
17
+ const date = new Date(Date.UTC(year, month - 1, day));
18
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day
19
+ ? date
20
+ : null;
21
+ }
22
+
23
+ function iso(date: Date): string {
24
+ return date.toISOString().slice(0, 10);
25
+ }
26
+
27
+ function addMonths(date: Date, amount: number): Date {
28
+ const out = new Date(date);
29
+ out.setUTCMonth(out.getUTCMonth() + amount);
30
+ return out;
31
+ }
32
+
33
+ function isUsHoliday(date: Date): boolean {
34
+ const month = date.getUTCMonth();
35
+ const day = date.getUTCDate();
36
+ // Fixed federal holidays plus the common observed weekday. The API remains the authority for
37
+ // an exact calendar; this prevents the local preview from presenting a known holiday as a work day.
38
+ if ((month === 0 && day === 1) || (month === 6 && day === 4) || (month === 11 && day === 25)) return true;
39
+ const weekday = date.getUTCDay();
40
+ if (month === 0 && day === 1 && weekday === 6) return true;
41
+ if (month === 0 && day === 2 && weekday === 1) return true;
42
+ if (month === 6 && day === 3 && weekday === 5) return true;
43
+ if (month === 6 && day === 5 && weekday === 1) return true;
44
+ if (month === 11 && day === 24 && weekday === 5) return true;
45
+ if (month === 11 && day === 26 && weekday === 1) return true;
46
+ // MLK, Memorial, Labor and Thanksgiving.
47
+ if (month === 0 && weekday === 1 && day >= 15 && day <= 21) return true;
48
+ if (month === 4 && weekday === 1 && day + 7 > 31) return true;
49
+ if (month === 8 && weekday === 1 && day <= 7) return true;
50
+ return month === 10 && weekday === 4 && day >= 22 && day <= 28;
51
+ }
52
+
53
+ export function nextRecurringDates(
54
+ start: string,
55
+ recurrence: Field["recurrence"],
56
+ count = 6,
57
+ ): string[] {
58
+ const seed = parseIso(start);
59
+ const frequency: Frequency = recurrence?.frequency ?? "none";
60
+ if (!seed || frequency === "none") return seed ? [iso(seed)] : [];
61
+ const interval = Math.max(1, Math.min(365, Math.round(recurrence?.interval ?? 1)));
62
+ const out: string[] = [];
63
+ let candidate = new Date(seed);
64
+ let guard = 0;
65
+ while (out.length < count && guard++ < count * 400) {
66
+ if (guard > 1) {
67
+ if (frequency === "daily") candidate.setUTCDate(candidate.getUTCDate() + interval);
68
+ else if (frequency === "weekly") candidate.setUTCDate(candidate.getUTCDate() + 7 * interval);
69
+ else if (frequency === "monthly") candidate = addMonths(candidate, interval);
70
+ else candidate.setUTCFullYear(candidate.getUTCFullYear() + interval);
71
+ }
72
+ const weekday = candidate.getUTCDay();
73
+ const allowedWeekday = !recurrence?.weekdays?.length || recurrence.weekdays.includes(weekday);
74
+ const holiday = recurrence?.skipHolidays && recurrence.holidayCalendar === "us" && isUsHoliday(candidate);
75
+ if (allowedWeekday && !holiday) out.push(iso(candidate));
76
+ }
77
+ return out;
78
+ }
79
+
80
+ export function DatePicker({
81
+ anchor,
82
+ field,
83
+ value,
84
+ today,
85
+ onChange,
86
+ onRecurrence,
87
+ onClose,
88
+ }: {
89
+ anchor: AnchorRect;
90
+ field: Field;
91
+ value: unknown;
92
+ today?: string;
93
+ onChange: (value: string) => void;
94
+ onRecurrence: (recurrence: NonNullable<Field["recurrence"]>, nextDate: string | undefined) => void;
95
+ onClose: () => void;
96
+ }) {
97
+ const selected = parseIso(value) ?? parseIso(today) ?? new Date();
98
+ const [cursor, setCursor] = useState(() => new Date(Date.UTC(selected.getUTCFullYear(), selected.getUTCMonth(), 1)));
99
+ const [frequency, setFrequency] = useState<Frequency>(field.recurrence?.frequency ?? "none");
100
+ const [interval, setInterval] = useState(field.recurrence?.interval ?? 1);
101
+ const [skipHolidays, setSkipHolidays] = useState(!!field.recurrence?.skipHolidays);
102
+ const recurrence = useMemo<NonNullable<Field["recurrence"]>>(
103
+ () => ({
104
+ ...field.recurrence,
105
+ frequency,
106
+ interval: Math.max(1, Math.min(365, Math.round(Number(interval) || 1))),
107
+ skipHolidays,
108
+ holidayCalendar: skipHolidays ? "us" : undefined,
109
+ }),
110
+ [field.recurrence, frequency, interval, skipHolidays],
111
+ );
112
+ const next = useMemo(
113
+ () => nextRecurringDates(iso(selected), recurrence),
114
+ [recurrence, selected],
115
+ );
116
+ const monthStart = new Date(Date.UTC(cursor.getUTCFullYear(), cursor.getUTCMonth(), 1));
117
+ const leading = (monthStart.getUTCDay() + 6) % 7;
118
+ const days = new Date(Date.UTC(cursor.getUTCFullYear(), cursor.getUTCMonth() + 1, 0)).getUTCDate();
119
+ const cells = Array.from({ length: Math.ceil((leading + days) / 7) * 7 }, (_, index) => index - leading + 1);
120
+ const selectedIso = iso(selected);
121
+
122
+ return (
123
+ <AnchoredOverlay
124
+ anchor={anchor}
125
+ className="cg-date-picker"
126
+ placement="bottom-start"
127
+ onDismiss={onClose}
128
+ role="dialog"
129
+ ariaLabel={`Choose a date for ${field.label}`}
130
+ dataKind="date-picker"
131
+ >
132
+ <div className="cg-date-picker-head">
133
+ <button type="button" className="cg-icon-button" aria-label="Previous month" onClick={() => setCursor(addMonths(cursor, -1))}>‹</button>
134
+ <strong>{MONTHS[cursor.getUTCMonth()]} {cursor.getUTCFullYear()}</strong>
135
+ <button type="button" className="cg-icon-button" aria-label="Next month" onClick={() => setCursor(addMonths(cursor, 1))}>›</button>
136
+ </div>
137
+ <div className="cg-date-weekdays">{WEEKDAYS.map((day) => <span key={day}>{day}</span>)}</div>
138
+ <div className="cg-date-grid">
139
+ {cells.map((day, index) => {
140
+ if (day < 1 || day > days) return <span key={`blank-${index}`} aria-hidden />;
141
+ const date = new Date(Date.UTC(cursor.getUTCFullYear(), cursor.getUTCMonth(), day));
142
+ const dateIso = iso(date);
143
+ return <button key={dateIso} type="button" className={"cg-date-day" + (dateIso === selectedIso ? " is-selected" : "")} aria-pressed={dateIso === selectedIso} onClick={() => onChange(dateIso)}>{day}</button>;
144
+ })}
145
+ </div>
146
+ <div className="cg-date-recurrence">
147
+ <div className="cg-pop-title">Repeat</div>
148
+ <label>Every <input className="cg-input cg-date-interval" min="1" max="365" type="number" value={interval} onChange={(event) => setInterval(Number(event.target.value))} /></label>
149
+ <select className="cg-select" value={frequency} aria-label="Recurrence frequency" onChange={(event) => setFrequency(event.target.value as Frequency)}>
150
+ <option value="none">Does not repeat</option>
151
+ <option value="daily">day</option>
152
+ <option value="weekly">week</option>
153
+ <option value="monthly">month</option>
154
+ <option value="yearly">year</option>
155
+ </select>
156
+ {frequency !== "none" && <label className="cg-date-holidays"><input type="checkbox" checked={skipHolidays} onChange={(event) => setSkipHolidays(event.target.checked)} /> Skip US public holidays</label>}
157
+ {frequency !== "none" && <button type="button" className="cg-link-btn" onClick={() => onRecurrence(recurrence, next[0])}>Save recurrence</button>}
158
+ </div>
159
+ <div className="cg-date-preview" aria-live="polite">
160
+ <div className="cg-pop-title">Next dates</div>
161
+ {next.slice(0, 6).map((date) => <span key={date}>{date}</span>)}
162
+ </div>
163
+ </AnchoredOverlay>
164
+ );
165
+ }
web/src/customer-grid/MapView.tsx CHANGED
@@ -93,16 +93,6 @@ import {
93
  } from "./mapProjection";
94
  import type { GeoStop, Pt, RouteStamp, View } from "./mapProjection";
95
  import { LP_INK, LP_MAP_SELECTED } from "./theme";
96
- // W42-T24 (contract C6) — the route NAVIGATION, and every door it needs.
97
- import { RouteNav } from "./RouteNav";
98
- import type { RouteNavRoute } from "./RouteNav";
99
- import type { GridFolder } from "./types";
100
- import { newFolderId } from "./folders";
101
- import { deleteRouteOrderField, patchRouteOrderField } from "./apiBridge";
102
- import { emitHostEvent, eventId } from "./hostBridge";
103
- import type { HostEvent } from "./types";
104
- // ⚠ `styles/wave42/route-nav.css` is NOT imported here: `index.css` already @imports it at the
105
- // top of the file, and a second import would ship the rules twice and change their cascade order.
106
  import "./map.css";
107
 
108
  /**
@@ -323,6 +313,48 @@ const SERIES: { fill: string; line: string }[] = [
323
  * ninth colour that repeats the first would make two meanings look identical. */
324
  const OVERFLOW = { fill: "#D7DBE3", line: "#8A909C" };
325
  const DEFAULT_PIN = { fill: "#9DBFF2", line: "#4F6079" };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
 
327
  interface MapPoint {
328
  pid: number;
@@ -420,6 +452,9 @@ export function MapView({
420
  // I18-R — the route planner. Off until asked for: a route drawn over a
421
  // selection nobody asked to route is just clutter.
422
  const [routeOn, setRouteOn] = useState(false);
 
 
 
423
  const [roundTrip, setRoundTrip] = useState(false);
424
  const [routeStartPid, setRouteStartPid] = useState<number | null>(null);
425
  const askRoadRef = useRef(false);
@@ -433,19 +468,6 @@ export function MapView({
433
  * Kept as pids rather than indices because the selection can change underneath it.
434
  */
435
  const [routeOrder, setRouteOrder] = useState<number[] | null>(null);
436
- /**
437
- * ⭐ W42-T21 — A POSITION CAN BE TYPED, so the visit number is a text box and needs somewhere
438
- * to hold what a person has typed but not yet committed. Keyed by pid rather than by index:
439
- * the index of the row being edited changes the instant the order does.
440
- */
441
- const [stopPosDraft, setStopPosDraft] = useState<{ pid: number; text: string } | null>(null);
442
- /**
443
- * ⛔ THE REFUSAL IS ON SCREEN, NOT IN THE REQUEST. `route_order_write` rejects any body that
444
- * is not a full 1..N permutation, so a bad number must never travel; and a box that silently
445
- * snapped back to the old value would leave a person retyping the same thing. It says what is
446
- * wrong, keeps the typed text visible, and nothing is sent.
447
- */
448
- const [stopPosError, setStopPosError] = useState<{ pid: number; msg: string } | null>(null);
449
  /**
450
  * ⛔ OWNER ITEM 6 — THE DEPOT UI IS GONE AND THIS STATE DELIBERATELY IS NOT. The owner removed
451
  * the "Optional route start" section: the start is the record dropdown and nothing else. What
@@ -473,6 +495,18 @@ export function MapView({
473
  * would have had to re-derive every one of those and would have drifted from the first.
474
  */
475
  const [addedPids, setAddedPids] = useState<ReadonlySet<number>>(EMPTY_PIDS);
 
 
 
 
 
 
 
 
 
 
 
 
476
  /**
477
  * W37-T36 — the ROAD answer, which is the half arithmetic cannot produce.
478
  *
@@ -509,46 +543,31 @@ export function MapView({
509
  * must not render "no saved orders".
510
  */
511
  const [routeCols, setRouteCols] = useState<
512
- (RouteNavRoute & { inputsHash: string; depot?: RouteDepot | null })[] | null
 
 
 
 
 
 
 
 
 
 
513
  >(null);
514
- /** A failed route-list read is not an empty route list. */
515
- const [routeListError, setRouteListError] = useState<string | null>(null);
516
- /**
517
- * ⭐⭐ W42-T24 (contract C6) — THIS READER'S ROUTE FOLDERS, and they ride the SAME listing.
518
- *
519
- * W42-T23 made the rail's folder rows travel with `GET /customers/route-order` for the reason
520
- * its own comment gives: a `folderId` with no folder list beside it names a section the client
521
- * cannot draw. So there is no second fetch and no second source of truth about which folders
522
- * exist.
523
- */
524
- const [routeFolders, setRouteFolders] = useState<GridFolder[]>([]);
525
- /**
526
- * ⚠ THE RAIL'S OWN ROUTE ORDER, AND IT IS CLIENT-LOCAL THIS WAVE. Filing a route is durable
527
- * (`PATCH /customers/route-order/{key}/folder`), but there is no per-user ORDER stratum for
528
- * routes: `view_reorder` writes `save_view_order`, which is the VIEWS rail's order and ignores
529
- * `surface` entirely, so emitting it for routes would silently replace the reader's view rail
530
- * arrangement with a list of route keys. Dragging therefore reorders for this session and is
531
- * declared as such rather than sent to a door that would answer the wrong question.
532
- */
533
- const [railOrder, setRailOrder] = useState<string[]>([]);
534
- /** The route just created, so the rail can PROMPT to share it. Null the rest of the time. */
535
- const [createdRoute, setCreatedRoute] = useState<{ key: string; label: string } | null>(null);
536
- /** Which route the rail is waiting on a server answer for. */
537
- const [routeBusyKey, setRouteBusyKey] = useState("");
538
- /** The rail's own message slot, on screen whether or not a plan exists. See `startNewRoute`. */
539
- const [railNotice, setRailNotice] = useState("");
540
-
541
- /**
542
- * ⭐⭐ W42-T49 — WITH THE ROUTE OPEN, A PIN CLICK ASKS ABOUT A STOP.
543
- *
544
- * The pin that was clicked, the name to say it by, and whether it is ALREADY a stop. ⛔ `on` is
545
- * MEMBERSHIP and never the map's selection: see `routeStopPids` for why those are two different
546
- * sets and why reading the wrong one would make this feature answer confidently and wrongly.
547
- * ⚠ Cleared when the route closes (the reset effect over `autoRouteRef`), so a prompt cannot
548
- * outlive the mode that raised it and greet somebody minutes later.
549
- */
550
- const [routePinAsk, setRoutePinAsk] =
551
- useState<{ pid: number; title: string; on: boolean } | null>(null);
552
  /** Which saved column a save writes to. `""` = a new field, named in the prompt below. */
553
  const [saveTarget, setSaveTarget] = useState("");
554
  /**
@@ -740,6 +759,163 @@ export function MapView({
740
  }, [mapRows, field.key, coordField, colorField, sizeField]);
741
  const noCoords = mapRows.length - points.length;
742
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
743
  // The fit is the INITIAL view, not the projection (see mapProjection.ts).
744
  const fit = useMemo(
745
  () => fitView(points.map((p) => p.p), VIEW_W, VIEW_H),
@@ -948,12 +1124,9 @@ export function MapView({
948
  const autoRouteRef = useRef(false);
949
  const [autoCapped, setAutoCapped] = useState(0);
950
  useEffect(() => {
951
- if (!routePanelOpen) {
952
  autoRouteRef.current = false;
953
  setAutoCapped(0);
954
- // W42-T49 — closing the route ends its mode completely. A prompt left standing would come
955
- // back with the panel, asking about a pin somebody clicked before they closed it.
956
- setRoutePinAsk(null);
957
  return;
958
  }
959
  if (autoRouteRef.current || points.length < 2) return;
@@ -964,7 +1137,7 @@ export function MapView({
964
  onSelectPids(take.map((p) => p.pid), "replace");
965
  setRouteOn(true);
966
  setRouteOrder(null);
967
- }, [routePanelOpen, points, selectedPids, onSelectPids]);
968
 
969
  /** The depot joins BOTH index-parallel arrays below at position zero, and only there. */
970
  const depotPoint = useMemo((): MapPoint | null => {
@@ -1081,7 +1254,7 @@ export function MapView({
1081
  startPid: depotPoint ? null : routable[start].pid,
1082
  links: googleRouteUrls(
1083
  ordered.map((p) => ({ lat: p.lat, lon: p.lon })),
1084
- { roundTrip, coarsePointer }
1085
  ),
1086
  /** The identity of THIS set of stops in THIS order. The road answer is only about the plan
1087
  * whose key it carries; anything else on screen makes it stale rather than wrong. */
@@ -1091,7 +1264,7 @@ export function MapView({
1091
  customerStops: customerRoutable.length,
1092
  };
1093
  }, [routeOn, routable, customerRoutable.length, depotPoint, depot, roundTrip, routeStartPid,
1094
- coarsePointer, routeOrder]);
1095
 
1096
  /** ⭐ ITEM 7 — a MODE change stales the drawn road exactly as a stop change does. Without the
1097
  * second clause, flipping to Walking would leave driving minutes on screen under a Walking
@@ -1177,35 +1350,27 @@ export function MapView({
1177
  * the only way the STALE marker can exist at all.
1178
  */
1179
  const loadRouteCols = useCallback(async () => {
1180
- setRouteListError(null);
1181
  try {
1182
  const res = await fetch("/api/v1/customers/route-order", { credentials: "same-origin" });
1183
- const body = await res.json().catch(() => null);
1184
- if (!res.ok || !Array.isArray(body?.fields)) {
1185
- const detail = body?.detail?.message || body?.detail || body?.error?.message;
1186
- setRouteListError(typeof detail === "string" && detail.trim()
1187
- ? detail
1188
- : "Saved routes could not be loaded. Retry to see them.");
1189
- setRouteCols([]);
1190
- setRouteFolders([]);
1191
- setNextLabel("");
1192
- return;
1193
- }
1194
- setRouteCols(body.fields);
1195
- // W42-T23 / C6 — the rail's own folder ROWS travel with the listing.
1196
- setRouteFolders(Array.isArray(body?.folders) ? (body.folders as GridFolder[]) : []);
1197
  setNextLabel(typeof body?.nextLabel === "string" ? body.nextLabel : "");
1198
  } catch {
1199
- setRouteListError("Saved routes could not be loaded. Retry to see them.");
 
1200
  setRouteCols([]);
1201
- setRouteFolders([]);
1202
- setNextLabel("");
1203
  }
1204
  }, []);
1205
 
1206
- const retryRouteList = useCallback(() => {
1207
- void loadRouteCols();
1208
- }, [loadRouteCols]);
 
 
 
 
 
 
1209
 
1210
  // ⭐ OWNER, 2026-08-23 — `routePanelOpen`, NOT `routeOn`. The saved-route picker is the first
1211
  // control in the panel and it is how a person reaches somebody's plan without solving one of
@@ -1215,6 +1380,100 @@ export function MapView({
1215
  useEffect(() => {
1216
  if ((routePanelOpen || routeOn) && routeCols === null) void loadRouteCols();
1217
  }, [routePanelOpen, routeOn, routeCols, loadRouteCols]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1218
 
1219
  /**
1220
  * ⭐⭐ OWNER, 2026-08-23 — **OPEN A SAVED ROUTE AND SEE IT ON THE MAP.**
@@ -1344,18 +1603,9 @@ export function MapView({
1344
  return;
1345
  }
1346
  const savedField = String(body?.field || "");
1347
- // ⭐ W42-T24 — A NEW ROUTE PROMPTS TO SHARE IT, AND ONLY A NEW ONE. `saveTarget` is the
1348
- // column this save WRITES TO, so a non-empty one means the person re-solved a route that
1349
- // already exists; its sharing was decided when it was made and asking again every time
1350
- // somebody recalculates would be nagging rather than a choice. Read BEFORE `setSaveTarget`
1351
- // below moves it to the saved key.
1352
- const wasNew = !saveTarget;
1353
  setSaveTarget(savedField);
1354
  setNaming(false);
1355
  if (savedField) onRouteFieldCreated?.(savedField);
1356
- if (savedField && wasNew) {
1357
- setCreatedRoute({ key: savedField, label: String(body?.label || savedField) });
1358
- }
1359
  setSaveMsg(
1360
  `Saved ${Number(body?.stops || 0).toLocaleString()} visit numbers to ` +
1361
  `${body?.label || "the column"}` +
@@ -1369,279 +1619,6 @@ export function MapView({
1369
  }
1370
  }, [plan, saveTarget, roundTrip, routeCols, nextLabel, loadRouteCols, onRouteFieldCreated]);
1371
 
1372
- // ─────────────── W42-T24 (instruction 10, contract C6): the route NAVIGATION's doors ────────
1373
- /**
1374
- * ⛔⛔ RENAME AND DELETE TAKE THE ROUTE'S OWN DOOR, NEVER THE GENERIC FIELD ONE.
1375
- *
1376
- * A route order is a SHARED column on the customers registry topic. The per-user `field_upsert`
1377
- * event and the `ut_*` definition PATCH both reach a different stratum, so sending a rename
1378
- * down either forks the tenant-wide column into a private copy of itself wearing the new name
1379
- * while everybody else keeps the old one. `apiBridge`'s two helpers carry the server's own
1380
- * refusal sentence, which distinguishes "somebody else planned this" from "that name is taken".
1381
- */
1382
- const renameRoute = useCallback(
1383
- (key: string, label: string) => {
1384
- setRouteBusyKey(key);
1385
- void patchRouteOrderField(key, { label }).then((ok) => {
1386
- setRouteBusyKey("");
1387
- if (ok) void loadRouteCols();
1388
- });
1389
- },
1390
- [loadRouteCols]
1391
- );
1392
-
1393
- const removeRoute = useCallback(
1394
- (key: string) => {
1395
- setRouteBusyKey(key);
1396
- void deleteRouteOrderField(key).then((ok) => {
1397
- setRouteBusyKey("");
1398
- if (!ok) return;
1399
- if (openedRoute === key) setOpenedRoute("");
1400
- if (saveTarget === key) setSaveTarget("");
1401
- void loadRouteCols();
1402
- });
1403
- },
1404
- [loadRouteCols, openedRoute, saveTarget]
1405
- );
1406
-
1407
- /**
1408
- * Duplicate a route: the SAME visit numbers under a new name.
1409
- *
1410
- * ⛔ THE RANKS COME OFF THE ROWS, NOT FROM A NEW FETCH, for `openSavedRoute`'s reason: a route
1411
- * column's rank rides every row the reader may see, so the copy is made from what is already in
1412
- * hand. ⚠ And it reads `allRows`, the book AFTER the row wall and BEFORE the view's filters, so
1413
- * a duplicate is the whole route rather than the part today's filter happens to show.
1414
- * ⚠ A RANK IS READ AS A NUMBER. `shared_overlay` stores cells as strings, so copying the raw
1415
- * values would hand the server "10" before "2" and mint a plausible day in the wrong sequence.
1416
- */
1417
- const duplicateRoute = useCallback(
1418
- async (key: string) => {
1419
- const src = (routeCols || []).find((f) => f.key === key);
1420
- if (!src) return;
1421
- const book = allRows && allRows.length ? allRows : rows;
1422
- const ranks: Record<number, number> = {};
1423
- for (const r of book) {
1424
- const raw = r[key];
1425
- if (raw === null || raw === undefined || raw === "") continue;
1426
- const rank = Number(raw);
1427
- if (Number.isFinite(rank)) ranks[r.pid] = rank;
1428
- }
1429
- if (Object.keys(ranks).length < 2) {
1430
- // ⛔ REPORTED, NEVER SILENT (standing rule 1's second sentence). A route whose stops are
1431
- // all outside this account's book cannot be copied, and a Duplicate that did nothing
1432
- // would read as a broken menu rather than as a wall doing its job.
1433
- setSaveErr(
1434
- "That route has fewer than two stops in your book, so there is nothing to copy. The " +
1435
- "records it was planned over may sit outside the rows you are permitted to see."
1436
- );
1437
- return;
1438
- }
1439
- setRouteBusyKey(key);
1440
- try {
1441
- const res = await fetch("/api/v1/customers/route-order", {
1442
- method: "POST",
1443
- credentials: "same-origin",
1444
- headers: { "Content-Type": "application/json" },
1445
- body: JSON.stringify({
1446
- label: `${src.label} copy`,
1447
- ranks,
1448
- inputsHash: src.inputsHash,
1449
- }),
1450
- });
1451
- const body = await res.json().catch(() => null);
1452
- if (!res.ok) {
1453
- setSaveErr((body && body.error && body.error.message) || "That route could not be copied.");
1454
- return;
1455
- }
1456
- const madeKey = String(body?.field || "");
1457
- if (madeKey) {
1458
- onRouteFieldCreated?.(madeKey);
1459
- setCreatedRoute({ key: madeKey, label: String(body?.label || madeKey) });
1460
- }
1461
- await loadRouteCols();
1462
- } catch {
1463
- setSaveErr("That route could not be copied.");
1464
- } finally {
1465
- setRouteBusyKey("");
1466
- }
1467
- },
1468
- [routeCols, allRows, rows, loadRouteCols, onRouteFieldCreated]
1469
- );
1470
-
1471
- /**
1472
- * ⭐⭐ SHARING RIDES THE EXISTING GENERIC FIELD DOOR (C6). A route IS a field, so its oid is
1473
- * `<tableKey>:<fieldKey>` exactly as `ColumnMenu.tsx::shareOid` builds one, and the dialog is
1474
- * the one a view or a field already opens.
1475
- *
1476
- * ⛔ THE EVENT LITERAL IS RE-SPELLED HERE ON PURPOSE. `customer-grid/**` is host neutral and
1477
- * may not import `shell/**`, so `SHARE_OPEN_EVENT` is not imported across the boundary. Both
1478
- * `ColumnMenu.tsx` and `ViewSidebar.tsx` spell it the same way for the same reason.
1479
- * ⚠ `topic` is omitted: the shell fills it from the active database, and a wrong guess here
1480
- * would open the dialog against a database this route does not live on.
1481
- */
1482
- const shareRoute = useCallback((key: string, label: string) => {
1483
- window.dispatchEvent(
1484
- new CustomEvent("aios:share-open", {
1485
- detail: { kind: "field", id: `customer_data:${key}`, label },
1486
- })
1487
- );
1488
- setCreatedRoute(null);
1489
- }, []);
1490
-
1491
- /**
1492
- * File a route into one of this reader's route folders.
1493
- *
1494
- * ⛔⛔ THE ROUTE'S OWN DOOR, AND THE GENERIC ONE IS NOT AVAILABLE HERE. `grid_events`'
1495
- * `item_move` gates the mover on `_own_ids(surface, ws)`, which is an `if views: ... else
1496
- * cohorts` two-way split rather than a lookup — so filing a route through it answers "you can
1497
- * file only the items you own" about a column the person planned themselves. W42-T23 built
1498
- * `PATCH /customers/route-order/{key}/folder` for exactly that, and it walls on "can you see
1499
- * it" rather than "is it yours", because a placement changes one account's sidebar only.
1500
- * ⚠ THE RECEIPT IS ADOPTED, not assumed. `validate_folder_tree` REPAIRS a placement whose
1501
- * folder was deleted rather than refusing it, and a repair the caller never hears about is a
1502
- * route that quietly moved.
1503
- */
1504
- const moveRoute = useCallback(
1505
- async (key: string, folderId: string | null) => {
1506
- setRouteBusyKey(key);
1507
- try {
1508
- const res = await fetch(
1509
- `/api/v1/customers/route-order/${encodeURIComponent(key)}/folder`,
1510
- {
1511
- method: "PATCH",
1512
- credentials: "same-origin",
1513
- headers: { "Content-Type": "application/json" },
1514
- body: JSON.stringify({ folderId }),
1515
- }
1516
- );
1517
- const body = await res.json().catch(() => null);
1518
- if (!res.ok) {
1519
- setSaveErr((body && body.error && body.error.message) || "That route could not be filed.");
1520
- return;
1521
- }
1522
- await loadRouteCols();
1523
- } catch {
1524
- setSaveErr("That route could not be filed.");
1525
- } finally {
1526
- setRouteBusyKey("");
1527
- }
1528
- },
1529
- [loadRouteCols]
1530
- );
1531
-
1532
- /**
1533
- * The routes rail's FOLDER rows, through the generic folder door.
1534
- *
1535
- * ⚠ THE GENERIC DOOR IS RIGHT FOR A FOLDER AND WRONG FOR A PLACEMENT, and the split is not
1536
- * arbitrary: `folder_create` / `folder_rename` / `folder_delete` / `folder_reorder` never
1537
- * consult `_own_ids` for an ITEM, so `surface: "routes"` passes through them unharmed. Only
1538
- * `item_move` has the ownership gate, and that is the one this file does not use.
1539
- *
1540
- * ⛔ THE CAST IS DECLARED, NOT HIDDEN. `types.ts::FolderSurface` is `"views" | "cohorts"`, and
1541
- * `types.ts` is not this ticket's file to widen, so a route folder event cannot be typed from
1542
- * here. `aios_grid.FOLDER_SURFACES` already carries `"routes"` (W42-T23), so the wire value is
1543
- * legal; what is missing is the client declaration, and it is owed.
1544
- */
1545
- const routeFolderEvent = useCallback((event: Record<string, unknown>) => {
1546
- emitHostEvent({ ...event, surface: "routes" } as unknown as HostEvent);
1547
- }, []);
1548
-
1549
- const createRouteFolder = useCallback(
1550
- (name: string, parent: string | null) => {
1551
- const folderId = newFolderId();
1552
- // Optimistic, like every other rail: the folder must exist on screen before a route can be
1553
- // dragged into it, and the listing's next read is what settles the truth.
1554
- setRouteFolders((cur) => [...cur, { id: folderId, name, order: cur.length, parent }]);
1555
- routeFolderEvent({ id: eventId("rtfold"), type: "folder_create", folderId, name, parent });
1556
- },
1557
- [routeFolderEvent]
1558
- );
1559
-
1560
- const renameRouteFolder = useCallback(
1561
- (folderId: string, name: string) => {
1562
- setRouteFolders((cur) => cur.map((f) => (f.id === folderId ? { ...f, name } : f)));
1563
- routeFolderEvent({ id: eventId("rtfold"), type: "folder_rename", folderId, name });
1564
- },
1565
- [routeFolderEvent]
1566
- );
1567
-
1568
- const deleteRouteFolder = useCallback(
1569
- (folderId: string) => {
1570
- // CONTENTS MOVE TO ROOT, never delete — the folder contract is explicit, and the menu's
1571
- // armed copy says so before this runs.
1572
- setRouteFolders((cur) => cur.filter((f) => f.id !== folderId));
1573
- routeFolderEvent({ id: eventId("rtfold"), type: "folder_delete", folderId });
1574
- // ⛔ NO RE-READ HERE, AND THE ABSENCE IS DELIBERATE. The listing is fetched over its own
1575
- // connection while the folder event is still in flight, so a reload fired now can answer
1576
- // out of the state that predates the delete and put the folder straight back on screen. The
1577
- // routes it held need no help: their stored placement names an id that no longer resolves,
1578
- // and both `groupByFolder` here and `_route_folder_id` on the server render exactly that as
1579
- // the top level, which is the contract's "contents move to root, never delete".
1580
- },
1581
- [routeFolderEvent]
1582
- );
1583
-
1584
- const reorderRouteFolders = useCallback(
1585
- (order: string[]) => {
1586
- setRouteFolders((cur) => {
1587
- const known = new Map(cur.map((f) => [f.id, f]));
1588
- const ranked = order.map((id) => known.get(id)).filter(Boolean) as GridFolder[];
1589
- for (const f of cur) if (!order.includes(f.id)) ranked.push(f);
1590
- return ranked;
1591
- });
1592
- routeFolderEvent({ id: eventId("rtfold"), type: "folder_reorder", order });
1593
- },
1594
- [routeFolderEvent]
1595
- );
1596
-
1597
- /**
1598
- * ⭐ CREATING A ROUTE IS A SEPARATE AFFORDANCE from opening one, and it lands in the planner
1599
- * rather than minting an empty object: a route IS a solved sequence, so "create" means "solve
1600
- * the stops you have and name the answer". `saveTarget` is cleared first so the save mints a
1601
- * NEW column instead of overwriting whichever route happens to be open.
1602
- */
1603
- const startNewRoute = useCallback(() => {
1604
- setCreatedRoute(null);
1605
- // ⛔⛔ REFUSED OUT LOUD, IN THE RAIL'S OWN SLOT. The name box lives inside the planner's
1606
- // `{plan && (...)}`, and `plan` is null until two records can actually be routed - so
1607
- // flipping `naming` with nothing selected would open a form that never renders and leave
1608
- // Create as a menu row that does nothing. The rail's `notice` is the one message slot that
1609
- // is on screen whether or not a plan exists, which is why the refusal goes there.
1610
- if (routable.length < 2) {
1611
- setRailNotice(
1612
- "A route is a solved sequence, so select at least two records on the map first. Then " +
1613
- "Create new gives you the name box."
1614
- );
1615
- return;
1616
- }
1617
- setRailNotice("");
1618
- setSaveTarget("");
1619
- setSaveErr(null);
1620
- setSaveMsg(null);
1621
- setRouteOn(true);
1622
- setNaming(true);
1623
- setNameDraft(nextLabel);
1624
- }, [nextLabel, routable]);
1625
-
1626
- /**
1627
- * The rail's routes, in the reader's own arrangement.
1628
- *
1629
- * ⚠ `railOrder` RANKS, IT DOES NOT FILTER. A route the order has never heard of keeps its place
1630
- * after the ranked ones, so a colleague's brand-new route appears rather than vanishing until
1631
- * somebody drags something.
1632
- */
1633
- const railRoutes = useMemo<RouteNavRoute[]>(() => {
1634
- const all = routeCols || [];
1635
- if (!railOrder.length) return all;
1636
- const rank = new Map(railOrder.map((k, i) => [k, i]));
1637
- return [...all].sort(
1638
- (a, b) => (rank.get(a.key) ?? Number.MAX_SAFE_INTEGER) - (rank.get(b.key) ?? Number.MAX_SAFE_INTEGER)
1639
- );
1640
- }, [routeCols, railOrder]);
1641
-
1642
- const reorderRail = useCallback((order: string[]) => setRailOrder(order), []);
1643
- const dismissCreated = useCallback(() => setCreatedRoute(null), []);
1644
-
1645
  /**
1646
  * The saved column selected for writing, and whether what is on screen would solve differently.
1647
  *
@@ -1847,142 +1824,6 @@ export function MapView({
1847
  [plan]
1848
  );
1849
 
1850
- /**
1851
- * ⭐ W42-T21 — TYPING A POSITION IS A MOVE-TO-POSITION, NOT A RANK.
1852
- *
1853
- * ⛔⛔ THE TYPED NUMBER IS A TARGET INDEX AND IS DISCARDED BEFORE ANY RANK EXISTS. Writing it
1854
- * as that record's rank is the trap: `routes_customers.py::route_order_write` refuses any body
1855
- * that is not a full 1..N permutation, so a straight-through write leaves a duplicate or a gap
1856
- * and the endpoint 400s, which reads to a person as "typing does not work". Here the value
1857
- * only chooses where the pid is re-inserted; the sequence is then rebuilt by the same
1858
- * remove-then-insert the arrows use, and `plan` inverts THAT into `ranksByPid` from array
1859
- * indices. So the saved order is 1..N by construction, whatever was typed.
1860
- *
1861
- * Returns the sentence to show, or null when the move was applied.
1862
- */
1863
- const moveStopTo = useCallback(
1864
- (pid: number, raw: string): string | null => {
1865
- if (!plan || pid === DEPOT_PID) return null;
1866
- const ids = plan.ordered.filter((p) => p.pid !== DEPOT_PID).map((p) => p.pid);
1867
- const at = ids.indexOf(pid);
1868
- if (at < 0) return "This stop is no longer on the route, so its position cannot be set.";
1869
- const text = raw.trim();
1870
- if (!/^[0-9]+$/.test(text)) {
1871
- return "A position is a whole number, so type a digit rather than anything else.";
1872
- }
1873
- const pos = Number(text);
1874
- if (pos < 1 || pos > ids.length) {
1875
- return ids.length === 1
1876
- ? "There is one stop on this route, so the only position is 1."
1877
- : `There are ${ids.length} stops on this route, so a position runs from 1 to ${ids.length}.`;
1878
- }
1879
- if (pos === at + 1) return null;
1880
- const next = [...ids];
1881
- next.splice(pos - 1, 0, next.splice(at, 1)[0]);
1882
- // ⚠ AN INVARIANT GUARD, NOT THE REFUSAL A PERSON WILL MEET. Remove-then-insert on a list
1883
- // that was already a permutation cannot duplicate or drop a pid, so this cannot fire from
1884
- // the keyboard; it is here so that a future edit which DOES break the sequence stops at
1885
- // the screen instead of at a 400 the user has no way to read.
1886
- if (next.length !== ids.length || new Set(next).size !== next.length) {
1887
- return "That would leave two stops sharing a position, so the route was left as it was.";
1888
- }
1889
- setRouteOrder(next);
1890
- return null;
1891
- },
1892
- [plan]
1893
- );
1894
-
1895
- /**
1896
- * Commit what is in the box. A refusal keeps the typed text on screen and sends nothing; a
1897
- * move clears both the draft and any refusal, and the row renumbers itself from `plan`.
1898
- */
1899
- const commitStopPos = useCallback(
1900
- (pid: number, raw: string) => {
1901
- const msg = moveStopTo(pid, raw);
1902
- if (msg) {
1903
- setStopPosError({ pid, msg });
1904
- return;
1905
- }
1906
- setStopPosDraft(null);
1907
- setStopPosError(null);
1908
- },
1909
- [moveStopTo]
1910
- );
1911
-
1912
- /**
1913
- * ⛔⛔ W42-T49 — MEMBERSHIP, AND IT IS NOT THE SELECTION.
1914
- *
1915
- * `selectedPids` is the map's highlight. The route panel SEEDS that highlight from a route when
1916
- * one is opened, which is exactly what makes the two sets easy to confuse and the confusion
1917
- * invisible. The question here is a different one: is this record a STOP on the route now on
1918
- * screen? The route on screen is `plan.ordered` (the depot is not a record, so it is dropped);
1919
- * before a plan has been solved there is still an order to answer from, either a hand-picked
1920
- * `routeOrder` or the ranks the saved column carries on the rows, read exactly as
1921
- * `openSavedRoute` reads them (as NUMBERS, since `shared_overlay` stores cells as strings).
1922
- *
1923
- * ⚠ THE SAVED CELLS ARE A LAST RESORT AND NEVER A UNION with the live list. A stop taken off
1924
- * the route keeps its old rank in the column until Save route writes the new sequence, so
1925
- * folding the cells into the live set would answer "still on it" for the stop just removed.
1926
- */
1927
- const routeStopPids = useMemo<ReadonlySet<number>>(() => {
1928
- if (plan) {
1929
- return new Set(plan.ordered.filter((p) => p.pid !== DEPOT_PID).map((p) => p.pid));
1930
- }
1931
- if (routeOrder && routeOrder.length) return new Set(routeOrder);
1932
- const out = new Set<number>();
1933
- if (!openedRoute) return out;
1934
- const book = allRows && allRows.length ? allRows : rows;
1935
- for (const r of book) {
1936
- const raw = r[openedRoute];
1937
- if (raw === null || raw === undefined || raw === "") continue;
1938
- if (Number.isFinite(Number(raw))) out.add(r.pid);
1939
- }
1940
- return out;
1941
- }, [plan, routeOrder, openedRoute, allRows, rows]);
1942
-
1943
- /**
1944
- * ⭐⭐ W42-T49 — THE PIN CLICK ASKS FIRST, AND IT ASKS THE RIGHT QUESTION.
1945
- *
1946
- * ⛔ IT CHANGES NOTHING. Raising the prompt is the whole of this handler: a pin is a target you
1947
- * had to aim at, and on a map where pins overlap an aimed click that silently rewrote somebody's
1948
- * day would be worse than the drawer it replaced.
1949
- */
1950
- const askRoutePin = useCallback(
1951
- (pid: number, title: string) => {
1952
- if (pid === DEPOT_PID) return;
1953
- setRoutePinAsk({ pid, title, on: routeStopPids.has(pid) });
1954
- },
1955
- [routeStopPids]
1956
- );
1957
-
1958
- /**
1959
- * ⛔⛔ W42-T49 — ADD AND REMOVE GO THROUGH THE PANEL'S OWN DOORS, SO THE SEQUENCE IS REBUILT.
1960
- *
1961
- * `route_order_write` refuses any body that is not a full 1..N permutation, so a rank written
1962
- * through for one record is the trap here exactly as it was for the typed position in W42-T21.
1963
- * Nothing in this path touches a rank: `addRecord` appends the pid to `routeOrder` and
1964
- * `removeStop` filters it out, `plan` then re-derives `ranksByPid` from ARRAY INDICES over
1965
- * whatever list survived, and `saveRouteOrder` sends that. The saved order is therefore 1..N by
1966
- * construction whichever pin was clicked.
1967
- *
1968
- * ⚠ AND IT IS THE ROUTE ON SCREEN THAT MOVES, NOT THE STORED COLUMN. `plan` has not recomputed
1969
- * in this tick, so saving from here would persist the sequence as it was BEFORE the stop moved:
1970
- * a plausible permutation describing the wrong day. The message says which act still writes.
1971
- */
1972
- const applyRoutePin = useCallback(() => {
1973
- const ask = routePinAsk;
1974
- if (!ask) return;
1975
- setRoutePinAsk(null);
1976
- const name = ask.title || `record ${ask.pid}`;
1977
- if (ask.on) {
1978
- removeStop(ask.pid);
1979
- setRailNotice(`${name} is off this route. Save route writes the new visit numbers.`);
1980
- return;
1981
- }
1982
- addRecord(ask.pid);
1983
- setRailNotice(`${name} joins this route at the end. Save route writes the new visit numbers.`);
1984
- }, [routePinAsk, removeStop, addRecord]);
1985
-
1986
  const paint = useCallback(
1987
  (p: MapPoint) => {
1988
  if (!colorBuckets) return DEFAULT_PIN;
@@ -2275,6 +2116,20 @@ export function MapView({
2275
  if (held) hits.push(p.pid);
2276
  }
2277
  onSelectPids(hits, e.altKey ? "add" : "replace");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2278
  }
2279
  setDrag(null);
2280
  }
@@ -2446,94 +2301,126 @@ export function MapView({
2446
  body was behind the two-selected wall this item removes; `plan.ordered[0]` with nothing
2447
  selected is a crash, not a blank.
2448
  ═══════════════════════════════════════════════════════════════════════════════════ */}
2449
- {routePanelOpen && (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2450
  <aside id="cg-route-popover" className="cg-route-popover" aria-label="Route navigation">
2451
  <div className="cg-route-popover-head">
2452
- <span className="cg-views-title">Route</span>
 
 
 
 
 
 
 
2453
  <span className="cg-route-popover-count">
2454
  {selectedPids.size > 0
2455
  ? `${selectedPids.size.toLocaleString()} selected`
2456
  : "Nothing selected"}
2457
  </span>
2458
  </div>
2459
- {/* ══ W42-T49 — THE PIN CLICK'S ANSWER, ASKED BEFORE ANYTHING MOVES ═════════════
2460
- ⭐ IT LIVES IN THE ROUTE'S OWN PANEL, at the top, because the route is what the
2461
- question is about and the panel is the surface that shows the consequence: the
2462
- stop list under it gains or loses the row the moment Add or Take off is pressed.
2463
- ⚠ EXISTING CLASSES ONLY (`cg-route-name`, the name box's row). The stylesheet is
2464
- not this ticket's file, and a lane stylesheet cannot override index.css anyway.
2465
- ⛔ THE BUTTON HANDLERS TAKE NO EVENT ARGUMENT, deliberately, and this note may not
2466
- spell the shape it is about either. `verify_map.py`'s `structural_scan` slices the
2467
- FIRST arrow-with-an-event click handler in this file and reads it as the pin's, so
2468
- any earlier handler declaring one - or any comment quoting that spelling - hands
2469
- the R10 referee somebody else's body to judge. */}
2470
- {routePinAsk && (
2471
- <div className="cg-route-name" role="group" aria-label="Change this route's stops">
2472
- <span className="cg-map-route-note">
2473
- {routePinAsk.on
2474
- ? `Take ${routePinAsk.title || `record ${routePinAsk.pid}`} off this route?`
2475
- : `Add ${routePinAsk.title || `record ${routePinAsk.pid}`} to this route?`}
2476
- </span>
2477
- <span className="cg-route-name-actions">
2478
- <button
2479
- type="button"
2480
- className="cg-btn cg-btn--primary"
2481
- autoFocus
2482
- onClick={applyRoutePin}
2483
- title={
2484
- routePinAsk.on
2485
- ? "Drop this stop and renumber the rest of the route"
2486
- : "Add this stop at the end of the route"
2487
- }
2488
- >
2489
- {routePinAsk.on ? "Take off route" : "Add to route"}
2490
- </button>
2491
- <button
2492
- type="button"
2493
- className="cg-btn"
2494
- onClick={() => setRoutePinAsk(null)}
2495
- title="Leave the route as it is"
2496
- >
2497
- Cancel
2498
- </button>
2499
- </span>
2500
- </div>
2501
- )}
2502
- {/* ══ W42-T24 (instruction 10, contract C6) — THE ROUTE NAVIGATION ═══════════════
2503
- ⭐⭐ THE LISTING IS NOW A NAVIGATION, not a dropdown. Every route this account may
2504
- see, mine and shared, each wearing the share mark when it is shared and carrying a
2505
- menu that renames, duplicates, deletes and SHARES it; routes drag into folders and
2506
- reorder; opening one is a single click and creating one is its own affordance.
2507
- ⚠ IT SITS ABOVE THE PLANNER AND DOES NOT REPLACE IT. The panel now reads
2508
- navigation first, then the planner that produces what the navigation lists.
2509
- ⚠ THE `Saved route` SELECT BELOW IS DELIBERATELY LEFT IN PLACE. `verify_map.py`'s
2510
- `saved-route-picker-is-unconditional` leg INDEXES the literal "Saved route" inside
2511
- `.cg-map-route` and would raise rather than fail without it; it is also still the
2512
- planner's own statement of which route is on screen. Removing it needs that leg
2513
- re-anchored, which is not this ticket's file. */}
2514
- <RouteNav
2515
- routes={railRoutes}
2516
- folders={routeFolders}
2517
- openKey={openedRoute}
2518
- busyKey={routeBusyKey}
2519
- notice={railNotice}
2520
- listError={routeListError}
2521
- onListRetry={retryRouteList}
2522
- onOpenRoute={openSavedRoute}
2523
- onCreateRoute={startNewRoute}
2524
- onRenameRoute={renameRoute}
2525
- onDuplicateRoute={duplicateRoute}
2526
- onDeleteRoute={removeRoute}
2527
- onShareRoute={shareRoute}
2528
- onRouteReorder={reorderRail}
2529
- onFolderReorder={reorderRouteFolders}
2530
- onRouteMove={moveRoute}
2531
- onFolderCreate={createRouteFolder}
2532
- onFolderRename={renameRouteFolder}
2533
- onFolderDelete={deleteRouteFolder}
2534
- created={createdRoute}
2535
- onCreatedDismiss={dismissCreated}
2536
- />
2537
  <div className="cg-map-route">
2538
  {/* ══ OWNER, 2026-08-23 — CHOOSE WHICH SAVED ROUTE TO LOOK AT ══════════════════
2539
  Owner: *"when I click the Route navigation button. I should be able to choose any
@@ -2838,70 +2725,21 @@ export function MapView({
2838
  <div className="cg-map-stoplist">
2839
  {plan.ordered.map((pt, i) => (
2840
  <span className="cg-map-stopitem" key={pt.pid}>
2841
- {/* ⭐ W42-T21 — THE VISIT NUMBER IS TYPEABLE. It stays inside the same
2842
- navy disc rather than becoming a box of its own, so the list reads as
2843
- the same numbered stack it always did and the affordance is that the
2844
- number takes a caret. The depot branch is untouched: a depot carries no
2845
- visit number and so has nothing to type into. The inline rules are the
2846
- input reset only (a text box's own chrome would draw a rectangle across
2847
- the disc); every colour and size still comes from `.cg-map-stopn`. */}
2848
  <span className="cg-map-stopn">
2849
- {pt.pid === DEPOT_PID ? "" : (
2850
- <input
2851
- type="text"
2852
- inputMode="numeric"
2853
- className="cg-map-stopnum"
2854
- style={{
2855
- width: "100%",
2856
- height: "100%",
2857
- padding: 0,
2858
- border: 0,
2859
- borderRadius: "50%",
2860
- background: "transparent",
2861
- color: "inherit",
2862
- font: "inherit",
2863
- textAlign: "center",
2864
- }}
2865
- value={
2866
- stopPosDraft && stopPosDraft.pid === pt.pid
2867
- ? stopPosDraft.text
2868
- : String(i + 1 - (plan.depot ? 1 : 0))
2869
- }
2870
- aria-label={`Position of ${pt.title || `#${pt.pid}`} on the route`}
2871
- title="Type a position to move this stop there"
2872
- aria-invalid={stopPosError && stopPosError.pid === pt.pid ? true : undefined}
2873
- aria-describedby={
2874
- stopPosError && stopPosError.pid === pt.pid
2875
- ? "cg-map-stoppos-error"
2876
- : undefined
2877
- }
2878
- onFocus={(e) => e.currentTarget.select()}
2879
- onChange={(e) => {
2880
- setStopPosDraft({ pid: pt.pid, text: e.target.value });
2881
- setStopPosError(null);
2882
- }}
2883
- onKeyDown={(e) => {
2884
- if (e.key === "Enter") {
2885
- e.preventDefault();
2886
- commitStopPos(pt.pid, e.currentTarget.value);
2887
- } else if (e.key === "Escape") {
2888
- e.preventDefault();
2889
- setStopPosDraft(null);
2890
- setStopPosError(null);
2891
- e.currentTarget.blur();
2892
- }
2893
- }}
2894
- onBlur={(e) => {
2895
- if (stopPosDraft && stopPosDraft.pid === pt.pid) {
2896
- commitStopPos(pt.pid, e.target.value);
2897
- }
2898
- }}
2899
- />
2900
- )}
2901
- </span>
2902
- <span className="cg-map-stopname" title={pt.title || `#${pt.pid}`}>
2903
- {pt.title || `#${pt.pid}`}
2904
  </span>
 
 
 
 
 
 
 
 
 
 
 
 
2905
  {pt.pid !== DEPOT_PID && (
2906
  <>
2907
  <button
@@ -2946,21 +2784,6 @@ export function MapView({
2946
  </div>
2947
  )}
2948
 
2949
- {/* ⭐ W42-T21 — THE REFUSAL, AND IT IS ON SCREEN RATHER THAN IN A REQUEST.
2950
- It sits directly under the stop list so it is the next thing below the box that
2951
- was typed into, is announced as an alert, and is what `aria-describedby` on
2952
- that box points at. Nothing is sent while it is showing. */}
2953
- {stopPosError && (
2954
- <span
2955
- id="cg-map-stoppos-error"
2956
- role="alert"
2957
- className="cg-map-route-note"
2958
- style={{ color: "var(--lp-red-deep)" }}
2959
- >
2960
- {stopPosError.msg}
2961
- </span>
2962
- )}
2963
-
2964
  {/* ⛔ WAVE 41 / R13 — THE DISCARD-MY-ORDER BUTTON STOOD HERE AND IS NOT REPLACED
2965
  IN PLACE. Discarding the hand-picked sequence is half of `Update calculation`
2966
  in the foot row now, so a control offering only that half would put the panel
@@ -3016,6 +2839,19 @@ export function MapView({
3016
  here, directly above the two buttons that finish the job. */}
3017
  {plan.links.length > 0 && (
3018
  <div className="cg-map-google-links" aria-label="Google Maps route links">
 
 
 
 
 
 
 
 
 
 
 
 
 
3019
  {plan.links.map((link) => (
3020
  <a
3021
  key={link.index}
@@ -3027,8 +2863,35 @@ export function MapView({
3027
  Google Maps route {link.index}
3028
  </a>
3029
  ))}
 
 
 
 
3030
  </div>
3031
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3032
  {/* ── ITEMS 4 AND 5: "Save route", and it ASKS FOR THE NAME ─────────────────
3033
  ⭐ ITEM 4 — the button read "Save visit order". Owner: *"Change the button
3034
  called 'Save visit order' to 'Save route'."* The FIELD is still the visit
@@ -3213,20 +3076,161 @@ export function MapView({
3213
  "every record without a pin", so a whole-table run is not a thing a user can reach or a
3214
  future edit can accidentally enable. */}
3215
  {geoControl}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3216
  {/* Every gesture the map has, named. `alt` (add to the selection rather
3217
  than replace it, onPointerUp) shipped in wave 8 and was disclosed
3218
  NOWHERE, so "select these as well" was a feature only the source
3219
  knew about. It needs shift too — alt alone still pans. */}
3220
  <span className="cg-map-hint">
3221
  Scroll to zoom · drag to pan · {lassoTool ? "shift-drag to lasso" : "shift-drag to select"}{" "}
3222
- · shift-alt-drag to extend the selection ·{" "}
3223
- {/* W42-T49 — the SIGHTED half of the pin's disclosure, and it follows the mode for the
3224
- same reason the aria-label does. Both wordings stay in the source, which is what
3225
- `verify_map.py::pin-gesture-disclosed` reads. */}
3226
- {routePanelOpen
3227
- ? "click a pin to add it to the route or take it off"
3228
- : "click a pin to open the record"}{" "}
3229
- · shift-click a pin to add or remove it from the selection
3230
  </span>
3231
  </div>
3232
  <div
@@ -3314,6 +3318,22 @@ export function MapView({
3314
  ))}
3315
  </>
3316
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3317
  {/* The planned path, UNDER the pins so it never hides a stop. Inside
3318
  the zoomed group, so it pans and scales with the geography; the
3319
  stroke is pre-divided by k like every other line here. */}
@@ -3383,18 +3403,7 @@ export function MapView({
3383
  // hint bar above is the SIGHTED half of this same disclosure. It said "Click to
3384
  // select, double click to open." until R10 made that false.
3385
  // Policed by `verify_ui.py::pin_label_states_the_gesture`.
3386
- // ⭐ W42-T49 — AND THE NAME FOLLOWS THE MODE, because the gesture does. With the
3387
- // route open a plain click no longer opens anything, and an accessible name
3388
- // still promising a record is the same class of lie R10 had to come back and
3389
- // fix here. The modifier half is unchanged in every branch: shift-click works
3390
- // the selection whatever the route is doing.
3391
- aria-label={`${p.title || "Untitled record"}. ${
3392
- routePanelOpen
3393
- ? routeStopPids.has(p.pid)
3394
- ? "Click to take this stop off the route, shift-click to select."
3395
- : "Click to add this stop to the route, shift-click to select."
3396
- : "Click to open, shift-click to select."
3397
- }`}
3398
  onMouseEnter={() => setHoverPid(p.pid)}
3399
  onMouseLeave={() => setHoverPid((h) => (h === p.pid ? null : h))}
3400
  onFocus={() => setHoverPid(p.pid)}
@@ -3412,20 +3421,6 @@ export function MapView({
3412
  pinSelect(p.pid, true);
3413
  return;
3414
  }
3415
- // ⭐⭐ W42-T49 — WITH THE ROUTE NAVIGATION OPEN, A PIN IS A STOP.
3416
- // The person has a day on screen and the thing they want after aiming at a
3417
- // pin is that day changed, not a drawer over the map hiding it. So the click
3418
- // asks, and the record detail is not opened: everything below this line is
3419
- // skipped, including the rail fold, which exists only to make room for a
3420
- // drawer that is not coming.
3421
- // ⛔ THE BRANCH IS THE PROP AND NOTHING ELSE. `routePanelOpen` is
3422
- // `CustomerGrid`'s own state for the route navigation, so with the route
3423
- // closed this is not taken and the two lines below are today's behaviour,
3424
- // reached by the same click on the same pin.
3425
- if (routePanelOpen) {
3426
- askRoutePin(p.pid, p.title);
3427
- return;
3428
- }
3429
  // ⭐⭐ W41-T48 (owner instruction 22) — OPENING A RECORD FOLDS THE RAIL, ON
3430
  // THE MAP EXACTLY AS IN THE GRID. `CustomerGrid.tsx::onCellClicked` raises
3431
  // this on every cell click; the map was the one surface that opened a record
@@ -3460,11 +3455,6 @@ export function MapView({
3460
  onDoubleClick={(e) => {
3461
  if (movedRef.current) return;
3462
  e.preventDefault();
3463
- // ⚠ W42-T49 — THIS IS A REPEAT OF THE PLAIN CLICK (see the note above), so it
3464
- // repeats what the plain click just did. With the route open that was a
3465
- // prompt, which is already on screen; opening the record here would let a
3466
- // double click reach the drawer the single click deliberately did not.
3467
- if (routePanelOpen) return;
3468
  onOpen(p.pid);
3469
  }}
3470
  onKeyDown={(e) => {
@@ -3476,13 +3466,6 @@ export function MapView({
3476
  // disambiguate, so the guard the pointer needs would only be superstition.
3477
  if (e.key === "Enter") {
3478
  e.preventDefault();
3479
- // W42-T49 — Enter is the plain click's mirror (see the note over the
3480
- // keyboard block), so it mirrors the route mode too. A keyboard user who
3481
- // cannot reach the prompt is a keyboard user who cannot work the route.
3482
- if (routePanelOpen) {
3483
- askRoutePin(p.pid, p.title);
3484
- return;
3485
- }
3486
  // W41-T48 — the keyboard mirror of the plain click, so it folds the rail
3487
  // for the same reason. ⚠ `!e.repeat` is this path's `e.detail <= 1`: a HELD
3488
  // Enter auto-repeats keydown for as long as the finger is down, and every
 
93
  } from "./mapProjection";
94
  import type { GeoStop, Pt, RouteStamp, View } from "./mapProjection";
95
  import { LP_INK, LP_MAP_SELECTED } from "./theme";
 
 
 
 
 
 
 
 
 
 
96
  import "./map.css";
97
 
98
  /**
 
313
  * ninth colour that repeats the first would make two meanings look identical. */
314
  const OVERFLOW = { fill: "#D7DBE3", line: "#8A909C" };
315
  const DEFAULT_PIN = { fill: "#9DBFF2", line: "#4F6079" };
316
+ const ZONE_COLOR_CHOICES = [
317
+ { value: "#9DBFF2", label: "Blue" },
318
+ { value: "#A5D8B4", label: "Green" },
319
+ { value: "#F5D989", label: "Yellow" },
320
+ { value: "#F0A8A0", label: "Red" },
321
+ { value: "#C7B7E8", label: "Purple" },
322
+ ];
323
+
324
+ type ZoneGeometry = {
325
+ type: "Polygon" | "MultiPolygon";
326
+ coordinates: number[][][] | number[][][][];
327
+ };
328
+
329
+ /** C3's durable map-domain DTO. Zones are not generic fields: geometry, visibility and the
330
+ * membership snapshot only make sense to this projection. */
331
+ interface MapZone {
332
+ id: string;
333
+ name: string;
334
+ color: string;
335
+ geometryGeoJson: ZoneGeometry;
336
+ visible: boolean;
337
+ geographicField: string;
338
+ memberships: number[];
339
+ createdBy?: string;
340
+ createdAt?: string;
341
+ }
342
+
343
+ interface RouteDelivery {
344
+ id: string;
345
+ name: string;
346
+ recipient: string;
347
+ schedule: { cron?: string; enabled?: boolean };
348
+ snapshot: {
349
+ sourceViewId: string;
350
+ sourceViewRevision: string;
351
+ sourceViewName: string;
352
+ timezone: string;
353
+ routeField: string;
354
+ orderedStopIds: number[];
355
+ mapsPerLink: number;
356
+ };
357
+ }
358
 
359
  interface MapPoint {
360
  pid: number;
 
452
  // I18-R — the route planner. Off until asked for: a route drawn over a
453
  // selection nobody asked to route is just clutter.
454
  const [routeOn, setRouteOn] = useState(false);
455
+ /** Route navigation is an index first; planning begins only after the explicit Create route
456
+ * action or an existing saved route has been opened. */
457
+ const [routeCreateOpen, setRouteCreateOpen] = useState(false);
458
  const [roundTrip, setRoundTrip] = useState(false);
459
  const [routeStartPid, setRouteStartPid] = useState<number | null>(null);
460
  const askRoadRef = useRef(false);
 
468
  * Kept as pids rather than indices because the selection can change underneath it.
469
  */
470
  const [routeOrder, setRouteOrder] = useState<number[] | null>(null);
 
 
 
 
 
 
 
 
 
 
 
 
 
471
  /**
472
  * ⛔ OWNER ITEM 6 — THE DEPOT UI IS GONE AND THIS STATE DELIBERATELY IS NOT. The owner removed
473
  * the "Optional route start" section: the start is the record dropdown and nothing else. What
 
495
  * would have had to re-derive every one of those and would have drifted from the first.
496
  */
497
  const [addedPids, setAddedPids] = useState<ReadonlySet<number>>(EMPTY_PIDS);
498
+ /** C3 Zone chooser/editor state. `null` means the tenant read has not answered; an empty
499
+ * array is an honest, editable no-Zones state. */
500
+ const [zones, setZones] = useState<MapZone[] | null>(null);
501
+ const [activeZoneIds, setActiveZoneIds] = useState<ReadonlySet<string>>(new Set());
502
+ const [zoneEditorId, setZoneEditorId] = useState("");
503
+ const [zoneName, setZoneName] = useState("");
504
+ const [zoneColor, setZoneColor] = useState(ZONE_COLOR_CHOICES[0].value);
505
+ const [zoneGeographicField, setZoneGeographicField] = useState("");
506
+ const [zoneGeographicValue, setZoneGeographicValue] = useState("");
507
+ const [drawnZoneGeometry, setDrawnZoneGeometry] = useState<ZoneGeometry | null>(null);
508
+ const [zoneBusy, setZoneBusy] = useState(false);
509
+ const [zoneErr, setZoneErr] = useState<string | null>(null);
510
  /**
511
  * W37-T36 — the ROAD answer, which is the half arithmetic cannot produce.
512
  *
 
543
  * must not render "no saved orders".
544
  */
545
  const [routeCols, setRouteCols] = useState<
546
+ {
547
+ key: string;
548
+ label: string;
549
+ inputsHash: string;
550
+ mine: boolean;
551
+ stops?: number;
552
+ solvedAt?: string;
553
+ solvedBy?: string;
554
+ note?: string;
555
+ depot?: RouteDepot | null;
556
+ }[] | null
557
  >(null);
558
+ const [routeEditKey, setRouteEditKey] = useState("");
559
+ const [routeEditName, setRouteEditName] = useState("");
560
+ const [routeEditNote, setRouteEditNote] = useState("");
561
+ const [routeEditBusy, setRouteEditBusy] = useState(false);
562
+ const [routeEditErr, setRouteEditErr] = useState<string | null>(null);
563
+ /** C2 keeps this bounded value in every frozen route snapshot. */
564
+ const [mapsPerLink, setMapsPerLink] = useState(10);
565
+ const [routeCopyMsg, setRouteCopyMsg] = useState<string | null>(null);
566
+ const [routeRecipient, setRouteRecipient] = useState("");
567
+ const [routeScheduleBusy, setRouteScheduleBusy] = useState(false);
568
+ const [routeScheduleMsg, setRouteScheduleMsg] = useState<string | null>(null);
569
+ const [routeScheduleErr, setRouteScheduleErr] = useState<string | null>(null);
570
+ const [routeDeliveries, setRouteDeliveries] = useState<RouteDelivery[] | null>(null);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
571
  /** Which saved column a save writes to. `""` = a new field, named in the prompt below. */
572
  const [saveTarget, setSaveTarget] = useState("");
573
  /**
 
759
  }, [mapRows, field.key, coordField, colorField, sizeField]);
760
  const noCoords = mapRows.length - points.length;
761
 
762
+ /** Geography is selected from existing row data rather than introduced as a parallel value
763
+ * store. The choice is also recorded on a Zone as C3 provenance. */
764
+ const geographicFields = useMemo(() => {
765
+ const candidates = new Set<string>();
766
+ for (const row of mapRows.slice(0, 250)) {
767
+ for (const key of Object.keys(row)) {
768
+ if (/(address|city|state|province|region|country|zip|postal|territory|area)/i.test(key))
769
+ candidates.add(key);
770
+ }
771
+ }
772
+ return [...candidates].sort((a, b) => a.localeCompare(b));
773
+ }, [mapRows]);
774
+ useEffect(() => {
775
+ if (zoneGeographicField && geographicFields.includes(zoneGeographicField)) return;
776
+ setZoneGeographicField(geographicFields[0] || "");
777
+ setZoneGeographicValue("");
778
+ }, [geographicFields, zoneGeographicField]);
779
+ const geographicValues = useMemo(() => {
780
+ if (!zoneGeographicField) return [];
781
+ const values = new Set<string>();
782
+ for (const row of mapRows) {
783
+ const value = String(row[zoneGeographicField] ?? "").trim();
784
+ if (value) values.add(value);
785
+ }
786
+ return [...values].sort((a, b) => a.localeCompare(b));
787
+ }, [mapRows, zoneGeographicField]);
788
+
789
+ const loadZones = useCallback(async () => {
790
+ try {
791
+ const res = await fetch("/api/v1/geo/zones", { credentials: "same-origin" });
792
+ const body = res.ok ? await res.json().catch(() => null) : null;
793
+ setZones(Array.isArray(body?.zones) ? body.zones : []);
794
+ } catch {
795
+ setZones([]);
796
+ }
797
+ }, []);
798
+ useEffect(() => { void loadZones(); }, [loadZones]);
799
+
800
+ const activeZones = useMemo(
801
+ () => (zones || []).filter((zone) => zone.visible && activeZoneIds.has(zone.id)),
802
+ [zones, activeZoneIds]
803
+ );
804
+ const activeZonePids = useMemo(() => {
805
+ const pids = new Set<number>();
806
+ for (const zone of activeZones) for (const pid of zone.memberships || []) pids.add(pid);
807
+ return pids;
808
+ }, [activeZones]);
809
+ const zoneEditor = useMemo(
810
+ () => (zones || []).find((zone) => zone.id === zoneEditorId) || null,
811
+ [zones, zoneEditorId]
812
+ );
813
+ const zonePolygons = useMemo(() => activeZones.flatMap((zone) => {
814
+ const geometry = zone.geometryGeoJson;
815
+ const polygons = geometry?.type === "Polygon"
816
+ ? [geometry.coordinates as number[][][]]
817
+ : geometry?.type === "MultiPolygon"
818
+ ? geometry.coordinates as number[][][][]
819
+ : [];
820
+ return polygons.flatMap((polygon, polygonIndex) => polygon.map((ring, ringIndex) => ({
821
+ key: `${zone.id}:${polygonIndex}:${ringIndex}`,
822
+ zone,
823
+ points: ring
824
+ .filter((pair) => Array.isArray(pair) && Number.isFinite(pair[0]) && Number.isFinite(pair[1]))
825
+ .map((pair) => project(pair[0], pair[1])),
826
+ })).filter((ring) => ring.points.length >= 4));
827
+ }), [activeZones]);
828
+
829
+ const selectionZoneGeometry = useCallback((): ZoneGeometry | null => {
830
+ if (drawnZoneGeometry) return drawnZoneGeometry;
831
+ const selected = points.filter((point) => selectedPids.has(point.pid));
832
+ if (selected.length < 2) return null;
833
+ const xs = selected.map((point) => point.p.x);
834
+ const ys = selected.map((point) => point.p.y);
835
+ const pad = Math.max(WORLD * 0.004, (Math.max(...xs) - Math.min(...xs)) * 0.12,
836
+ (Math.max(...ys) - Math.min(...ys)) * 0.12);
837
+ const corners = [
838
+ { x: Math.min(...xs) - pad, y: Math.min(...ys) - pad },
839
+ { x: Math.max(...xs) + pad, y: Math.min(...ys) - pad },
840
+ { x: Math.max(...xs) + pad, y: Math.max(...ys) + pad },
841
+ { x: Math.min(...xs) - pad, y: Math.max(...ys) + pad },
842
+ ].map(unproject).map(({ lon, lat }) => [lon, lat]);
843
+ return { type: "Polygon", coordinates: [[...corners, corners[0]]] };
844
+ }, [drawnZoneGeometry, points, selectedPids]);
845
+
846
+ const saveZone = useCallback(async (existing?: MapZone) => {
847
+ const geometryGeoJson = selectionZoneGeometry();
848
+ const name = zoneName.trim() || existing?.name || "";
849
+ if (!name || !geometryGeoJson) {
850
+ setZoneErr("Name a Zone and draw or select at least two mapped records first.");
851
+ return;
852
+ }
853
+ setZoneBusy(true);
854
+ setZoneErr(null);
855
+ try {
856
+ const res = await fetch(existing ? `/api/v1/geo/zones/${encodeURIComponent(existing.id)}` : "/api/v1/geo/zones", {
857
+ method: existing ? "PATCH" : "POST",
858
+ credentials: "same-origin",
859
+ headers: { "Content-Type": "application/json" },
860
+ body: JSON.stringify({
861
+ name,
862
+ color: zoneColor || existing?.color || ZONE_COLOR_CHOICES[0].value,
863
+ geometryGeoJson,
864
+ visible: existing?.visible ?? true,
865
+ geographicField: zoneGeographicField,
866
+ memberships: [...selectedPids],
867
+ }),
868
+ });
869
+ const body = await res.json().catch(() => null);
870
+ if (!res.ok) {
871
+ setZoneErr(body?.error?.message || "The Zone could not be saved.");
872
+ return;
873
+ }
874
+ const saved = body?.zone as MapZone | undefined;
875
+ if (saved) {
876
+ setZones((current) => {
877
+ const without = (current || []).filter((zone) => zone.id !== saved.id);
878
+ return [...without, saved].sort((a, b) => a.name.localeCompare(b.name));
879
+ });
880
+ setActiveZoneIds((current) => new Set([...current, saved.id]));
881
+ }
882
+ setDrawnZoneGeometry(null);
883
+ setZoneName("");
884
+ } catch {
885
+ setZoneErr("The Zone could not be saved.");
886
+ } finally {
887
+ setZoneBusy(false);
888
+ }
889
+ }, [selectionZoneGeometry, zoneName, zoneColor, zoneGeographicField, selectedPids]);
890
+
891
+ const selectActiveZoneRecords = useCallback(() => {
892
+ if (activeZonePids.size) onSelectPids([...activeZonePids], "replace");
893
+ }, [activeZonePids, onSelectPids]);
894
+
895
+ const setZoneVisible = useCallback(async (zone: MapZone, visible: boolean) => {
896
+ setZoneBusy(true);
897
+ setZoneErr(null);
898
+ try {
899
+ const res = await fetch(`/api/v1/geo/zones/${encodeURIComponent(zone.id)}`, {
900
+ method: "PATCH",
901
+ credentials: "same-origin",
902
+ headers: { "Content-Type": "application/json" },
903
+ body: JSON.stringify({ visible }),
904
+ });
905
+ const body = await res.json().catch(() => null);
906
+ if (!res.ok) {
907
+ setZoneErr(body?.error?.message || "The Zone visibility could not be updated.");
908
+ return;
909
+ }
910
+ const saved = body?.zone as MapZone | undefined;
911
+ if (saved) setZones((current) => (current || []).map((item) => item.id === saved.id ? saved : item));
912
+ } catch {
913
+ setZoneErr("The Zone visibility could not be updated.");
914
+ } finally {
915
+ setZoneBusy(false);
916
+ }
917
+ }, []);
918
+
919
  // The fit is the INITIAL view, not the projection (see mapProjection.ts).
920
  const fit = useMemo(
921
  () => fitView(points.map((p) => p.p), VIEW_W, VIEW_H),
 
1124
  const autoRouteRef = useRef(false);
1125
  const [autoCapped, setAutoCapped] = useState(0);
1126
  useEffect(() => {
1127
+ if (!routePanelOpen || !routeCreateOpen) {
1128
  autoRouteRef.current = false;
1129
  setAutoCapped(0);
 
 
 
1130
  return;
1131
  }
1132
  if (autoRouteRef.current || points.length < 2) return;
 
1137
  onSelectPids(take.map((p) => p.pid), "replace");
1138
  setRouteOn(true);
1139
  setRouteOrder(null);
1140
+ }, [routePanelOpen, routeCreateOpen, points, selectedPids, onSelectPids]);
1141
 
1142
  /** The depot joins BOTH index-parallel arrays below at position zero, and only there. */
1143
  const depotPoint = useMemo((): MapPoint | null => {
 
1254
  startPid: depotPoint ? null : routable[start].pid,
1255
  links: googleRouteUrls(
1256
  ordered.map((p) => ({ lat: p.lat, lon: p.lon })),
1257
+ { roundTrip, coarsePointer, maxStops: mapsPerLink }
1258
  ),
1259
  /** The identity of THIS set of stops in THIS order. The road answer is only about the plan
1260
  * whose key it carries; anything else on screen makes it stale rather than wrong. */
 
1264
  customerStops: customerRoutable.length,
1265
  };
1266
  }, [routeOn, routable, customerRoutable.length, depotPoint, depot, roundTrip, routeStartPid,
1267
+ coarsePointer, routeOrder, mapsPerLink]);
1268
 
1269
  /** ⭐ ITEM 7 — a MODE change stales the drawn road exactly as a stop change does. Without the
1270
  * second clause, flipping to Walking would leave driving minutes on screen under a Walking
 
1350
  * the only way the STALE marker can exist at all.
1351
  */
1352
  const loadRouteCols = useCallback(async () => {
 
1353
  try {
1354
  const res = await fetch("/api/v1/customers/route-order", { credentials: "same-origin" });
1355
+ const body = res.ok ? await res.json().catch(() => null) : null;
1356
+ setRouteCols(Array.isArray(body?.fields) ? body.fields : []);
 
 
 
 
 
 
 
 
 
 
 
 
1357
  setNextLabel(typeof body?.nextLabel === "string" ? body.nextLabel : "");
1358
  } catch {
1359
+ // A listing that cannot be fetched is "none known", not an error banner over the map: the
1360
+ // planner still works, and the save below reports its own failure in its own words.
1361
  setRouteCols([]);
 
 
1362
  }
1363
  }, []);
1364
 
1365
+ const loadRouteDeliveries = useCallback(async () => {
1366
+ try {
1367
+ const res = await fetch("/api/v1/customers/route-deliveries", { credentials: "same-origin" });
1368
+ const body = res.ok ? await res.json().catch(() => null) : null;
1369
+ setRouteDeliveries(Array.isArray(body?.deliveries) ? body.deliveries : []);
1370
+ } catch {
1371
+ setRouteDeliveries([]);
1372
+ }
1373
+ }, []);
1374
 
1375
  // ⭐ OWNER, 2026-08-23 — `routePanelOpen`, NOT `routeOn`. The saved-route picker is the first
1376
  // control in the panel and it is how a person reaches somebody's plan without solving one of
 
1380
  useEffect(() => {
1381
  if ((routePanelOpen || routeOn) && routeCols === null) void loadRouteCols();
1382
  }, [routePanelOpen, routeOn, routeCols, loadRouteCols]);
1383
+ useEffect(() => {
1384
+ if (routePanelOpen && routeDeliveries === null) void loadRouteDeliveries();
1385
+ }, [routePanelOpen, routeDeliveries, loadRouteDeliveries]);
1386
+
1387
+ const updateRouteDetails = useCallback(async () => {
1388
+ if (!routeEditKey || !routeEditName.trim()) return;
1389
+ setRouteEditBusy(true);
1390
+ setRouteEditErr(null);
1391
+ try {
1392
+ const res = await fetch(`/api/v1/customers/route-order/${encodeURIComponent(routeEditKey)}`, {
1393
+ method: "PATCH",
1394
+ credentials: "same-origin",
1395
+ headers: { "Content-Type": "application/json" },
1396
+ body: JSON.stringify({ label: routeEditName.trim(), note: routeEditNote }),
1397
+ });
1398
+ const body = await res.json().catch(() => null);
1399
+ if (!res.ok) {
1400
+ setRouteEditErr(body?.error?.message || "The route details could not be saved.");
1401
+ return;
1402
+ }
1403
+ setRouteEditKey("");
1404
+ setRouteEditName("");
1405
+ setRouteEditNote("");
1406
+ await loadRouteCols();
1407
+ } catch {
1408
+ setRouteEditErr("The route details could not be saved.");
1409
+ } finally {
1410
+ setRouteEditBusy(false);
1411
+ }
1412
+ }, [routeEditKey, routeEditName, routeEditNote, loadRouteCols]);
1413
+
1414
+ const copyRouteLinks = useCallback(async () => {
1415
+ if (!plan?.links.length) return;
1416
+ const text = plan.links.map((link) => link.url).join("\n");
1417
+ if (!navigator.clipboard?.writeText) {
1418
+ setRouteCopyMsg("Clipboard access is unavailable in this browser.");
1419
+ return;
1420
+ }
1421
+ try {
1422
+ await navigator.clipboard.writeText(text);
1423
+ setRouteCopyMsg(`${plan.links.length.toLocaleString()} Google Maps link${plan.links.length === 1 ? "" : "s"} copied.`);
1424
+ } catch {
1425
+ setRouteCopyMsg("The Google Maps links could not be copied.");
1426
+ }
1427
+ }, [plan]);
1428
+
1429
+ const scheduleRouteDelivery = useCallback(async () => {
1430
+ if (!plan || !routeRecipient.trim()) return;
1431
+ const orderedStopIds = plan.ordered.map((point) => point.pid).filter((pid) => pid > 0);
1432
+ if (orderedStopIds.length < 2) return;
1433
+ setRouteScheduleBusy(true);
1434
+ setRouteScheduleErr(null);
1435
+ setRouteScheduleMsg(null);
1436
+ try {
1437
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
1438
+ const res = await fetch("/api/v1/customers/route-deliveries", {
1439
+ method: "POST",
1440
+ credentials: "same-origin",
1441
+ headers: { "Content-Type": "application/json" },
1442
+ body: JSON.stringify({
1443
+ name: openedRoute
1444
+ ? `${(routeCols || []).find((route) => route.key === openedRoute)?.label || "Route"} delivery`
1445
+ : "Scheduled route",
1446
+ recipient: routeRecipient.trim(),
1447
+ schedule: { cron: "0 8 * * *", enabled: true },
1448
+ routeSnapshot: {
1449
+ // MapView deliberately consumes C2's snapshot seam rather than persisting anything
1450
+ // through View/field machinery it does not own. The fingerprint is the frozen revision.
1451
+ sourceViewId: "map-current",
1452
+ sourceViewRevision: plan.fingerprint,
1453
+ sourceViewName: `${field.label} map route`,
1454
+ timezone,
1455
+ routeField: saveTarget || openedRoute,
1456
+ orderedStopIds,
1457
+ mapsPerLink,
1458
+ },
1459
+ }),
1460
+ });
1461
+ const body = await res.json().catch(() => null);
1462
+ if (!res.ok) {
1463
+ setRouteScheduleErr(body?.error?.message || "The route schedule could not be saved.");
1464
+ return;
1465
+ }
1466
+ setRouteScheduleMsg(`Scheduled ${orderedStopIds.length.toLocaleString()} frozen stops to ${routeRecipient.trim()} each day at 08:00.`);
1467
+ setRouteDeliveries((current) => {
1468
+ const delivery = body?.delivery as RouteDelivery | undefined;
1469
+ return delivery ? [...(current || []), delivery] : current;
1470
+ });
1471
+ } catch {
1472
+ setRouteScheduleErr("The route schedule could not be saved.");
1473
+ } finally {
1474
+ setRouteScheduleBusy(false);
1475
+ }
1476
+ }, [plan, routeRecipient, openedRoute, routeCols, field.label, saveTarget, mapsPerLink]);
1477
 
1478
  /**
1479
  * ⭐⭐ OWNER, 2026-08-23 — **OPEN A SAVED ROUTE AND SEE IT ON THE MAP.**
 
1603
  return;
1604
  }
1605
  const savedField = String(body?.field || "");
 
 
 
 
 
 
1606
  setSaveTarget(savedField);
1607
  setNaming(false);
1608
  if (savedField) onRouteFieldCreated?.(savedField);
 
 
 
1609
  setSaveMsg(
1610
  `Saved ${Number(body?.stops || 0).toLocaleString()} visit numbers to ` +
1611
  `${body?.label || "the column"}` +
 
1619
  }
1620
  }, [plan, saveTarget, roundTrip, routeCols, nextLabel, loadRouteCols, onRouteFieldCreated]);
1621
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1622
  /**
1623
  * The saved column selected for writing, and whether what is on screen would solve differently.
1624
  *
 
1824
  [plan]
1825
  );
1826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1827
  const paint = useCallback(
1828
  (p: MapPoint) => {
1829
  if (!colorBuckets) return DEFAULT_PIN;
 
2116
  if (held) hits.push(p.pid);
2117
  }
2118
  onSelectPids(hits, e.altKey ? "add" : "replace");
2119
+ // A selection gesture is also a deliberate geographic outline. Keep its exact
2120
+ // lon/lat geometry ready for C3's Save Zone action; the membership snapshot above
2121
+ // remains the answer to "which current records were in it".
2122
+ const outline = drag.kind === "rect"
2123
+ ? [
2124
+ { x: b.x0, y: b.y0 }, { x: b.x1, y: b.y0 },
2125
+ { x: b.x1, y: b.y1 }, { x: b.x0, y: b.y1 },
2126
+ ]
2127
+ : drag.pts;
2128
+ const coordinates = outline
2129
+ .map((screen) => unproject(fromScreen(screen, view)))
2130
+ .map(({ lon, lat }) => [lon, lat]);
2131
+ if (coordinates.length >= 3)
2132
+ setDrawnZoneGeometry({ type: "Polygon", coordinates: [[...coordinates, coordinates[0]]] });
2133
  }
2134
  setDrag(null);
2135
  }
 
2301
  body was behind the two-selected wall this item removes; `plan.ordered[0]` with nothing
2302
  selected is a crash, not a blank.
2303
  ═══════════════════════════════════════════════════════════════════════════════════ */}
2304
+ {routePanelOpen && !routeCreateOpen && (
2305
+ <aside id="cg-route-popover" className="cg-route-popover cg-route-index" aria-label="Routes">
2306
+ <div className="cg-route-popover-head">
2307
+ <span className="cg-views-title">Routes</span>
2308
+ <button
2309
+ type="button"
2310
+ className="cg-route-index-create"
2311
+ onClick={() => {
2312
+ setOpenedRoute("");
2313
+ setRouteOn(false);
2314
+ setRouteOrder(null);
2315
+ setRouteCreateOpen(true);
2316
+ }}
2317
+ >
2318
+ Create route
2319
+ </button>
2320
+ </div>
2321
+ {routeCols === null ? (
2322
+ <span className="cg-route-index-empty">Loading routes.</span>
2323
+ ) : routeCols.length === 0 ? (
2324
+ <span className="cg-route-index-empty">No routes yet. Create one from selected map records.</span>
2325
+ ) : (
2326
+ <div className="cg-route-index-list">
2327
+ {routeCols.map((route) => (
2328
+ <div className="cg-route-index-row" key={route.key}>
2329
+ <button
2330
+ type="button"
2331
+ className="cg-route-index-name"
2332
+ onClick={() => {
2333
+ setRouteCreateOpen(true);
2334
+ openSavedRoute(route.key);
2335
+ }}
2336
+ title={`Open ${route.label}`}
2337
+ >
2338
+ {route.label}
2339
+ </button>
2340
+ {route.mine && (
2341
+ <button
2342
+ type="button"
2343
+ className="cg-route-index-gear"
2344
+ aria-label={`Edit ${route.label}`}
2345
+ title={`Edit ${route.label}`}
2346
+ onClick={() => {
2347
+ setRouteEditErr(null);
2348
+ setRouteEditKey(route.key);
2349
+ setRouteEditName(route.label);
2350
+ setRouteEditNote(route.note || "");
2351
+ }}
2352
+ >
2353
+ <svg viewBox="0 0 16 16" aria-hidden="true">
2354
+ <path d="M6.5 2.2h3l.5 1.6 1.5.9 1.6-.4 1.5 2.6-1.2 1.1v1.8l1.2 1.1-1.5 2.6-1.6-.4-1.5.9-.5 1.6h-3L6 14l-1.5-.9-1.6.4-1.5-2.6 1.2-1.1V7.9L2.4 6.8l1.5-2.6 1.6.4L6 3.8z" />
2355
+ <circle cx="8" cy="8.8" r="2.1" />
2356
+ </svg>
2357
+ </button>
2358
+ )}
2359
+ <span className="cg-route-index-detail">
2360
+ {typeof route.stops === "number" ? `${route.stops.toLocaleString()} stops` : "Route"}
2361
+ {route.solvedBy ? ` · ${route.solvedBy}` : ""}
2362
+ {route.solvedAt ? ` · ${route.solvedAt.slice(0, 10)}` : ""}
2363
+ </span>
2364
+ {route.note && <span className="cg-route-index-detail">{route.note}</span>}
2365
+ {routeEditKey === route.key && (
2366
+ <div className="cg-route-index-edit" role="group" aria-label={`Edit ${route.label}`}>
2367
+ <input
2368
+ className="cg-input"
2369
+ value={routeEditName}
2370
+ aria-label="Route name"
2371
+ maxLength={120}
2372
+ onChange={(event) => setRouteEditName(event.target.value)}
2373
+ />
2374
+ <input
2375
+ className="cg-input"
2376
+ value={routeEditNote}
2377
+ aria-label="Route details"
2378
+ placeholder="Details"
2379
+ maxLength={240}
2380
+ onChange={(event) => setRouteEditNote(event.target.value)}
2381
+ />
2382
+ <span className="cg-route-index-actions">
2383
+ <button type="button" className="cg-btn cg-btn--primary" disabled={routeEditBusy || !routeEditName.trim()} onClick={() => void updateRouteDetails()}>
2384
+ {routeEditBusy ? "Saving" : "Save"}
2385
+ </button>
2386
+ <button type="button" className="cg-btn" onClick={() => setRouteEditKey("")}>Cancel</button>
2387
+ </span>
2388
+ {routeEditErr && <span className="cg-cal-nodate">{routeEditErr}</span>}
2389
+ </div>
2390
+ )}
2391
+ </div>
2392
+ ))}
2393
+ </div>
2394
+ )}
2395
+ {routeDeliveries && routeDeliveries.length > 0 && (
2396
+ <div className="cg-route-index-schedules" aria-label="Scheduled routes">
2397
+ <span className="cg-route-index-label">Scheduled</span>
2398
+ {routeDeliveries.map((delivery) => (
2399
+ <span className="cg-route-index-detail" key={delivery.id}>
2400
+ {delivery.name} · {delivery.recipient} · {delivery.snapshot.orderedStopIds.length.toLocaleString()} stops
2401
+ </span>
2402
+ ))}
2403
+ </div>
2404
+ )}
2405
+ </aside>
2406
+ )}
2407
+ {routePanelOpen && routeCreateOpen && (
2408
  <aside id="cg-route-popover" className="cg-route-popover" aria-label="Route navigation">
2409
  <div className="cg-route-popover-head">
2410
+ <button
2411
+ type="button"
2412
+ className="cg-route-index-back"
2413
+ onClick={() => setRouteCreateOpen(false)}
2414
+ title="Back to routes"
2415
+ >
2416
+ Routes
2417
+ </button>
2418
  <span className="cg-route-popover-count">
2419
  {selectedPids.size > 0
2420
  ? `${selectedPids.size.toLocaleString()} selected`
2421
  : "Nothing selected"}
2422
  </span>
2423
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2424
  <div className="cg-map-route">
2425
  {/* ══ OWNER, 2026-08-23 — CHOOSE WHICH SAVED ROUTE TO LOOK AT ══════════════════
2426
  Owner: *"when I click the Route navigation button. I should be able to choose any
 
2725
  <div className="cg-map-stoplist">
2726
  {plan.ordered.map((pt, i) => (
2727
  <span className="cg-map-stopitem" key={pt.pid}>
 
 
 
 
 
 
 
2728
  <span className="cg-map-stopn">
2729
+ {pt.pid === DEPOT_PID ? "" : i + 1 - (plan.depot ? 1 : 0)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2730
  </span>
2731
+ {pt.pid === DEPOT_PID ? (
2732
+ <span className="cg-map-stopname">{pt.title || "Depot"}</span>
2733
+ ) : (
2734
+ <button
2735
+ type="button"
2736
+ className="cg-map-stopname cg-map-stopopen"
2737
+ title={`Open ${pt.title || `record #${pt.pid}`} details`}
2738
+ onClick={() => onOpen(pt.pid)}
2739
+ >
2740
+ {pt.title || `#${pt.pid}`}
2741
+ </button>
2742
+ )}
2743
  {pt.pid !== DEPOT_PID && (
2744
  <>
2745
  <button
 
2784
  </div>
2785
  )}
2786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2787
  {/* ⛔ WAVE 41 / R13 — THE DISCARD-MY-ORDER BUTTON STOOD HERE AND IS NOT REPLACED
2788
  IN PLACE. Discarding the hand-picked sequence is half of `Update calculation`
2789
  in the foot row now, so a control offering only that half would put the panel
 
2839
  here, directly above the two buttons that finish the job. */}
2840
  {plan.links.length > 0 && (
2841
  <div className="cg-map-google-links" aria-label="Google Maps route links">
2842
+ <label className="cg-map-route-opt cg-route-maps-cap">
2843
+ Stops per Google Maps link
2844
+ <select
2845
+ className="cg-route-select"
2846
+ value={mapsPerLink}
2847
+ aria-label="Stops per Google Maps link"
2848
+ onChange={(event) => setMapsPerLink(Math.max(2, Math.min(10, Number(event.target.value) || 10)))}
2849
+ >
2850
+ {Array.from({ length: 9 }, (_, index) => index + 2).map((count) => (
2851
+ <option key={count} value={count}>{count}</option>
2852
+ ))}
2853
+ </select>
2854
+ </label>
2855
  {plan.links.map((link) => (
2856
  <a
2857
  key={link.index}
 
2863
  Google Maps route {link.index}
2864
  </a>
2865
  ))}
2866
+ <button type="button" className="cg-route-copy-links" onClick={() => void copyRouteLinks()}>
2867
+ Copy links
2868
+ </button>
2869
+ {routeCopyMsg && <span className="cg-map-route-note">{routeCopyMsg}</span>}
2870
  </div>
2871
  )}
2872
+ <div className="cg-route-schedule" role="group" aria-label="Schedule route delivery">
2873
+ <label className="cg-map-route-opt">
2874
+ Inbox recipient
2875
+ <input
2876
+ className="cg-input"
2877
+ value={routeRecipient}
2878
+ aria-label="Inbox recipient"
2879
+ placeholder="Account username"
2880
+ onChange={(event) => setRouteRecipient(event.target.value)}
2881
+ />
2882
+ </label>
2883
+ <button
2884
+ type="button"
2885
+ className="cg-btn"
2886
+ disabled={routeScheduleBusy || !routeRecipient.trim()}
2887
+ onClick={() => void scheduleRouteDelivery()}
2888
+ title="Send this frozen route to the selected account's Inbox every day at 08:00"
2889
+ >
2890
+ {routeScheduleBusy ? "Scheduling" : "Schedule daily"}
2891
+ </button>
2892
+ {routeScheduleMsg && <span className="cg-map-route-note">{routeScheduleMsg}</span>}
2893
+ {routeScheduleErr && <span className="cg-cal-nodate">{routeScheduleErr}</span>}
2894
+ </div>
2895
  {/* ── ITEMS 4 AND 5: "Save route", and it ASKS FOR THE NAME ─────────────────
2896
  ⭐ ITEM 4 — the button read "Save visit order". Owner: *"Change the button
2897
  called 'Save visit order' to 'Save route'."* The FIELD is still the visit
 
3076
  "every record without a pin", so a whole-table run is not a thing a user can reach or a
3077
  future edit can accidentally enable. */}
3078
  {geoControl}
3079
+ {zones !== null && (
3080
+ <div className="cg-map-zones" role="group" aria-label="Map Zones">
3081
+ <label className="cg-map-zone-control">
3082
+ Zones
3083
+ <select
3084
+ className="cg-route-select"
3085
+ multiple
3086
+ value={[...activeZoneIds]}
3087
+ aria-label="Visible map Zones"
3088
+ onChange={(event) => {
3089
+ const ids = [...event.currentTarget.selectedOptions].map((option) => option.value);
3090
+ setActiveZoneIds(new Set(ids));
3091
+ const chosenZone = (zones || []).find((zone) => zone.id === ids[0]);
3092
+ setZoneEditorId(chosenZone?.id || "");
3093
+ if (chosenZone) {
3094
+ setZoneName(chosenZone.name);
3095
+ setZoneColor(chosenZone.color);
3096
+ setZoneGeographicField(chosenZone.geographicField || "");
3097
+ }
3098
+ }}
3099
+ >
3100
+ {(zones || []).map((zone) => (
3101
+ <option key={zone.id} value={zone.id}>
3102
+ {zone.visible ? zone.name : `${zone.name} (hidden)`}
3103
+ </option>
3104
+ ))}
3105
+ </select>
3106
+ </label>
3107
+ <button
3108
+ type="button"
3109
+ className="cg-btn"
3110
+ onClick={() => {
3111
+ setZoneEditorId("");
3112
+ setZoneName("");
3113
+ setZoneColor(ZONE_COLOR_CHOICES[0].value);
3114
+ setDrawnZoneGeometry(null);
3115
+ }}
3116
+ >
3117
+ New Zone
3118
+ </button>
3119
+ <button
3120
+ type="button"
3121
+ className="cg-btn"
3122
+ disabled={activeZonePids.size === 0}
3123
+ onClick={selectActiveZoneRecords}
3124
+ title="Select records in the chosen visible Zones"
3125
+ >
3126
+ Select Zone records
3127
+ </button>
3128
+ <button
3129
+ type="button"
3130
+ className="cg-btn"
3131
+ disabled={activeZonePids.size < 2}
3132
+ onClick={() => {
3133
+ selectActiveZoneRecords();
3134
+ setRouteCreateOpen(true);
3135
+ setRouteOn(false);
3136
+ setRouteOrder(null);
3137
+ }}
3138
+ title="Use the selected visible Zones as this route's records"
3139
+ >
3140
+ Route Zones
3141
+ </button>
3142
+ {zoneEditor && (
3143
+ <button
3144
+ type="button"
3145
+ className="cg-btn"
3146
+ disabled={zoneBusy}
3147
+ onClick={() => void setZoneVisible(zoneEditor, !zoneEditor.visible)}
3148
+ >
3149
+ {zoneEditor.visible ? "Hide Zone" : "Show Zone"}
3150
+ </button>
3151
+ )}
3152
+ <label className="cg-map-zone-control">
3153
+ Geography
3154
+ <select
3155
+ className="cg-route-select"
3156
+ value={zoneGeographicField}
3157
+ aria-label="Geographic field"
3158
+ onChange={(event) => {
3159
+ setZoneGeographicField(event.target.value);
3160
+ setZoneGeographicValue("");
3161
+ }}
3162
+ >
3163
+ <option value="">Choose a geographic field</option>
3164
+ {geographicFields.map((key) => <option key={key} value={key}>{key}</option>)}
3165
+ </select>
3166
+ </label>
3167
+ {zoneGeographicField && (
3168
+ <label className="cg-map-zone-control">
3169
+ Group
3170
+ <select
3171
+ className="cg-route-select"
3172
+ value={zoneGeographicValue}
3173
+ aria-label="Geographic group"
3174
+ onChange={(event) => {
3175
+ const value = event.target.value;
3176
+ setZoneGeographicValue(value);
3177
+ if (value) {
3178
+ onSelectPids(
3179
+ mapRows.filter((row) => String(row[zoneGeographicField] ?? "").trim() === value).map((row) => row.pid),
3180
+ "replace"
3181
+ );
3182
+ }
3183
+ }}
3184
+ >
3185
+ <option value="">Choose a group</option>
3186
+ {geographicValues.map((value) => <option key={value} value={value}>{value}</option>)}
3187
+ </select>
3188
+ </label>
3189
+ )}
3190
+ <label className="cg-map-zone-control">
3191
+ Zone name
3192
+ <input
3193
+ className="cg-input"
3194
+ value={zoneName}
3195
+ maxLength={120}
3196
+ aria-label="Zone name"
3197
+ placeholder="Name this Zone"
3198
+ onChange={(event) => setZoneName(event.target.value)}
3199
+ />
3200
+ </label>
3201
+ <label className="cg-map-zone-control">
3202
+ Color
3203
+ <select
3204
+ className="cg-route-select"
3205
+ value={zoneColor}
3206
+ aria-label="Zone color"
3207
+ onChange={(event) => setZoneColor(event.target.value)}
3208
+ >
3209
+ {ZONE_COLOR_CHOICES.map((choice) => (
3210
+ <option key={choice.value} value={choice.value}>{choice.label}</option>
3211
+ ))}
3212
+ </select>
3213
+ </label>
3214
+ <button
3215
+ type="button"
3216
+ className="cg-btn"
3217
+ disabled={zoneBusy}
3218
+ onClick={() => void saveZone(zoneEditor || undefined)}
3219
+ title={drawnZoneGeometry ? "Save the drawn Zone" : "Save a Zone around the selected records"}
3220
+ >
3221
+ {zoneBusy ? "Saving Zone" : zoneEditor ? "Update Zone" : "Save Zone"}
3222
+ </button>
3223
+ {zoneErr && <span className="cg-cal-nodate">{zoneErr}</span>}
3224
+ </div>
3225
+ )}
3226
  {/* Every gesture the map has, named. `alt` (add to the selection rather
3227
  than replace it, onPointerUp) shipped in wave 8 and was disclosed
3228
  NOWHERE, so "select these as well" was a feature only the source
3229
  knew about. It needs shift too — alt alone still pans. */}
3230
  <span className="cg-map-hint">
3231
  Scroll to zoom · drag to pan · {lassoTool ? "shift-drag to lasso" : "shift-drag to select"}{" "}
3232
+ · shift-alt-drag to extend the selection · click a pin to open the record · shift-click a
3233
+ pin to add or remove it from the selection
 
 
 
 
 
 
3234
  </span>
3235
  </div>
3236
  <div
 
3318
  ))}
3319
  </>
3320
  )}
3321
+ {zonePolygons.map((ring) => (
3322
+ <polygon
3323
+ key={ring.key}
3324
+ className="cg-map-zone"
3325
+ points={ring.points.map((point) => `${point.x.toFixed(2)},${point.y.toFixed(2)}`).join(" ")}
3326
+ fill={ring.zone.color}
3327
+ stroke={ring.zone.color}
3328
+ strokeWidth={hair(1.4)}
3329
+ onClick={(event) => {
3330
+ event.stopPropagation();
3331
+ onSelectPids(ring.zone.memberships, "replace");
3332
+ }}
3333
+ >
3334
+ <title>{`${ring.zone.name}: select Zone records`}</title>
3335
+ </polygon>
3336
+ ))}
3337
  {/* The planned path, UNDER the pins so it never hides a stop. Inside
3338
  the zoomed group, so it pans and scales with the geography; the
3339
  stroke is pre-divided by k like every other line here. */}
 
3403
  // hint bar above is the SIGHTED half of this same disclosure. It said "Click to
3404
  // select, double click to open." until R10 made that false.
3405
  // Policed by `verify_ui.py::pin_label_states_the_gesture`.
3406
+ aria-label={`${p.title || "Untitled record"}. Click to open, shift-click to select.`}
 
 
 
 
 
 
 
 
 
 
 
3407
  onMouseEnter={() => setHoverPid(p.pid)}
3408
  onMouseLeave={() => setHoverPid((h) => (h === p.pid ? null : h))}
3409
  onFocus={() => setHoverPid(p.pid)}
 
3421
  pinSelect(p.pid, true);
3422
  return;
3423
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3424
  // ⭐⭐ W41-T48 (owner instruction 22) — OPENING A RECORD FOLDS THE RAIL, ON
3425
  // THE MAP EXACTLY AS IN THE GRID. `CustomerGrid.tsx::onCellClicked` raises
3426
  // this on every cell click; the map was the one surface that opened a record
 
3455
  onDoubleClick={(e) => {
3456
  if (movedRef.current) return;
3457
  e.preventDefault();
 
 
 
 
 
3458
  onOpen(p.pid);
3459
  }}
3460
  onKeyDown={(e) => {
 
3466
  // disambiguate, so the guard the pointer needs would only be superstition.
3467
  if (e.key === "Enter") {
3468
  e.preventDefault();
 
 
 
 
 
 
 
3469
  // W41-T48 — the keyboard mirror of the plain click, so it folds the rail
3470
  // for the same reason. ⚠ `!e.repeat` is this path's `e.detail <= 1`: a HELD
3471
  // Enter auto-repeats keydown for as long as the finger is down, and every
web/src/customer-grid/RecordDetail.tsx CHANGED
@@ -1569,7 +1569,7 @@ export default function RecordDetail({
1569
  <section className="cg-detail-section cg-detail-relsec">
1570
  <h3 className="cg-detail-sechead">
1571
  {relTargets.length === 0 ? (
1572
- <span>Related</span>
1573
  ) : (
1574
  <button
1575
  type="button"
@@ -1577,7 +1577,7 @@ export default function RecordDetail({
1577
  aria-expanded={relOpen}
1578
  onClick={() => setRelOpen((open) => !open)}
1579
  >
1580
- Related
1581
  </button>
1582
  )}
1583
  <span className="cg-detail-seccount">
 
1569
  <section className="cg-detail-section cg-detail-relsec">
1570
  <h3 className="cg-detail-sechead">
1571
  {relTargets.length === 0 ? (
1572
+ <span>Relational</span>
1573
  ) : (
1574
  <button
1575
  type="button"
 
1577
  aria-expanded={relOpen}
1578
  onClick={() => setRelOpen((open) => !open)}
1579
  >
1580
+ Relational
1581
  </button>
1582
  )}
1583
  <span className="cg-detail-seccount">
web/src/customer-grid/SwipeView.tsx CHANGED
@@ -1,586 +1,586 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / SwipeView.tsx
3
- // ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) — the SWIPE deck.
4
- //
5
- // One record at a time, decided left or right into two options of ONE
6
- // single-select. R2 fixes the shape and it is narrow on purpose:
7
- // · SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
8
- // · the deck holds only the records whose bound field is EMPTY — a record
9
- // that already has a value has been decided, and re-asking is not triage.
10
- // · a swipe writes through the NORMAL cell door (`onSwipe`, which the host
11
- // maps to the same `patchAndRecord` a kanban card move uses), so undo,
12
- // echo-suppression and the permission wall all hold without being
13
- // re-implemented here.
14
- //
15
- // Honesty rules carried from the other modes:
16
- // · nothing is silently hidden — the deck states what is left, and the
17
- // empty state names the bound field rather than saying "all done".
18
- // · a lost binding is SHOWN, never repaired by guessing. `_clean_display`
19
- // validates that `fieldKey` names a field the table HAS and stops there;
20
- // it cannot know the field is still a select, or that the two options are
21
- // still in its vocabulary (its docstring draws that line explicitly). So
22
- // those three losses land here, and each one says what happened and
23
- // re-opens the picker — the `viewModes.tsx:190-194` rule, which exists
24
- // because the wave-7 trap was a picker silently falling back to its first
25
- // option.
26
- // ---------------------------------------------------------------------------
27
-
28
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
- // ⭐⭐ W41-T48 (owner instruction 22) — opening a record from the swipe deck folds the shell's
30
- // navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`.
31
- import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
32
- import { choiceOptions } from "./types";
33
- import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
34
- // ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is
35
- // loaded here) — the same import `RecordComments` takes for the same prop.
36
- import type { SurfaceScope } from "./apiBridge";
37
- import RecordComments from "./RecordComments";
38
- import { Documents } from "./Documents";
39
- import { formatDisplay } from "./cells";
40
- import { actionHref } from "./display";
41
- import { optionTint } from "./choiceColors";
42
- import { ModeIcon } from "./icons";
43
- // ⭐ W29-T73 — the line its three siblings all have, and the one this file shipped without.
44
- // `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
45
- // unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right —
46
- // a partially-styled surface reads as a design choice, which is why nobody reported it and no
47
- // gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
48
- import "./SwipeView.css";
49
-
50
- export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
51
-
52
- /** The three ways a stored binding can rot that the host cannot see (see the header note). */
53
- type BindingFault =
54
- | { kind: "unbound" }
55
- | { kind: "field-gone"; fieldKey: string }
56
- | { kind: "not-select"; field: Field }
57
- | { kind: "option-gone"; field: Field; missing: string[] };
58
-
59
- function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):
60
- { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
61
- if (!spec) return { ok: false, fault: { kind: "unbound" } };
62
- const field = fieldByKey.get(spec.fieldKey);
63
- if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
64
- // R2 — SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
65
- // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
66
- // adds and sometimes overwrites is two gestures wearing one button.
67
- if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
68
- const options = choiceOptions(field);
69
- const has = new Set(options.map((o) => o.toLowerCase()));
70
- const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
71
- if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
72
- return { ok: true, field, spec };
73
- }
74
-
75
- /** The bound cell is EMPTY — the one predicate that decides deck membership (R2). */
76
- const isUndecided = (row: Row, key: string): boolean =>
77
- String(row[key] ?? "").trim() === "";
78
-
79
- export function SwipeView({
80
- rows,
81
- fields,
82
- fieldByKey,
83
- spec,
84
- cardKeys,
85
- detailKeys,
86
- scope,
87
- viewer,
88
- docs,
89
- docPayload,
90
- onDocAdd,
91
- onDocFetch,
92
- onDocDelete,
93
- titleKey,
94
- canWrite,
95
- readOnlyReason,
96
- canBind,
97
- onSpec,
98
- onSwipe,
99
- onOpen,
100
- }: {
101
- /** DISTINCT data rows from the full pipeline, overlay edits layered — the kanban's contract.
102
- * The deck re-derives from these, so a written record leaves it as soon as the optimistic
103
- * patch lands; there is no local cursor to drift out of step with the data. */
104
- rows: Row[];
105
- /** Every field, for the picker's field list. */
106
- fields: Field[];
107
- fieldByKey: Map<string, Field>;
108
- /** The stored binding, or undefined for a deck nobody has configured yet. */
109
- spec: SwipeSpec | undefined;
110
- /** The handful of visible fields the card lists under its title. */
111
- cardKeys: string[];
112
- titleKey: string;
113
- /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
114
- canWrite: boolean;
115
- /** Stated when the deck cannot be decided — permissions, or a computed column. */
116
- readOnlyReason: string | null;
117
- /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
118
- * view-editing permission and NOT `canWrite` — conflating the two is
119
- * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
120
- * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
121
- canBind: boolean;
122
- /** `undefined` DELETES the binding — absent is the honest unconfigured state, and storing a
123
- * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
124
- onSpec: (next: SwipeSpec | undefined) => void;
125
- onSwipe: (pid: number, value: string) => void;
126
- onOpen: (pid: number) => void;
127
- /**
128
- * ⭐⭐ WAVE-29 T26 (owner R9) — WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.
129
- *
130
- * R9: *"the swipe CARD itself renders the record detail inline — fields, comments and
131
- * attachments — so a reviewer decides without leaving the deck."* Everything below is that,
132
- * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply
133
- * different amounts. A card must render with none of them rather than throw — the standalone
134
- * embed has no `scope`, and a deployment with no document storage serves no handlers.
135
- */
136
- /** Every field the VIEW shows, in its order — not the three-key card summary. */
137
- detailKeys?: string[];
138
- /** The surface these records live on. Comments are keyed by it; absent ⇒ no comments section,
139
- * which is the pre-existing precondition `RecordDetail` already carries. */
140
- scope?: SurfaceScope;
141
- viewer?: Viewer;
142
- /** This record's attachments, and the plumbing. Handlers absent ⇒ the section is not rendered
143
- * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app
144
- * cannot keep). */
145
- /** Keyed by pid, because a deck shows many records — `RecordDetail` takes ONE record's list
146
- * and that shape cannot serve a deck. */
147
- docs?: Record<string, CustomerDoc[]>;
148
- docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };
149
- /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE
150
- * open record. A deck paints many records at once, so a handler bound to a single pid would
151
- * attach every reviewer's upload to whichever card happened to be open. */
152
- onDocAdd?: (
153
- pid: number,
154
- file: { name: string; mime: string; size: number; data_b64: string }
155
- ) => void;
156
- onDocFetch?: (pid: number, docId: string) => void;
157
- onDocDelete?: (pid: number, docId: string) => void;
158
- }) {
159
- // "Later" — session-only, never stored. A deck with no way past a record you cannot decide
160
- // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
161
- // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
162
- // state rather than quietly shrinking the deck (rule 8b).
163
- const [later, setLater] = useState<Set<number>>(new Set());
164
- const deckRef = useRef<HTMLDivElement>(null);
165
-
166
- const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
167
- const boundKey = binding.ok ? binding.field.key : null;
168
-
169
- const undecided = useMemo(
170
- () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
171
- [rows, boundKey]
172
- );
173
- const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
174
- const card = deck[0];
175
-
176
- // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever —
177
- // otherwise the disclosed skip count drifts away from what is actually on the deck.
178
- useEffect(() => {
179
- setLater((prev) => {
180
- if (prev.size === 0) return prev;
181
- const live = new Set(undecided.map((r) => r.pid));
182
- const next = new Set([...prev].filter((pid) => live.has(pid)));
183
- return next.size === prev.size ? prev : next;
184
- });
185
- }, [undecided]);
186
-
187
- const decide = useCallback(
188
- (value: string) => {
189
- if (!card || !canWrite) return;
190
- onSwipe(card.pid, value);
191
- },
192
- [card, canWrite, onSwipe]
193
- );
194
-
195
- // �� / → decide, and they are the SAME two actions the buttons are rather than a second code
196
- // path: the whole point of the mode is that one hand can clear a queue.
197
- useEffect(() => {
198
- if (!binding.ok || !canWrite || !card) return;
199
- const onKey = (e: KeyboardEvent) => {
200
- if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
201
- const el = document.activeElement as HTMLElement | null;
202
- // Never steal an arrow key from a text field or a native control the user is inside.
203
- if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
204
- return;
205
- if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
206
- e.preventDefault();
207
- decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
208
- };
209
- window.addEventListener("keydown", onKey);
210
- return () => window.removeEventListener("keydown", onKey);
211
- }, [binding, canWrite, card, decide]);
212
-
213
- if (!binding.ok) {
214
- return (
215
- <div className="cg-swipe" ref={deckRef}>
216
- <SwipeBinder
217
- fault={binding.fault}
218
- fields={fields}
219
- fieldByKey={fieldByKey}
220
- spec={spec}
221
- canBind={canBind}
222
- onSpec={onSpec}
223
- />
224
- </div>
225
- );
226
- }
227
-
228
- const { field } = binding;
229
- const leftTint = optionTint(field, binding.spec.leftOption);
230
- const rightTint = optionTint(field, binding.spec.rightOption);
231
-
232
- return (
233
- <div className="cg-swipe" ref={deckRef} tabIndex={-1}>
234
- <div className="cg-swipe-bar">
235
- <span className="cg-swipe-bound">
236
- <ModeIcon mode="swipe" />
237
- Sorting into <strong>{field.label}</strong>
238
- </span>
239
- <span className="cg-swipe-left">
240
- {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
241
- </span>
242
- {canBind && (
243
- <button
244
- type="button"
245
- className="cg-link-btn"
246
- onClick={() => onSpec(undefined)}
247
- title="Choose a different field or different options for this deck"
248
- >
249
- Change
250
- </button>
251
- )}
252
- </div>
253
- {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
254
- {card ? (
255
- <div className="cg-swipe-deck">
256
- <button
257
- type="button"
258
- className="cg-swipe-side cg-swipe-side--left"
259
- disabled={!canWrite}
260
- style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}
261
- onClick={() => decide(binding.spec.leftOption)}
262
- title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
263
- >
264
- <span aria-hidden className="cg-swipe-arrow">
265
- <svg width="16" height="16" viewBox="0 0 16 16">
266
- <path
267
- d="M11 3.2 6.2 8l4.8 4.8"
268
- fill="none"
269
- stroke="currentColor"
270
- strokeWidth="1.6"
271
- strokeLinecap="round"
272
- strokeLinejoin="round"
273
- />
274
- </svg>
275
- </span>
276
- {binding.spec.leftOption}
277
- </button>
278
- <article
279
- className="cg-swipe-card"
280
- role="button"
281
- tabIndex={0}
282
- onClick={(e) => {
283
- // ⭐ W41-T48 — the card IS the deck's record open, so it folds the rail.
284
- // ⚠ Nothing that is NOT an open can reach this line: every control inside the
285
- // card (a url cell, the comments box, the document tray) already stops its own
286
- // click, and the left/right decision buttons are siblings of the card, not
287
- // children of it. The deck also has no pointer drag to disambiguate — its swipe
288
- // is the two buttons and the arrow keys, neither of which opens anything.
289
- // ⚠ `<article role="button">`, not a native button, so a keyboard activation
290
- // never arrives here as a synthetic click; the keydown path below is the whole
291
- // keyboard story and the two cannot both fire for one gesture.
292
- if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT);
293
- onOpen(card.pid);
294
- }}
295
- onKeyDown={(e) => {
296
- if (e.key !== "Enter" && e.key !== " ") return;
297
- e.preventDefault();
298
- // W41-T48 — `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space
299
- // auto-repeats keydown, and every one of those repeats is the SAME gesture.
300
- if (!e.repeat) signal(NAV_MINIMIZE_EVENT);
301
- onOpen(card.pid);
302
- }}
303
- >
304
- <h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3>
305
- <div className="cg-swipe-cells">
306
- {/* ⭐ WAVE-29 T26 (R9) — the RECORD's visible fields, not the three-key summary the
307
- kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not
308
- been widened yet renders exactly what it rendered before. */}
309
- {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {
310
- const f = fieldByKey.get(k);
311
- if (!f) return null;
312
- const text = formatDisplay(f, card[k]);
313
- if (!text) return null;
314
- // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
315
- // scheme guard — and every gesture that reaches it must be stopped from also
316
- // reaching the card, which is a button (the kanban card's note, same trap).
317
- const href = actionHref(f, card[k]);
318
- return (
319
- <div key={k} className="cg-swipe-cell">
320
- <span className="cg-lv-k">{f.label}</span>
321
- {href ? (
322
- <a
323
- className="cg-lv-v"
324
- href={href}
325
- target="_blank"
326
- rel="noopener noreferrer"
327
- title={text}
328
- onClick={(e) => e.stopPropagation()}
329
- onKeyDown={(e) => e.stopPropagation()}
330
- >
331
- {text}
332
- </a>
333
- ) : (
334
- <span className="cg-lv-v">{text}</span>
335
- )}
336
- </div>
337
- );
338
- })}
339
- </div>
340
- {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"`
341
- that opens the record, and a click on a comment box or an upload control must not
342
- also open the modal it exists to make unnecessary (the kanban card's link trap,
343
- one surface over). */}
344
- {onDocAdd && onDocFetch && onDocDelete && (
345
- <div
346
- className="cg-swipe-docs"
347
- onClick={(e) => e.stopPropagation()}
348
- onKeyDown={(e) => e.stopPropagation()}
349
- role="presentation"
350
- >
351
- <Documents
352
- pid={Number(card.pid)}
353
- docs={docs?.[String(card.pid)] ?? []}
354
- docPayload={docPayload}
355
- onAdd={(file) => onDocAdd(card.pid, file)}
356
- onFetch={(docId) => onDocFetch(card.pid, docId)}
357
- onDelete={(docId) => onDocDelete(card.pid, docId)}
358
- />
359
- </div>
360
- )}
361
- {scope != null && (
362
- <div
363
- className="cg-swipe-comments"
364
- onClick={(e) => e.stopPropagation()}
365
- onKeyDown={(e) => e.stopPropagation()}
366
- role="presentation"
367
- >
368
- {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React
369
- reuses the mounted instance across a card change and paints one record's
370
- comments under another's name until the fetch returns. */}
371
- <RecordComments
372
- key={`${scope}:${Number(card.pid)}`}
373
- scope={scope}
374
- pid={Number(card.pid)}
375
- viewer={viewer}
376
- />
377
- </div>
378
- )}
379
- {canWrite && (
380
- <button
381
- type="button"
382
- className="cg-link-btn cg-swipe-later"
383
- onClick={(e) => {
384
- e.stopPropagation();
385
- setLater((prev) => new Set(prev).add(card.pid));
386
- }}
387
- >
388
- Decide later
389
- </button>
390
- )}
391
- </article>
392
- <button
393
- type="button"
394
- className="cg-swipe-side cg-swipe-side--right"
395
- disabled={!canWrite}
396
- style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}
397
- onClick={() => decide(binding.spec.rightOption)}
398
- title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
399
- >
400
- {binding.spec.rightOption}
401
- <span aria-hidden className="cg-swipe-arrow">
402
- <svg width="16" height="16" viewBox="0 0 16 16">
403
- <path
404
- d="M5 3.2 9.8 8 5 12.8"
405
- fill="none"
406
- stroke="currentColor"
407
- strokeWidth="1.6"
408
- strokeLinecap="round"
409
- strokeLinejoin="round"
410
- />
411
- </svg>
412
- </span>
413
- </button>
414
- </div>
415
- ) : (
416
- // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
417
- // between "the deck is finished" and "the filter hid everything", and the two want
418
- // different next actions. `later` is disclosed rather than quietly subtracted.
419
- <div className="cg-mode-empty cg-swipe-empty">
420
- {later.size > 0 ? (
421
- <>
422
- <p>
423
- {later.size.toLocaleString()}{" "}
424
- {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
425
- in this view is missing a <strong>{field.label}</strong>.
426
- </p>
427
- <button type="button" className="cg-btn" onClick={() => setLater(new Set())}>
428
- Bring them back
429
- </button>
430
- </>
431
- ) : (
432
- <p>
433
- Every record in this view already has a <strong>{field.label}</strong>. Widen the
434
- view's filters to sort more.
435
- </p>
436
- )}
437
- </div>
438
- )}
439
- </div>
440
- );
441
- }
442
-
443
- /**
444
- * The binding picker: field + two options. It is also the surface every LOST binding lands on,
445
- * with the loss stated above it — one place that answers "what is this deck for", rather than an
446
- * error screen beside a separate setup screen.
447
- */
448
- function SwipeBinder({
449
- fault,
450
- fields,
451
- fieldByKey,
452
- spec,
453
- canBind,
454
- onSpec,
455
- }: {
456
- fault: BindingFault;
457
- fields: Field[];
458
- fieldByKey: Map<string, Field>;
459
- spec: SwipeSpec | undefined;
460
- canBind: boolean;
461
- onSpec: (next: SwipeSpec | undefined) => void;
462
- }) {
463
- const selects = useMemo(
464
- () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
465
- [fields]
466
- );
467
- const [fieldKey, setFieldKey] = useState<string>(() => {
468
- if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
469
- return selects[0]?.key ?? "";
470
- });
471
- const chosen = fieldByKey.get(fieldKey);
472
- const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
473
- const [left, setLeft] = useState<string>("");
474
- const [right, setRight] = useState<string>("");
475
-
476
- // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
477
- // pick survives re-renders, and reset whenever the field changes — carrying an option from the
478
- // previous field would offer a value the new field cannot hold.
479
- useEffect(() => {
480
- setLeft(options[0] ?? "");
481
- setRight(options.find((o) => o !== options[0]) ?? "");
482
- }, [options]);
483
-
484
- const message = ((): string => {
485
- switch (fault.kind) {
486
- case "field-gone":
487
- return "The field this deck sorted into has been deleted. Pick another one.";
488
- case "not-select":
489
- return `“${fault.field.label}” is no longer a single-select, so it has no options to`
490
- + " sort into. Pick another field.";
491
- case "option-gone":
492
- return `${fault.missing.map((m) => `“${m}”`).join(" and ")} ${
493
- fault.missing.length === 1 ? "is" : "are"
494
- } no longer ${fault.missing.length === 1 ? "an option" : "options"} on “${
495
- fault.field.label
496
- }”. Pick the sides again.`;
497
- default:
498
- return "Sort records one at a time into two options of a single-select field.";
499
- }
500
- })();
501
-
502
- if (!canBind) {
503
- return (
504
- <div className="cg-mode-empty">
505
- <p>{message}</p>
506
- <p>Its creator or an admin can set this view up.</p>
507
- </div>
508
- );
509
- }
510
- if (selects.length === 0) {
511
- // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
512
- // requirement is what turns a dead end into a next action.
513
- return (
514
- <div className="cg-mode-empty">
515
- <p>
516
- A swipe deck sorts into a single-select field with at least two options. This database
517
- does not have one yet — add a single-select column, then come back.
518
- </p>
519
- </div>
520
- );
521
- }
522
- const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
523
- return (
524
- <div className="cg-swipe-setup">
525
- <p className="cg-swipe-setup-note">{message}</p>
526
- <label className="cg-swipe-setup-row">
527
- <span>Sort into</span>
528
- <select
529
- className="cg-select"
530
- value={fieldKey}
531
- onChange={(e) => setFieldKey(e.target.value)}
532
- >
533
- {/* Every option carries an explicit `value`: a <select> whose value names nothing
534
- renders its FIRST option and reports a choice the user never made
535
- ([[cg-condition-builder-items]]). */}
536
- {selects.map((f) => (
537
- <option key={f.key} value={f.key}>
538
- {f.label}
539
- </option>
540
- ))}
541
- </select>
542
- </label>
543
- <div className="cg-swipe-setup-sides">
544
- <label className="cg-swipe-setup-row">
545
- <span>Swipe left</span>
546
- <select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>
547
- {options.map((o) => (
548
- <option key={o} value={o}>
549
- {o}
550
- </option>
551
- ))}
552
- </select>
553
- </label>
554
- <label className="cg-swipe-setup-row">
555
- <span>Swipe right</span>
556
- <select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>
557
- {options.map((o) => (
558
- <option key={o} value={o}>
559
- {o}
560
- </option>
561
- ))}
562
- </select>
563
- </label>
564
- </div>
565
- {!ready && left && right && (
566
- // Stated, not silently refused: both engines DROP a binding whose sides are the same
567
- // option, so a Save that looked like it worked would simply not persist.
568
- <p className="cg-swipe-setup-warn">
569
- The two sides must be different options — otherwise both gestures do the same thing.
570
- </p>
571
- )}
572
- <button
573
- type="button"
574
- className="cg-btn cg-btn--primary"
575
- disabled={!ready}
576
- onClick={() =>
577
- chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
578
- }
579
- >
580
- Start sorting
581
- </button>
582
- </div>
583
- );
584
- }
585
-
586
- export default SwipeView;
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / SwipeView.tsx
3
+ // ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) — the SWIPE deck.
4
+ //
5
+ // One record at a time, decided left or right into two options of ONE
6
+ // single-select. R2 fixes the shape and it is narrow on purpose:
7
+ // · SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
8
+ // · the deck holds only the records whose bound field is EMPTY — a record
9
+ // that already has a value has been decided, and re-asking is not triage.
10
+ // · a swipe writes through the NORMAL cell door (`onSwipe`, which the host
11
+ // maps to the same `patchAndRecord` a kanban card move uses), so undo,
12
+ // echo-suppression and the permission wall all hold without being
13
+ // re-implemented here.
14
+ //
15
+ // Honesty rules carried from the other modes:
16
+ // · nothing is silently hidden — the deck states what is left, and the
17
+ // empty state names the bound field rather than saying "all done".
18
+ // · a lost binding is SHOWN, never repaired by guessing. `_clean_display`
19
+ // validates that `fieldKey` names a field the table HAS and stops there;
20
+ // it cannot know the field is still a select, or that the two options are
21
+ // still in its vocabulary (its docstring draws that line explicitly). So
22
+ // those three losses land here, and each one says what happened and
23
+ // re-opens the picker — the `viewModes.tsx:190-194` rule, which exists
24
+ // because the wave-7 trap was a picker silently falling back to its first
25
+ // option.
26
+ // ---------------------------------------------------------------------------
27
+
28
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
+ // ⭐⭐ W41-T48 (owner instruction 22) — opening a record from the swipe deck folds the shell's
30
+ // navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`.
31
+ import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
32
+ import { choiceOptions } from "./types";
33
+ import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
34
+ // ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is
35
+ // loaded here) — the same import `RecordComments` takes for the same prop.
36
+ import type { SurfaceScope } from "./apiBridge";
37
+ import RecordComments from "./RecordComments";
38
+ import { Documents } from "./Documents";
39
+ import { formatDisplay } from "./cells";
40
+ import { actionHref } from "./display";
41
+ import { optionTint } from "./choiceColors";
42
+ import { ModeIcon } from "./icons";
43
+ // ⭐ W29-T73 — the line its three siblings all have, and the one this file shipped without.
44
+ // `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
45
+ // unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right —
46
+ // a partially-styled surface reads as a design choice, which is why nobody reported it and no
47
+ // gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
48
+ import "./SwipeView.css";
49
+
50
+ export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
51
+
52
+ /** The three ways a stored binding can rot that the host cannot see (see the header note). */
53
+ type BindingFault =
54
+ | { kind: "unbound" }
55
+ | { kind: "field-gone"; fieldKey: string }
56
+ | { kind: "not-select"; field: Field }
57
+ | { kind: "option-gone"; field: Field; missing: string[] };
58
+
59
+ function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):
60
+ { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
61
+ if (!spec) return { ok: false, fault: { kind: "unbound" } };
62
+ const field = fieldByKey.get(spec.fieldKey);
63
+ if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
64
+ // R2 — SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
65
+ // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
66
+ // adds and sometimes overwrites is two gestures wearing one button.
67
+ if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
68
+ const options = choiceOptions(field);
69
+ const has = new Set(options.map((o) => o.toLowerCase()));
70
+ const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
71
+ if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
72
+ return { ok: true, field, spec };
73
+ }
74
+
75
+ /** The bound cell is EMPTY — the one predicate that decides deck membership (R2). */
76
+ const isUndecided = (row: Row, key: string): boolean =>
77
+ String(row[key] ?? "").trim() === "";
78
+
79
+ export function SwipeView({
80
+ rows,
81
+ fields,
82
+ fieldByKey,
83
+ spec,
84
+ cardKeys,
85
+ detailKeys,
86
+ scope,
87
+ viewer,
88
+ docs,
89
+ docPayload,
90
+ onDocAdd,
91
+ onDocFetch,
92
+ onDocDelete,
93
+ titleKey,
94
+ canWrite,
95
+ readOnlyReason,
96
+ canBind,
97
+ onSpec,
98
+ onSwipe,
99
+ onOpen,
100
+ }: {
101
+ /** DISTINCT data rows from the full pipeline, overlay edits layered — the kanban's contract.
102
+ * The deck re-derives from these, so a written record leaves it as soon as the optimistic
103
+ * patch lands; there is no local cursor to drift out of step with the data. */
104
+ rows: Row[];
105
+ /** Every field, for the picker's field list. */
106
+ fields: Field[];
107
+ fieldByKey: Map<string, Field>;
108
+ /** The stored binding, or undefined for a deck nobody has configured yet. */
109
+ spec: SwipeSpec | undefined;
110
+ /** The handful of visible fields the card lists under its title. */
111
+ cardKeys: string[];
112
+ titleKey: string;
113
+ /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
114
+ canWrite: boolean;
115
+ /** Stated when the deck cannot be decided — permissions, or a computed column. */
116
+ readOnlyReason: string | null;
117
+ /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
118
+ * view-editing permission and NOT `canWrite` — conflating the two is
119
+ * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
120
+ * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
121
+ canBind: boolean;
122
+ /** `undefined` DELETES the binding — absent is the honest unconfigured state, and storing a
123
+ * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
124
+ onSpec: (next: SwipeSpec | undefined) => void;
125
+ onSwipe: (pid: number, value: string) => void;
126
+ onOpen: (pid: number) => void;
127
+ /**
128
+ * ⭐⭐ WAVE-29 T26 (owner R9) — WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.
129
+ *
130
+ * R9: *"the swipe CARD itself renders the record detail inline — fields, comments and
131
+ * attachments — so a reviewer decides without leaving the deck."* Everything below is that,
132
+ * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply
133
+ * different amounts. A card must render with none of them rather than throw — the standalone
134
+ * embed has no `scope`, and a deployment with no document storage serves no handlers.
135
+ */
136
+ /** Every field the VIEW shows, in its order — not the three-key card summary. */
137
+ detailKeys?: string[];
138
+ /** The surface these records live on. Comments are keyed by it; absent ⇒ no comments section,
139
+ * which is the pre-existing precondition `RecordDetail` already carries. */
140
+ scope?: SurfaceScope;
141
+ viewer?: Viewer;
142
+ /** This record's attachments, and the plumbing. Handlers absent ⇒ the section is not rendered
143
+ * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app
144
+ * cannot keep). */
145
+ /** Keyed by pid, because a deck shows many records — `RecordDetail` takes ONE record's list
146
+ * and that shape cannot serve a deck. */
147
+ docs?: Record<string, CustomerDoc[]>;
148
+ docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };
149
+ /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE
150
+ * open record. A deck paints many records at once, so a handler bound to a single pid would
151
+ * attach every reviewer's upload to whichever card happened to be open. */
152
+ onDocAdd?: (
153
+ pid: number,
154
+ file: { name: string; mime: string; size: number; data_b64: string }
155
+ ) => void;
156
+ onDocFetch?: (pid: number, docId: string) => void;
157
+ onDocDelete?: (pid: number, docId: string) => void;
158
+ }) {
159
+ // "Later" — session-only, never stored. A deck with no way past a record you cannot decide
160
+ // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
161
+ // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
162
+ // state rather than quietly shrinking the deck (rule 8b).
163
+ const [later, setLater] = useState<Set<number>>(new Set());
164
+ const deckRef = useRef<HTMLDivElement>(null);
165
+
166
+ const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
167
+ const boundKey = binding.ok ? binding.field.key : null;
168
+
169
+ const undecided = useMemo(
170
+ () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
171
+ [rows, boundKey]
172
+ );
173
+ const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
174
+ const card = deck[0];
175
+
176
+ // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever —
177
+ // otherwise the disclosed skip count drifts away from what is actually on the deck.
178
+ useEffect(() => {
179
+ setLater((prev) => {
180
+ if (prev.size === 0) return prev;
181
+ const live = new Set(undecided.map((r) => r.pid));
182
+ const next = new Set([...prev].filter((pid) => live.has(pid)));
183
+ return next.size === prev.size ? prev : next;
184
+ });
185
+ }, [undecided]);
186
+
187
+ const decide = useCallback(
188
+ (value: string) => {
189
+ if (!card || !canWrite) return;
190
+ onSwipe(card.pid, value);
191
+ },
192
+ [card, canWrite, onSwipe]
193
+ );
194
+
195
+ // ← / → decide, and they are the SAME two actions the buttons are rather than a second code
196
+ // path: the whole point of the mode is that one hand can clear a queue.
197
+ useEffect(() => {
198
+ if (!binding.ok || !canWrite || !card) return;
199
+ const onKey = (e: KeyboardEvent) => {
200
+ if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
201
+ const el = document.activeElement as HTMLElement | null;
202
+ // Never steal an arrow key from a text field or a native control the user is inside.
203
+ if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
204
+ return;
205
+ if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
206
+ e.preventDefault();
207
+ decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
208
+ };
209
+ window.addEventListener("keydown", onKey);
210
+ return () => window.removeEventListener("keydown", onKey);
211
+ }, [binding, canWrite, card, decide]);
212
+
213
+ if (!binding.ok) {
214
+ return (
215
+ <div className="cg-swipe" ref={deckRef}>
216
+ <SwipeBinder
217
+ fault={binding.fault}
218
+ fields={fields}
219
+ fieldByKey={fieldByKey}
220
+ spec={spec}
221
+ canBind={canBind}
222
+ onSpec={onSpec}
223
+ />
224
+ </div>
225
+ );
226
+ }
227
+
228
+ const { field } = binding;
229
+ const leftTint = optionTint(field, binding.spec.leftOption);
230
+ const rightTint = optionTint(field, binding.spec.rightOption);
231
+
232
+ return (
233
+ <div className="cg-swipe" ref={deckRef} tabIndex={-1}>
234
+ <div className="cg-swipe-bar">
235
+ <span className="cg-swipe-bound">
236
+ <ModeIcon mode="swipe" />
237
+ Sorting into <strong>{field.label}</strong>
238
+ </span>
239
+ <span className="cg-swipe-left">
240
+ {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
241
+ </span>
242
+ {canBind && (
243
+ <button
244
+ type="button"
245
+ className="cg-link-btn"
246
+ onClick={() => onSpec(undefined)}
247
+ title="Choose a different field or different options for this deck"
248
+ >
249
+ Change
250
+ </button>
251
+ )}
252
+ </div>
253
+ {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
254
+ {card ? (
255
+ <div className="cg-swipe-deck">
256
+ <button
257
+ type="button"
258
+ className="cg-swipe-side cg-swipe-side--left"
259
+ disabled={!canWrite}
260
+ style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}
261
+ onClick={() => decide(binding.spec.leftOption)}
262
+ title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
263
+ >
264
+ <span aria-hidden className="cg-swipe-arrow">
265
+ <svg width="16" height="16" viewBox="0 0 16 16">
266
+ <path
267
+ d="M11 3.2 6.2 8l4.8 4.8"
268
+ fill="none"
269
+ stroke="currentColor"
270
+ strokeWidth="1.6"
271
+ strokeLinecap="round"
272
+ strokeLinejoin="round"
273
+ />
274
+ </svg>
275
+ </span>
276
+ {binding.spec.leftOption}
277
+ </button>
278
+ <article
279
+ className="cg-swipe-card"
280
+ role="button"
281
+ tabIndex={0}
282
+ onClick={(e) => {
283
+ // ⭐ W41-T48 — the card IS the deck's record open, so it folds the rail.
284
+ // ⚠ Nothing that is NOT an open can reach this line: every control inside the
285
+ // card (a url cell, the comments box, the document tray) already stops its own
286
+ // click, and the left/right decision buttons are siblings of the card, not
287
+ // children of it. The deck also has no pointer drag to disambiguate — its swipe
288
+ // is the two buttons and the arrow keys, neither of which opens anything.
289
+ // ⚠ `<article role="button">`, not a native button, so a keyboard activation
290
+ // never arrives here as a synthetic click; the keydown path below is the whole
291
+ // keyboard story and the two cannot both fire for one gesture.
292
+ if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT);
293
+ onOpen(card.pid);
294
+ }}
295
+ onKeyDown={(e) => {
296
+ if (e.key !== "Enter" && e.key !== " ") return;
297
+ e.preventDefault();
298
+ // W41-T48 — `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space
299
+ // auto-repeats keydown, and every one of those repeats is the SAME gesture.
300
+ if (!e.repeat) signal(NAV_MINIMIZE_EVENT);
301
+ onOpen(card.pid);
302
+ }}
303
+ >
304
+ <h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3>
305
+ <div className="cg-swipe-cells">
306
+ {/* ⭐ WAVE-29 T26 (R9) — the RECORD's visible fields, not the three-key summary the
307
+ kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not
308
+ been widened yet renders exactly what it rendered before. */}
309
+ {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {
310
+ const f = fieldByKey.get(k);
311
+ if (!f) return null;
312
+ const text = formatDisplay(f, card[k]);
313
+ if (!text) return null;
314
+ // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
315
+ // scheme guard — and every gesture that reaches it must be stopped from also
316
+ // reaching the card, which is a button (the kanban card's note, same trap).
317
+ const href = actionHref(f, card[k]);
318
+ return (
319
+ <div key={k} className="cg-swipe-cell">
320
+ <span className="cg-lv-k">{f.label}</span>
321
+ {href ? (
322
+ <a
323
+ className="cg-lv-v"
324
+ href={href}
325
+ target="_blank"
326
+ rel="noopener noreferrer"
327
+ title={text}
328
+ onClick={(e) => e.stopPropagation()}
329
+ onKeyDown={(e) => e.stopPropagation()}
330
+ >
331
+ {text}
332
+ </a>
333
+ ) : (
334
+ <span className="cg-lv-v">{text}</span>
335
+ )}
336
+ </div>
337
+ );
338
+ })}
339
+ </div>
340
+ {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"`
341
+ that opens the record, and a click on a comment box or an upload control must not
342
+ also open the modal it exists to make unnecessary (the kanban card's link trap,
343
+ one surface over). */}
344
+ {onDocAdd && onDocFetch && onDocDelete && (
345
+ <div
346
+ className="cg-swipe-docs"
347
+ onClick={(e) => e.stopPropagation()}
348
+ onKeyDown={(e) => e.stopPropagation()}
349
+ role="presentation"
350
+ >
351
+ <Documents
352
+ pid={Number(card.pid)}
353
+ docs={docs?.[String(card.pid)] ?? []}
354
+ docPayload={docPayload}
355
+ onAdd={(file) => onDocAdd(card.pid, file)}
356
+ onFetch={(docId) => onDocFetch(card.pid, docId)}
357
+ onDelete={(docId) => onDocDelete(card.pid, docId)}
358
+ />
359
+ </div>
360
+ )}
361
+ {scope != null && (
362
+ <div
363
+ className="cg-swipe-comments"
364
+ onClick={(e) => e.stopPropagation()}
365
+ onKeyDown={(e) => e.stopPropagation()}
366
+ role="presentation"
367
+ >
368
+ {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React
369
+ reuses the mounted instance across a card change and paints one record's
370
+ comments under another's name until the fetch returns. */}
371
+ <RecordComments
372
+ key={`${scope}:${Number(card.pid)}`}
373
+ scope={scope}
374
+ pid={Number(card.pid)}
375
+ viewer={viewer}
376
+ />
377
+ </div>
378
+ )}
379
+ {canWrite && (
380
+ <button
381
+ type="button"
382
+ className="cg-link-btn cg-swipe-later"
383
+ onClick={(e) => {
384
+ e.stopPropagation();
385
+ setLater((prev) => new Set(prev).add(card.pid));
386
+ }}
387
+ >
388
+ Decide later
389
+ </button>
390
+ )}
391
+ </article>
392
+ <button
393
+ type="button"
394
+ className="cg-swipe-side cg-swipe-side--right"
395
+ disabled={!canWrite}
396
+ style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}
397
+ onClick={() => decide(binding.spec.rightOption)}
398
+ title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
399
+ >
400
+ {binding.spec.rightOption}
401
+ <span aria-hidden className="cg-swipe-arrow">
402
+ <svg width="16" height="16" viewBox="0 0 16 16">
403
+ <path
404
+ d="M5 3.2 9.8 8 5 12.8"
405
+ fill="none"
406
+ stroke="currentColor"
407
+ strokeWidth="1.6"
408
+ strokeLinecap="round"
409
+ strokeLinejoin="round"
410
+ />
411
+ </svg>
412
+ </span>
413
+ </button>
414
+ </div>
415
+ ) : (
416
+ // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
417
+ // between "the deck is finished" and "the filter hid everything", and the two want
418
+ // different next actions. `later` is disclosed rather than quietly subtracted.
419
+ <div className="cg-mode-empty cg-swipe-empty">
420
+ {later.size > 0 ? (
421
+ <>
422
+ <p>
423
+ {later.size.toLocaleString()}{" "}
424
+ {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
425
+ in this view is missing a <strong>{field.label}</strong>.
426
+ </p>
427
+ <button type="button" className="cg-btn" onClick={() => setLater(new Set())}>
428
+ Bring them back
429
+ </button>
430
+ </>
431
+ ) : (
432
+ <p>
433
+ Every record in this view already has a <strong>{field.label}</strong>. Widen the
434
+ view's filters to sort more.
435
+ </p>
436
+ )}
437
+ </div>
438
+ )}
439
+ </div>
440
+ );
441
+ }
442
+
443
+ /**
444
+ * The binding picker: field + two options. It is also the surface every LOST binding lands on,
445
+ * with the loss stated above it — one place that answers "what is this deck for", rather than an
446
+ * error screen beside a separate setup screen.
447
+ */
448
+ function SwipeBinder({
449
+ fault,
450
+ fields,
451
+ fieldByKey,
452
+ spec,
453
+ canBind,
454
+ onSpec,
455
+ }: {
456
+ fault: BindingFault;
457
+ fields: Field[];
458
+ fieldByKey: Map<string, Field>;
459
+ spec: SwipeSpec | undefined;
460
+ canBind: boolean;
461
+ onSpec: (next: SwipeSpec | undefined) => void;
462
+ }) {
463
+ const selects = useMemo(
464
+ () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
465
+ [fields]
466
+ );
467
+ const [fieldKey, setFieldKey] = useState<string>(() => {
468
+ if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
469
+ return selects[0]?.key ?? "";
470
+ });
471
+ const chosen = fieldByKey.get(fieldKey);
472
+ const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
473
+ const [left, setLeft] = useState<string>("");
474
+ const [right, setRight] = useState<string>("");
475
+
476
+ // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
477
+ // pick survives re-renders, and reset whenever the field changes — carrying an option from the
478
+ // previous field would offer a value the new field cannot hold.
479
+ useEffect(() => {
480
+ setLeft(options[0] ?? "");
481
+ setRight(options.find((o) => o !== options[0]) ?? "");
482
+ }, [options]);
483
+
484
+ const message = ((): string => {
485
+ switch (fault.kind) {
486
+ case "field-gone":
487
+ return "The field this deck sorted into has been deleted. Pick another one.";
488
+ case "not-select":
489
+ return `“${fault.field.label}” is no longer a single-select, so it has no options to`
490
+ + " sort into. Pick another field.";
491
+ case "option-gone":
492
+ return `${fault.missing.map((m) => `“${m}”`).join(" and ")} ${
493
+ fault.missing.length === 1 ? "is" : "are"
494
+ } no longer ${fault.missing.length === 1 ? "an option" : "options"} on “${
495
+ fault.field.label
496
+ }”. Pick the sides again.`;
497
+ default:
498
+ return "Sort records one at a time into two options of a single-select field.";
499
+ }
500
+ })();
501
+
502
+ if (!canBind) {
503
+ return (
504
+ <div className="cg-mode-empty">
505
+ <p>{message}</p>
506
+ <p>Its creator or an admin can set this view up.</p>
507
+ </div>
508
+ );
509
+ }
510
+ if (selects.length === 0) {
511
+ // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
512
+ // requirement is what turns a dead end into a next action.
513
+ return (
514
+ <div className="cg-mode-empty">
515
+ <p>
516
+ A swipe deck sorts into a single-select field with at least two options. This database
517
+ does not have one yet — add a single-select column, then come back.
518
+ </p>
519
+ </div>
520
+ );
521
+ }
522
+ const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
523
+ return (
524
+ <div className="cg-swipe-setup">
525
+ <p className="cg-swipe-setup-note">{message}</p>
526
+ <label className="cg-swipe-setup-row">
527
+ <span>Sort into</span>
528
+ <select
529
+ className="cg-select"
530
+ value={fieldKey}
531
+ onChange={(e) => setFieldKey(e.target.value)}
532
+ >
533
+ {/* Every option carries an explicit `value`: a <select> whose value names nothing
534
+ renders its FIRST option and reports a choice the user never made
535
+ ([[cg-condition-builder-items]]). */}
536
+ {selects.map((f) => (
537
+ <option key={f.key} value={f.key}>
538
+ {f.label}
539
+ </option>
540
+ ))}
541
+ </select>
542
+ </label>
543
+ <div className="cg-swipe-setup-sides">
544
+ <label className="cg-swipe-setup-row">
545
+ <span>Swipe left</span>
546
+ <select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>
547
+ {options.map((o) => (
548
+ <option key={o} value={o}>
549
+ {o}
550
+ </option>
551
+ ))}
552
+ </select>
553
+ </label>
554
+ <label className="cg-swipe-setup-row">
555
+ <span>Swipe right</span>
556
+ <select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>
557
+ {options.map((o) => (
558
+ <option key={o} value={o}>
559
+ {o}
560
+ </option>
561
+ ))}
562
+ </select>
563
+ </label>
564
+ </div>
565
+ {!ready && left && right && (
566
+ // Stated, not silently refused: both engines DROP a binding whose sides are the same
567
+ // option, so a Save that looked like it worked would simply not persist.
568
+ <p className="cg-swipe-setup-warn">
569
+ The two sides must be different options — otherwise both gestures do the same thing.
570
+ </p>
571
+ )}
572
+ <button
573
+ type="button"
574
+ className="cg-btn cg-btn--primary"
575
+ disabled={!ready}
576
+ onClick={() =>
577
+ chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
578
+ }
579
+ >
580
+ Start sorting
581
+ </button>
582
+ </div>
583
+ );
584
+ }
585
+
586
+ export default SwipeView;
web/src/customer-grid/Toolbar.tsx CHANGED
@@ -35,8 +35,8 @@ import { viewDisplayMode } from "./types";
35
  import { PIVOT_WINDOWS, PIVOT_WINDOW_LABELS } from "./types";
36
  import { COPY_PARTS, COPY_PART_KEYS, copyViewConfig } from "./copyConfig";
37
  import type { CopyPart } from "./copyConfig";
38
- import { directionLabel, filterTreeConj, filterTreeNodes, isFilterGroup, isGroupableField,
39
- isOfferableField, offerableFields, routeSortRefusal } from "./types";
40
  import type { WindowSpec } from "./windows";
41
  import { AnchoredOverlay } from "./OverlaySurface";
42
  import { EyeOffIcon, FieldTypeIcon, ModeIcon } from "./icons";
@@ -49,10 +49,6 @@ import type { PoolProgress } from "./counts";
49
  // keeps everything that is genuinely toolbar: the strip, its buttons, sort, group, colour,
50
  // rows, search, the count, and the copy-configuration door it hands the builder as a slot.
51
  import { FilterBuilderPanel, FieldsHidePanel, Popover } from "../filter-kit";
52
- // ⭐⭐ W42-T12 — WHO IS LOOKING, so contract C2's rights pair can be asked inside the manager
53
- // panel at all. `import type`, because `verbatimModuleSyntax` is on and this file takes no
54
- // runtime dependency on `fieldClass.ts`.
55
- import type { FieldViewer } from "../filter-kit/fieldClass";
56
  import { MEASURE_OP_LIST, countConditions, newRuleId, opsForType } from "../filter-kit/ops";
57
  import "./filters.css";
58
 
@@ -76,28 +72,8 @@ export interface ToolbarProps {
76
  * menu's Delete: only keys in `deletableKeys` (created strata) render the control. */
77
  deletableKeys?: ReadonlySet<string>;
78
  onDeleteField?: (key: string) => void;
79
-
80
- /**
81
- * ⭐⭐ W42-T12 (D-485) — THE FIELD MANAGER'S SIX DOORS, AND EVERY ONE OF THEM IS REQUIRED.
82
- *
83
- * This toolbar carries the ONLY mount of `FieldsHidePanel` that runs in manager mode, so a
84
- * ticked selection with a Share, Reassign, Hide, Show or Delete button behind it is this
85
- * component's responsibility to feed. Optional would have compiled, rendered the whole bulk
86
- * bar and done nothing on every press — a feature that looks built and is not, which is
87
- * exactly the shape D-485 records. Required means an unfed host fails the typecheck instead
88
- * of failing the user.
89
- *
90
- * ⚠ `viewer` IS NOT A DOOR AND IS STILL REQUIRED. Without it the panel cannot ask C2's rights
91
- * pair, so every row falls back to "rights unknown" and the manager withdraws affordances that
92
- * ship today. The five handlers come from `CustomerGrid::useFieldBulkDoors`, which batches
93
- * each act into ONE config write; none of them may be built here by looping a per-key prop.
94
- */
95
- viewer: FieldViewer | undefined;
96
- onSetFieldsHidden: ((keys: string[], hidden: boolean) => void) | null;
97
- onShareFields: ((keys: string[]) => void) | null;
98
- onReassignFields: ((keys: string[]) => void) | null;
99
- onDeleteFields: ((keys: string[]) => void) | null;
100
- onRemoveField: ((key: string) => void) | null;
101
 
102
  /**
103
  * ⭐⭐ W38-T07 (owner instruction 12) — THE ONE COLOUR CONTROL, and it names a FIELD rather than
@@ -167,8 +143,6 @@ export interface ToolbarProps {
167
  * not, so the marker says something different and does not go away.
168
  */
169
  unresolvedCount?: number;
170
- /** Exact reasons for unresolved conditions, shown in the marker's native hover text. */
171
- unresolvedReasons?: readonly string[];
172
  /** Owner item 5 — the cohorts this user has, for `Where [Cohort] [is part of] […]`. */
173
  lists?: { id: string; name: string }[];
174
  /** ⭐⭐ W37-T26 (C4) — the views a `Where [View] [is] […]` condition may name. A PASS-THROUGH:
@@ -268,6 +242,8 @@ export interface ToolbarProps {
268
  onRelationalWindow?: (window: PivotWindow) => void;
269
  /** The source table's name, for the way back. Absent falls back to the shared structural word. */
270
  sourceLabel?: string;
 
 
271
  }
272
 
273
  // --- tiny inline icons (14px, stroke = currentColor) -----------------------
@@ -323,6 +299,14 @@ function IconRows() {
323
  </svg>
324
  );
325
  }
 
 
 
 
 
 
 
 
326
  // W41-T42 — two nodes and the edge between them, at the same 14px/1.5 stroke weight every other
327
  // button in this strip wears. The relation is the LINE, which is the whole idea of the control.
328
  function IconRelational() {
@@ -557,51 +541,19 @@ function SortBuilder({
557
  fieldByKey,
558
  sorts,
559
  onSorts,
560
- filterTree,
561
  }: {
562
  fields: Field[];
563
  fieldByKey: Map<string, Field>;
564
  sorts: SortSpec;
565
  onSorts: (s: SortSpec) => void;
566
- /** R22 — the CURRENT filter, because whether a route-order sort means anything is a fact
567
- * about the filter and not about the column. */
568
- filterTree: FilterTree;
569
  }) {
570
- // C11 (W42-T54) — the sort picker is a field picker, so it offers the offerable columns.
571
- // ⛔ BOTH the picker's list AND `add()`'s seed read this ONE list: filtering only the picker
572
- // would leave "Add sort" free to seed a withheld route column, which is the same defect
573
- // wearing a different control.
574
- const offerable = useMemo(() => offerableFields(fields), [fields]);
575
  const update = (i: number, patch: Partial<SortRule>) =>
576
  onSorts(sorts.map((s, j) => (j === i ? { ...s, ...patch } : s)));
577
  const remove = (i: number) => onSorts(sorts.filter((_, j) => j !== i));
578
- /**
579
- * ⛔⛔ R22 — THE REFUSAL. Sorting by the route projection column orders records by their STOP
580
- * POSITION, which is an ordinal inside ONE route and means nothing across two. So the sort is
581
- * REFUSED, on screen, with a sentence saying why: it is never quietly accepted and then
582
- * ordered by the cell's raw text, which would put `Route A - 10` before `Route A - 2`.
583
- *
584
- * ⛔ REFUSED AT THE COMMIT, not merely annotated after it. The grid orders rows from
585
- * `config.sorts` (`useVisibleRows.ts`); a rule that reaches that array HAS been applied, and a
586
- * message beside an applied wrong order is a caption, not a refusal.
587
- */
588
- const [refusal, setRefusal] = useState<{ at: number; text: string } | null>(null);
589
- const pickField = (i: number, key: string) => {
590
- const why = routeSortRefusal(key, filterTree, fields);
591
- if (why) { setRefusal({ at: i, text: why }); return; }
592
- setRefusal(null);
593
- update(i, { colId: key });
594
- };
595
  const add = () => {
596
  const used = new Set(sorts.map((s) => s.colId));
597
- // The seed skips anything a fresh rule would immediately be refused for: an "Add sort" that
598
- // lands on a rule the builder then rejects reads as the control being broken.
599
- const free = offerable.filter(
600
- (fl) => !used.has(fl.key) && !routeSortRefusal(fl.key, filterTree, fields)
601
- );
602
- const f = free[0] ?? offerable.find((fl) => !routeSortRefusal(fl.key, filterTree, fields));
603
  if (!f) return;
604
- setRefusal(null);
605
  onSorts([...sorts, { colId: f.key, dir: "asc" }]);
606
  };
607
 
@@ -615,10 +567,6 @@ function SortBuilder({
615
  )}
616
  {sorts.map((rule, i) => {
617
  const t = fieldByKey.get(rule.colId)?.type ?? "text";
618
- // A rule that is ALREADY stored against the projection column (a saved view, or the
619
- // filter changing under a sort that used to be fine) says the same sentence.
620
- const ruleWhy = routeSortRefusal(rule.colId, filterTree, fields);
621
- const why = refusal?.at === i ? refusal.text : ruleWhy;
622
  return (
623
  <div className="cg-cond-line" key={i}>
624
  <span className="cg-cond-prefix">{i === 0 ? "Sort by" : "then by"}</span>
@@ -631,8 +579,8 @@ function SortBuilder({
631
  className="cg-cond-field"
632
  ariaLabel="Sort field"
633
  value={rule.colId}
634
- onChange={(key) => pickField(i, key)}
635
- fields={offerable.map((fl) => ({
636
  key: fl.key, label: fl.label, type: fl.type,
637
  }))}
638
  />
@@ -656,11 +604,6 @@ function SortBuilder({
656
  ×
657
  </button>
658
  </span>
659
- {why && (
660
- <div className="cg-pop-note" role="status">
661
- {why}
662
- </div>
663
- )}
664
  </div>
665
  );
666
  })}
@@ -699,14 +642,7 @@ export default function Toolbar({
699
  onFieldOrder,
700
  deletableKeys,
701
  onDeleteField,
702
- // ⭐⭐ W42-T12 — no defaults, deliberately: each of the six is required, so a default would be
703
- // a value standing in for a host that never arrived. See `ToolbarProps` for why.
704
- viewer,
705
- onSetFieldsHidden,
706
- onShareFields,
707
- onReassignFields,
708
- onDeleteFields,
709
- onRemoveField,
710
  colorField,
711
  colorChoices,
712
  onColorField,
@@ -724,7 +660,6 @@ export default function Toolbar({
724
  measures = [],
725
  pendingMeasureCount = 0,
726
  unresolvedCount = 0,
727
- unresolvedReasons = [],
728
  lists = [],
729
  viewChoices = [],
730
  cohortLock,
@@ -747,6 +682,7 @@ export default function Toolbar({
747
  onRelational,
748
  onRelationalWindow,
749
  sourceLabel,
 
750
  }: ToolbarProps) {
751
  const shownCount = fields.filter((f) => visible.has(f.key)).length;
752
 
@@ -868,7 +804,7 @@ export default function Toolbar({
868
  : "Color";
869
  // W41-T42 — the same idiom `colorLabel` and `groupLabel` already use: a control that HAS a
870
  // current answer names it on the trigger, so the reader does not have to open it to find out.
871
- const relationalLabel = relational ? `Related: ${relational.label}` : "Related";
872
 
873
  /**
874
  * R11's greying, as one attribute. `inert` is not in React 18's JSX typings (it landed with
@@ -904,37 +840,13 @@ export default function Toolbar({
904
  // every other caller of the panel invert twice.
905
  hidden={hiddenKeys}
906
  onToggle={(key) => onColumnVisible(key, !visible.has(key))}
907
- /* C11 (W42-T54) — "Show all" shows all of what the panel LISTS. The panel narrows
908
- to the offerable fields, so passing the unnarrowed list here would make one
909
- button reveal ~64 route columns the list beside it does not name, with no way
910
- back through this panel. A withheld column that is visible TODAY is kept
911
- visible: this control shows things, it does not hide them. */
912
- onShowAll={() =>
913
- onColumnsVisible(
914
- fields
915
- .filter((field) => isOfferableField(field) || visible.has(field.key))
916
- .map((field) => field.key)
917
- )
918
- }
919
  onHideAll={() => onColumnsVisible([lockedKey])}
920
  lockedKey={lockedKey}
921
  onFieldOrder={onFieldOrder}
922
  deletableKeys={deletableKeys}
923
  onDeleteField={onDeleteField}
924
- /* ⭐⭐ W42-T12 — `manager` IS STATED HERE, and stating it is what makes the six props
925
- below mandatory. The panel defaults `manager` from `sharedSections`, which this
926
- mount also leaves unsaid, so the value would be `true` either way; but a default
927
- is a runtime fact and TypeScript narrows a union only on what a mount WRITES.
928
- Written, this mount is checked against the manager arm, and dropping any one of
929
- the six stops the build. Unwritten, it would match the plain arm and every bulk
930
- control would render inert. */
931
- manager
932
- viewer={viewer}
933
- onSetFieldsHidden={onSetFieldsHidden}
934
- onShareFields={onShareFields}
935
- onReassignFields={onReassignFields}
936
- onDeleteFields={onDeleteFields}
937
- onRemoveField={onRemoveField}
938
  />
939
  )}
940
  </Popover>
@@ -991,7 +903,6 @@ export default function Toolbar({
991
  fieldByKey={fieldByKey}
992
  sorts={sorts}
993
  onSorts={onSorts}
994
- filterTree={filterTree}
995
  />
996
  )}
997
  </Popover>
@@ -1200,6 +1111,18 @@ export default function Toolbar({
1200
  )}
1201
  </Popover>
1202
 
 
 
 
 
 
 
 
 
 
 
 
 
1203
  {/* Rows — height */}
1204
  <Popover label="Rows" icon={<IconRows />} active={rowHeightMode !== "short"}>
1205
  {() => (
@@ -1325,10 +1248,9 @@ export default function Toolbar({
1325
  <span
1326
  className="cg-count cg-count-pending"
1327
  title={
1328
- unresolvedReasons.length
1329
- ? unresolvedReasons.join("\n")
1330
- : `${unresolvedCount} condition${unresolvedCount === 1 ? "" : "s"} cannot be ` +
1331
- "evaluated. Rows are hidden rather than shown under a count that would be wrong."
1332
  }
1333
  >
1334
  Filter unresolved
@@ -1350,7 +1272,7 @@ export default function Toolbar({
1350
  <span
1351
  className="cg-count cg-count-partial"
1352
  title={
1353
- `Loading the rest of your ${nouns} in the background. You can browse, ` +
1354
  "filter and sort what is already here."
1355
  }
1356
  >
 
35
  import { PIVOT_WINDOWS, PIVOT_WINDOW_LABELS } from "./types";
36
  import { COPY_PARTS, COPY_PART_KEYS, copyViewConfig } from "./copyConfig";
37
  import type { CopyPart } from "./copyConfig";
38
+ import { directionLabel, filterTreeConj, filterTreeNodes, isFilterGroup, isGroupableField }
39
+ from "./types";
40
  import type { WindowSpec } from "./windows";
41
  import { AnchoredOverlay } from "./OverlaySurface";
42
  import { EyeOffIcon, FieldTypeIcon, ModeIcon } from "./icons";
 
49
  // keeps everything that is genuinely toolbar: the strip, its buttons, sort, group, colour,
50
  // rows, search, the count, and the copy-configuration door it hands the builder as a slot.
51
  import { FilterBuilderPanel, FieldsHidePanel, Popover } from "../filter-kit";
 
 
 
 
52
  import { MEASURE_OP_LIST, countConditions, newRuleId, opsForType } from "../filter-kit/ops";
53
  import "./filters.css";
54
 
 
72
  * menu's Delete: only keys in `deletableKeys` (created strata) render the control. */
73
  deletableKeys?: ReadonlySet<string>;
74
  onDeleteField?: (key: string) => void;
75
+ /** The Hide fields edit icon reuses ColumnMenu's existing normal field editor. */
76
+ onEditField?: (key: string, anchor: DOMRect) => void;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
  /**
79
  * ⭐⭐ W38-T07 (owner instruction 12) — THE ONE COLOUR CONTROL, and it names a FIELD rather than
 
143
  * not, so the marker says something different and does not go away.
144
  */
145
  unresolvedCount?: number;
 
 
146
  /** Owner item 5 — the cohorts this user has, for `Where [Cohort] [is part of] […]`. */
147
  lists?: { id: string; name: string }[];
148
  /** ⭐⭐ W37-T26 (C4) — the views a `Where [View] [is] […]` condition may name. A PASS-THROUGH:
 
242
  onRelationalWindow?: (window: PivotWindow) => void;
243
  /** The source table's name, for the way back. Absent falls back to the shared structural word. */
244
  sourceLabel?: string;
245
+ /** Opens the active view's existing ellipsis menu. */
246
+ onViewActions?: (anchor: HTMLButtonElement) => void;
247
  }
248
 
249
  // --- tiny inline icons (14px, stroke = currentColor) -----------------------
 
299
  </svg>
300
  );
301
  }
302
+ function IconGear() {
303
+ return (
304
+ <svg {...ic} aria-hidden>
305
+ <circle cx="8" cy="8" r="2.2" {...stroke} />
306
+ <path d="M8 2.2v1.5M8 12.3v1.5M13.8 8h-1.5M3.7 8H2.2M12.1 3.9 11 5M5 11l-1.1 1.1M12.1 12.1 11 11M5 5 3.9 3.9" {...stroke} />
307
+ </svg>
308
+ );
309
+ }
310
  // W41-T42 — two nodes and the edge between them, at the same 14px/1.5 stroke weight every other
311
  // button in this strip wears. The relation is the LINE, which is the whole idea of the control.
312
  function IconRelational() {
 
541
  fieldByKey,
542
  sorts,
543
  onSorts,
 
544
  }: {
545
  fields: Field[];
546
  fieldByKey: Map<string, Field>;
547
  sorts: SortSpec;
548
  onSorts: (s: SortSpec) => void;
 
 
 
549
  }) {
 
 
 
 
 
550
  const update = (i: number, patch: Partial<SortRule>) =>
551
  onSorts(sorts.map((s, j) => (j === i ? { ...s, ...patch } : s)));
552
  const remove = (i: number) => onSorts(sorts.filter((_, j) => j !== i));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
553
  const add = () => {
554
  const used = new Set(sorts.map((s) => s.colId));
555
+ const f = fields.find((fl) => !used.has(fl.key)) ?? fields[0];
 
 
 
 
 
556
  if (!f) return;
 
557
  onSorts([...sorts, { colId: f.key, dir: "asc" }]);
558
  };
559
 
 
567
  )}
568
  {sorts.map((rule, i) => {
569
  const t = fieldByKey.get(rule.colId)?.type ?? "text";
 
 
 
 
570
  return (
571
  <div className="cg-cond-line" key={i}>
572
  <span className="cg-cond-prefix">{i === 0 ? "Sort by" : "then by"}</span>
 
579
  className="cg-cond-field"
580
  ariaLabel="Sort field"
581
  value={rule.colId}
582
+ onChange={(key) => update(i, { colId: key })}
583
+ fields={fields.map((fl) => ({
584
  key: fl.key, label: fl.label, type: fl.type,
585
  }))}
586
  />
 
604
  ×
605
  </button>
606
  </span>
 
 
 
 
 
607
  </div>
608
  );
609
  })}
 
642
  onFieldOrder,
643
  deletableKeys,
644
  onDeleteField,
645
+ onEditField,
 
 
 
 
 
 
 
646
  colorField,
647
  colorChoices,
648
  onColorField,
 
660
  measures = [],
661
  pendingMeasureCount = 0,
662
  unresolvedCount = 0,
 
663
  lists = [],
664
  viewChoices = [],
665
  cohortLock,
 
682
  onRelational,
683
  onRelationalWindow,
684
  sourceLabel,
685
+ onViewActions,
686
  }: ToolbarProps) {
687
  const shownCount = fields.filter((f) => visible.has(f.key)).length;
688
 
 
804
  : "Color";
805
  // W41-T42 — the same idiom `colorLabel` and `groupLabel` already use: a control that HAS a
806
  // current answer names it on the trigger, so the reader does not have to open it to find out.
807
+ const relationalLabel = relational ? `Relational: ${relational.label}` : "Relational";
808
 
809
  /**
810
  * R11's greying, as one attribute. `inert` is not in React 18's JSX typings (it landed with
 
840
  // every other caller of the panel invert twice.
841
  hidden={hiddenKeys}
842
  onToggle={(key) => onColumnVisible(key, !visible.has(key))}
843
+ onShowAll={() => onColumnsVisible(fields.map((field) => field.key))}
 
 
 
 
 
 
 
 
 
 
 
844
  onHideAll={() => onColumnsVisible([lockedKey])}
845
  lockedKey={lockedKey}
846
  onFieldOrder={onFieldOrder}
847
  deletableKeys={deletableKeys}
848
  onDeleteField={onDeleteField}
849
+ onEditField={onEditField}
 
 
 
 
 
 
 
 
 
 
 
 
 
850
  />
851
  )}
852
  </Popover>
 
903
  fieldByKey={fieldByKey}
904
  sorts={sorts}
905
  onSorts={onSorts}
 
906
  />
907
  )}
908
  </Popover>
 
1111
  )}
1112
  </Popover>
1113
 
1114
+ {onViewActions && (
1115
+ <button
1116
+ type="button"
1117
+ className="cg-tb-btn cg-view-actions"
1118
+ aria-label="View actions"
1119
+ title="View actions"
1120
+ onClick={(event) => onViewActions(event.currentTarget)}
1121
+ >
1122
+ <IconGear />
1123
+ </button>
1124
+ )}
1125
+
1126
  {/* Rows — height */}
1127
  <Popover label="Rows" icon={<IconRows />} active={rowHeightMode !== "short"}>
1128
  {() => (
 
1248
  <span
1249
  className="cg-count cg-count-pending"
1250
  title={
1251
+ `${unresolvedCount} condition${unresolvedCount === 1 ? "" : "s"} cannot be ` +
1252
+ "evaluated — a date that does not resolve, or a list this view refers to that no " +
1253
+ "longer exists. Rows are hidden rather than shown under a count that would be wrong."
 
1254
  }
1255
  >
1256
  Filter unresolved
 
1272
  <span
1273
  className="cg-count cg-count-partial"
1274
  title={
1275
+ `Loading the rest of your ${nouns} in the background — you can browse, ` +
1276
  "filter and sort what is already here."
1277
  }
1278
  >
web/src/customer-grid/ViewSidebar.tsx CHANGED
@@ -44,7 +44,6 @@ import { FolderMark, LockMark, MenuLabel, ModeIcon, ToneModeIcon } from "./icons
44
  */
45
  import { WORKSPACE_STALE_EVENT, signal } from "../apiContract";
46
  import { ROOT_FOLDER_ID } from "./folders";
47
- import { pathStorageKey, resolveStoredPath } from "./viewEcho";
48
  // ⭐ W32-T23 (owner item 17) — THE BELL, from the shared layer rather than redrawn here.
49
  // The alert row wore `cohortAdd` (a LIST with a plus), which names "add to a cohort" on the
50
  // one row that creates an ALERT — a borrowed mark is a small lie a menu repeats every time
@@ -56,18 +55,11 @@ import { BellIcon, StarIcon } from "../ui/icons";
56
  // ⚠ `SHARED_FOLDER_ID` is no longer imported: W34-T25 replaced both of its call sites with
57
  // `isSyntheticFolderId`, and `noUnusedLocals` turns a leftover import into a build error rather
58
  // than into dead weight. The constant itself is still exported and still used by `folders.ts`.
59
- // ⚠ `folderHiddenByCollapse` is no longer imported: W42-T43 replaced the whole expand/collapse
60
- // tree with a path (R12.2), so this rail has no ancestor to be hidden by. The function is still
61
- // exported from `folders.ts` and still belongs to that file's own contract.
62
  import {
 
63
  folderNesting,
64
- // ⭐⭐ W42-T43 (C9) — the ONE path resolver over both folder systems, from W42-T41.
65
- // `folderPath` is the breadcrumb (outermost first); `levelAt` answers which folders are the
66
- // CHILDREN of where the user is standing, which is the whole of the drill.
67
- folderPath,
68
  groupByFolder,
69
  isSyntheticFolderId,
70
- levelAt,
71
  mayFileView,
72
  mayNestFolder,
73
  reorderFolderIds,
@@ -414,6 +406,9 @@ interface ViewSidebarProps {
414
  * throws). The behaviour is not silently degraded — the row is ABSENT, which a reader can see.
415
  */
416
  onToggleImportant?: (viewId: string, important: boolean) => void;
 
 
 
417
  /* wave17 R1 / C-LOCKV — `cohorts` and `onSelectCohort` are GONE from this component's
418
  surface. They carried the transient-lock selection for the retired Cohorts section; a
419
  locked view is now an ordinary member of `views` and is selected by `onSelect` like any
@@ -475,17 +470,13 @@ interface ViewSidebarProps {
475
  * *"a folder shared to another user reverts to the default folder icon"*, and the cause is that
476
  * the wire has never carried one: `core/grid_events.py::_granted_views` stamps
477
  * `v['sharedFolder'] = <the folder's NAME>`, a string, so the receiver's rail synthesises a group
478
- * from a name and an owner. ⭐ W42-T18 CLOSED THAT HALF, and it closed it as a SECOND KEY rather
479
- * than a replacement: the host sends the folder RECORD alongside, on `sharedFolderRecord`
480
- * (`grid_events.py::_shared_folder_record`), while `sharedFolder` stays the plain name string
481
- * that `verify_folders.py` and `verify_api.py` both pin. So the icon has somewhere to travel and
482
- * the string contract is untouched.
483
  *
484
- * ⚠ SO BOTH SHAPES ARE READ, and the string one is not a fallback but TODAY's name source. The
485
- * NAME comes from the string; the ICON comes from the record. A payload with no record, or with
486
- * a record carrying no icon, yields a name with no icon and renders the DEFAULT mark: an absent
487
- * key means "the owner chose none", never "guess". Nothing paints a mark the sharer did not
488
- * choose.
489
  *
490
  * ⚠ THE ICON GOES THROUGH `cleanFolderIcon`, the same whitelist the create pane and the host
491
  * validator use. An unknown shape drops the icon rather than substituting a picture nobody
@@ -505,41 +496,11 @@ function sharedFolderRecord(
505
  via && typeof via === "object" && !Array.isArray(via)
506
  ? (via as Record<string, unknown>)
507
  : null;
508
- /**
509
- * ⭐⭐ WAVE 42 · T18 — THE SECOND SOURCE, AND THE NAME COLLISION IS DELIBERATE.
510
- *
511
- * ⛔ `sharedFolderRecord` IS BOTH THIS FUNCTION AND A WIRE KEY. The server named its key after
512
- * what this function returns, so `wireRec` below is `v['sharedFolderRecord']` off the payload
513
- * and has nothing to do with the enclosing function. A grep for the bare name finds this
514
- * function four times over; only `.sharedFolderRecord` finds the wire field.
515
- *
516
- * ⛔ ONLY THE `icon` IS TAKEN. The record also carries `id`, which is the SENDER's folder id
517
- * and collides with `groupByFolder`'s id namespace — the receiver's group id is synthesised by
518
- * `sharedFolderGroupId(owner, name)`, so borrowing `rec.id` would key a group on a folder that
519
- * does not exist in this user's store. `name` keeps coming from the string, which is what
520
- * `grid_events.py` stamps on `sharedFolder` and what two gates pin as a string contract.
521
- *
522
- * ⚠ PRECEDENCE: an inline object on `sharedFolder` WINS over the wire record. The reason is
523
- * that the name and the icon then come from one object, so they cannot describe two different
524
- * folders. This is documentation today rather than behaviour: `sharedFolder` is a string in
525
- * every real payload, so the wire record is what actually supplies the icon.
526
- *
527
- * ⚠ A malformed, absent, array-shaped or icon-less record degrades to no icon and the rail
528
- * draws `FolderMark`'s default. `cleanFolderIcon` is the same whitelist the create pane uses,
529
- * so an unknown shape drops the mark rather than inventing one nobody picked.
530
- */
531
- const wireRec = (view as { sharedFolderRecord?: unknown }).sharedFolderRecord;
532
- const granted =
533
- wireRec && typeof wireRec === "object" && !Array.isArray(wireRec)
534
- ? (wireRec as Record<string, unknown>)
535
- : null;
536
  const rawName = typeof via === "string" ? via : record?.name;
537
  const name = typeof rawName === "string" ? rawName.trim() : "";
538
  const owner = typeof view.owner === "string" ? view.owner.trim() : "";
539
  if (!name || !owner) return null;
540
- const icon =
541
- (record ? cleanFolderIcon(record.icon) : undefined) ??
542
- (granted ? cleanFolderIcon(granted.icon) : undefined);
543
  return icon ? { name, owner, icon } : { name, owner };
544
  }
545
 
@@ -586,92 +547,6 @@ function FolderIconPicker({
586
  );
587
  }
588
 
589
- // ── WAVE 42 · T45 (ruling R12, contract C9): THE BROWSER HALF OF "the path is where I left it" ──
590
- //
591
- // R12.6 chose PER-BROWSER persistence of the rail's open folder over always resetting to the top
592
- // level, and over putting the path in the URL. The URL option was judged the more useful one and
593
- // is booked as O4; it is deliberately NOT built here.
594
- //
595
- // ⛔⛔ WHY THIS IS IN THE COMPONENT FILE AND NOT IN `viewEcho.ts`. `verify_view_echo.py` compiles
596
- // `_test/viewEcho.test.ts` and runs it under BARE NODE — no jsdom, no `window`, no
597
- // `localStorage`, and the test installs no shim. Anything touching `window` in that module would
598
- // be untestable by its own gate: both databases would fall into the same `catch` and answer
599
- // identically, so "two databases keep separate positions" would go green over nothing. So the
600
- // module keeps the two PURE pieces the gate can actually prove (`pathStorageKey`,
601
- // `resolveStoredPath`) and the three `window` reads live here, beside the `aios-views-rail`
602
- // try/catch this file already owns.
603
- //
604
- // ⛔⛔ THE ACCESSOR ITSELF THROWS. In a private window, with site data cleared, or in a browser
605
- // configured to block storage, `window.localStorage` throws on PROPERTY ACCESS — not on
606
- // `getItem`. So the familiar `typeof window !== "undefined" && window.localStorage` feature test
607
- // IS the throwing expression, and it must sit INSIDE the `try`, never in front of it. A rail that
608
- // throws on mount is a blank shell, so all three helpers are total: they answer a value, or they
609
- // do nothing.
610
-
611
- /**
612
- * The database this browser is remembering a position for, taken from the route.
613
- *
614
- * ⚠ DELIBERATE DUPLICATION, NAMED SO IT READS AS A TRADE RATHER THAN AS DRIFT. The canonical
615
- * transform is `shell/nav.ts::routeKeyOf`; this is a second copy of it. The import is REFUSED
616
- * because it would INVERT the layering: `shell/` imports `customer-grid/` seventeen times, so
617
- * this is the LOWER layer, and importing upward is the front-end reading of CLAUDE.md's "core
618
- * never imports up". Reading the hash from inside `customer-grid` is already precedent
619
- * (`CustomerGrid.tsx:1020` tests `window.location.hash.startsWith("#/query")`).
620
- *
621
- * ⚠ THE ROUTE AND NOT A PROP: this component takes 42 props and not one carries a database key,
622
- * and it is mounted from `CustomerGrid.tsx`, another lane's file. The hash IS the database
623
- * identity here — the shell itself resolves a database from the route rather than from the rail,
624
- * because a person reaches one from Home, Starred, a notification or a bookmark.
625
- *
626
- * ⚠ SCOUTED, so the next reader need not: a database route's hash is exactly `#/<databaseKey>`
627
- * (`shell/Shell.tsx:1105`) with no query string and no sub-path, and the active view or tab is
628
- * never encoded into it. That is what makes this key stable for as long as the viewer stays in
629
- * one database, which is what "remembered per database, across a reload" rests on. The `?` and
630
- * nested-`#` stripping reproduced here is pinned by `shell/_test/shell.test.ts:1152`.
631
- *
632
- * ⚠ An unreadable hash and an absent one both answer `""`. That collapses every unidentifiable
633
- * route onto one key, which is harmless — no database identity means no position worth keeping —
634
- * but it is NOT per-route isolation and must not be read as such.
635
- */
636
- function railDbKey(): string {
637
- try {
638
- const hash = window.location.hash;
639
- return typeof hash === "string" ? hash.replace(/^#\/?/, "").split("?")[0].split("#")[0] : "";
640
- } catch {
641
- return "";
642
- }
643
- }
644
-
645
- /** The folder id this browser last had open for `dbKey`, RAW and still UNRESOLVED: it names a
646
- * folder that may since have been deleted, so it is only ever handed to `resolveStoredPath`
647
- * before anything is rendered from it. `null` for absent, blocked, wrong type or empty. */
648
- function readRailPath(dbKey: string): string | null {
649
- try {
650
- const raw = localStorage.getItem(pathStorageKey(dbKey));
651
- return typeof raw === "string" && raw !== "" ? raw : null;
652
- } catch {
653
- return null;
654
- }
655
- }
656
-
657
- /**
658
- * Remember (or forget) this browser's position for `dbKey`. `null` — the top level — REMOVES the
659
- * entry rather than storing a sentinel, so "never visited" and "back at the top" are one state
660
- * with one representation.
661
- *
662
- * Silent on failure by design: storage being blocked or full must not turn opening a folder into
663
- * an error the viewer sees. Losing the memory is the correct degradation.
664
- */
665
- function writeRailPath(dbKey: string, folderId: string | null): void {
666
- try {
667
- const key = pathStorageKey(dbKey);
668
- if (folderId) localStorage.setItem(key, folderId);
669
- else localStorage.removeItem(key);
670
- } catch {
671
- // blocked, full, or a private window: the position is simply not remembered.
672
- }
673
- }
674
-
675
  export default function ViewSidebar({
676
  agentPanel = null,
677
  agentOpen = false,
@@ -712,6 +587,8 @@ export default function ViewSidebar({
712
  viewer,
713
  onToggleLock,
714
  onToggleImportant,
 
 
715
  }: ViewSidebarProps) {
716
  /**
717
  * I14 — creating a view now always knows WHICH KIND of view is being created, because the
@@ -723,88 +600,76 @@ export default function ViewSidebar({
723
  const [name, setName] = useState("");
724
  const [menu, setMenu] = useState<{
725
  viewId: string;
726
- anchor: HTMLButtonElement;
727
  } | null>(null);
728
  const [renamingId, setRenamingId] = useState<string | null>(null);
729
  const [noteFor, setNoteFor] = useState<{
730
  viewId: string;
731
- anchor: HTMLButtonElement;
732
  } | null>(null);
733
  const [noteDraft, setNoteDraft] = useState("");
734
  const [addFor, setAddFor] = useState<{
735
  viewId: string;
736
- anchor: HTMLButtonElement;
737
  } | null>(null);
738
  /** Item 12 (C-LOCK) — which view's cohort lock the picker is open for. */
739
  const [lockFor, setLockFor] = useState<{
740
  viewId: string;
741
- anchor: HTMLButtonElement;
742
  } | null>(null);
743
  const [newListName, setNewListName] = useState("");
744
  /** W2 — the Export format pane, anchored where the "…" menu was. */
745
  const [exportFor, setExportFor] = useState<{
746
  viewId: string;
747
- anchor: HTMLButtonElement;
748
  } | null>(null);
749
  const exportView = exportFor
750
  ? views.find((view) => view.id === exportFor.viewId)
751
  : undefined;
752
- /**
753
- * ⭐⭐ WAVE 42 · T44 (ruling R12, contract C9) — THE "Move to" PICKER, and which view it is
754
- * open for. It is the SECOND door onto the move the drag already performs, not a replacement:
755
- * with the rail navigating by path, a view and a folder ten levels away are never on screen
756
- * together, so drag alone leaves most destinations unreachable. R12.5 chose both doors.
757
- */
758
- const [moveFor, setMoveFor] = useState<{
759
- viewId: string;
760
- anchor: HTMLButtonElement;
761
- } | null>(null);
762
- const moveView = moveFor
763
- ? views.find((view) => view.id === moveFor.viewId)
764
- : undefined;
765
  const addView = addFor ? views.find((view) => view.id === addFor.viewId) : undefined;
766
  const menuView = menu ? views.find((view) => view.id === menu.viewId) : undefined;
 
 
 
 
 
 
767
  /** C4 — may this viewer change the menu view's IDENTITY? Courtesy only; the host is the
768
  * wall. C3's lock toggle ANDs with this rather than replacing it: the two contracts
769
  * compose (C4 says who may edit, C3 says who may freeze the mode). */
770
  const canEditMenuView = !!menuView && mayEditView(menuView, viewer);
771
- // I11c local UI state. Where in the folder path you are standing is deliberately LOCAL
772
- // (C4: "minimize state local") — it is a per-person, per-session habit, not a property of
773
- // the shared workspace.
774
  /**
775
- * ⭐⭐ WAVE 42 · T43 (instruction 16, R12) — THE STATE IS WHERE THE USER IS STANDING, AND
776
- * THE TREE IS GONE.
777
  *
778
- * Owner: *"When I click a folder it opens that folder not as a dropdown BUT as a path … it
779
- * should only show (in the View navigation) what is IN that folder, and I should be able to go
780
- * back and forth."* R12.2 deletes the twisty, the indentation and every scrap of expand state
781
- * with it, so what replaced W41-T34's `opened` set is not a smaller set: it is ONE id.
782
  *
783
- * ⛔ `null` IS THE TOP LEVEL, never `ROOT_FOLDER_ID`. The resolver accepts the sentinel as an
784
- * input and reads it as the top, but this rail only ever writes a real folder id or `null`, so
785
- * "am I at the top" is one comparison everywhere below rather than two.
 
 
 
 
786
  *
787
- * ⚠ IT MAY NAME A SYNTHETIC GROUP. "Shared with me" and each shared folder own a head on this
788
- * rail while having no record in `folders`; drilling into one is the same gesture the user just
789
- * made on a folder of their own, so it is allowed and `atId` below validates against the GROUPS
790
- * rather than against the stored list.
 
 
791
  *
792
- * ⭐⭐ WAVE 42 · T45 (R12.6) AMENDS THE LINE THAT STOOD HERE. T43 wrote "session here means the
793
- * component's lifetime … there is no localStorage", on the reasoning that reopening three
794
- * folders deep on the next login would be the old "a folder is open when the user next logs in"
795
- * defect wearing a path. R12.6 REVERSED that: the position now survives a reload, PER DATABASE,
796
- * in this viewer's own browser. The old defect is not what returns, because it was about a
797
- * SHARED, server-side expand state deciding what everyone saw; this is one browser remembering
798
- * one person's own last gesture, and it is resolved against the live rail before it is trusted.
799
- *
800
- * ⛔ SEEDED RAW, DELIBERATELY. What comes out of storage may name a folder deleted by another
801
- * session, so it is NOT validated here — `atId` below is the single validator, and it re-runs
802
- * on every render against the groups that actually exist. Seeding through a validator would
803
- * also be wrong at this instant: the workspace has not arrived at first render
804
- * [[grid-init-runs-before-the-workspace-arrives]], so `groups` is empty and every stored path
805
- * would resolve to `null` and be erased before the rail could ever honour it.
806
  */
807
- const [at, setAt] = useState<string | null>(() => readRailPath(railDbKey()));
808
  const [folderMenu, setFolderMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null);
809
  /**
810
  * ⭐ W41-T35 (instruction 11) — WHICH FOLDER'S MARK IS BEING CHANGED, and off which button.
@@ -995,39 +860,6 @@ export default function ViewSidebar({
995
  () => folderNesting(foldersOn ? (folders as GridFolder[]) : []),
996
  [foldersOn, folders]
997
  );
998
- /**
999
- * ⭐⭐ WAVE 42 · T44 (R12, C9) — MAY THIS VIEWER FILE THE MENU'S VIEW, computed HERE rather
1000
- * than inline on the row.
1001
- *
1002
- * ⛔ AND THE REASON IS A GATE, WHICH IS WHY IT IS NOT A STYLE CHOICE. `verify_wiring.py`'s
1003
- * W39-T29 leg reads the 900 code-characters immediately BEFORE the Share view row and fails if
1004
- * `canEditMenuView` appears in them — that is how it proves sharing is offered outside the
1005
- * edit-only predicate. A "Move to" row written just above Share view with its gate spelled out
1006
- * inline would drop that identifier straight into the window and turn a correct row into a red
1007
- * on a claim it has nothing to do with. Named once up here, the row reads `canFileMenuView`.
1008
- *
1009
- * ⚠ `mayFileView`, NOT `mayEditView`, matching the DRAG site exactly (W34-T22 / D-249): filing
1010
- * writes a placement into the reader's own workspace stratum and never touches the owner's
1011
- * object, so a read-only shared view may still be filed. Two doors onto one move must also
1012
- * agree about who may open them.
1013
- */
1014
- const canFileMenuView =
1015
- foldersOn && !!menuView && mayFileView(menuView, canEditMenuView);
1016
- /**
1017
- * ⭐⭐ WAVE 42 · T44 — EVERY FOLDER IN THIS DATABASE, DEPTH-FIRST. This is the whole ticket:
1018
- * the picker offers the FULL tree, not the level the rail happens to be standing on, so a
1019
- * folder ten deep is one click away from the top level with no navigating.
1020
- *
1021
- * ⛔ SYNTHETIC IDS ARE NOT DESTINATIONS. "Shared with me" and every shared-folder group are
1022
- * invented by the grouping pass and have no record in the stored list, so filing a view "into"
1023
- * one would write an id nothing owns — the same write `isSyntheticFolderId` exists to stop at
1024
- * the drop site. They cannot normally reach `folders` at all; the filter is here so that if one
1025
- * ever does, this picker is not the door that lets it through.
1026
- */
1027
- const moveFolders = useMemo(
1028
- () => nesting.ordered.filter((f) => !isSyntheticFolderId(f.id)),
1029
- [nesting]
1030
- );
1031
  /**
1032
  * ⭐⭐ WAVE 41 · T37 (owner instruction 14) — THE GROUPING RUNS ONCE PER INPUT CHANGE, NOT
1033
  * ONCE PER RENDER.
@@ -1118,13 +950,9 @@ export default function ViewSidebar({
1118
  * `groupByFolder` keys with — over the record `sharedFolderRecord` returns to BOTH. One
1119
  * extractor, one key function, so no second spelling of "which folder is this" exists.
1120
  *
1121
- * ⭐ POPULATED SINCE W42-T18. The wire carries the folder NAME on `sharedFolder` and the folder
1122
- * RECORD on `sharedFolderRecord`, and `sharedFolderRecord` (the function, four lines of scroll
1123
- * up from every call site) pulls the icon off the second while still taking the name from the
1124
- * first. A shared folder whose owner picked a mark now wears that mark here; one whose owner
1125
- * picked none still falls through to `FolderMark`'s default, which is the right answer rather
1126
- * than a gap. The map is keyed by the RECEIVER's synthesised group id, never by the sender's
1127
- * folder id, so nothing here can name a folder this user does not have.
1128
  */
1129
  const sharedFolderIcons = useMemo(() => {
1130
  const marks = new Map<string, FolderIcon>();
@@ -1135,194 +963,43 @@ export default function ViewSidebar({
1135
  return marks;
1136
  }, [shownViews]);
1137
  /**
1138
- * ⭐⭐ WAVE 42 · T43 (instruction 16, R12.1) — WHERE THE USER IS ACTUALLY STANDING.
1139
- *
1140
- * ⛔ VALIDATED AGAINST THE GROUPS, NOT AGAINST `folders`, and for the reason the collapsed set
1141
- * this replaces gave: a synthesised group ("Shared with me", and one per shared folder) owns a
1142
- * head on this rail while having no record in the stored list, so validating against `folders`
1143
- * would bounce the user straight back out of a folder they had just opened. A folder that is
1144
- * deleted, revoked or filtered away while the user stands inside it falls back to the top level
1145
- * rather than leaving the rail showing an empty level with no way out.
1146
- *
1147
- * ⚠ A LIVE SEARCH KEEPS `at` UNTOUCHED. Search flattens across every level (see `levelGroups`),
1148
- * so `atId` is not read while a needle is live; recomputing it against the SEARCH-FILTERED
1149
- * groups would silently reset the path, and clearing the search would land the user at the top
1150
- * instead of back where they were.
1151
- *
1152
- * ⭐⭐ WAVE 42 · T45 — AND THIS IS ALSO THE STALE-STORED-PATH GUARD. There is exactly ONE
1153
- * definition of "a place I can stand" in this rail, and it is the set below: a path restored
1154
- * from localStorage is judged by the same expression as a path the user walked to a moment ago.
1155
- * A second validator for the restored case is the drift C9 exists to prevent, and it would fail
1156
- * in a specific, near-unreportable way — validating against `folders` (which has no record of a
1157
- * synthesised shared group) would call a live shared folder deleted and bounce the viewer out
1158
- * of a folder they had just opened, reading as "reload sometimes forgets where I was".
1159
- */
1160
- const standableIds = useMemo(() => {
1161
- const ids: string[] = [];
1162
- for (const g of groups) if (g.folder) ids.push(g.folder.id);
1163
- return ids;
1164
- }, [groups]);
1165
- const atId = useMemo(() => {
1166
- if (at === null) return null;
1167
- if (viewNeedle) return at;
1168
- return resolveStoredPath(at, standableIds);
1169
- }, [at, standableIds, viewNeedle]);
1170
- /**
1171
- * ⭐⭐ WAVE 42 · T45 (R12.6) — THE WRITE HALF, and it persists `at` rather than `atId`.
1172
- *
1173
- * ⛔ THAT CHOICE IS THE WHOLE SAFETY OF THIS EFFECT. `atId` is `null` whenever the groups are
1174
- * not there yet, and at first render they are not [[grid-init-runs-before-the-workspace-arrives]].
1175
- * Persisting it would erase the stored path microseconds after reading it, on every single
1176
- * load, and the feature would fail with storage working perfectly and nothing red anywhere.
1177
- * `at` moves only when the viewer moves, so what is written is always a gesture.
1178
- *
1179
- * ⚠ A STALE ENTRY IS ALLOWED TO SIT. If the folder was deleted elsewhere, `at` keeps the dead
1180
- * id while `atId` renders the top level; the next navigation overwrites it. Nothing is rendered
1181
- * from the untrusted value at any point, so cleaning it eagerly would buy nothing and cost the
1182
- * erasure above.
1183
- *
1184
- * ⚠ THE KEY IS RE-READ AT WRITE TIME rather than captured at mount, so a route change cannot
1185
- * write one database's position into another's slot.
1186
- */
1187
- useEffect(() => {
1188
- writeRailPath(railDbKey(), at);
1189
- }, [at]);
1190
- /**
1191
- * ⭐⭐ WAVE 42 · T43 (contract C9) — THE LEVEL, FROM T41'S RESOLVER.
1192
- *
1193
- * ⛔ THE PARENT WALK IS NOT REDONE HERE. `levelAt` is the one resolver C9 puts over both folder
1194
- * systems, and it is what answers "which folders are the children of where I am standing" and
1195
- * "what is one level out". A second spelling of that walk in the rail is exactly the drift C9
1196
- * exists to prevent — and it is what the parity gate's negative control (drop the parent pass,
1197
- * watch a two-deep folder resolve to the wrong level) is watching for.
1198
- *
1199
- * ⚠ THE VIEWS ARE HANDED IN BUT THE LEAVES ARE NOT READ BACK. The rail renders its rows out of
1200
- * `groups`, which carries the pin bucket, the synthesised shared groups and every drag key the
1201
- * handlers below compare against; `levelAt`'s own leaf split would be a second, poorer reading
1202
- * of the same views. What is read is `folders` (the child folder records) and `parent` (the
1203
- * back step), which is the half no other pass in this file computes.
1204
- */
1205
- const level = useMemo(
1206
- () =>
1207
- levelAt(
1208
- atId,
1209
- foldersOn ? (folders as GridFolder[]) : [],
1210
- shownViews,
1211
- (v) => (folderIdOf ? folderIdOf(v.id) : null)
1212
- ),
1213
- [atId, foldersOn, folders, shownViews, folderIdOf]
1214
- );
1215
- /**
1216
- * ⭐ R12.1 — ONE CONTINUOUS PATH, outermost first, the folder the user is in last.
1217
- * Empty at the top level, which is what makes "is there a back step" one truthiness test.
1218
- * The database half of that path (`Data › Sales stuff › Odoo Customers`) belongs to the shell
1219
- * rail; this is the views half, and the two read as one line because they use one vocabulary.
1220
- */
1221
- const crumbs = useMemo(
1222
- () => folderPath(atId, foldersOn ? (folders as GridFolder[]) : []),
1223
- [atId, foldersOn, folders]
1224
- );
1225
- /**
1226
- * ⚠ THE NAME OF THE LEVEL WHEN THE PATH CANNOT SPELL IT. `folderPath` walks records, and a
1227
- * synthesised group ("Shared with me", a colleague's folder) has none — so the crumb list is
1228
- * empty for one even though the user is standing inside it. The GROUP knows its own name, which
1229
- * is the same name its head was wearing when it was clicked.
1230
- */
1231
- const atLabel = useMemo(
1232
- () => (atId === null ? null : groups.find((g) => g.folder?.id === atId)?.folder?.name ?? null),
1233
- [atId, groups]
1234
- );
1235
- /**
1236
- * ⭐ W42-T43 — WHAT THE PATH ROW SAYS, AND WHAT PRESSING IT DOES, as two strings that are
1237
- * assembled into ONE accessible name.
1238
- *
1239
- * ⛔ THE ACCESSIBLE NAME CONTAINS THE VISIBLE TEXT. `aria-label` REPLACES a button's visible
1240
- * text for a screen reader, so a bare "Back to Sales stuff" on a row reading "Sales stuff › Q3"
1241
- * would announce a different label than the one on screen — the label-in-name failure, and on
1242
- * the one control that tells the user where they are. The visible path leads, the action
1243
- * follows it.
1244
- */
1245
- const pathLabel = crumbs.length
1246
- ? crumbs.map((f) => f.name).join(" › ")
1247
- : (atLabel ?? "All views");
1248
- const backLabel = crumbs.length > 1 ? crumbs[crumbs.length - 2].name : "all views";
1249
- /**
1250
- * ⭐⭐ WAVE 42 · T43 (R12.2, R12.4) — THE ROWS OF THIS LEVEL, FOLDERS FIRST.
1251
  *
1252
- * `groups` stays FLAT and stays the render source (C9: the drag handlers key off folder ids and
1253
- * `parent`, never a path string). This pass decides two things per group and nothing else:
1254
- * whether it belongs to the level on screen, and whether it renders as a HEAD you can drill
1255
- * into or as the LEAVES you are standing among.
1256
  *
1257
- * ⛔⛔ THE PIN BUCKET STAYS FIRST AT THE TOP LEVEL, AND THAT IS A RULING CALL, NOT AN OVERSIGHT.
1258
- * R12.4 orders a level "folders first, then its leaves"; W40-T28 is an owner instruction that
1259
- * an unfiled default view *"must sit at the very top above all folders unless the user moves it
1260
- * down"*. Read literally the two disagree here. This takes W40-T28, because R12.4's own
1261
- * rejected alternatives ("interleaved in manual drag order", "views first") are both readings
1262
- * of the ORDINARY leaf bucket — R12 never mentions the pin — and because the pin holds the
1263
- * per-database default view, so ordering it under every folder would put the rail's
1264
- * most-clicked row last. The conflict was reported rather than resolved here, and RULED:
1265
- * ⭐⭐ AMENDMENT A27 (2026-08-25) settles it THIS way, on a stronger ground than the one above.
1266
- * W40-T28's words are *"above all folders"* — a phrase nobody writes without knowing folders
1267
- * are there, so it does not merely fail to contemplate R12.4, it ANTICIPATES it and overrides
1268
- * it for this one row.
1269
- * ⛔ AND THE LIMIT IS IN THE SAME SENTENCE: the condition is *"when it is NOT IN A FOLDER"*.
1270
- * The pin outranks folders ONLY while unfiled. File the view and it returns to ordinary leaf
1271
- * ordering, behind the folders, which is what makes A27 consistent with both rulings rather
1272
- * than a win for one of them.
1273
  *
1274
- * ⭐ SEARCH FLATTENS ACROSS EVERY LEVEL. With expand/collapse deleted there is no "open
1275
- * everything" left for a search to do, and a search that quietly saw only the folder you happen
1276
- * to be standing in would answer "no such view" about a view that exists. So while a needle is
1277
- * live every matching view is listed wherever it lives, folder heads are suppressed (a head
1278
- * carries no matches of its own), and the path row above says so in as many words.
 
 
 
1279
  */
1280
- const levelGroups = useMemo(() => {
1281
- const pin: typeof groups = [];
1282
- const heads: typeof groups = [];
1283
- const leaves: typeof groups = [];
1284
- /**
1285
- * ⛔⛔ A SYNTHETIC LEVEL HAS NO CHILDREN, AND SAYING SO IS NOT OPTIONAL. `levelAt` resolves
1286
- * an id it has no record of as the TOP level (`levelIdOf` returns null for an unknown id),
1287
- * so standing inside "Shared with me" would otherwise hand back every top-level folder as
1288
- * this level's children and redraw the whole root under a shared heading. The shared groups
1289
- * are a reading of the view list, not records, so their contents are exactly their views.
1290
- */
1291
- const childIds = new Set(
1292
- atId !== null && isSyntheticFolderId(atId) ? [] : level.folders.map((f) => f.id)
1293
- );
1294
- for (const group of groups) {
1295
- const gid = group.folder?.id ?? null;
1296
- if (viewNeedle) {
1297
- // Flattened: every group contributes its matches, no heads, no levels.
1298
- if (group.items.length > 0) leaves.push(group);
1299
- continue;
1300
- }
1301
- if (group.pinned === true) {
1302
- if (atId === null) pin.push(group);
1303
- continue;
1304
- }
1305
- if (gid === null) {
1306
- // The ungrouped bucket is the TOP level's leaves and exists nowhere else.
1307
- if (atId === null) leaves.push(group);
1308
- continue;
1309
  }
1310
- if (gid === atId) {
1311
- // The folder the user is standing IN renders as its own contents, head suppressed.
1312
- leaves.push(group);
1313
- continue;
1314
- }
1315
- // ⚠ A SYNTHETIC GROUP HAS NO RECORD, so `levelAt` cannot list it as a child: it is a
1316
- // reading of the view list rather than a folder, and it sits at the top level exactly
1317
- // where it sat before this ticket.
1318
- if (isSyntheticFolderId(gid)) {
1319
- if (atId === null) heads.push(group);
1320
- continue;
1321
- }
1322
- if (childIds.has(gid)) heads.push(group);
1323
  }
1324
- return { heads, rows: [...pin, ...heads, ...leaves] };
1325
- }, [groups, level, atId, viewNeedle]);
1326
  const folderMenuF = folderMenu ? folders?.find((f) => f.id === folderMenu.id) : undefined;
1327
  /**
1328
  * ⭐⭐ W41-T35 — THE FOLDER WHOSE MARK IS BEING CHANGED, AND THE SECOND REFUSAL OF A SYNTHETIC
@@ -1349,10 +1026,30 @@ export default function ViewSidebar({
1349
  * the SAME `nesting` the rail renders from, so the verdict and the picture cannot disagree.
1350
  */
1351
  const nestHere = folderMenuF ? mayNestFolder(nesting, folderMenuF.id) : null;
1352
- /* ⛔ W42-T43 — `searchKeepsFolder` IS DELETED WITH THE TREE. It existed to keep a folder head
1353
- on screen when only a folder INSIDE it matched, which was a rule about hiding descendants.
1354
- R12.2 removes descendants from the rail entirely and search now flattens across every level,
1355
- so the matching view is listed in its own right and there is no parent left to orphan. */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1356
  const addPreview = addTarget && folderAddPreview ? folderAddPreview(addTarget) : null;
1357
  /**
1358
  * ONE pair of drop handlers per group, serving TWO drags — a view being filed into this
@@ -1488,21 +1185,24 @@ export default function ViewSidebar({
1488
  // folder can always go.
1489
  const into = mayNestFolder(nesting, folderParent).ok ? folderParent : null;
1490
  /**
1491
- * ⭐⭐ WAVE 42 · T43 (R12.1) — CREATING A FOLDER INSIDE ONE WALKS YOU INTO IT, or the new
1492
- * folder is created out of sight.
 
 
 
 
 
 
 
1493
  *
1494
- * ⛔ THIS IS T34's REGRESSION, ONE NAVIGATION MODEL LATER. The "New folder inside" row hangs
1495
- * off a folder HEAD, and a head is a folder one level DOWN from where the user is standing:
1496
- * the child it creates therefore belongs to a level the rail is not showing. The user names a
1497
- * folder, presses Create, and nothing moves. T34 answered this by opening the parent; the
1498
- * path answers it by ENTERING the parent, which is the same sentence in the new vocabulary
1499
- * and leaves the user looking straight at what they just made.
1500
  *
1501
- * ⚠ A REFUSED PARENT (`into === null`) LEAVES THE PATH ALONE rather than jumping to the top:
1502
- * the folder was created at the top level, but yanking the user out of the folder they were
1503
- * standing in would be a second surprise on top of the first.
1504
  */
1505
- if (into) setAt(into);
1506
  // cleanFolderIcon returns undefined for the all-defaults pair, so a folder the user
1507
  // never restyled stays byte-identical to a pre-wave-9 one (the no-churn rule).
1508
  onFolderCreate?.(value, cleanFolderIcon(folderIcon), into);
@@ -1956,69 +1656,31 @@ export default function ViewSidebar({
1956
  </AnchoredOverlay>
1957
  )}
1958
 
1959
- {/* ⭐⭐ W42-T43 (instruction 16, R12.1) — THE PATH, AND THE ONE WAY BACK.
1960
- Owner: *"I should be able to go back and forth."*
1961
-
1962
- ⛔ OUTSIDE `.cg-view-list`, DELIBERATELY, and both halves of that matter. The list is
1963
- the scroll container (`.cg-views-scroll`), so a back control inside it scrolls away
1964
- from a user standing at the bottom of a long folder: the only way out of a level would
1965
- disappear as you looked through it. And as a direct child of `.cg-views` it obeys
1966
- `.cg-views.is-collapsed > :not(.cg-views-top)`, so a folded rail hides the path with
1967
- everything else rather than leaving one orphan row.
1968
-
1969
- ⚠ NO NEW CONTROL SHAPE (DESIGN.md §4): the row is a `.cg-fold-head` carrying a
1970
- `.cg-fold-toggle`, which is the folder row this rail already teaches, read backwards.
1971
- The mark is the caret the shell rail uses for a step, not a second glyph vocabulary. */}
1972
- {(atId !== null || viewNeedle) && (
1973
- <div className="cg-fold-head">
1974
- {viewNeedle ? (
1975
- /* ⛔ THE SCOPE IS STATED, never implied. Search flattens across every level, so the
1976
- list on screen is not the level the path names; leaving the breadcrumb up would
1977
- claim otherwise. One line, no action needed to fix it (clearing the field is the
1978
- action), so it is a `.cg-fold-empty` note rather than a control. */
1979
- <div className="cg-fold-empty">Showing matches in every folder</div>
1980
- ) : (
1981
- <button
1982
- type="button"
1983
- className="cg-fold-toggle"
1984
- aria-label={`${pathLabel}. Back to ${backLabel}`}
1985
- title={`Back to ${backLabel}`}
1986
- onClick={() => setAt(level.parent)}
1987
- >
1988
- <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
1989
- <path
1990
- d="M9.8 3.6 5.4 8l4.4 4.4"
1991
- stroke="currentColor"
1992
- strokeWidth="1.35"
1993
- strokeLinecap="round"
1994
- strokeLinejoin="round"
1995
- />
1996
- </svg>
1997
- {/* ⚠ THE WHOLE PATH, ellipsised by `.cg-fold-name`, not just the folder you are in:
1998
- R12.1 asks for one continuous path, and on a narrow rail the tail is the part
1999
- that survives the ellipsis, which is the part the user needs. `›` is the
2000
- separator the owner wrote the ruling in. */}
2001
- <span className="cg-fold-name">{pathLabel}</span>
2002
- </button>
2003
- )}
2004
- </div>
2005
- )}
2006
-
2007
  <div className="cg-view-list cg-views-scroll">
2008
- {levelGroups.rows.map((group) => {
2009
  const gid = group.folder?.id ?? null;
 
 
 
 
 
 
 
2010
  /**
2011
- * ⭐⭐ WAVE 42 · T43 (instruction 16, R12.2) — IS THIS GROUP THE LEVEL, OR A DOOR INTO ONE?
 
2012
  *
2013
- * `levelGroups` above already decided which groups belong on screen; this is the one bit
2014
- * it cannot express as membership. A group with a folder is either the folder the user is
2015
- * STANDING IN, which renders its views and no head, or a CHILD of that folder, which
2016
- * renders its head and none of its views. There is no third state, and that is R12.2:
2017
- * the depth term, the `folderHiddenByCollapse` ancestor test and the whole expand set that
2018
- * used to live on these lines are gone, so a row's indentation no longer encodes anything
2019
- * and a folder's contents are reached by entering it.
2020
  */
2021
- const asLeaves = !group.folder || gid === atId || !!viewNeedle;
 
 
 
 
 
2022
  /**
2023
  * ⭐⭐ WAVE 40 · T28 (owner instruction 30) — THE PIN GROUP: the unfiled default views,
2024
  * rendered above every folder.
@@ -2054,43 +1716,32 @@ export default function ViewSidebar({
2054
  // "Shared with me" while offering them on a colleague's folder would emit `item_move` /
2055
  // `folder_rename` / `folder_delete` against an id that exists in nobody's store.
2056
  const isSynthetic = isSyntheticFolderId(gid);
2057
- /**
2058
- * ⭐ W42-T43 — THE DROP AREA FOR "FILE THIS INTO THE FOLDER I AM IN".
2059
- *
2060
- * ⛔ A SECOND BOOLEAN, NEVER A WIDER `isRoot`. `isRoot` means the TOP-LEVEL ungrouped
2061
- * bucket and `verify_grid_ux.py`'s `empty-root-loses-its-drop-area` control drops the
2062
- * drop area from exactly that surface; widening the name would leave the control
2063
- * injecting and failing while testing something else entirely.
2064
- *
2065
- * ⚠ THE TWO CANNOT BOTH BE TRUE: `isRoot` needs `gid === null`, which only the top level
2066
- * has, and this needs a folder the user has drilled into. Same class, same area rule
2067
- * (`.cg-fold-root.is-viewdrop`), because the head that used to accept this drop is not
2068
- * on screen at its own level.
2069
- */
2070
- // ⚠ `!isSynthetic`: a synthesised group takes no drop handlers (see the spread below),
2071
- // so painting it a drop AREA would advertise a target that silently refuses the release.
2072
- const isLevelFolder = asLeaves && gid !== null && !isSynthetic && !viewNeedle;
2073
  return (
2074
  <div
2075
  /* ⭐ W40-T28 — a key of its own. Both this group and the ungrouped section have a null
2076
  folder, so the old `gid ?? "__root__"` would give React two children with the same
2077
  key and it would reconcile one over the other. */
2078
  key={isPinnedGroup ? "__pinned__" : gid ?? "__root__"}
2079
- /* ⛔ W42-T43 (R12.2) — THE PER-LEVEL INDENT IS GONE, and nothing replaced it. T33 set a
2080
- nested folder in by `(depth - 1) * 12`px because the tree had to show you where a row
2081
- sat; a path shows you by only rendering one level at a time, so an indent here would
2082
- be a second, weaker answer to a question the path has already answered. This element
2083
- now carries no `style` at all. */
 
 
 
 
 
 
 
 
2084
  className={
2085
  /* ⭐ W40-T28 — `gid === null`, not `isRoot`: the pin group wears the SAME class as
2086
  the ungrouped section (no head, the rail's measured root indent) because it is the
2087
  same shape of thing rendered in a different place. DESIGN.md §4 — this is an
2088
- existing element joining the existing rhythm, not a new control shape.
2089
- ⭐ W42-T43 widens that to every HEADLESS group: the folder you are standing in
2090
- renders its views with no head of its own, which is the same shape again, and
2091
- `.cg-fold .cg-view-row`'s 12px child indent would set them in under a head that
2092
- is not there. */
2093
- (asLeaves ? "cg-fold-root" : "cg-fold") +
2094
  (!isPinnedGroup && dropTarget === (gid ?? "__root__") ? " is-drop" : "") +
2095
  // Item 19 — the insertion rule reads "the folder you are dragging lands HERE":
2096
  // above this folder, or above the ungrouped section, which is after them all.
@@ -2126,11 +1777,7 @@ export default function ViewSidebar({
2126
  // at `null` beside a `gid` that is `null` for this very section — that is the
2127
  // `foldDrag === gid` trap two lines up, which faded the whole ungrouped section
2128
  // permanently once already. `isRoot` is a separate boolean, so the two cannot collide.
2129
- (isRoot && viewDrag !== null ? " is-viewdrop" : "") +
2130
- // ⭐ W42-T43 — the same area, one level in: see `isLevelFolder`. Written as its own
2131
- // term rather than folded into the line above, so that line stays exactly the
2132
- // literal `verify_grid_ux.py` injects its root-drop control into.
2133
- (isLevelFolder && viewDrag !== null ? " is-viewdrop" : "")
2134
  }
2135
  {/* No drop handlers on the synthetic group — see `isSynthetic`. Spreading `{}`
2136
  rather than branching the element keeps ONE render path for every group.
@@ -2141,11 +1788,7 @@ export default function ViewSidebar({
2141
  somewhere else on screen. The ungrouped section below is the one root target. */
2142
  ...(isSynthetic || isPinnedGroup ? {} : dropHandlers(gid))}
2143
  >
2144
- {/* ⛔ W42-T43 — THE FOLDER YOU ARE STANDING IN HAS NO HEAD HERE. Its name is on the path
2145
- row above the list, which is the one place it can be while still carrying the way
2146
- back out; drawing it a second time at the top of its own contents would offer a
2147
- folder row that opens the folder you are already in. */}
2148
- {group.folder && !asLeaves && (
2149
  <div
2150
  className="cg-fold-head"
2151
  // ── Item 19 — the folder itself is the drag handle ─────────────────────
@@ -2167,31 +1810,38 @@ export default function ViewSidebar({
2167
  flow shifts the folder's name to the right, and this rail's indent is
2168
  MEASURED to the pixel (index.css: "root view name 41.00px / folder header
2169
  48.36px" — the whole point of the wave-10 item-2 fix); the gutter it would
2170
- otherwise hide in was the disclosure chevron's until W42-T43 deleted it, and
2171
- it is where a mark would still have to go. The view rows above have been
2172
  draggable with no handle since wave 8, so a folder that drags the same way
2173
  is the vocabulary this list already teaches, not a hidden feature. */}
2174
  <button
2175
  type="button"
2176
  className="cg-fold-toggle"
 
2177
  /**
2178
- * ⭐⭐ W42-T43 (instruction 16, R12.1) — THIS BUTTON IS THE DRILL NOW.
 
2179
  *
2180
- * ⛔ THE BUTTON SURVIVED THE TWISTY, AND THE DISTINCTION IS LOAD-BEARING. What
2181
- * R12.2 deletes is the `aria-expanded` behaviour and the `.cg-fold-chev` glyph;
2182
- * `.cg-fold-toggle` itself carries this row's whole layout, its reset chrome and
2183
- * the MEASURED wave-10 item-2 indent fix, so it keeps its rule and takes a new
2184
- * job. The chevron was absolutely positioned in the rail's gutter (`left: -8px`),
2185
- * out of flow, so removing it moves the folder's mark and name by nothing at all.
2186
- *
2187
- * ⚠ NO `aria-expanded`. Nothing expands: the control replaces the list with this
2188
- * folder's contents, and announcing a collapsed/expanded state for a list that
2189
- * has neither is the wrong sentence read aloud. The label below says what the
2190
- * press does instead.
2191
  */
2192
- aria-label={`Open folder ${group.folder.name}`}
2193
- onClick={() => setAt(group.folder!.id)}
 
 
 
 
 
 
2194
  >
 
 
 
2195
  {/* I14/I15 — the folder wears its chosen mark; a folder that never chose one
2196
  (every pre-wave-9 folder) renders the default grey folder shape, which is
2197
  precisely "existing folders get the folder icon". */}
@@ -2206,9 +1856,8 @@ export default function ViewSidebar({
2206
  ⛔ AND THE FALLBACK IS `undefined`, WHICH IS THE ANSWER RATHER THAN A GAP:
2207
  `FolderMark` draws the default folder in the default tone for an absent icon,
2208
  which is exactly what "the payload does not carry one yet" should look like.
2209
- ⭐ W42-T18 PUT THE FOLDER RECORD ON THE READ, so this map now carries a mark
2210
- for every shared folder whose owner picked one, and this line paints it. A
2211
- shared folder whose owner picked none still lands on the default. */}
2212
  <FolderMark
2213
  icon={group.folder.icon ?? (gid ? sharedFolderIcons.get(gid) : undefined)}
2214
  size={16}
@@ -2294,11 +1943,9 @@ export default function ViewSidebar({
2294
  )}
2295
  </div>
2296
  )}
2297
- {/* ⭐ W42-T43 — A FOLDER HEAD SHOWS NO ROWS AND STAYS A DROP TARGET. It is a door into
2298
- a level, so its views live behind it; the drop handlers above are on this same
2299
- element, which is what keeps "drag a view onto a folder to file it" working from
2300
- the level the folder is a door on. */}
2301
- {asLeaves &&
2302
  group.items.map((view) => {
2303
  const active = view.id === activeViewId;
2304
  const renaming = renamingId === view.id;
@@ -2603,13 +2250,7 @@ export default function ViewSidebar({
2603
  </div>
2604
  );
2605
  })}
2606
- {/* ⛔ W42-T43 — THE EMPTY LINE IS ABOUT THE LEVEL, NOT THE BUCKET. A folder can hold
2607
- folders now, so its own view list being empty no longer means the level is: the
2608
- heads of this level render as siblings of this group, and saying "Empty" above a
2609
- list of subfolders would be false. DESIGN.md §4 — one line and the action that
2610
- fills it, which is the line this rail already used. */}
2611
- {group.folder && asLeaves && group.items.length === 0
2612
- && levelGroups.heads.length === 0 && (
2613
  <div className="cg-fold-empty">Empty. Drag a view here.</div>
2614
  )}
2615
  </div>
@@ -2796,43 +2437,26 @@ export default function ViewSidebar({
2796
  </AnchoredOverlay>
2797
  )}
2798
 
2799
- {/* ⭐⭐ WAVE 41 · T35 (owner instruction 11) → WAVE 42 · T55 (ruling R25) — THE CHANGE-ICON
2800
- PANEL. It holds the SAME picker the create pane holds, mounted twice and never copied.
2801
- W41-T35 also gave it the folder menu's panel class, and R25 is where that was corrected:
2802
- "that navigation already exist, no need to reinvent the wheel." `cg-view-menu` is built
2803
- for menu ROWS, so the same swatch grid arrived in a narrower, tighter box than the create
2804
- step's and read as a second control. The panel now wears `cg-fold-icon-pop`, whose rule
2805
- lives in `styles/wave42/rail-views.css` and takes its padding, hairline, radius, surface
2806
- and heading type from the create step's own rules.
2807
- ⛔ `cg-view-menu` IS DELIBERATELY UNTOUCHED — the view menu, the folder menu, the column
2808
- menu and the create flyout all wear it, so fixing this panel through that class would
2809
- have restyled four surfaces to correct one.
2810
  ⚠ IT WRITES ON EVERY CLICK rather than behind a Save. Shape and tone are two independent
2811
  picks and the folder head repaints under the panel as they land, so the panel IS the
2812
  preview — a confirm step would put a button between the user and a change they can see
2813
  and undo by clicking again (§4, never over-explain). Dismissing is therefore not a
2814
- cancel, and nothing here pretends it is.
2815
- ⛔⛔ R25 ASKS FOR THE CREATE STEP'S PRESENTATION, NOT ITS FOOTER, AND THIS IS SETTLED —
2816
- do not re-open it. `cg-form-actions` belongs to the FORM (Create and Cancel for the whole
2817
- folder-creation), not to the icon step. What is shared is the icon step's container
2818
- treatment, its padding and width around the grid, and a heading naming the folder. The
2819
- dismissal that matches is the AFFORDANCES — outside click and Escape, both from
2820
- `useOverlayLayer` — not a button pair. A Cancel here would not revert anything, and a
2821
- control that lies about what it does is worse than the inconsistency it removes. */}
2822
  {iconMenu && iconMenuF && onFolderIconChange && (
2823
  <AnchoredOverlay
2824
  anchor={iconMenu.anchor}
2825
- className="cg-fold-icon-pop"
2826
  placement="bottom-end"
2827
  role="dialog"
2828
  ariaLabel={`Icon for folder ${iconMenuF.name}`}
2829
  onDismiss={() => setIconMenu(null)}
2830
  dataKind="folder-icon"
2831
  >
2832
- {/* The create step's label carries its destination and so does this heading: one line,
2833
- the folder's own name, sentence case, no explanation (DESIGN.md §4, and it mirrors
2834
- the `New folder in <name>` label the create pane shows one door away). */}
2835
- <div className="cg-fold-icon-title">{`Icon for ${iconMenuF.name}`}</div>
2836
  {/* ⚠ RESOLVED AGAINST THE DEFAULTS RATHER THAN PASSED AS `undefined`: the picker draws
2837
  a selection ring on the swatch that is currently chosen, and a folder that never
2838
  chose an icon IS wearing the default shape in the default tone (`FolderMark` reads
@@ -2848,93 +2472,6 @@ export default function ViewSidebar({
2848
  </AnchoredOverlay>
2849
  )}
2850
 
2851
- {/* ⭐⭐ WAVE 42 · T44 (ruling R12, contract C9) — THE "Move to" PICKER.
2852
- It is this rail's OWN picker vocabulary, not a second implementation: the same
2853
- `AnchoredOverlay`, the same `cg-pop` panel, `cg-pop-title`, `cg-pop-list` and
2854
- `cg-pick-row` the cohort-lock picker two blocks down already wears, hung off the same
2855
- "…" anchor the menu used. No new class and NO NEW CSS AT ALL, which is deliberate as
2856
- well as convenient: `index.css` @imports the lane sheet from the top, so a rule written
2857
- in `styles/wave42/rail-views.css` loses every equal-specificity fight silently, and the
2858
- indent this list needs is one inline `paddingLeft` on a row that already has a shape.
2859
- ⚠ `role="dialog"`, matching the icon and lock pickers rather than the "…" menu: the
2860
- rows sit inside a scrolling `cg-pop-list`, and a `menu` whose items are owned by an
2861
- intermediate element is a broken ownership tree rather than a keyboard nicety. */}
2862
- {moveFor && moveView && (() => {
2863
- const currentId = folderIdOf ? folderIdOf(moveFor.viewId) : null;
2864
- /**
2865
- * ⛔⛔ THE TWO DOORS EMIT THE SAME ID, AND THIS LINE IS WHERE THAT IS TRUE.
2866
- * It is the drop handler's expression verbatim — `onItemMove?.(id, folderId ??
2867
- * ROOT_FOLDER_ID)` — so the top-level row passes `null` and the sentinel is applied HERE,
2868
- * exactly as the drag applies it. `null` means "no placement", which `groupByFolder`
2869
- * reads as "arrived by grant" and would file a shared view straight back under "Shared
2870
- * with me"; `ROOT_FOLDER_ID` is the receiver saying they filed it at the top. A picker
2871
- * that emitted the raw `null` would give one action two behaviours with every gate green.
2872
- */
2873
- const fileInto = (folderId: string | null) => {
2874
- onItemMove?.(moveFor.viewId, folderId ?? ROOT_FOLDER_ID);
2875
- setMoveFor(null);
2876
- };
2877
- return (
2878
- <AnchoredOverlay
2879
- anchor={moveFor.anchor}
2880
- className="cg-pop"
2881
- placement="bottom-end"
2882
- role="dialog"
2883
- ariaLabel={`Move ${viewDisplayName(moveView)} to a folder`}
2884
- onDismiss={() => setMoveFor(null)}
2885
- dataKind="view-move-to"
2886
- >
2887
- <div className="cg-pop-title">Move to</div>
2888
- <div className="cg-pop-list">
2889
- {/* ⭐ THE TOP LEVEL IS A DESTINATION LIKE ANY OTHER, and it is marked current for
2890
- BOTH shapes of "already at the top": the stored sentinel and a view with no
2891
- placement at all. They are different facts about how the view got there and the
2892
- same fact about where it is, so a mark that recognised only the sentinel would
2893
- re-open the absence/sentinel confusion the drop handler exists to close. */}
2894
- <button
2895
- type="button"
2896
- className={
2897
- "cg-pick-row" +
2898
- (currentId === null || currentId === ROOT_FOLDER_ID ? " is-on" : "")
2899
- }
2900
- onClick={() => fileInto(null)}
2901
- >
2902
- <FolderMark size={16} />
2903
- Top level
2904
- </button>
2905
- {/* ⭐⭐ EVERY FOLDER IN THE DATABASE, not the level on screen. `nesting.ordered` is
2906
- depth-first, so this list runs in the order the rail itself draws the tree, and
2907
- `nesting.depth` indents each row to the level it sits at. A folder ten deep is
2908
- therefore offered, and selectable, from the top level with nothing to navigate.
2909
- ⚠ THE FOLDER THE VIEW IS ALREADY IN IS LISTED AND MARKED, not removed. Dropping
2910
- it would make the list a different shape for every view, so a user learning
2911
- where a folder sits in it would have to relearn that on the next view; and the
2912
- row is harmlessly idempotent, since choosing it emits the placement the view
2913
- already carries. `title` carries the full trail for a name that truncates. */}
2914
- {moveFolders.map((f) => (
2915
- <button
2916
- type="button"
2917
- key={f.id}
2918
- className={"cg-pick-row" + (f.id === currentId ? " is-on" : "")}
2919
- style={{ paddingLeft: 6 + (nesting.depth[f.id] ?? 0) * 12 }}
2920
- title={folderPath(f.id, moveFolders).map((p) => p.name).join(" / ")}
2921
- onClick={() => fileInto(f.id)}
2922
- >
2923
- <FolderMark icon={f.icon} size={16} />
2924
- {f.name}
2925
- </button>
2926
- ))}
2927
- {moveFolders.length === 0 && (
2928
- <div className="cg-pop-note">
2929
- There are no folders in this database yet. Make one from the rail and this view
2930
- can be filed into it.
2931
- </div>
2932
- )}
2933
- </div>
2934
- </AnchoredOverlay>
2935
- );
2936
- })()}
2937
-
2938
  {/* Item 12 (C-LOCK) — the lock picker. Lists the cohorts this reader can see, marks the
2939
  current one, and offers Unlock when there is one: a lock removable only from
2940
  somewhere other than where it was applied is a trap, and the owner asked for a
@@ -3193,30 +2730,6 @@ export default function ViewSidebar({
3193
  >
3194
  <MenuLabel icon="duplicate" text="Duplicate" />
3195
  </button>
3196
- {/* ⭐⭐ WAVE 42 · T44 (ruling R12, contract C9) — MOVE TO, THE SECOND DOOR ONTO THE
3197
- MOVE THE DRAG ALREADY PERFORMS.
3198
- ⛔ NOT POLISH, AND R12.5 SAYS SO. Now that the rail navigates by PATH, the level on
3199
- screen holds a view and its siblings and nothing else — so a folder anywhere but
3200
- here is never on screen at the same time as the view being moved, and drag alone
3201
- silently makes most destinations unreachable. The picker lists the WHOLE tree.
3202
- ⚠ NO GLYPH IN `MENU_ICONS` SAYS "folder", so the mark is passed as a NODE, the way
3203
- "Share folder" passes `ShareMark` and "Change icon" passes the folder's own mark.
3204
- The plain `FolderMark` is the honest picture of where this row sends the view, and
3205
- it keeps `icons.tsx` (another fence entirely) out of this change.
3206
- ⚠ NO ELLIPSIS ON THE LABEL: `verify_icons`'s T23 sweep reds on one in any
3207
- `MenuLabel` text, and DESIGN §4 asks for sentence case, so the row reads `Move to`. */}
3208
- {canFileMenuView && (
3209
- <button
3210
- type="button"
3211
- role="menuitem"
3212
- onClick={() => {
3213
- setMoveFor({ viewId: menuView.id, anchor: menu.anchor });
3214
- setMenu(null);
3215
- }}
3216
- >
3217
- <MenuLabel icon={<FolderMark size={16} />} text="Move to" />
3218
- </button>
3219
- )}
3220
  {/* WAVE 20 items 23/26 (R10) — "who else can reach this view", the same
3221
  editor a folder and a database open. Deliberately NOT gated on
3222
  `canEditMenuView`: the server decides who may administer (owner or
 
44
  */
45
  import { WORKSPACE_STALE_EVENT, signal } from "../apiContract";
46
  import { ROOT_FOLDER_ID } from "./folders";
 
47
  // ⭐ W32-T23 (owner item 17) — THE BELL, from the shared layer rather than redrawn here.
48
  // The alert row wore `cohortAdd` (a LIST with a plus), which names "add to a cohort" on the
49
  // one row that creates an ALERT — a borrowed mark is a small lie a menu repeats every time
 
55
  // ⚠ `SHARED_FOLDER_ID` is no longer imported: W34-T25 replaced both of its call sites with
56
  // `isSyntheticFolderId`, and `noUnusedLocals` turns a leftover import into a build error rather
57
  // than into dead weight. The constant itself is still exported and still used by `folders.ts`.
 
 
 
58
  import {
59
+ folderHiddenByCollapse,
60
  folderNesting,
 
 
 
 
61
  groupByFolder,
62
  isSyntheticFolderId,
 
63
  mayFileView,
64
  mayNestFolder,
65
  reorderFolderIds,
 
406
  * throws). The behaviour is not silently degraded — the row is ABSENT, which a reader can see.
407
  */
408
  onToggleImportant?: (viewId: string, important: boolean) => void;
409
+ /** Toolbar gear anchor. It opens this rail's actual ellipsis menu, never a copy of its actions. */
410
+ actionAnchor?: HTMLElement | null;
411
+ onActionAnchorConsumed?: () => void;
412
  /* wave17 R1 / C-LOCKV — `cohorts` and `onSelectCohort` are GONE from this component's
413
  surface. They carried the transient-lock selection for the retired Cohorts section; a
414
  locked view is now an ordinary member of `views` and is selected by `onSelect` like any
 
470
  * *"a folder shared to another user reverts to the default folder icon"*, and the cause is that
471
  * the wire has never carried one: `core/grid_events.py::_granted_views` stamps
472
  * `v['sharedFolder'] = <the folder's NAME>`, a string, so the receiver's rail synthesises a group
473
+ * from a name and an owner and there is nothing for an icon to travel in. C9 replaces that string
474
+ * with the whole folder RECORD — and **that half is W41-T14's, in another lane's file.**
 
 
 
475
  *
476
+ * ⚠ SO BOTH SHAPES ARE READ, and the older one is not a fallback but TODAY. A string yields a
477
+ * name with no icon, which renders the DEFAULT mark exactly as it does now: an absent key means
478
+ * "not built yet", never "guess". Nothing paints a mark the sharer did not choose while T14 is
479
+ * outstanding, and the day it lands this reader needs no second change.
 
480
  *
481
  * ⚠ THE ICON GOES THROUGH `cleanFolderIcon`, the same whitelist the create pane and the host
482
  * validator use. An unknown shape drops the icon rather than substituting a picture nobody
 
496
  via && typeof via === "object" && !Array.isArray(via)
497
  ? (via as Record<string, unknown>)
498
  : null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
499
  const rawName = typeof via === "string" ? via : record?.name;
500
  const name = typeof rawName === "string" ? rawName.trim() : "";
501
  const owner = typeof view.owner === "string" ? view.owner.trim() : "";
502
  if (!name || !owner) return null;
503
+ const icon = record ? cleanFolderIcon(record.icon) : undefined;
 
 
504
  return icon ? { name, owner, icon } : { name, owner };
505
  }
506
 
 
547
  );
548
  }
549
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550
  export default function ViewSidebar({
551
  agentPanel = null,
552
  agentOpen = false,
 
587
  viewer,
588
  onToggleLock,
589
  onToggleImportant,
590
+ actionAnchor,
591
+ onActionAnchorConsumed,
592
  }: ViewSidebarProps) {
593
  /**
594
  * I14 — creating a view now always knows WHICH KIND of view is being created, because the
 
600
  const [name, setName] = useState("");
601
  const [menu, setMenu] = useState<{
602
  viewId: string;
603
+ anchor: HTMLElement;
604
  } | null>(null);
605
  const [renamingId, setRenamingId] = useState<string | null>(null);
606
  const [noteFor, setNoteFor] = useState<{
607
  viewId: string;
608
+ anchor: HTMLElement;
609
  } | null>(null);
610
  const [noteDraft, setNoteDraft] = useState("");
611
  const [addFor, setAddFor] = useState<{
612
  viewId: string;
613
+ anchor: HTMLElement;
614
  } | null>(null);
615
  /** Item 12 (C-LOCK) — which view's cohort lock the picker is open for. */
616
  const [lockFor, setLockFor] = useState<{
617
  viewId: string;
618
+ anchor: HTMLElement;
619
  } | null>(null);
620
  const [newListName, setNewListName] = useState("");
621
  /** W2 — the Export format pane, anchored where the "…" menu was. */
622
  const [exportFor, setExportFor] = useState<{
623
  viewId: string;
624
+ anchor: HTMLElement;
625
  } | null>(null);
626
  const exportView = exportFor
627
  ? views.find((view) => view.id === exportFor.viewId)
628
  : undefined;
 
 
 
 
 
 
 
 
 
 
 
 
 
629
  const addView = addFor ? views.find((view) => view.id === addFor.viewId) : undefined;
630
  const menuView = menu ? views.find((view) => view.id === menu.viewId) : undefined;
631
+ useEffect(() => {
632
+ if (!actionAnchor) return;
633
+ const active = views.find((view) => view.id === activeViewId);
634
+ if (active) setMenu({ viewId: active.id, anchor: actionAnchor });
635
+ onActionAnchorConsumed?.();
636
+ }, [actionAnchor, activeViewId, onActionAnchorConsumed, views]);
637
  /** C4 — may this viewer change the menu view's IDENTITY? Courtesy only; the host is the
638
  * wall. C3's lock toggle ANDs with this rather than replacing it: the two contracts
639
  * compose (C4 says who may edit, C3 says who may freeze the mode). */
640
  const canEditMenuView = !!menuView && mayEditView(menuView, viewer);
641
+ // I11c local UI state. Collapse is deliberately LOCAL (C4: "minimize state
642
+ // local") — which folders you have open is a per-person, per-session habit,
643
+ // not a property of the shared workspace.
644
  /**
645
+ * ⭐⭐ WAVE 41 · T34 (instruction 13) — THE STATE IS "WHICH FOLDERS THE USER OPENED", AND THE
646
+ * COLLAPSED SET IS DERIVED FROM IT.
647
  *
648
+ * Owner: *"When a user logs in, a folder defaults to CLOSED, not open."* This used to hold the
649
+ * collapsed ids, so an empty set — the state every mount starts in — meant every folder OPEN,
650
+ * the exact opposite of the instruction. Inverting the question is what makes the default fall
651
+ * out of the initial state instead of having to be installed into it.
652
  *
653
+ * ⛔ WHY NOT SEED THE COLLAPSED SET INSTEAD. `useState(() => new Set(folderIds))` captures the
654
+ * folders present at FIRST RENDER only, and this rail mounts before its workspace lands, so on
655
+ * the real load order it would seed from an EMPTY list and every folder would still open. Every
656
+ * folder arriving later — the workspace payload, a newly granted share, a folder T33's nesting
657
+ * reveals — would be open too. The `useEffect`-collapses-new-arrivals variant fixes the
658
+ * membership but paints one frame with everything open first, so "on first load every folder is
659
+ * collapsed" would be false for exactly as long as a user can see it.
660
  *
661
+ * ⛔ NOTHING BUT THE USER'S OWN TOGGLE EVER REMOVES AN ID FROM HERE, which is the whole of
662
+ * "expanding one and returning later keeps it expanded". A folder that leaves the list and
663
+ * comes back (a live search, a refreshed payload) keeps its id in this set and returns open.
664
+ * The set therefore also retains ids of deleted folders; at `MAX_FOLDERS` = 60 and a lifetime
665
+ * bounded by the component's, that is a rounding error, and pruning it is what would
666
+ * re-introduce the "opened folder silently re-closes" bug.
667
  *
668
+ * ⚠ SESSION HERE MEANS THE COMPONENT'S LIFETIME, deliberately. There is no localStorage and no
669
+ * server preference, and adding one would defeat instruction 13's own first clause: a
670
+ * preference that survives a reload is a folder that is open when the user next logs in.
 
 
 
 
 
 
 
 
 
 
 
671
  */
672
+ const [opened, setOpened] = useState<Set<string>>(new Set());
673
  const [folderMenu, setFolderMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null);
674
  /**
675
  * ⭐ W41-T35 (instruction 11) — WHICH FOLDER'S MARK IS BEING CHANGED, and off which button.
 
860
  () => folderNesting(foldersOn ? (folders as GridFolder[]) : []),
861
  [foldersOn, folders]
862
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
863
  /**
864
  * ⭐⭐ WAVE 41 · T37 (owner instruction 14) — THE GROUPING RUNS ONCE PER INPUT CHANGE, NOT
865
  * ONCE PER RENDER.
 
950
  * `groupByFolder` keys with — over the record `sharedFolderRecord` returns to BOTH. One
951
  * extractor, one key function, so no second spelling of "which folder is this" exists.
952
  *
953
+ * ⚠ EMPTY UNTIL W41-T14 LANDS. The wire carries a folder NAME today, so no entry is ever
954
+ * written and every shared folder head falls through to `FolderMark`'s default — which is what
955
+ * the rail already draws. The gap is a missing icon, never a wrong one.
 
 
 
 
956
  */
957
  const sharedFolderIcons = useMemo(() => {
958
  const marks = new Map<string, FolderIcon>();
 
963
  return marks;
964
  }, [shownViews]);
965
  /**
966
+ * ⭐⭐ WAVE 41 · T34 (instruction 13) — WHICH FOLDERS ARE SHUT RIGHT NOW.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
967
  *
968
+ * Read as "every folder head on screen that the user has not opened", so a folder nobody has
969
+ * touched is closed WHENEVER it appears — at mount, and equally when it arrives afterwards.
970
+ * That is the same sentence as `opened` above, from the rendering side, and it is why no
971
+ * effect, no ref of already-seen ids and no second render are needed to hold the default.
972
  *
973
+ * ⛔ DERIVED FROM `groups`, NOT FROM `folders`, AND THE CHEVRON IS WHY. `groupByFolder` emits
974
+ * one group per stored folder (empty ones included) AND the synthesised groups — "Shared with
975
+ * me", plus one per shared folder — which own a folder head and a working disclosure chevron
976
+ * while having no record in `folders` at all. Derived from the stored list, those ids could
977
+ * never enter this set: their chevron would write to `opened` and nothing would ever read it
978
+ * back, so the toggle would be DEAD and the group permanently open. Reading the groups also
979
+ * settles instruction 13 for them the same way it settles it for a stored folder, which is
980
+ * what the user sees: a folder head is a folder head. Collapse is presentation with no write
981
+ * behind it, so `isSyntheticFolderId` — the guard that keeps `item_move` / `folder_rename` off
982
+ * these ids — has nothing to say here.
 
 
 
 
 
 
983
  *
984
+ * ⛔⛔ A LIVE SEARCH YIELDS, and without this clause T34 would silently kill W41-T33. Search
985
+ * hides folders that matched nothing (below) and T33 taught it to KEEP a parent whose child
986
+ * matched. With every folder shut by default, `folderHiddenByCollapse` drops those descendants
987
+ * before they can render and the survivors show as bare heads with no rows: the user types a
988
+ * view's name and the rail answers with chevrons and nothing else, on the very first search of
989
+ * every session. So while a needle is live nothing is collapsed. It is presentation only and
990
+ * it never touches `opened`, so clearing the search returns each folder to exactly the state
991
+ * the user left it in.
992
  */
993
+ const collapsed = useMemo(() => {
994
+ const shut = new Set<string>();
995
+ if (!viewNeedle) {
996
+ for (const group of groups) {
997
+ const id = group.folder?.id;
998
+ if (id && !opened.has(id)) shut.add(id);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
999
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
1000
  }
1001
+ return shut;
1002
+ }, [groups, opened, viewNeedle]);
1003
  const folderMenuF = folderMenu ? folders?.find((f) => f.id === folderMenu.id) : undefined;
1004
  /**
1005
  * ⭐⭐ W41-T35 — THE FOLDER WHOSE MARK IS BEING CHANGED, AND THE SECOND REFUSAL OF A SYNTHETIC
 
1026
  * the SAME `nesting` the rail renders from, so the verdict and the picture cannot disagree.
1027
  */
1028
  const nestHere = folderMenuF ? mayNestFolder(nesting, folderMenuF.id) : null;
1029
+ /**
1030
+ * ⭐ WAVE 41 · T33 — THE ANCESTORS OF EVERY FOLDER A SEARCH MATCHED INSIDE.
1031
+ *
1032
+ * Item 9's rule ("a folder with no matches is noise") was written when a folder could only
1033
+ * hold views. A parent now holds folders too, so its own `items` being empty says nothing
1034
+ * about whether anything under it matched — and hiding it would orphan the child that did.
1035
+ *
1036
+ * ⚠ BUILT ONLY WHILE A SEARCH IS LIVE. With no needle the set is never walked and the rule it
1037
+ * serves never fires, so the idle rail pays nothing for it.
1038
+ */
1039
+ const searchKeepsFolder = useMemo(() => {
1040
+ const keep = new Set<string>();
1041
+ if (viewNeedle) {
1042
+ for (const g of groups) {
1043
+ if (!g.folder || g.items.length === 0) continue;
1044
+ let up = nesting.parent[g.folder.id] ?? null;
1045
+ while (up && !keep.has(up)) {
1046
+ keep.add(up);
1047
+ up = nesting.parent[up] ?? null;
1048
+ }
1049
+ }
1050
+ }
1051
+ return keep;
1052
+ }, [groups, nesting, viewNeedle]);
1053
  const addPreview = addTarget && folderAddPreview ? folderAddPreview(addTarget) : null;
1054
  /**
1055
  * ONE pair of drop handlers per group, serving TWO drags — a view being filed into this
 
1185
  // folder can always go.
1186
  const into = mayNestFolder(nesting, folderParent).ok ? folderParent : null;
1187
  /**
1188
+ * ⭐⭐ WAVE 41 · T34 — FILING A FOLDER INTO ONE OPENS IT, or the new folder is created
1189
+ * INVISIBLY.
1190
+ *
1191
+ * ⛔ THIS IS T34's OWN REGRESSION ON T33, and it only exists once folders default to shut.
1192
+ * A collapsed folder KEEPS ITS HEAD (`folderHiddenByCollapse` reads ancestors only), so its
1193
+ * "…" menu — and T33's "New folder inside" row on it — stays reachable while it is closed.
1194
+ * Create a folder in there and `folderHiddenByCollapse` finds the shut parent above the new
1195
+ * child and renders it as null: the user names a folder, presses Create, and the rail does
1196
+ * not move. Before T34 the parent was open by default and the path could not be walked.
1197
  *
1198
+ * ⚠ THE PARENT ALONE IS ENOUGH, no ancestor walk. The head that carries this menu renders
1199
+ * only when NO ancestor of it is collapsed, so reaching this line already proves every
1200
+ * folder above `into` is open.
 
 
 
1201
  *
1202
+ * �� IT CAN ONLY ADD. Nothing here removes an id, so this cannot close a folder the user
1203
+ * opened, and the same-set short-circuit keeps a repeat create from re-rendering the rail.
 
1204
  */
1205
+ if (into) setOpened((prev) => (prev.has(into) ? prev : new Set(prev).add(into)));
1206
  // cleanFolderIcon returns undefined for the all-defaults pair, so a folder the user
1207
  // never restyled stays byte-identical to a pre-wave-9 one (the no-churn rule).
1208
  onFolderCreate?.(value, cleanFolderIcon(folderIcon), into);
 
1656
  </AnchoredOverlay>
1657
  )}
1658
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1659
  <div className="cg-view-list cg-views-scroll">
1660
+ {groups.map((group) => {
1661
  const gid = group.folder?.id ?? null;
1662
+ // Item 9 — while a search is live, a folder with no matches is noise, not a target.
1663
+ // ⭐ W41-T33 — …UNLESS A FOLDER INSIDE IT MATCHED. Once folders nest, "no matching views
1664
+ // of its own" and "nothing under here at all" stop being the same fact: dropping a
1665
+ // parent on the first would leave its matching child indented under whatever row
1666
+ // happened to precede it, attached to the wrong folder on screen.
1667
+ if (viewNeedle && group.folder && group.items.length === 0
1668
+ && !searchKeepsFolder.has(group.folder.id)) return null;
1669
  /**
1670
+ * ⭐⭐ WAVE 41 · T33 (instruction 12, R1) — HOW DEEP THIS FOLDER SITS, AND WHETHER IT
1671
+ * SHOWS AT ALL.
1672
  *
1673
+ * ⚠ A SYNTHETIC GROUP HAS NO ENTRY IN `nesting` and must not acquire one: `__shared__`
1674
+ * and every `__sharedfld__:` group are a reading of the view list, not records, so they
1675
+ * fall to level 1 and to "not hidden" — which is exactly where they rendered before this
1676
+ * ticket. The same is true of both `folder: null` groups.
 
 
 
1677
  */
1678
+ const depth = gid ? nesting.depth[gid] ?? 1 : 1;
1679
+ // ⛔ A FOLDER INSIDE A COLLAPSED FOLDER DOES NOT RENDER. `shut` below hides a folder's
1680
+ // VIEWS; without this its child FOLDERS would keep their rows and stay indented under a
1681
+ // parent that is no longer showing anything, which reads as the collapse having half
1682
+ // worked. Ancestors only, so the collapsed folder itself keeps the head you re-open it by.
1683
+ if (gid && folderHiddenByCollapse(nesting, gid, collapsed)) return null;
1684
  /**
1685
  * ⭐⭐ WAVE 40 · T28 (owner instruction 30) — THE PIN GROUP: the unfiled default views,
1686
  * rendered above every folder.
 
1716
  // "Shared with me" while offering them on a colleague's folder would emit `item_move` /
1717
  // `folder_rename` / `folder_delete` against an id that exists in nobody's store.
1718
  const isSynthetic = isSyntheticFolderId(gid);
1719
+ const shut = gid != null && collapsed.has(gid);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1720
  return (
1721
  <div
1722
  /* ⭐ W40-T28 — a key of its own. Both this group and the ungrouped section have a null
1723
  folder, so the old `gid ?? "__root__"` would give React two children with the same
1724
  key and it would reconcile one over the other. */
1725
  key={isPinnedGroup ? "__pinned__" : gid ?? "__root__"}
1726
+ /**
1727
+ * ⭐⭐ WAVE 41 · T33 (instruction 12) — A NESTED FOLDER IS THIS ROW, INDENTED.
1728
+ *
1729
+ * DESIGN.md §4: new nav joins the existing rhythm and never introduces a control
1730
+ * shape. 12px is not a new number either — it is the step `.cg-fold .cg-view-row`
1731
+ * already uses to set a view in from its folder head, so a folder inside a folder
1732
+ * lands exactly where a view inside a folder lands, one level on.
1733
+ *
1734
+ * ⚠ INLINE BECAUSE THE DEPTH IS DATA, not because the rail is short of a class. A
1735
+ * stylesheet would need one rule per level to a cap the model owns, and the two
1736
+ * numbers would then have to be kept equal by hand.
1737
+ */
1738
+ style={depth > 1 ? { marginLeft: (depth - 1) * 12 } : undefined}
1739
  className={
1740
  /* ⭐ W40-T28 — `gid === null`, not `isRoot`: the pin group wears the SAME class as
1741
  the ungrouped section (no head, the rail's measured root indent) because it is the
1742
  same shape of thing rendered in a different place. DESIGN.md §4 — this is an
1743
+ existing element joining the existing rhythm, not a new control shape. */
1744
+ (gid === null ? "cg-fold-root" : "cg-fold") +
 
 
 
 
1745
  (!isPinnedGroup && dropTarget === (gid ?? "__root__") ? " is-drop" : "") +
1746
  // Item 19 — the insertion rule reads "the folder you are dragging lands HERE":
1747
  // above this folder, or above the ungrouped section, which is after them all.
 
1777
  // at `null` beside a `gid` that is `null` for this very section — that is the
1778
  // `foldDrag === gid` trap two lines up, which faded the whole ungrouped section
1779
  // permanently once already. `isRoot` is a separate boolean, so the two cannot collide.
1780
+ (isRoot && viewDrag !== null ? " is-viewdrop" : "")
 
 
 
 
1781
  }
1782
  {/* No drop handlers on the synthetic group — see `isSynthetic`. Spreading `{}`
1783
  rather than branching the element keeps ONE render path for every group.
 
1788
  somewhere else on screen. The ungrouped section below is the one root target. */
1789
  ...(isSynthetic || isPinnedGroup ? {} : dropHandlers(gid))}
1790
  >
1791
+ {group.folder && (
 
 
 
 
1792
  <div
1793
  className="cg-fold-head"
1794
  // ── Item 19 — the folder itself is the drag handle ─────────────────────
 
1810
  flow shifts the folder's name to the right, and this rail's indent is
1811
  MEASURED to the pixel (index.css: "root view name 41.00px / folder header
1812
  48.36px" — the whole point of the wave-10 item-2 fix); the gutter it would
1813
+ otherwise hide in is already occupied by the disclosure chevron, whose
1814
+ open/shut state is the only one this row has. The view rows above have been
1815
  draggable with no handle since wave 8, so a folder that drags the same way
1816
  is the vocabulary this list already teaches, not a hidden feature. */}
1817
  <button
1818
  type="button"
1819
  className="cg-fold-toggle"
1820
+ aria-expanded={!shut}
1821
  /**
1822
+ * ⚠ W41-T34 — THE CLICK IS READ OFF `shut`, THE STATE THE CHEVRON IS DRAWING,
1823
+ * not off membership of `opened`.
1824
  *
1825
+ * With no search live the two are the same sentence and this behaves exactly as
1826
+ * the old symmetric toggle did. They come apart during a SEARCH, which shows
1827
+ * every folder open whatever `opened` holds: keyed on membership, clicking the
1828
+ * chevron of a folder the user had never opened would ADD it — the row would not
1829
+ * move, because the search is still forcing it open, and the folder would then be
1830
+ * open once the search cleared. The user pressed "close" and got "open", one
1831
+ * gesture later. Reading the drawn state makes the click mean what it looks like.
 
 
 
 
1832
  */
1833
+ onClick={() =>
1834
+ setOpened((prev) => {
1835
+ const next = new Set(prev);
1836
+ if (shut) next.add(group.folder!.id);
1837
+ else next.delete(group.folder!.id);
1838
+ return next;
1839
+ })
1840
+ }
1841
  >
1842
+ <span className={"cg-fold-chev" + (shut ? " is-shut" : "")} aria-hidden>
1843
+ ▾
1844
+ </span>
1845
  {/* I14/I15 — the folder wears its chosen mark; a folder that never chose one
1846
  (every pre-wave-9 folder) renders the default grey folder shape, which is
1847
  precisely "existing folders get the folder icon". */}
 
1856
  ⛔ AND THE FALLBACK IS `undefined`, WHICH IS THE ANSWER RATHER THAN A GAP:
1857
  `FolderMark` draws the default folder in the default tone for an absent icon,
1858
  which is exactly what "the payload does not carry one yet" should look like.
1859
+ Until W41-T14 puts the folder RECORD on the wire this map is empty and this
1860
+ line renders precisely what it rendered before. */}
 
1861
  <FolderMark
1862
  icon={group.folder.icon ?? (gid ? sharedFolderIcons.get(gid) : undefined)}
1863
  size={16}
 
1943
  )}
1944
  </div>
1945
  )}
1946
+ {/* A collapsed folder hides its rows but stays a DROP TARGET, so you can
1947
+ file something into a folder you have tidied away. */}
1948
+ {!shut &&
 
 
1949
  group.items.map((view) => {
1950
  const active = view.id === activeViewId;
1951
  const renaming = renamingId === view.id;
 
2250
  </div>
2251
  );
2252
  })}
2253
+ {group.folder && !shut && group.items.length === 0 && (
 
 
 
 
 
 
2254
  <div className="cg-fold-empty">Empty. Drag a view here.</div>
2255
  )}
2256
  </div>
 
2437
  </AnchoredOverlay>
2438
  )}
2439
 
2440
+ {/* ⭐⭐ WAVE 41 · T35 (owner instruction 11) — THE CHANGE-ICON PANEL.
2441
+ It is the folder menu's own panel shape (`cg-view-menu`, `bottom-end`, the same anchor
2442
+ the "…" gave the menu), holding the SAME picker the create pane holds. No new class and
2443
+ no new CSS: DESIGN.md §4 asks new nav to join the existing rhythm, and `.cg-fold-pick`
2444
+ is already a top-level rule rather than one scoped to the create form.
 
 
 
 
 
 
2445
  ⚠ IT WRITES ON EVERY CLICK rather than behind a Save. Shape and tone are two independent
2446
  picks and the folder head repaints under the panel as they land, so the panel IS the
2447
  preview — a confirm step would put a button between the user and a change they can see
2448
  and undo by clicking again (§4, never over-explain). Dismissing is therefore not a
2449
+ cancel, and nothing here pretends it is. */}
 
 
 
 
 
 
 
2450
  {iconMenu && iconMenuF && onFolderIconChange && (
2451
  <AnchoredOverlay
2452
  anchor={iconMenu.anchor}
2453
+ className="cg-view-menu"
2454
  placement="bottom-end"
2455
  role="dialog"
2456
  ariaLabel={`Icon for folder ${iconMenuF.name}`}
2457
  onDismiss={() => setIconMenu(null)}
2458
  dataKind="folder-icon"
2459
  >
 
 
 
 
2460
  {/* ⚠ RESOLVED AGAINST THE DEFAULTS RATHER THAN PASSED AS `undefined`: the picker draws
2461
  a selection ring on the swatch that is currently chosen, and a folder that never
2462
  chose an icon IS wearing the default shape in the default tone (`FolderMark` reads
 
2472
  </AnchoredOverlay>
2473
  )}
2474
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2475
  {/* Item 12 (C-LOCK) — the lock picker. Lists the cohorts this reader can see, marks the
2476
  current one, and offers Unlock when there is one: a lock removable only from
2477
  somewhere other than where it was applied is a trap, and the owner asked for a
 
2730
  >
2731
  <MenuLabel icon="duplicate" text="Duplicate" />
2732
  </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2733
  {/* WAVE 20 items 23/26 (R10) — "who else can reach this view", the same
2734
  editor a folder and a database open. Deliberately NOT gated on
2735
  `canEditMenuView`: the server decides who may administer (owner or
web/src/customer-grid/apiBridge.ts CHANGED
@@ -149,29 +149,6 @@ export function clearWorkspaceCache(): void {
149
  wsCache.clear();
150
  }
151
 
152
- /**
153
- * ⭐⭐ W42 AMENDMENT A13 — LOOK AT WHAT IS ALREADY CACHED FOR A SCOPE, AND DO NOTHING ELSE.
154
- *
155
- * ⛔ A PEEK, NOT A READ-THROUGH. It never fetches, never writes, never evicts and never touches
156
- * the entry's clock. `grep -rE "export (function|const) (peek|get)?[Ww]orkspace"` over `web/src`
157
- * returned nothing before this line, which is why the shell could not see a database's views at
158
- * all: the rail had no way to ask, so it announced that it was reading them forever. The
159
- * alternative was a second fetch from the shell, which contract C5 forbids and which would also
160
- * have pinned the "do we already know this database?" flag permanently true.
161
- *
162
- * ⛔ THE `ws`, NOT THE `{at, ws}` ENTRY. The wrapper is this module's own bookkeeping; handing it
163
- * out would make every caller a second reader of a shape only `fetchWorkspace` may reason about.
164
- *
165
- * ⚠ `at` IS DELIBERATELY NOT CONSULTED, and this is a choice rather than an omission. There is no
166
- * refresh path behind a peek, so answering `undefined` for a present-but-elderly envelope would
167
- * trade a slightly stale list of views — which is correct and useful — for a blank rail that
168
- * never fills. Freshness belongs to `fetchWorkspace`, which owns the clock and the re-read; a
169
- * caller that needs guaranteed-current data must go through it.
170
- */
171
- export function peekWorkspace(scope: string): GridWorkspace | undefined {
172
- return wsCache.get(scope)?.ws;
173
- }
174
-
175
  export function clearCustomersCache(): void {
176
  rowsCache.clear();
177
  // ⛔ THE ENVELOPE IS SESSION-SCOPED FOR THE SAME REASON THE ROWS ARE, and it carries MORE that
@@ -329,8 +306,6 @@ export interface RowWindowRequest {
329
  filterConj?: string;
330
  sorts?: SortSpec | null;
331
  search?: string;
332
- /** Existing Link choices retained when a new picker condition no longer matches them. */
333
- includePids?: readonly number[];
334
  }
335
 
336
  /**
@@ -362,11 +337,6 @@ export function windowRowsPath(tableKey: string, req: RowWindowRequest): string
362
  if (req.sorts && req.sorts.length) q.set("sorts", JSON.stringify(req.sorts));
363
  const search = (req.search ?? "").trim();
364
  if (search) q.set("search", search);
365
- if (req.includePids && req.includePids.length) {
366
- const ids = [...new Set(req.includePids.filter((pid) => Number.isInteger(pid) && pid > 0))]
367
- .sort((a, b) => a - b);
368
- if (ids.length) q.set("includePids", JSON.stringify(ids));
369
- }
370
  return `odoo-tables/${encodeURIComponent(tableKey)}/rows?${q.toString()}`;
371
  }
372
 
@@ -1128,144 +1098,6 @@ export async function deleteTableField(
1128
  }
1129
  }
1130
 
1131
- /**
1132
- * ⭐⭐ W42-T58 (contract C4) — DELETE SEVERAL DEFINITION COLUMNS IN ONE REQUEST, AND REPORT WHICH
1133
- * ONES ACTUALLY WENT, KEY BY KEY.
1134
- *
1135
- * ⚠ ONE LINE OF HISTORY, BECAUSE THE SHAPE THIS REPLACES WAS NOT A MISTAKE: W42-T11 walked the
1136
- * per key door N times and documented why at this very spot, and it was CORRECT against the
1137
- * server that existed then, which had no plural door at all. W42-T28 shipped one. What changed is
1138
- * the server, not the reasoning.
1139
- *
1140
- * ⛔ ONE REQUEST FOR EVERY N, INCLUDING N = 1. A singular special case would leave two ways for a
1141
- * delete to be answered and only one of them carrying the per key verdict, so the commonest act
1142
- * on this surface would be the least explained one.
1143
- *
1144
- * ⛔ THE VERDICT IS RETURNED, NOT SHOUTED FROM IN HERE. A refusal used to reach the person as a
1145
- * toast raised inside the singular request, one per key, which is why several refusals raced into
1146
- * one toast slot with nothing naming which column each sentence belonged to. The plural answer
1147
- * carries a status, a machine code and a sentence PER KEY, and the caller owns what is read.
1148
- *
1149
- * ⚠ A REFUSED KEY IS RETURNED, NOT SWALLOWED. Reconciling a refused key out of the view would
1150
- * take the column off the screen while it still exists on the server — the field would be gone
1151
- * until the next workspace fetch put it back, which reads as a flicker rather than a refusal.
1152
- *
1153
- * ⚠ AND AN OLDER SERVER IS ALLOWED FOR, NOT TRUSTED. An accepted answer that names no key at all
1154
- * is read as neither a silent success nor a blanket refusal: it is reported as an answer this
1155
- * client could not read, with the unreadable flag raised, so the caller fetches the truth instead
1156
- * of painting a guess over the view.
1157
- */
1158
- export interface FieldDeleteResult {
1159
- key: string;
1160
- status: "deleted" | "refused";
1161
- code?: string;
1162
- reason?: string;
1163
- contract?: string;
1164
- removed?: number;
1165
- }
1166
-
1167
- export interface FieldDeleteOutcome {
1168
- deleted: string[];
1169
- refused: string[];
1170
- results: FieldDeleteResult[];
1171
- /** The server was reached, accepted the act, and named no key either way. */
1172
- unreadable: boolean;
1173
- }
1174
-
1175
- /**
1176
- * ⚠ USER-FACING, AND IT PROMISES WHAT THE CALLER ACTUALLY DOES: the unreadable branch below is
1177
- * paired with a refetch on the caller's side, so this sentence is not asking the person to do the
1178
- * app's job for it.
1179
- */
1180
- const DELETE_ANSWER_NAMED_NO_COLUMN =
1181
- "The server accepted that delete without saying which columns went, so the table is being read " +
1182
- "again rather than guessed at.";
1183
-
1184
- function refusedWholesale(
1185
- fieldKeys: readonly string[],
1186
- reason: string | undefined,
1187
- code: string,
1188
- unreadable = false
1189
- ): FieldDeleteOutcome {
1190
- return {
1191
- deleted: [],
1192
- refused: [...fieldKeys],
1193
- results: fieldKeys.map((key) => ({ key, status: "refused" as const, code, reason })),
1194
- unreadable,
1195
- };
1196
- }
1197
-
1198
- export async function deleteTableFields(
1199
- tableKey: string,
1200
- fieldKeys: readonly string[]
1201
- ): Promise<FieldDeleteOutcome> {
1202
- if (fieldKeys.length === 0) {
1203
- return { deleted: [], refused: [], results: [], unreadable: false };
1204
- }
1205
- let res: Response;
1206
- try {
1207
- res = await fetch(
1208
- `${API_V1}/tables/${encodeURIComponent(tableKey)}/fields/delete`,
1209
- {
1210
- method: "POST",
1211
- credentials: CREDENTIALS,
1212
- headers: JSON_HEADERS,
1213
- body: JSON.stringify({ keys: [...fieldKeys] }),
1214
- }
1215
- );
1216
- } catch {
1217
- return refusedWholesale(fieldKeys, "That delete did not reach the server.", "unreachable");
1218
- }
1219
- // ⚠ NO SENTENCE ON THIS PATH. `handledSession` has already taken the person somewhere else, so
1220
- // a reason here would be copy nobody is left to read.
1221
- if (handledSession(res)) return refusedWholesale(fieldKeys, undefined, "session_ended");
1222
- const body = (await readJson(res)) as {
1223
- results?: unknown;
1224
- deleted?: unknown;
1225
- refused?: unknown;
1226
- error?: { message?: string; code?: string };
1227
- } | null;
1228
- if (!res.ok) {
1229
- const code = typeof body?.error?.code === "string" ? body.error.code : "refused";
1230
- return refusedWholesale(fieldKeys, refusalMessage(body, res.status), code);
1231
- }
1232
- const rawResults = body?.results;
1233
- const results: FieldDeleteResult[] = [];
1234
- if (Array.isArray(rawResults)) {
1235
- for (const entry of rawResults as unknown[]) {
1236
- const raw = entry as Record<string, unknown> | null;
1237
- if (!raw || typeof raw.key !== "string") continue;
1238
- results.push({
1239
- key: raw.key,
1240
- status: raw.status === "deleted" ? "deleted" : "refused",
1241
- code: typeof raw.code === "string" ? raw.code : undefined,
1242
- reason: typeof raw.reason === "string" ? raw.reason : undefined,
1243
- contract: typeof raw.contract === "string" ? raw.contract : undefined,
1244
- removed: typeof raw.removed === "number" ? raw.removed : undefined,
1245
- });
1246
- }
1247
- } else {
1248
- // A server that answers the plural door with only the two key lists is still answering it.
1249
- // Every key is accounted for; what is missing is the explanation, not the verdict.
1250
- const named = (value: unknown): string[] =>
1251
- Array.isArray(value) ? value.filter((k): k is string => typeof k === "string") : [];
1252
- for (const key of named(body?.deleted)) results.push({ key, status: "deleted" });
1253
- for (const key of named(body?.refused)) results.push({ key, status: "refused" });
1254
- }
1255
- if (results.length === 0) {
1256
- // Nothing here can say whether the schema moved, so nothing cached about it is trustworthy.
1257
- dropTableRowsCache(tableKey);
1258
- return refusedWholesale(fieldKeys, DELETE_ANSWER_NAMED_NO_COLUMN, "unreadable_answer", true);
1259
- }
1260
- const deleted = results.filter((r) => r.status === "deleted").map((r) => r.key);
1261
- const refused = results.filter((r) => r.status === "refused").map((r) => r.key);
1262
- // The schema moved for every key that went, and a deleted LINK takes its reciprocal and every
1263
- // rollup that folded it with it, so the cached rows are values behind and not merely a column
1264
- // behind. ONE act, ONE drop, and none at all when the server kept every column.
1265
- if (deleted.length > 0) dropTableRowsCache(tableKey);
1266
- return { deleted, refused, results, unreadable: false };
1267
- }
1268
-
1269
  /**
1270
  * ⭐⭐ 2026-08-09 — THE DEFINITION SHAPE, NOT A THREE-KEY SUMMARY.
1271
  *
 
149
  wsCache.clear();
150
  }
151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  export function clearCustomersCache(): void {
153
  rowsCache.clear();
154
  // ⛔ THE ENVELOPE IS SESSION-SCOPED FOR THE SAME REASON THE ROWS ARE, and it carries MORE that
 
306
  filterConj?: string;
307
  sorts?: SortSpec | null;
308
  search?: string;
 
 
309
  }
310
 
311
  /**
 
337
  if (req.sorts && req.sorts.length) q.set("sorts", JSON.stringify(req.sorts));
338
  const search = (req.search ?? "").trim();
339
  if (search) q.set("search", search);
 
 
 
 
 
340
  return `odoo-tables/${encodeURIComponent(tableKey)}/rows?${q.toString()}`;
341
  }
342
 
 
1098
  }
1099
  }
1100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1101
  /**
1102
  * ⭐⭐ 2026-08-09 — THE DEFINITION SHAPE, NOT A THREE-KEY SUMMARY.
1103
  *
web/src/customer-grid/folders.ts CHANGED
@@ -801,166 +801,3 @@ export function newFolderId(): string {
801
  : Math.random().toString(36).slice(2, 10);
802
  return `fld_${rand}`;
803
  }
804
-
805
- // ---------------------------------------------------------------------------
806
- // ⭐⭐ WAVE 42 · T41 (ruling R12, contract C9) — ONE PATH MODEL, OVER BOTH FOLDER SYSTEMS.
807
- //
808
- // ⛔ THERE WERE TWO FOLDER SYSTEMS AND THEY SHARED NOTHING. `shell/nav.ts::foldNav` groups
809
- // DATABASES under the per-user nav folders; everything above this line groups VIEWS. Same word on
810
- // screen, two spellings of "what is inside this folder", and R12.3 says a DATABASE folder must
811
- // drill exactly like a VIEW folder. So one resolver answers the two questions a path needs —
812
- // *what is at this path* and *what is the parent of this path* — for both.
813
- //
814
- // ⛔ IT ADDS, IT DOES NOT REWRITE. {@link groupByFolder} keeps its FLAT `FolderGroup<T>[]` shape
815
- // and {@link folderNesting} stays a separate pass, because every drag handler in the rail keys off
816
- // folder IDs and `parent` and none of them keys off a path string. A builder who flattened the
817
- // tree into a linear path and dropped the nesting pass would collapse every nested folder to one
818
- // level, silently, with the rail still rendering.
819
- //
820
- // ⚠ THE PARENT ANSWER COMES FROM {@link folderNesting}, NEVER FROM RE-DERIVING A PATH. That is
821
- // the whole correctness of this file: the nesting pass is where cycles are cut, where a dangling
822
- // parent is re-rooted, and where depth is counted. A second derivation would be a second truth.
823
- // ---------------------------------------------------------------------------
824
-
825
- /**
826
- * The least a folder must be for the path model to place it.
827
- *
828
- * ⚠ STRUCTURAL, AND DECLARED HERE RATHER THAN IMPORTED, so the two systems meet without either
829
- * one learning the other's type. `GridFolder` (a view folder: `id`, `name`, `order?`, `icon?`,
830
- * `parent?`) and `shell/nav.ts::NavFolder` (a nav folder: `id`, `name`) both satisfy it as they
831
- * stand, and neither had to change.
832
- *
833
- * ⛔ A NAV FOLDER HAS NO `parent` TODAY AND MUST NOT BE GIVEN ONE HERE. `parseNavPrefs` mirrors
834
- * the server's `_clean_nav_prefs`, which builds a strict `{id, name}` row, so a parent written
835
- * client-side would be dropped on the next save. Parentless folders simply come back from
836
- * {@link folderNesting} at level 1 with a `null` parent, which is exactly "a flat rail", and
837
- * {@link levelAt} drills them with the same code that drills a ten-deep view folder.
838
- */
839
- export interface PathFolder {
840
- id: string;
841
- name: string;
842
- parent?: string | null;
843
- }
844
-
845
- /**
846
- * One level of the path: what is AT it, and the way back OUT of it.
847
- *
848
- * ⭐ `folders` AND `leaves` ARE SEPARATE ARRAYS, which is R12.4 ("every level lists FOLDERS
849
- * FIRST, then its leaves") expressed as data rather than as an ordering convention a renderer
850
- * has to remember. A caller renders `folders` then `leaves` and cannot get the order wrong; a
851
- * single interleaved list would have made the rule a comment.
852
- */
853
- export interface FolderLevel<F, T> {
854
- /** The folder this level IS, or `null` at the top level. */
855
- folder: F | null;
856
- /** The folders directly inside this level, in the nesting's own sibling order. */
857
- folders: F[];
858
- /** The items filed directly at this level. Never the ones inside a subfolder. */
859
- leaves: T[];
860
- /**
861
- * The id of the level one step OUT, or `null` when that step lands at the top.
862
- *
863
- * ⛔ `null`, NEVER {@link ROOT_FOLDER_ID}. That constant is a reserved ITEM placement and
864
- * {@link folderNesting} already refuses it as a folder parent; emitting it here would put an
865
- * item-placement id in a folder-parent slot. It is ACCEPTED as an input `at` (an item really
866
- * can carry it) and read as "the top level".
867
- */
868
- parent: string | null;
869
- /** 0 at the top level, 1 for a top-level folder, up to {@link FOLDER_DEPTH_MAX}. */
870
- depth: number;
871
- }
872
-
873
- /**
874
- * Read `at` as a level id: absence, the root sentinel and a dangling id all mean the top level.
875
- *
876
- * ⚠ THE DANGLING RULE IS {@link resolveFolderId}'s, REUSED. A path segment naming a folder that
877
- * has just been deleted has to land SOMEWHERE, or drilling into it would render nothing at all
878
- * and read as an empty app.
879
- *
880
- * ⚠ It deliberately does NOT distinguish "never placed" (absence) from "placed at root" (the
881
- * sentinel). That split is W32-T27's and it decides the PIN in {@link groupByFolder}; a LEVEL has
882
- * no such question to answer, because both render at the top.
883
- */
884
- function levelIdOf(raw: string | null | undefined, known: ReadonlySet<string>): string | null {
885
- if (raw == null || raw === ROOT_FOLDER_ID) return null;
886
- return known.has(raw) ? raw : null;
887
- }
888
-
889
- /**
890
- * ⭐⭐ WHAT IS AT THIS PATH — the one resolver, for view folders and database folders alike.
891
- *
892
- * `at` is the folder id the user has drilled to, `null`/absent/{@link ROOT_FOLDER_ID} being the
893
- * top. `folderIdOf` is how an item names its folder, which is the only thing the two systems
894
- * spell differently: a VIEW carries its `folderId`, while the nav's placement lives in a
895
- * per-user map (see `shell/nav.ts::navFolderIdOf`, which closes over it and hands back the same
896
- * shape). Both arrive here as one function from an item to a folder id.
897
- *
898
- * ⛔ DEPTH IS NOT ENFORCED HERE and must not be. {@link mayNestFolder} refuses the eleventh
899
- * level at the moment a folder is placed; this function RENDERS whatever exists, so a folder at
900
- * {@link FOLDER_DEPTH_MAX} is still reachable by walking levels one at a time, which is what R12
901
- * asks the path to do.
902
- */
903
- export function levelAt<F extends PathFolder, T>(
904
- at: string | null | undefined,
905
- folders: readonly F[],
906
- items: readonly T[],
907
- folderIdOf: (item: T) => string | null | undefined
908
- ): FolderLevel<F, T> {
909
- const list: F[] = [...folders];
910
- const byId = new Map<string, F>(list.map((f) => [f.id, f]));
911
- const known = new Set<string>(byId.keys());
912
- const nesting = folderNesting(list);
913
- // ⛔⛔ THE PARENT PASS, AND THE WHOLE POINT OF THE NEGATIVE CONTROL THAT DROPS IT. Every
914
- // parent/child answer below reads THIS map — the one `folderNesting` built, with its cycles
915
- // cut and its dangling parents re-rooted. Re-deriving the relationship from a flattened path
916
- // string instead is the failure C9 names: nested folders collapse to one level, and a
917
- // two-deep folder answers as though it sat at the top.
918
- const parentOf: Record<string, string | null> = nesting.parent;
919
- const hereId = levelIdOf(at, known);
920
- const here = hereId == null ? null : (byId.get(hereId) ?? null);
921
- const parent = here ? (parentOf[here.id] ?? null) : null;
922
- const depth = here ? (nesting.depth[here.id] ?? 1) : 0;
923
- const subfolders: F[] = [];
924
- // ⚠ WALKED IN `nesting.ordered`, not in input order: that list is depth-first, so siblings come
925
- // out in the order the rail already draws them and one folder moving cannot reshuffle a level.
926
- for (const f of nesting.ordered) {
927
- const own = byId.get(f.id);
928
- if (!own) continue;
929
- if ((parentOf[f.id] ?? null) === (here ? here.id : null)) subfolders.push(own);
930
- }
931
- const leaves: T[] = [];
932
- for (const item of items) {
933
- if (levelIdOf(folderIdOf(item), known) === (here ? here.id : null)) leaves.push(item);
934
- }
935
- return { folder: here, folders: subfolders, leaves, parent, depth };
936
- }
937
-
938
- /**
939
- * ⭐ WHAT IS THE PARENT OF THIS PATH, asked all the way up — the breadcrumb R12.1 renders as
940
- * "one continuous path", outermost folder first, `at` itself last.
941
- *
942
- * ⚠ SAME `folderNesting` PARENT MAP as {@link levelAt}, walked upward with the same walk-guard
943
- * every other walk in this file carries: a payload that arrived with a loop cannot hang the
944
- * render. An empty array means the top level, so a caller renders the root crumb and nothing else.
945
- */
946
- export function folderPath<F extends PathFolder>(
947
- at: string | null | undefined,
948
- folders: readonly F[]
949
- ): F[] {
950
- const list: F[] = [...folders];
951
- const byId = new Map<string, F>(list.map((f) => [f.id, f]));
952
- const nesting = folderNesting(list);
953
- const parentOf: Record<string, string | null> = nesting.parent;
954
- let cursor: string | null = levelIdOf(at, new Set(byId.keys()));
955
- const out: F[] = [];
956
- const walked = new Set<string>();
957
- while (cursor) {
958
- if (walked.has(cursor)) break;
959
- walked.add(cursor);
960
- const f = byId.get(cursor);
961
- if (!f) break;
962
- out.unshift(f);
963
- cursor = parentOf[cursor] ?? null;
964
- }
965
- return out;
966
- }
 
801
  : Math.random().toString(36).slice(2, 10);
802
  return `fld_${rand}`;
803
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/customer-grid/formulaEngine.ts CHANGED
@@ -6,11 +6,7 @@
6
  //
7
  // GRAMMAR (v2 — the shared contract; v1 remains a strict subset):
8
  // numbers 1 0.5 .5 1200.75 (no separators, no exponents)
9
- // strings "text" with "" escaping a quote — Excel's own rule.
10
- // 'text' with '' escaping a quote — the SAME literal, in
11
- // the spelling Airtable's own docs use for a unit or format
12
- // argument: DATETIME_DIFF({a}, {b}, 'days'). A formula the
13
- // user copies out of that documentation must parse.
14
  // booleans TRUE FALSE (bare constants)
15
  // field refs {revenue_ytd} (slug charset [A-Za-z0-9_])
16
  // arithmetic + - * / ^ ( ) (usual precedence; ^ is
@@ -25,29 +21,7 @@
25
  // logic IF AND OR NOT IFERROR ISBLANK
26
  // text CONCATENATE/CONCAT LEFT RIGHT MID LEN TRIM
27
  // UPPER LOWER PROPER VALUE TEXT
28
- // SUBSTITUTE FIND REGEX_EXTRACT REGEX_REPLACE
29
- // logic SWITCH
30
  // date TODAY YEAR MONTH DAY DAYS (ISO YYYY-MM-DD)
31
- // DATEADD DATETIME_DIFF DATETIME_FORMAT
32
- //
33
- // WAVE 42 G7 — REGEX, SUBSTITUTION AND DATE ARITHMETIC. Three notes that are
34
- // load-bearing rather than decorative:
35
- //
36
- // 1. A REGEX PATTERN IS USER INPUT REACHING A REGEX ENGINE. This runs in the
37
- // tenant's one process, so an unbounded pattern is a denial of service and
38
- // not merely a slow cell. `safeRegex` below is the ONLY door to `RegExp`:
39
- // it caps the pattern, caps the SUBJECT (backtracking is exponential in
40
- // the input, so this cap does more work than any shape test), and refuses
41
- // the (a+)+ / (a*)* nested-unbounded-quantifier shape outright.
42
- // 2. A PATTERN MAY NOT CONTAIN `{`. The host's structural validator reads
43
- // `{...}` as a FIELD REFERENCE wherever it appears, including inside a
44
- // string, so `"[0-9]{3}"` is refused on save. Refusing it here too means
45
- // the user gets an error while typing instead of a save that fails later.
46
- // The cost is that the `\d{4}` idiom is unavailable; `\d\d\d\d` works.
47
- // 3. DATES ARE CALENDAR DATES. DATEADD/DATETIME_DIFF/DATETIME_FORMAT take and
48
- // return the ISO day this engine already speaks. Time units (hours,
49
- // minutes, seconds) are BLANK rather than approximated, and bare 'm' is
50
- // refused because it means minutes to some readers and months to others.
51
  //
52
  // THE ONE RULE, unchanged: **any error → BLANK, never a wrong number.** An
53
  // unknown ref, a divide-by-zero, a boolean fed to arithmetic, an unreadable
@@ -93,12 +67,10 @@ export type FormulaAst =
93
  export type FormulaFn =
94
  | "ABS" | "ROUND" | "ROUNDUP" | "ROUNDDOWN" | "INT" | "MOD" | "SQRT" | "POWER"
95
  | "EXP" | "LN" | "SUM" | "AVERAGE" | "COUNT" | "COUNTA" | "MIN" | "MAX"
96
- | "IF" | "AND" | "OR" | "NOT" | "IFERROR" | "ISBLANK" | "SWITCH"
97
  | "CONCATENATE" | "LEFT" | "RIGHT" | "MID" | "LEN" | "TRIM"
98
  | "UPPER" | "LOWER" | "PROPER" | "VALUE" | "TEXT"
99
- | "SUBSTITUTE" | "FIND" | "REGEX_EXTRACT" | "REGEX_REPLACE"
100
- | "TODAY" | "YEAR" | "MONTH" | "DAY" | "DAYS"
101
- | "DATEADD" | "DATETIME_DIFF" | "DATETIME_FORMAT";
102
 
103
  const MANY = 30; // variadic cap — bounded, far above any honest use
104
 
@@ -125,9 +97,6 @@ const FN_ARITY: Record<FormulaFn, [number, number]> = {
125
  NOT: [1, 1],
126
  IFERROR: [2, 2],
127
  ISBLANK: [1, 1],
128
- // SWITCH(subject, pattern, result, [pattern, result]…, [fallback]) — at least
129
- // one pair, so three arguments is the floor.
130
- SWITCH: [3, MANY],
131
  CONCATENATE: [1, MANY],
132
  LEFT: [1, 2],
133
  RIGHT: [1, 2],
@@ -139,23 +108,11 @@ const FN_ARITY: Record<FormulaFn, [number, number]> = {
139
  PROPER: [1, 1],
140
  VALUE: [1, 1],
141
  TEXT: [2, 2],
142
- // SUBSTITUTE(text, old, new, [occurrence]) — the 4th argument picks ONE
143
- // occurrence, 1-based; without it every occurrence is replaced.
144
- SUBSTITUTE: [3, 4],
145
- // FIND(stringToFind, whereToSearch, [startFromPosition]) — NEEDLE FIRST.
146
- FIND: [2, 3],
147
- REGEX_EXTRACT: [2, 2],
148
- REGEX_REPLACE: [3, 3],
149
  TODAY: [0, 0],
150
  YEAR: [1, 1],
151
  MONTH: [1, 1],
152
  DAY: [1, 1],
153
  DAYS: [2, 2],
154
- // DATEADD(date, count, units) and DATETIME_DIFF(date1, date2, [units]) —
155
- // Airtable's own order, confirmed against its documentation screenshots.
156
- DATEADD: [3, 3],
157
- DATETIME_DIFF: [2, 3],
158
- DATETIME_FORMAT: [2, 2],
159
  };
160
 
161
  /** Excel spells it CONCAT in modern versions; both names, one function. */
@@ -196,20 +153,15 @@ function tokenize(src: string): Token[] | string {
196
  i = end + 1;
197
  continue;
198
  }
199
- // "string" / 'string' — Excel's own escape: a doubled quote is one quote.
200
- // ONE literal in two spellings: Airtable's documentation writes a unit or a
201
- // date format in single quotes ('days', 'MM/DD/YYYY') and a user pastes it
202
- // exactly as printed, so both must parse. A quote of the OTHER kind inside
203
- // is an ordinary character, which is what makes "it's" and 'say "hi"' work.
204
- if (c === '"' || c === "'") {
205
- const q = c;
206
  let j = i + 1;
207
  let s = "";
208
  for (;;) {
209
  if (j >= src.length) return "a text value is missing its closing quote";
210
- if (src[j] === q) {
211
- if (src[j + 1] === q) {
212
- s += q;
213
  j += 2;
214
  continue;
215
  }
@@ -402,9 +354,7 @@ export function parseFormula(src: string): ParseResult {
402
  }
403
  const fn = (FN_ALIASES[upper] ?? upper) as FormulaFn;
404
  if (!(fn in FN_ARITY))
405
- // ⛔ STANDING RULE 2. This message carried an em dash until wave 42; it is
406
- // user-facing copy, so the sentence is rewritten rather than the character dropped.
407
- return fail(`${upper} is not a function this engine knows. The formula help lists what is available.`);
408
  pos += 1;
409
  if (!isOp("(")) return fail(`${fn} must be called with parentheses: ${fn}(…)`);
410
  pos += 1;
@@ -551,187 +501,6 @@ function dateSerial(p: { y: number; m: number; d: number }): number {
551
  return Date.UTC(p.y, p.m - 1, p.d) / 86_400_000;
552
  }
553
 
554
- // ---------------------------------------------------------------------------
555
- // WAVE 42 G7 — the bounded regex door.
556
- // ---------------------------------------------------------------------------
557
-
558
- /** Longest pattern a formula may hand to the regex engine. */
559
- export const MAX_REGEX_PATTERN = 200;
560
- /** Longest subject a pattern may run OVER. Catastrophic backtracking is
561
- * exponential in the INPUT length, so this cap is the load-bearing one: a
562
- * pathological pattern over 4 000 characters is slow, over a 100 KB long-text
563
- * field it is a hung tab. */
564
- export const MAX_REGEX_SUBJECT = 4_000;
565
- /** Longest text result a substitution may produce, so a replacement cannot be
566
- * used to inflate one cell into megabytes. */
567
- export const MAX_TEXT_RESULT = 20_000;
568
-
569
- /**
570
- * The catastrophic shape: a parenthesised group whose body already carries an
571
- * unbounded quantifier, quantified AGAIN. `(a+)+`, `(a*)*`, `(?:\d+)*` and
572
- * friends. Matching those against a non-matching subject is exponential.
573
- *
574
- * ⚠ It is applied ONLY to a pattern, never to whole formula source. `({a} + {b}) * 2`
575
- * has exactly this character shape and is ordinary arithmetic.
576
- */
577
- const NESTED_QUANT = /\((?:[^()\\]|\\.)*[*+](?:[^()\\]|\\.)*\)\??\s*[*+]/;
578
-
579
- /** Compiled patterns, so a formula re-evaluated per row per render compiles
580
- * once rather than once per cell. Bounded, and cleared wholesale when full. */
581
- const RX_CACHE = new Map<string, RegExp | null>();
582
- const RX_CACHE_MAX = 200;
583
-
584
- /**
585
- * The ONE door to `RegExp` in this engine. Returns null (which is BLANK, the
586
- * engine's one rule) for anything unbounded, malformed, or carrying `{`.
587
- */
588
- function safeRegex(pattern: string, flags: string): RegExp | null {
589
- if (typeof pattern !== "string") return null;
590
- if (pattern === "" || pattern.length > MAX_REGEX_PATTERN) return null;
591
- // `{` cannot appear: the host reads `{...}` as a field reference wherever it
592
- // sits, so a pattern containing one is refused on SAVE. Refusing it here
593
- // keeps both sides saying the same thing.
594
- if (pattern.includes("{") || pattern.includes("}")) return null;
595
- if (NESTED_QUANT.test(pattern)) return null;
596
- // The separator is written as an ESCAPE, not as a literal NUL byte. A raw NUL byte in the
597
- // source makes every `grep` classify this file as BINARY and skip it silently, which
598
- // blinds any gate or reader that searches it -- the file is unsearchable, not merely
599
- // odd. The runtime value is identical; only the source encoding changes.
600
- const key = flags + "\u0000" + pattern;
601
- const hit = RX_CACHE.get(key);
602
- if (hit !== undefined) return hit;
603
- let rx: RegExp | null = null;
604
- try {
605
- rx = new RegExp(pattern, flags);
606
- } catch {
607
- rx = null;
608
- }
609
- if (RX_CACHE.size >= RX_CACHE_MAX) RX_CACHE.clear();
610
- RX_CACHE.set(key, rx);
611
- return rx;
612
- }
613
-
614
- // ---------------------------------------------------------------------------
615
- // WAVE 42 G7 — calendar arithmetic over the ISO day this engine already speaks.
616
- // ---------------------------------------------------------------------------
617
-
618
- type DateUnit = "d" | "w" | "M" | "Q" | "y";
619
-
620
- /**
621
- * Airtable's unit words, plus the unambiguous single letters. Bare 'm' is
622
- * ABSENT on purpose: it reads as minutes to one person and months to another,
623
- * and a date silently off by 30 days is exactly the wrong-number-with-a-
624
- * confident-face this engine refuses to produce.
625
- */
626
- const DATE_UNITS: Record<string, DateUnit> = {
627
- day: "d", days: "d", d: "d",
628
- week: "w", weeks: "w", w: "w",
629
- month: "M", months: "M",
630
- quarter: "Q", quarters: "Q", q: "Q",
631
- year: "y", years: "y", y: "y",
632
- };
633
-
634
- function dateUnit(v: Value): DateUnit | null {
635
- if (typeof v !== "string") return null;
636
- const k = v.trim().toLowerCase();
637
- return DATE_UNITS[k] ?? null;
638
- }
639
-
640
- function pad(n: number, width: number): string {
641
- const s = String(Math.abs(n));
642
- return (n < 0 ? "-" : "") + (s.length >= width ? s : "0".repeat(width - s.length) + s);
643
- }
644
-
645
- function isoFromParts(p: { y: number; m: number; d: number }): string {
646
- return pad(p.y, 4) + "-" + pad(p.m, 2) + "-" + pad(p.d, 2);
647
- }
648
-
649
- function daysInMonth(y: number, m: number): number {
650
- return new Date(Date.UTC(y, m, 0)).getUTCDate();
651
- }
652
-
653
- /** Calendar month arithmetic with Excel's clamp: 31 Jan plus one month is the
654
- * 28th (or 29th) of February, never the 3rd of March. */
655
- function addMonths(p: { y: number; m: number; d: number }, k: number) {
656
- const total = p.y * 12 + (p.m - 1) + k;
657
- const y = Math.floor(total / 12);
658
- const m = total - y * 12 + 1;
659
- return { y, m, d: Math.min(p.d, daysInMonth(y, m)) };
660
- }
661
-
662
- function partsFromSerial(serial: number) {
663
- const d = new Date(serial * 86_400_000);
664
- return { y: d.getUTCFullYear(), m: d.getUTCMonth() + 1, d: d.getUTCDate() };
665
- }
666
-
667
- /** Whole months from `b` to `a`, the calendar way: 31 Jan to 28 Feb is 0. */
668
- function wholeMonths(
669
- a: { y: number; m: number; d: number },
670
- b: { y: number; m: number; d: number }
671
- ): number {
672
- let n = (a.y - b.y) * 12 + (a.m - b.m);
673
- if (n > 0 && a.d < b.d) n -= 1;
674
- if (n < 0 && a.d > b.d) n += 1;
675
- return n;
676
- }
677
-
678
- const MONTH_NAMES = [
679
- "January", "February", "March", "April", "May", "June",
680
- "July", "August", "September", "October", "November", "December",
681
- ];
682
- const DAY_NAMES = [
683
- "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
684
- ];
685
-
686
- /** Longest format string DATETIME_FORMAT will look at. */
687
- const MAX_DATE_FORMAT = 64;
688
-
689
- /**
690
- * DATETIME_FORMAT's token set: YYYY YY MMMM MMM MM M DD D dddd ddd Q, with
691
- * `[literal]` escaping a run of text. Punctuation passes through. An
692
- * UNRECOGNISED letter is BLANK, never a guess at what it meant, which is
693
- * `textFormat`'s convention one function up and the same reason for it.
694
- */
695
- function formatDate(p: { y: number; m: number; d: number }, fmt: string): string | null {
696
- if (fmt.length === 0 || fmt.length > MAX_DATE_FORMAT) return null;
697
- const dow = ((Math.round(dateSerial(p)) % 7) + 7 + 4) % 7; // serial 0 was a Thursday
698
- let out = "";
699
- let i = 0;
700
- while (i < fmt.length) {
701
- const ch = fmt[i];
702
- if (ch === "[") {
703
- const end = fmt.indexOf("]", i + 1);
704
- if (end < 0) return null;
705
- out += fmt.slice(i + 1, end);
706
- i = end + 1;
707
- continue;
708
- }
709
- const m = /^(YYYY|YY|MMMM|MMM|MM|M|DDDD|DD|D|dddd|ddd|Q)/.exec(fmt.slice(i));
710
- if (m) {
711
- switch (m[0]) {
712
- case "YYYY": out += pad(p.y, 4); break;
713
- case "YY": out += pad(p.y % 100, 2); break;
714
- case "MMMM": out += MONTH_NAMES[p.m - 1]; break;
715
- case "MMM": out += MONTH_NAMES[p.m - 1].slice(0, 3); break;
716
- case "MM": out += pad(p.m, 2); break;
717
- case "M": out += String(p.m); break;
718
- case "DDDD":
719
- case "dddd": out += DAY_NAMES[dow]; break;
720
- case "ddd": out += DAY_NAMES[dow].slice(0, 3); break;
721
- case "DD": out += pad(p.d, 2); break;
722
- case "D": out += String(p.d); break;
723
- case "Q": out += String(Math.floor((p.m - 1) / 3) + 1); break;
724
- }
725
- i += m[0].length;
726
- continue;
727
- }
728
- if (/[A-Za-z]/.test(ch)) return null; // an unknown token is blank, not a literal
729
- out += ch;
730
- i += 1;
731
- }
732
- return out;
733
- }
734
-
735
  /**
736
  * TEXT(value, format) — the common Excel number formats, fail-closed:
737
  * "0" "0.00" fixed decimals
@@ -940,18 +709,6 @@ function evalNode(n: FormulaAst, get: (key: string) => unknown, env: FormulaEnv)
940
  const v = ev(n.args[0]);
941
  return v == null || v === "";
942
  }
943
- case "SWITCH": {
944
- // SWITCH(subject, pattern, result, [pattern, result]…, [fallback]).
945
- // LAZY like IF: only the arm that wins is evaluated, so a guard arm
946
- // can protect the arithmetic in the arm beside it.
947
- const subject = ev(n.args[0]);
948
- let i = 1;
949
- for (; i + 1 < n.args.length; i += 2) {
950
- if (switchMatch(subject, ev(n.args[i]))) return ev(n.args[i + 1]);
951
- }
952
- // A leftover odd argument is the fallback; without one, blank.
953
- return i < n.args.length ? ev(n.args[i]) : null;
954
- }
955
  case "CONCATENATE":
956
  return n.args.map((a) => asText(ev(a))).join("");
957
  case "LEFT":
@@ -993,75 +750,6 @@ function evalNode(n: FormulaAst, get: (key: string) => unknown, env: FormulaEnv)
993
  if (v == null || typeof fmt !== "string") return null;
994
  return textFormat(v, fmt);
995
  }
996
- case "SUBSTITUTE": {
997
- // SUBSTITUTE(text, oldText, newText, [occurrence]) — plain text, no
998
- // pattern, so nothing here reaches the regex engine.
999
- const s = asText(ev(n.args[0]));
1000
- const oldText = asText(ev(n.args[1]));
1001
- const newText = asText(ev(n.args[2]));
1002
- if (oldText === "") return s; // replacing nothing is the identity
1003
- let out: string = s;
1004
- if (n.args.length > 3) {
1005
- const k = asNumber(ev(n.args[3]));
1006
- if (k == null || !Number.isInteger(k) || k < 1) return null;
1007
- let from = 0;
1008
- let seen = 0;
1009
- for (;;) {
1010
- const at = s.indexOf(oldText, from);
1011
- if (at < 0) return s; // fewer than k occurrences: unchanged
1012
- seen += 1;
1013
- if (seen === k) {
1014
- out = s.slice(0, at) + newText + s.slice(at + oldText.length);
1015
- break;
1016
- }
1017
- from = at + oldText.length;
1018
- }
1019
- } else {
1020
- out = s.split(oldText).join(newText);
1021
- }
1022
- return out.length > MAX_TEXT_RESULT ? null : out;
1023
- }
1024
- case "FIND": {
1025
- // FIND(stringToFind, whereToSearch, [startFromPosition]) — NEEDLE
1026
- // FIRST, 1-based, and 0 (not blank) when it is not there, because
1027
- // "absent" is an answer and callers test it with = 0.
1028
- // Case-SENSITIVE, as FIND is in both Excel and Airtable.
1029
- const needle = asText(ev(n.args[0]));
1030
- const hay = asText(ev(n.args[1]));
1031
- let start = 1;
1032
- if (n.args.length > 2) {
1033
- const k = asNumber(ev(n.args[2]));
1034
- if (k == null || !Number.isInteger(k) || k < 1) return null;
1035
- start = k;
1036
- }
1037
- const at = hay.indexOf(needle, start - 1);
1038
- return at < 0 ? 0 : at + 1;
1039
- }
1040
- case "REGEX_EXTRACT": {
1041
- // REGEX_EXTRACT(text, pattern) -> the FIRST WHOLE MATCH, blank when
1042
- // the pattern does not match. (Airtable returns the whole match, not
1043
- // a capture group; a group is still useful for grouping alternation.)
1044
- const s = asText(ev(n.args[0]));
1045
- const pat = ev(n.args[1]);
1046
- if (typeof pat !== "string" || s.length > MAX_REGEX_SUBJECT) return null;
1047
- const rx = safeRegex(pat, "");
1048
- if (!rx) return null;
1049
- const m = rx.exec(s);
1050
- return m ? m[0] : null;
1051
- }
1052
- case "REGEX_REPLACE": {
1053
- // REGEX_REPLACE(text, pattern, replacement) -> EVERY match replaced.
1054
- const s = asText(ev(n.args[0]));
1055
- const pat = ev(n.args[1]);
1056
- const rep = asText(ev(n.args[2]));
1057
- if (typeof pat !== "string" || s.length > MAX_REGEX_SUBJECT) return null;
1058
- if (rep.length > MAX_REGEX_PATTERN) return null;
1059
- const rx = safeRegex(pat, "g");
1060
- if (!rx) return null;
1061
- rx.lastIndex = 0; // a cached /g/ regex carries state between calls
1062
- const out = s.replace(rx, rep);
1063
- return out.length > MAX_TEXT_RESULT ? null : out;
1064
- }
1065
  case "TODAY":
1066
  return typeof env.today === "string" && dateParts(env.today) ? env.today : null;
1067
  case "YEAR":
@@ -1078,46 +766,6 @@ function evalNode(n: FormulaAst, get: (key: string) => unknown, env: FormulaEnv)
1078
  if (!end || !start) return null;
1079
  return Math.round(dateSerial(end) - dateSerial(start));
1080
  }
1081
- case "DATEADD": {
1082
- // DATEADD(date, count, units) -> the ISO day, shifted. Airtable's own
1083
- // argument order, read off its documentation.
1084
- const p = dateParts(ev(n.args[0]));
1085
- const count = asNumber(ev(n.args[1]));
1086
- const unit = dateUnit(ev(n.args[2]));
1087
- if (!p || count == null || !unit) return null;
1088
- const k = Math.trunc(count);
1089
- if (!Number.isFinite(k) || Math.abs(k) > 1_000_000) return null;
1090
- if (unit === "M") return isoFromParts(addMonths(p, k));
1091
- if (unit === "Q") return isoFromParts(addMonths(p, k * 3));
1092
- if (unit === "y") return isoFromParts(addMonths(p, k * 12));
1093
- const shifted = dateSerial(p) + (unit === "w" ? k * 7 : k);
1094
- if (!Number.isFinite(shifted) || Math.abs(shifted) > 3_000_000) return null;
1095
- return isoFromParts(partsFromSerial(shifted));
1096
- }
1097
- case "DATETIME_DIFF": {
1098
- // DATETIME_DIFF(date1, date2, [units]) = date1 MINUS date2, so a due
1099
- // date ahead of a start date is POSITIVE. Units default to days.
1100
- // Truncated toward zero: a part-week is not a week.
1101
- const a = dateParts(ev(n.args[0]));
1102
- const b = dateParts(ev(n.args[1]));
1103
- if (!a || !b) return null;
1104
- const unit = n.args.length > 2 ? dateUnit(ev(n.args[2])) : "d";
1105
- if (!unit) return null;
1106
- const days = Math.round(dateSerial(a) - dateSerial(b));
1107
- if (unit === "d") return days;
1108
- if (unit === "w") return Math.trunc(days / 7);
1109
- const months = wholeMonths(a, b);
1110
- if (unit === "M") return months;
1111
- if (unit === "Q") return Math.trunc(months / 3);
1112
- return Math.trunc(months / 12);
1113
- }
1114
- case "DATETIME_FORMAT": {
1115
- // DATETIME_FORMAT(date, format) -> text in the caller's spelling.
1116
- const p = dateParts(ev(n.args[0]));
1117
- const fmt = ev(n.args[1]);
1118
- if (!p || typeof fmt !== "string") return null;
1119
- return formatDate(p, fmt);
1120
- }
1121
  }
1122
  return null;
1123
  }
@@ -1126,25 +774,6 @@ function evalNode(n: FormulaAst, get: (key: string) => unknown, env: FormulaEnv)
1126
  }
1127
  }
1128
 
1129
- /**
1130
- * SWITCH's arm test. It follows the engine's OWN equality rather than inventing
1131
- * a second one: numbers (and numeric text) compare numerically, text compares
1132
- * case-insensitively after trimming, and blank matches blank. A mixed pair does
1133
- * NOT match, so it simply falls through to the next arm or the fallback.
1134
- */
1135
- function switchMatch(subject: Value, pattern: Value): boolean {
1136
- if (subject == null || subject === "") return pattern == null || pattern === "";
1137
- if (pattern == null || pattern === "") return false;
1138
- if (typeof subject === "boolean" || typeof pattern === "boolean")
1139
- return subject === pattern;
1140
- const a = asNumber(subject);
1141
- const b = asNumber(pattern);
1142
- if (a != null && b != null) return a === b;
1143
- if (typeof subject === "string" && typeof pattern === "string")
1144
- return subject.trim().toLowerCase() === pattern.trim().toLowerCase();
1145
- return false;
1146
- }
1147
-
1148
  function cmpNums(op: "<" | "<=" | ">" | ">=" | "=" | "!=", l: number, r: number): boolean {
1149
  switch (op) {
1150
  case "<": return l < r;
@@ -1226,58 +855,6 @@ export function orderFormulas(sources: ReadonlyMap<string, string>): {
1226
  * can walk the graph; `selfKey` names the field being edited (absent on
1227
  * create, where no cycle is possible yet).
1228
  */
1229
- /**
1230
- * ⛔⛔ THE COMPOSITE HOLE, closed at AUTHORING time (wave 42 G7).
1231
- *
1232
- * A pattern this engine refuses at EVALUATION time is still a formula that parses, and the
1233
- * host's wall is structural, so `REGEX_EXTRACT({notes}, "[0-9]{3}")` SAVES and then reads
1234
- * blank forever with nothing going red. That is this ticket's own scar wearing the other
1235
- * face: last time a legal formula could not be stored, this time an unusable one can.
1236
- *
1237
- * So a pattern written as a LITERAL is put through `safeRegex` here, where the author is
1238
- * still looking at it. A pattern assembled at run time cannot be judged from the tree and
1239
- * degrades to blank, which is the engine's one rule and the honest answer.
1240
- */
1241
- function badPattern(ast: FormulaAst): string | null {
1242
- let problem: string | null = null;
1243
- const walk = (n: FormulaAst): void => {
1244
- if (problem) return;
1245
- switch (n.t) {
1246
- case "neg":
1247
- walk(n.e);
1248
- return;
1249
- case "bin":
1250
- case "cmp":
1251
- walk(n.l);
1252
- walk(n.r);
1253
- return;
1254
- case "call": {
1255
- if (n.fn === "REGEX_EXTRACT" || n.fn === "REGEX_REPLACE") {
1256
- const p = n.args[1];
1257
- if (p && p.t === "str") {
1258
- if (p.v.includes("{") || p.v.includes("}"))
1259
- problem =
1260
- "a search pattern cannot contain { or }, because a formula reads those as a " +
1261
- "field name. Write \\d\\d\\d rather than \\d{3}.";
1262
- else if (p.v === "" || p.v.length > MAX_REGEX_PATTERN)
1263
- problem = `a search pattern must be 1 to ${MAX_REGEX_PATTERN} characters long`;
1264
- else if (safeRegex(p.v, "") === null)
1265
- problem =
1266
- "that search pattern is either not valid or could run for an unbounded time. " +
1267
- "A repeat inside a repeated group, such as (a+)+, is refused.";
1268
- }
1269
- }
1270
- n.args.forEach(walk);
1271
- return;
1272
- }
1273
- default:
1274
- return;
1275
- }
1276
- };
1277
- walk(ast);
1278
- return problem;
1279
- }
1280
-
1281
  export function validateFormula(
1282
  src: string,
1283
  knownKeys: ReadonlySet<string>,
@@ -1286,8 +863,6 @@ export function validateFormula(
1286
  ): { ok: boolean; error?: string; refs: string[] } {
1287
  const parsed = parseFormula(src);
1288
  if (!parsed.ok) return { ok: false, error: parsed.error, refs: [] };
1289
- const patternError = badPattern(parsed.ast);
1290
- if (patternError) return { ok: false, error: patternError, refs: parsed.refs };
1291
  for (const k of parsed.refs) {
1292
  if (!knownKeys.has(k) && !formulaSources.has(k))
1293
  return { ok: false, error: `{${k}} is not a field of this table`, refs: parsed.refs };
 
6
  //
7
  // GRAMMAR (v2 — the shared contract; v1 remains a strict subset):
8
  // numbers 1 0.5 .5 1200.75 (no separators, no exponents)
9
+ // strings "text" with "" escaping a quote — Excel's own rule
 
 
 
 
10
  // booleans TRUE FALSE (bare constants)
11
  // field refs {revenue_ytd} (slug charset [A-Za-z0-9_])
12
  // arithmetic + - * / ^ ( ) (usual precedence; ^ is
 
21
  // logic IF AND OR NOT IFERROR ISBLANK
22
  // text CONCATENATE/CONCAT LEFT RIGHT MID LEN TRIM
23
  // UPPER LOWER PROPER VALUE TEXT
 
 
24
  // date TODAY YEAR MONTH DAY DAYS (ISO YYYY-MM-DD)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  //
26
  // THE ONE RULE, unchanged: **any error → BLANK, never a wrong number.** An
27
  // unknown ref, a divide-by-zero, a boolean fed to arithmetic, an unreadable
 
67
  export type FormulaFn =
68
  | "ABS" | "ROUND" | "ROUNDUP" | "ROUNDDOWN" | "INT" | "MOD" | "SQRT" | "POWER"
69
  | "EXP" | "LN" | "SUM" | "AVERAGE" | "COUNT" | "COUNTA" | "MIN" | "MAX"
70
+ | "IF" | "AND" | "OR" | "NOT" | "IFERROR" | "ISBLANK"
71
  | "CONCATENATE" | "LEFT" | "RIGHT" | "MID" | "LEN" | "TRIM"
72
  | "UPPER" | "LOWER" | "PROPER" | "VALUE" | "TEXT"
73
+ | "TODAY" | "YEAR" | "MONTH" | "DAY" | "DAYS";
 
 
74
 
75
  const MANY = 30; // variadic cap — bounded, far above any honest use
76
 
 
97
  NOT: [1, 1],
98
  IFERROR: [2, 2],
99
  ISBLANK: [1, 1],
 
 
 
100
  CONCATENATE: [1, MANY],
101
  LEFT: [1, 2],
102
  RIGHT: [1, 2],
 
108
  PROPER: [1, 1],
109
  VALUE: [1, 1],
110
  TEXT: [2, 2],
 
 
 
 
 
 
 
111
  TODAY: [0, 0],
112
  YEAR: [1, 1],
113
  MONTH: [1, 1],
114
  DAY: [1, 1],
115
  DAYS: [2, 2],
 
 
 
 
 
116
  };
117
 
118
  /** Excel spells it CONCAT in modern versions; both names, one function. */
 
153
  i = end + 1;
154
  continue;
155
  }
156
+ // "string" — Excel's own escape: "" inside a string is one quote
157
+ if (c === '"') {
 
 
 
 
 
158
  let j = i + 1;
159
  let s = "";
160
  for (;;) {
161
  if (j >= src.length) return "a text value is missing its closing quote";
162
+ if (src[j] === '"') {
163
+ if (src[j + 1] === '"') {
164
+ s += '"';
165
  j += 2;
166
  continue;
167
  }
 
354
  }
355
  const fn = (FN_ALIASES[upper] ?? upper) as FormulaFn;
356
  if (!(fn in FN_ARITY))
357
+ return fail(`unknown function ${upper} — see the formula help for what is available`);
 
 
358
  pos += 1;
359
  if (!isOp("(")) return fail(`${fn} must be called with parentheses: ${fn}(…)`);
360
  pos += 1;
 
501
  return Date.UTC(p.y, p.m - 1, p.d) / 86_400_000;
502
  }
503
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504
  /**
505
  * TEXT(value, format) — the common Excel number formats, fail-closed:
506
  * "0" "0.00" fixed decimals
 
709
  const v = ev(n.args[0]);
710
  return v == null || v === "";
711
  }
 
 
 
 
 
 
 
 
 
 
 
 
712
  case "CONCATENATE":
713
  return n.args.map((a) => asText(ev(a))).join("");
714
  case "LEFT":
 
750
  if (v == null || typeof fmt !== "string") return null;
751
  return textFormat(v, fmt);
752
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
753
  case "TODAY":
754
  return typeof env.today === "string" && dateParts(env.today) ? env.today : null;
755
  case "YEAR":
 
766
  if (!end || !start) return null;
767
  return Math.round(dateSerial(end) - dateSerial(start));
768
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
769
  }
770
  return null;
771
  }
 
774
  }
775
  }
776
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
777
  function cmpNums(op: "<" | "<=" | ">" | ">=" | "=" | "!=", l: number, r: number): boolean {
778
  switch (op) {
779
  case "<": return l < r;
 
855
  * can walk the graph; `selfKey` names the field being edited (absent on
856
  * create, where no cycle is possible yet).
857
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
858
  export function validateFormula(
859
  src: string,
860
  knownKeys: ReadonlySet<string>,
 
863
  ): { ok: boolean; error?: string; refs: string[] } {
864
  const parsed = parseFormula(src);
865
  if (!parsed.ok) return { ok: false, error: parsed.error, refs: [] };
 
 
866
  for (const k of parsed.refs) {
867
  if (!knownKeys.has(k) && !formulaSources.has(k))
868
  return { ok: false, error: `{${k}} is not a field of this table`, refs: parsed.refs };
web/src/customer-grid/icons.tsx CHANGED
@@ -104,21 +104,6 @@ export function FieldTypeIcon({
104
  );
105
  }
106
 
107
- /**
108
- * The compact, outline-only information mark shared by field surfaces. Its canvas sibling is
109
- * `HEADER_ICONS.aiosInfo`; keeping the same ring-and-i geometry makes an explanation read as the
110
- * same affordance whether it sits in a grid header or beside a picker option.
111
- */
112
- export function InfoMark({ size = 14 }: { size?: number }) {
113
- return (
114
- <svg width={size} height={size} viewBox="0 0 16 16" fill="none" aria-hidden="true">
115
- <circle cx="8" cy="8" r="6.1" stroke="currentColor" strokeWidth="1.25" />
116
- <path d="M8 7.4v3.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
117
- <circle cx="8" cy="5.1" r="0.85" fill="currentColor" />
118
- </svg>
119
- );
120
- }
121
-
122
  /** The display-mode mark for the View switcher (I18). */
123
  export function ModeIcon({ mode, size = 14 }: { mode: DisplayMode; size?: number }) {
124
  return (
 
104
  );
105
  }
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  /** The display-mode mark for the View switcher (I18). */
108
  export function ModeIcon({ mode, size = 14 }: { mode: DisplayMode; size?: number }) {
109
  return (
web/src/customer-grid/map.css CHANGED
@@ -112,8 +112,10 @@
112
  flex: 0 0 auto;
113
  width: 100%;
114
  max-width: none;
115
- max-height: 240px;
116
- overflow-y: auto;
 
 
117
  padding-bottom: 2px;
118
  scrollbar-width: thin;
119
  }
@@ -162,6 +164,19 @@
162
  white-space: nowrap;
163
  }
164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  .cg-map-stopmove {
166
  display: inline-grid;
167
  place-items: center;
@@ -211,6 +226,37 @@
211
  stroke-linejoin: round;
212
  }
213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  /* --- the address lookup (T37) ---------------------------------------------
215
  *
216
  * ⛔ THE PROGRESS LINE IS A REQUIREMENT, NOT A COURTESY. The free geocoder allows about one
 
112
  flex: 0 0 auto;
113
  width: 100%;
114
  max-width: none;
115
+ /* The route panel itself is the sole vertical scroll owner. A nested stop-list scrollbar
116
+ strands the lower controls behind a second wheel target. */
117
+ max-height: none;
118
+ overflow: visible;
119
  padding-bottom: 2px;
120
  scrollbar-width: thin;
121
  }
 
164
  white-space: nowrap;
165
  }
166
 
167
+ .cg-map-stopopen {
168
+ padding: 0;
169
+ border: 0;
170
+ background: transparent;
171
+ font: inherit;
172
+ color: var(--lp-blue-solid);
173
+ cursor: pointer;
174
+ text-align: left;
175
+ }
176
+
177
+ .cg-map-stopopen:hover { text-decoration: underline; }
178
+ .cg-map-stopopen:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 1px; }
179
+
180
  .cg-map-stopmove {
181
  display: inline-grid;
182
  place-items: center;
 
226
  stroke-linejoin: round;
227
  }
228
 
229
+ /* A Zone is a person-drawn geographic selection, not a second basemap. Its translucent tint
230
+ keeps pins, routes and the actual map legible; clicking it chooses its durable C3 membership. */
231
+ .cg-map-zone {
232
+ fill-opacity: 0.18;
233
+ stroke-opacity: 0.9;
234
+ cursor: pointer;
235
+ }
236
+
237
+ .cg-map-zone:hover { fill-opacity: 0.28; }
238
+
239
+ .cg-map-zones {
240
+ display: flex;
241
+ align-items: end;
242
+ flex-wrap: wrap;
243
+ gap: 6px;
244
+ width: 100%;
245
+ padding-top: 4px;
246
+ border-top: 1px solid var(--lp-line);
247
+ }
248
+
249
+ .cg-map-zone-control {
250
+ display: flex;
251
+ flex: 0 1 160px;
252
+ flex-direction: column;
253
+ gap: 3px;
254
+ color: var(--lp-muted);
255
+ font: 500 var(--lp-fs-3xs)/1.35 Inter, system-ui, sans-serif;
256
+ }
257
+
258
+ .cg-map-zone-control select[multiple] { min-height: 52px; }
259
+
260
  /* --- the address lookup (T37) ---------------------------------------------
261
  *
262
  * ⛔ THE PROGRESS LINE IS A REQUIREMENT, NOT A COURTESY. The free geocoder allows about one
web/src/customer-grid/mapProjection.ts CHANGED
@@ -714,12 +714,15 @@ export function routeStopCap(coarsePointer: boolean, roundTrip = false): number
714
  */
715
  export function googleRouteUrl(
716
  stops: GeoStop[],
717
- opts: { roundTrip?: boolean; coarsePointer?: boolean } = {}
718
  ): { url: string; used: number } | null {
719
  if (stops.length < 2) return null;
720
  const roundTrip = !!opts.roundTrip;
721
  const at = (s: GeoStop) => `${s.lat.toFixed(6)},${s.lon.toFixed(6)}`;
722
- let used = Math.min(stops.length, routeStopCap(!!opts.coarsePointer, roundTrip));
 
 
 
723
  for (;;) {
724
  const chosen = stops.slice(0, used);
725
  const origin = chosen[0];
@@ -743,16 +746,22 @@ export function googleRouteUrl(
743
  */
744
  export function googleRouteUrls(
745
  stops: GeoStop[],
746
- opts: { roundTrip?: boolean; coarsePointer?: boolean } = {}
747
  ): { url: string; index: number; start: number; end: number }[] {
748
  if (stops.length < 2) return [];
749
  const links: { url: string; index: number; start: number; end: number }[] = [];
750
- const cap = routeStopCap(!!opts.coarsePointer, false);
 
 
 
 
 
 
751
  let start = 0;
752
  while (start < stops.length - 1) {
753
  const end = Math.min(stops.length, start + cap);
754
  const segment = stops.slice(start, end);
755
- const built = googleRouteUrl(segment, { coarsePointer: opts.coarsePointer });
756
  if (!built || built.used < 2) break;
757
  links.push({
758
  url: built.url,
@@ -771,7 +780,11 @@ export function googleRouteUrls(
771
  const last = links[links.length - 1];
772
  const segment = stops.slice(last.start, last.end);
773
  if (segment.length >= 2 && last.end === stops.length) {
774
- const returned = googleRouteUrl([...segment, stops[0]], { roundTrip: false, coarsePointer: opts.coarsePointer });
 
 
 
 
775
  if (returned) last.url = returned.url;
776
  }
777
  }
 
714
  */
715
  export function googleRouteUrl(
716
  stops: GeoStop[],
717
+ opts: { roundTrip?: boolean; coarsePointer?: boolean; maxStops?: number } = {}
718
  ): { url: string; used: number } | null {
719
  if (stops.length < 2) return null;
720
  const roundTrip = !!opts.roundTrip;
721
  const at = (s: GeoStop) => `${s.lat.toFixed(6)},${s.lon.toFixed(6)}`;
722
+ const requested = typeof opts.maxStops === "number" && Number.isFinite(opts.maxStops)
723
+ ? Math.max(2, Math.min(10, Math.trunc(opts.maxStops)))
724
+ : 10;
725
+ let used = Math.min(stops.length, routeStopCap(!!opts.coarsePointer, roundTrip), requested);
726
  for (;;) {
727
  const chosen = stops.slice(0, used);
728
  const origin = chosen[0];
 
746
  */
747
  export function googleRouteUrls(
748
  stops: GeoStop[],
749
+ opts: { roundTrip?: boolean; coarsePointer?: boolean; maxStops?: number } = {}
750
  ): { url: string; index: number; start: number; end: number }[] {
751
  if (stops.length < 2) return [];
752
  const links: { url: string; index: number; start: number; end: number }[] = [];
753
+ // The UI and C2 snapshots promise 2–10 stops per hand-off. Keep the existing
754
+ // provider/mobile cap as the stricter ceiling; a schedule can never create a
755
+ // longer browser URL than the planner would draw today.
756
+ const requested = typeof opts.maxStops === "number" && Number.isFinite(opts.maxStops)
757
+ ? Math.max(2, Math.min(10, Math.trunc(opts.maxStops)))
758
+ : 10;
759
+ const cap = Math.min(routeStopCap(!!opts.coarsePointer, false), requested);
760
  let start = 0;
761
  while (start < stops.length - 1) {
762
  const end = Math.min(stops.length, start + cap);
763
  const segment = stops.slice(start, end);
764
+ const built = googleRouteUrl(segment, { coarsePointer: opts.coarsePointer, maxStops: cap });
765
  if (!built || built.used < 2) break;
766
  links.push({
767
  url: built.url,
 
780
  const last = links[links.length - 1];
781
  const segment = stops.slice(last.start, last.end);
782
  if (segment.length >= 2 && last.end === stops.length) {
783
+ const returned = googleRouteUrl([...segment, stops[0]], {
784
+ roundTrip: false,
785
+ coarsePointer: opts.coarsePointer,
786
+ maxStops: cap,
787
+ });
788
  if (returned) last.url = returned.url;
789
  }
790
  }
web/src/customer-grid/types.ts CHANGED
@@ -102,21 +102,7 @@ export const AI_STATE_PREFIX = "_ai_";
102
  /** What `_ai_<colId>` can say. `empty` is never stamped: an absent key IS empty. */
103
  export type AiCellState = "agent" | "human" | "stale" | "error";
104
 
105
- /**
106
- * ⭐⭐ W42-T09 (contract C2) — `"topic"` JOINS THE VOCABULARY, and the reason it must be widened
107
- * HERE rather than loosened at the boundary that consumes it is the whole point of the ticket.
108
- *
109
- * `GET /grid/hop-topics` hands the client a governed topic's dimensions already shaped as
110
- * `Field[]` so the existing condition builder can take them as its `fields` prop with no adapter
111
- * in between; those fields describe a column of the SEMANTIC MODEL, not a column of this
112
- * workspace, and `"odoo"` would be a lie about where they come from while `"overlay"` would make
113
- * them look editable.
114
- *
115
- * ⚠ NOTHING RENDERS ONE AS A GRID COLUMN. A topic dim reaches only `hopTopics[].dims`, which the
116
- * link editor feeds to `FilterBuilderPanel` as an operand list; it never enters the grid's own
117
- * `fields` array, so no editability, permission or formatting path is asked about `"topic"`.
118
- */
119
- export type FieldSource = "odoo" | "overlay" | "topic";
120
 
121
  /**
122
  * R13 — the languages a `code` column may declare. Mirrors `aios_grid.CODE_LANGUAGES`
@@ -241,18 +227,7 @@ export const CREATABLE_TYPES: readonly FieldType[] = [
241
  * asymmetry is honest rather than an oversight, and it is the reason the exported set below is
242
  * `string[]` while its first half is not.
243
  */
244
- const ADVANCED_FIELD_KINDS: readonly FieldType[] = [
245
- "automation", "json", "code", "ai_enrich",
246
- // ⭐⭐ W42-T37 (owner instruction 20) — AND IT IS SEVEN. The relational pair and the formula
247
- // column join the group, so the unheaded list above it holds only the kinds somebody types a
248
- // value into. Named outright by the instruction, like the five before them, and READ from that
249
- // ruling rather than inferred from any property these three share.
250
- //
251
- // ⚠ THEY GO HERE, IN THE TYPED HALF, AND NOT IN THE EXPORTED `string[]` BELOW. This array is
252
- // `readonly FieldType[]`, so a misspelling fails `tsc`; the exported set is `string[]` because
253
- // one PSEUDO-kind cannot be typed, and a name added there groups nothing and says nothing.
254
- "link", "rollup", "formula",
255
- ];
256
 
257
  /** The advanced set the picker groups on: the four real types above plus the geocode pseudo-kind,
258
  * which joins by VALUE because it cannot join by type. */
@@ -266,87 +241,6 @@ export const ADVANCED_CREATE_KINDS: readonly string[] = [...ADVANCED_FIELD_KINDS
266
  */
267
  export const ADVANCED_TYPES_HEADING = "Advanced";
268
 
269
- /**
270
- * ⭐⭐ W42-T37 (ruling R24) — THE PICKER'S PLAIN-LANGUAGE LINE, one per type, under its label.
271
- *
272
- * ⛔⛔ IT IS A CORRECTION, NOT POLISH, AND `rollup` IS WHY THE TABLE EXISTS. The owner chose to
273
- * KEEP the label "Rollup from another record", and that label is wrong twice: singular, where a
274
- * rollup folds MANY records, and false for the read-through mode, whose bag needs a topic, a
275
- * measure, a grouping and a matching column and NO LINK AT ALL. The label is settled, so this
276
- * line is the only place the truth gets told, and its entry must cover both modes or the type
277
- * still ships mis-described.
278
- *
279
- * ⚠ NO DASH OF ANY KIND IN ANY SENTENCE HERE (standing rule 2). Every one of these reaches a
280
- * screen, and a description is exactly where an em dash reads naturally; use a colon, a
281
- * semicolon, or two sentences.
282
- *
283
- * ⛔ IT LIVES HERE RATHER THAN BESIDE `TYPE_LABELS` for the reason this file's grouping helper
284
- * already gives: `iconShapes.ts` and `ColumnMenu.tsx` are not loadable by the node gates, and a
285
- * sentence no gate can read is a sentence that silently rots. `Record<..., string>` over the
286
- * whole picker vocabulary is what makes `tsc` the enforcer: a new kind with no description here
287
- * does not compile.
288
- */
289
- export const TYPE_DESCRIPTIONS: Record<
290
- FieldType | "measure" | "geocode" | "count" | "lookup",
291
- string
292
- > = {
293
- text: "Words typed in by hand: a name, a note, a reference.",
294
- status: "A workflow state chosen from a fixed list.",
295
- select: "One choice from a list you define.",
296
- multiselect: "Any number of choices from a list you define.",
297
- user: "The person a record belongs to.",
298
- int: "A whole number, with no decimals.",
299
- currency: "An amount of money, shown with its symbol.",
300
- pct: "A percentage, stored as the number people say out loud.",
301
- date: "A calendar date, with an optional time of day.",
302
- checkbox: "A yes or no box.",
303
- phone: "A phone number, dialable from the cell.",
304
- email: "An email address, ready to write to.",
305
- url: "A web address that opens in a new tab.",
306
- rating: "A score out of five, drawn as stars.",
307
- created_time: "When the record was first created. Filled in for you.",
308
- formula: "A value calculated from this row's other columns.",
309
- automation: "A value a scheduled job writes; nobody types into it.",
310
- metric: "A business number over a time window, computed at read time.",
311
- image: "A picture: uploaded here, or named from the catalog.",
312
- json: "A structured document such as an API response or a webhook body.",
313
- code: "A snippet of code, shown in the language you choose.",
314
- ai_enrich: "A value the assistant fills in from a prompt you write.",
315
- link: "Points at rows of another database, so this row can reach them.",
316
- // ⛔ BOTH MODES, IN ONE LINE, AND IT IS THE ONLY CORRECT DESCRIPTION OF THIS KIND ON SCREEN.
317
- rollup: "Folds MANY records into one number: the records this row links to, or a live topic "
318
- + "matched on a column of this database.",
319
- measure: "A business number this workspace already publishes, over a period you pick.",
320
- geocode: "Latitude and longitude, read from an address column of this database.",
321
- count: "How many records this row links to. A rollup, with the folding already chosen.",
322
- lookup: "Shows a column of the records this row links to. A rollup, with the folding already "
323
- + "chosen.",
324
- };
325
-
326
- /**
327
- * ⭐⭐ W42-T37 (D-497) — THE KINDS A `ut_*` DATABASE REFUSES, so the picker stops offering one.
328
- *
329
- * ⛔ THE SERVER IS RIGHT AND SO IS ITS GATE. `_created` is stamped by the connector modules and a
330
- * row of a runtime database never has one, so `user_tables.UT_FIELD_TYPES` leaves `created_time`
331
- * out on purpose and `verify_fields_contract.py` exempts it deliberately. The defect was on THIS
332
- * side: `ColumnMenu.FIELD_TYPES` maps `CREATABLE_TYPES` with no user-table filter, so the menu
333
- * offered a kind `_clean_field` then returns `None` for. The fix is to stop offering it, never to
334
- * teach the server the kind.
335
- *
336
- * ⛔ AND THIS IS A MIRROR WITH AN ENFORCER, NOT A SECOND OPINION. TypeScript cannot import the
337
- * server's set, so `verify_rollup_editor.py` holds this list to `CREATABLE_TYPES - UT_FIELD_TYPES`
338
- * read from `user_tables` itself, with a server-side negative control that widens that set and
339
- * requires the leg to go red. A mirror nobody diffs is how the two ends drift
340
- * ([[limit-with-no-enforcer]]).
341
- */
342
- export const UT_UNSUPPORTED_CREATE_KINDS: readonly string[] = ["created_time"];
343
-
344
- /** Whether a create-menu row may be offered on this surface. `isUserTable` is the `ut_*` runtime
345
- * database; every other grid is Odoo-backed and offers the whole vocabulary. */
346
- export function offerableCreateKind(value: string, isUserTable: boolean): boolean {
347
- return !isUserTable || !UT_UNSUPPORTED_CREATE_KINDS.includes(value);
348
- }
349
-
350
  /** A run of field-type picker rows under an optional heading. `heading: null` is the ordinary
351
  * group, deliberately unlabelled: naming the majority case is chrome nobody reads, and the
352
  * divider under it already says where the ordinary list ends. */
@@ -437,49 +331,14 @@ export function isPickType(t: FieldType): boolean {
437
  }
438
 
439
  /**
440
- * ⭐⭐ W42-T37 (contract C8b) — THE DECLARED OPTION CAP, CLIENT HALF.
441
- *
442
- * ⛔ THE NUMBER BELONGS TO THE WAVE CONTRACT, NOT TO THIS FILE AND NOT TO THE SERVER. The server
443
- * half (`core.user_tables`) pins the same integer independently, in its own lane, with its own
444
- * gate leg. There is deliberately NO cross-language grep between the two: a leg asserting this
445
- * literal against a Python symbol is red until the other lane merges, and a leg softened to
446
- * tolerate the symbol's absence passes when the two ends pick different numbers. So
447
- * `verify_rollup_editor.py` reads the integer out of `CONTRACTS.md` and compares it to this
448
- * declaration; the contract is the single source and each end answers to it separately.
449
- *
450
- * ⛔⛔ AND THE CAP IS REPORTED, NEVER SILENTLY APPLIED. This used to be a bare tail slice: paste
451
- * 300 statuses, save, and the column came back holding the first fifty with nothing said. That is
452
- * standing rule 1's second half exactly ("a limit that genuinely cannot be removed must be
453
- * REPORTED, with cause and a recommended fix, never silently enforced"), so raising the ceiling
454
- * without changing the behaviour would only have moved where the silence happened.
455
- */
456
- export const MAX_OPTIONS = 200;
457
-
458
- /**
459
- * What `parseOptions` hands back: the cleaned list, how many choices sit beyond the cap, and the
460
- * sentence to show when any do. `message` is `null` on the ordinary path, which is what the save
461
- * doors test.
462
- *
463
- * ⚠ `options` IS NOT TRUNCATED. The surplus is refused rather than dropped, so the list a person
464
- * typed is still the list they see while the message tells them what to remove; a truncated array
465
- * here would put the silence back one layer down.
466
- */
467
- export interface ParsedOptions {
468
- options: string[];
469
- refused: number;
470
- message: string | null;
471
- }
472
-
473
- /**
474
- * One choice per line, blanks dropped, duplicates collapsed, order preserved, and the declared
475
- * cap REFUSED rather than applied.
476
  * Case-INSENSITIVE dedupe: "Blocked" and "blocked" are one choice to a human, so the first
477
  * spelling wins rather than the column growing two pills that look like a typo.
478
  *
479
  * Lives here, not in ColumnMenu.tsx — a component file that also exports plain functions
480
  * breaks React fast refresh (the same reason counts.ts is its own module).
481
  */
482
- export function parseOptions(text: string): ParsedOptions {
483
  const seen = new Set<string>();
484
  const out: string[] = [];
485
  for (const raw of text.split("\n")) {
@@ -490,19 +349,7 @@ export function parseOptions(text: string): ParsedOptions {
490
  seen.add(k);
491
  out.push(v);
492
  }
493
- const refused = Math.max(0, out.length - MAX_OPTIONS);
494
- return {
495
- options: out,
496
- refused,
497
- // ⚠ THE COUNT IS IN THE SENTENCE, both of them: how many were given and how many may stay.
498
- // "Too many choices" is a refusal a person cannot act on.
499
- message: refused
500
- // ⚠ "this column", not "a select column": the same parser serves the multi select editor,
501
- // and a sentence that names the wrong kind is wrong for half the people who see it.
502
- ? `This list has ${out.length} choices and a column holds ${MAX_OPTIONS}. `
503
- + `Remove ${refused} of them, then save.`
504
- : null,
505
- };
506
  }
507
 
508
  /**
@@ -538,44 +385,7 @@ export function uniqueDisplayName(
538
  * condition on it reads as a fact about the customer. It still displays and still sorts.
539
  */
540
  export function filterableFields(fields: Field[]): Field[] {
541
- return offerableFields(fields).filter((f) => f.filterable !== false);
542
- }
543
-
544
- /**
545
- * ⭐⭐ WAVE-42 C11 — THE KEY OF THE ONE PRE-SET ROUTE PROJECTION COLUMN (W42-T20).
546
- *
547
- * The contract spells this literal so that neither end invents a name: the server serves ~64
548
- * `route_order` columns with `offerable: false`, and this ONE column, which lists every route a
549
- * record is on with its stop position, must pass THROUGH the same filter that withholds them.
550
- */
551
- export const ROUTE_PROJECTION_KEY = "routes";
552
-
553
- /**
554
- * ⭐⭐ WAVE-42 C11 — IS THIS FIELD OFFERED IN A FIELD PICKER?
555
- *
556
- * ⛔ PRESENTATION ONLY. Not a permission and not a deletion: the payload still carries every
557
- * withheld field, the grid still stores and renders it, and its own doors are untouched. What
558
- * this answers is whether a person is offered it in a list of columns to pick from.
559
- *
560
- * ⛔ THE FLAG IS OPTIONAL AND ABSENT MEANS OFFERABLE, deliberately, so that every field that
561
- * predates it and every stored fixture stays byte-identical. Only an explicit `false` withholds
562
- * (same reasoning as `colorCodeOptions` and C-A2's `strict?`); the alternative silently
563
- * reclassifies the whole existing field list.
564
- *
565
- * ⛔ THE PROJECTION COLUMN IS EXEMPT, IN CODE, NOT BY CONVENTION. C11's positive half is a
566
- * contract clause in its own right: withholding `routes` fails the ticket exactly as surely as
567
- * withholding nothing does. Reading that off the server's flag alone would make the positive
568
- * half depend on lane D never over-stamping the column it is itself minting, and there is no
569
- * client-side signal left to catch it if it does.
570
- */
571
- export function isOfferableField(field: Field): boolean {
572
- if (field.key === ROUTE_PROJECTION_KEY) return true;
573
- return field.offerable !== false;
574
- }
575
-
576
- /** C11 — the columns a field picker may offer. See `isOfferableField`. */
577
- export function offerableFields(fields: Field[]): Field[] {
578
- return fields.filter(isOfferableField);
579
  }
580
 
581
  /** Wave-5 item 10 — per-field display format. One optional bag; each type reads its half. */
@@ -2252,11 +2062,6 @@ export function directionLabel(t: FieldType, dir: "asc" | "desc"): string {
2252
  * "(empty)" group every other type uses.
2253
  */
2254
  export function isGroupableField(field: Field, lockedKey: string): boolean {
2255
- // C11 (W42-T54) — a withheld field is not offered in ANY field picker, and the group picker
2256
- // is one. Composed here rather than at the two call sites (this Toolbar's radio list and the
2257
- // column menu's "Group by this field") for the reason the note above already gives: two
2258
- // copies of a predicate drift.
2259
- if (!isOfferableField(field)) return false;
2260
  return (
2261
  field.type === "status" ||
2262
  field.type === "select" ||
@@ -2300,17 +2105,6 @@ export interface Field {
2300
  * reason (see `runPipeline`).
2301
  */
2302
  multi?: boolean;
2303
- /**
2304
- * ⭐⭐ WAVE-42 C11 — WHETHER ANY FIELD PICKER OFFERS THIS COLUMN. Absent or `true` means it
2305
- * does; an explicit `false` WITHHOLDS it. Served by `routes_customers.py` on every field of
2306
- * kind `route_order` (~64 of them on a 53-field grid, 99.4% blank), because a route is
2307
- * something you plan on a map, not something you pick out of a field list.
2308
- *
2309
- * ⛔ Presentation only: not a permission, not a deletion, and the payload still carries the
2310
- * field. Read it through `isOfferableField`, never directly, so the projection column's
2311
- * exemption travels with the question.
2312
- */
2313
- offerable?: boolean;
2314
  /** header pin hint from the API (unused in Inc 0) */
2315
  pinned?: boolean;
2316
  /** default-visible unless explicitly false */
@@ -2351,16 +2145,22 @@ export interface Field {
2351
  preset?: boolean;
2352
  /** Choices for a `select` / `multiselect` field. Ignored for every other type. */
2353
  options?: string[];
2354
- /** Stored default for a newly created row, in the field's wire vocabulary. */
2355
- defaultValue?: string | number | boolean | string[];
2356
- /** A user field accepts one person rather than a comma-joined set. */
2357
- single?: boolean;
2358
- /** A rating field's declared symbol. */
2359
- symbol?: string;
2360
- /** A checkbox field's declared mark. */
2361
- icon?: string;
2362
- /** A checkbox field's declared colour. */
2363
- color?: string;
 
 
 
 
 
 
2364
  /**
2365
  * Whether select-family choices render with coloured pills. Absent means true so legacy
2366
  * fields keep their existing appearance; an explicit false is the user's opt-out.
@@ -2609,48 +2409,6 @@ export interface Field {
2609
  reciprocal?: string;
2610
  /** Airtable's `prefersSingleRecordLink` */
2611
  single?: boolean;
2612
- /**
2613
- * W42-T35 — static conditions that narrow the records offered by an ordinary Link picker.
2614
- * They never rewrite existing link cells: a new filter constrains the next selection only.
2615
- */
2616
- conditions?: RollupCondition[];
2617
- conditionConj?: "and" | "or";
2618
- /**
2619
- * ⭐⭐ W42-T09 (R1, contract C1) — THE TWO-HOP JOIN, DECLARED. **Absent is today's one-hop
2620
- * link and is byte-identical to every link stored before the hop existed**, so there is no
2621
- * migration and no default: a bag that never carried a `via` still does not.
2622
- *
2623
- * A hop says *reach the target through a governed topic*: customers to products is two hops
2624
- * through `sales_lines`, and the naive one-hop join yields a column of nulls that reads as
2625
- * never sold. `topic` names the bridge; `source_dim` and `target_dim` are the bridge's own
2626
- * dimensions; `target_key` is the TARGET GRID's join column and `scope_key` is this cohort's
2627
- * scope — neither of those two is a dim, and both are required, because a bag missing
2628
- * `scope_key` loses every cohort leaf without a word.
2629
- *
2630
- * ⛔ DECLARED HERE, RE-DECLARED RATHER THAN IMPORTED, and that is deliberate. The editor's
2631
- * `HopViaBag` lives in `ColumnMenu.tsx`, which imports from this file; importing back would
2632
- * close a cycle. The two are STRUCTURALLY IDENTICAL key for key, which is what makes the
2633
- * editor's emitted bag assignable here with no cast and no adapter.
2634
- *
2635
- * ⚠ `window` IS A BARE `string`, ON PURPOSE. C1 spells whole history `"all"` and the live
2636
- * validator `core.user_tables.ROLLUP_SOURCE_WINDOWS` spells it `"all_time"`, which is what
2637
- * `ColumnMenu.HOP_WINDOW_ALL` emits. A literal union here would have to pick one and turn a
2638
- * known, unruled deviation into a compile error against the value actually shipped.
2639
- *
2640
- * ⛔ ONE HOP ONLY. There is no `via` inside a `via`: the server refuses a nested one whole,
2641
- * and `source_key` is deliberately absent from the bag rather than missing from it.
2642
- */
2643
- via?: {
2644
- topic: string;
2645
- source_dim: string;
2646
- target_dim: string;
2647
- target_key: string;
2648
- scope_key: string;
2649
- measure: string;
2650
- filter: FilterNode[];
2651
- filterConj: Conjunction;
2652
- window: string;
2653
- };
2654
  };
2655
  /**
2656
  * ⭐ 2026-08-07 — an AGGREGATE over the rows a `link` column resolves (Airtable's `rollup`).
@@ -2790,58 +2548,6 @@ export const ROLLUP_FNS = [
2790
  ] as const;
2791
  export type RollupFn = (typeof ROLLUP_FNS)[number];
2792
 
2793
- /**
2794
- * ⭐⭐ W42-T37 (`airtable-field-parity.md` G3) — COUNT AND LOOKUP, WHICH ARE MENU PRESETS OVER THE
2795
- * ROLLUP AND NOT NEW FIELD KINDS.
2796
- *
2797
- * ⛔⛔ THE DISTINCTION IS CONTRACT C8's AND IT IS NOT COSMETIC. A KIND is a member of five
2798
- * vocabularies at once (`FieldType`, `CREATABLE_TYPES`, `user_tables.UT_FIELD_TYPES`,
2799
- * `aios_grid.CUSTOM_FIELD_TYPES` and the shape/label tables) plus a cell renderer, and that
2800
- * landing cannot be split across tickets: wave 34 took `api_api` from 969/969 to 968/969 on a
2801
- * server half alone. Wave 42 ships no new kind. So neither name appears in any of those five
2802
- * lists; both save a `rollup` and both re-open as a rollup.
2803
- *
2804
- * ⭐ AND THE FEATURE IS DISCOVERABILITY, NOT CAPABILITY. Our rollup is already a strict superset
2805
- * of Airtable's fold (16 folds, rank-and-limit, sigma thresholds, a read-through source mode), so
2806
- * a person migrating searched the menu for "Count", found nothing, and concluded the product
2807
- * could not do the one thing it does best. These two rows are that search hitting.
2808
- */
2809
- export const ROLLUP_PRESETS = ["count", "lookup"] as const;
2810
- export type RollupPreset = (typeof ROLLUP_PRESETS)[number];
2811
-
2812
- /** The fold each preset fixes, so the editor can ask only what the preset still needs.
2813
- * `countall` counts linked RECORDS and takes no column; `arrayjoin` is the one fold whose result
2814
- * is the linked values themselves, which is what a lookup is. */
2815
- export const ROLLUP_PRESET_FNS: Record<RollupPreset, RollupFn> = {
2816
- count: "countall",
2817
- lookup: "arrayjoin",
2818
- };
2819
-
2820
- /**
2821
- * Which preset a stored bag IS, or `null` for a rollup that is simply a rollup.
2822
- *
2823
- * ⛔⛔ EXACT, NEVER "STARTS WITH". A bag that also carries a window, a de-duplication or either
2824
- * condition list is NOT a preset, and answering `"count"` for one would open it in the reduced
2825
- * editor with those controls hidden and their values still in the bag: configuration a person can
2826
- * no longer see, edit or remove. So every key outside the preset's own shape disqualifies it.
2827
- *
2828
- * ⚠ THIS IS ALSO THE ROUND-TRIP'S OWN READING. `_clean_rollup` rebuilds its output key by key and
2829
- * drops anything it does not know, so a preset bag survives it unchanged and comes back through
2830
- * this function as the same preset. `verify_rollup_editor.py` asserts exactly that composition.
2831
- */
2832
- export function rollupPresetOf(
2833
- bag: NonNullable<Field["rollup"]> | null | undefined
2834
- ): RollupPreset | null {
2835
- if (!bag || bag.source) return null;
2836
- const plain =
2837
- !bag.limit && !bag.sortBy && !bag.sortDir && !bag.distinctBy
2838
- && !(bag.where && bag.where.length) && !(bag.conditions && bag.conditions.length);
2839
- if (!plain || !bag.link) return null;
2840
- if (bag.fn === ROLLUP_PRESET_FNS.count && !bag.field) return "count";
2841
- if (bag.fn === ROLLUP_PRESET_FNS.lookup && !!bag.field) return "lookup";
2842
- return null;
2843
- }
2844
-
2845
  /** The rollup functions whose RESULT is a number — the render/align/sort family. */
2846
  export const ROLLUP_NUMERIC_FNS: ReadonlySet<string> =
2847
  new Set(["sum", "average", "stdev", "min", "max", "count", "counta", "countall"]);
@@ -3368,23 +3074,6 @@ export interface FilterRule {
3368
  id?: string;
3369
  }
3370
 
3371
- /**
3372
- * W42-T35 — the server validates a Link's static Rollup-style conditions, while the picker
3373
- * reuses the grid's existing filter engine. This adapter is the one vocabulary crossing; it
3374
- * cannot introduce a dynamic field, a set statistic, a view, a cohort, or a rank condition.
3375
- */
3376
- export function linkPickerFilterNodes(conditions: readonly RollupCondition[]): FilterRule[] {
3377
- return conditions.map((condition, index) => ({
3378
- id: `link-picker-${index}-${condition.field}`,
3379
- colId: condition.field,
3380
- op: condition.op === "not_contains" ? "doesNotContain"
3381
- : condition.op === "is_empty" ? "isEmpty"
3382
- : condition.op === "is_not_empty" ? "isNotEmpty"
3383
- : condition.op,
3384
- value: condition.value ?? "",
3385
- }));
3386
- }
3387
-
3388
  /**
3389
  * Is this rule doing any work? A half-typed condition is INACTIVE and gets IGNORED by the
3390
  * combinator — not treated as `true`, which under `or` would show every record.
@@ -3682,143 +3371,6 @@ export function filterTreeConj(tree: FilterTree | null | undefined): Conjunction
3682
  return tree?.conj === "or" ? "or" : "and";
3683
  }
3684
 
3685
- /* --- WAVE-42 R22 — route order sorts only where it means something ------------- */
3686
-
3687
- /**
3688
- * The one value `Field.kind` takes today (`routes_customers.ROUTE_KIND`). ⛔ READ, NEVER
3689
- * INFERRED FROM THE KEY: `route_` is a naming convention and the server says so in as many
3690
- * words. See `Field.kind`.
3691
- */
3692
- export const ROUTE_ORDER_KIND = "route_order";
3693
-
3694
- /**
3695
- * ⛔⛔ WAVE-42 R22 — WHY THIS IS A REFUSAL AND NOT A FALLBACK.
3696
- *
3697
- * A stop position is an ordinal INSIDE one route. Across two routes it is not a scale, and the
3698
- * projection column's cell is text (`Route A - 10, Route B - 2`), so the only thing an ordinary
3699
- * sort could do with it is compare strings: `Route A - 10` would land BEFORE `Route A - 2`. No
3700
- * numeric-aware comparator exists anywhere in this codebase (`useVisibleRows.ts`, `export.ts`,
3701
- * `folders.ts`), so there is nothing to fall back TO that would be correct, and a silent
3702
- * fallback is a wrong answer that looks like an answer.
3703
- *
3704
- * ⛔ NO EM DASH OR EN DASH (standing rule 2): two sentences, because the natural "because"
3705
- * clause here wants one.
3706
- */
3707
- export const ROUTE_SORT_REFUSAL_TEXT =
3708
- "Route order only means something inside one route. Filter this view to a single route, then sort by it.";
3709
-
3710
- /** Why a route-order sort was refused, or which route it is allowed inside. */
3711
- export type RouteSortVerdict =
3712
- | { ok: true; routeKey: string }
3713
- | { ok: false; reason: "no-route" | "many-routes" | "not-narrowing" };
3714
-
3715
- /**
3716
- * The ops on a route-order column that imply MEMBERSHIP of that route. A stop position is
3717
- * written only for a record that is ON the route, so any op asserting a value narrows to it.
3718
- *
3719
- * ⛔ `isEmpty` and `neq` are deliberately absent: "not on route A" is the whole rest of the
3720
- * world, which is the permissive direction the ticket names as the failure.
3721
- */
3722
- const ROUTE_MEMBERSHIP_OPS: ReadonlySet<string> = new Set([
3723
- "isNotEmpty", "eq", "gt", "gte", "lt", "lte", "between",
3724
- ]);
3725
-
3726
- /** C11/R20 — a per-route stop-position column, matched on the DECLARED kind. */
3727
- export function isRouteOrderField(field: Field): boolean {
3728
- return field.kind === ROUTE_ORDER_KIND;
3729
- }
3730
-
3731
- /** Does anything anywhere under this node condition a route column? Fail-closed helper. */
3732
- function nodeTouchesRoute(node: FilterNode, routeKeys: ReadonlySet<string>): boolean {
3733
- if (isFilterGroup(node)) {
3734
- return node.children.some((child) => nodeTouchesRoute(child, routeKeys));
3735
- }
3736
- return routeKeys.has(node.colId);
3737
- }
3738
-
3739
- /**
3740
- * ⭐⭐ WAVE-42 R22 — IS THIS VIEW NARROWED TO EXACTLY ONE ROUTE?
3741
- *
3742
- * PURE and EXPORTED on purpose: nothing in a lane may start a server, so the only way this
3743
- * decision is OBSERVED rather than asserted is a gate leg or a probe calling it directly.
3744
- *
3745
- * The boundary cases, each named, all failing CLOSED:
3746
- * - no filter at all, or no leaf on any route column -> `no-route`.
3747
- * - two or more route columns conditioned -> `many-routes`.
3748
- * - a route leaf inside a nested condition GROUP -> `not-narrowing`. A group carries its own
3749
- * conjunction and this walk does not evaluate filters; treating it as narrowing would be a
3750
- * guess in the permissive direction.
3751
- * - the ROOT list joined by `or` with more than one node -> `not-narrowing`, because anything
3752
- * ORed beside the route condition puts other routes' records back in.
3753
- * - a leaf on some other column entirely -> ignored. Under an `and` root it can only narrow
3754
- * further, and a narrower set is still inside the one route.
3755
- * - a route leaf whose op does not assert membership (`isEmpty`, `neq`) -> not counted, so the
3756
- * verdict falls through to `no-route`.
3757
- */
3758
- export function singleRouteScope(
3759
- tree: FilterTree | null | undefined,
3760
- fields: Field[],
3761
- ): RouteSortVerdict {
3762
- const routeKeys = new Set(fields.filter(isRouteOrderField).map((f) => f.key));
3763
- const nodes = filterTreeNodes(tree);
3764
- if (filterTreeConj(tree) === "or" && nodes.length > 1) {
3765
- return { ok: false, reason: "not-narrowing" };
3766
- }
3767
- const named = new Set<string>();
3768
- for (const node of nodes) {
3769
- if (isFilterGroup(node)) {
3770
- if (nodeTouchesRoute(node, routeKeys)) return { ok: false, reason: "not-narrowing" };
3771
- continue;
3772
- }
3773
- if (!routeKeys.has(node.colId)) continue;
3774
- if (!ROUTE_MEMBERSHIP_OPS.has(node.op)) continue;
3775
- named.add(node.colId);
3776
- }
3777
- if (named.size === 0) return { ok: false, reason: "no-route" };
3778
- if (named.size > 1) return { ok: false, reason: "many-routes" };
3779
- return { ok: true, routeKey: [...named][0] };
3780
- }
3781
-
3782
- /**
3783
- * R22 — the sentence to show, or `null` when this sort is allowed. Only the ONE projection
3784
- * column is judged; the per-route stop columns each hold a plain integer inside one route and
3785
- * sort correctly on their own.
3786
- */
3787
- export function routeSortRefusal(
3788
- colId: string,
3789
- tree: FilterTree | null | undefined,
3790
- fields: Field[],
3791
- ): string | null {
3792
- if (colId !== ROUTE_PROJECTION_KEY) return null;
3793
- return singleRouteScope(tree, fields).ok ? null : ROUTE_SORT_REFUSAL_TEXT;
3794
- }
3795
-
3796
- /**
3797
- * R22, the POSITIVE half — the stop position this record holds on ONE named route, read out of
3798
- * the projection cell (`Route A - 3, Route B - 7`), or `null` when the record is not on it.
3799
- *
3800
- * ⚠ The cell is CSV by contract (W42-T20 chose it so `groupRows`' `cell.split(",")` fans out),
3801
- * and the separator between name and position is a plain ASCII hyphen, so a route whose NAME
3802
- * contains one still resolves: the position is taken from the LAST separator in the entry.
3803
- *
3804
- * ⛔ EXPORTED WITH NO CALL SITE IN THIS LANE. Ordering the grid by it happens in
3805
- * `useVisibleRows.ts`, which is outside this ticket's fence. See the handoff.
3806
- */
3807
- export function routeStopPosition(cell: unknown, routeLabel: string): number | null {
3808
- if (typeof cell !== "string") return null;
3809
- const want = routeLabel.trim();
3810
- if (!want) return null;
3811
- for (const entry of cell.split(",")) {
3812
- const text = entry.trim();
3813
- const cut = text.lastIndexOf(" - ");
3814
- if (cut < 0) continue;
3815
- if (text.slice(0, cut).trim() !== want) continue;
3816
- const n = Number.parseInt(text.slice(cut + 3).trim(), 10);
3817
- if (Number.isFinite(n)) return n;
3818
- }
3819
- return null;
3820
- }
3821
-
3822
  export type RowHeightMode = "short" | "medium" | "tall";
3823
  export type ThemeMode = "light" | "dark";
3824
 
@@ -3853,6 +3405,8 @@ export interface ViewConfig {
3853
  /** Wave-6 item 11 — freeze the first N visible columns (host-clamped 1..8). Absent = 1,
3854
  * the locked identity column — every legacy view's behavior. */
3855
  frozenCount?: number;
 
 
3856
  /**
3857
  * Item 12 (contract C-LOCK, 2026-08-02) — this view is LOCKED to a cohort: the id of the
3858
  * set whose members are the only rows it can ever show.
@@ -3906,20 +3460,13 @@ export interface ViewConfig {
3906
  * the primary filter carried across. Absent = the ordinary view of its own table, which is
3907
  * every view saved before this wave (no migration, the `memberPids` precedent).
3908
  *
3909
- * ⭐⭐ **THE ROUND TRIP IS CLOSED — CORRECTED 2026-08-25 (W42-T09).** The note here used to
3910
- * say the server half was "not in this wave" and that a pivot rendered but did not persist.
3911
- * That was true when it was written and is false now: `grid_events.py::handle_one` names
3912
- * `secondaryView` in the `view_upsert` allowlist and runs it through `_clean_secondary_view`,
3913
- * so the key survives the write as well as the read.
3914
- *
3915
- * ⛔ THE STALE HALF IS THE DANGEROUS HALF, which is why it is corrected rather than deleted. A
3916
- * comment saying a feature does not persist is exactly what a later session greps before
3917
- * deciding a defect is already known, and it would have sent one hunting for a dropped write
3918
- * that no longer happens [[two-lanes-one-contract-dead-feature]].
3919
- *
3920
- * ⚠ The client half is unchanged and still carries its own weight: `normalizeConfig` spreads,
3921
- * so this key survives the read, and `sameConfig` is a whole-object compare, so it is picked
3922
- * up free. `cleanSecondaryView` below fails it closed on either half of the relation.
3923
  */
3924
  secondaryView?: SecondaryView;
3925
  }
@@ -4051,13 +3598,6 @@ export function cleanSecondaryView(raw: unknown): SecondaryView | undefined {
4051
  *
4052
  * ⚠ AN EMPTY LIST IS A TRUTHFUL ANSWER, not a failure: it means this table has no link field
4053
  * yet. The control says so rather than offering a pivot that cannot be resolved.
4054
- *
4055
- * ⭐⭐ W42-T09 (R1, C1) — A TWO-HOP LINK IS OFFERED HERE WITH NO CHANGE AT ALL, AND THAT IS THE
4056
- * FINDING, not an oversight. Eligibility is purely structural — `type === "link"` and a truthy
4057
- * `link.table` — so a field carrying `link.via` satisfies both tests exactly as a one-hop link
4058
- * does and joins the offer beside it. Adding a `via` branch here would be a SECOND opinion about
4059
- * what can be pivoted to, and the two would drift; the hop changes how the server RESOLVES the
4060
- * relation, never whether the relation exists. `Toolbar.tsx` renders this list unchanged.
4061
  */
4062
  export function relationalTargets(fields: Field[]): RelationalTarget[] {
4063
  const out: RelationalTarget[] = [];
@@ -4132,13 +3672,6 @@ export interface PivotResponse {
4132
  * ⚠ `filters` is the SOURCE view's tree, passed straight through. That is how the primary filter
4133
  * is carried across (owner instruction 23) and it is also T44's door: one record is one filter
4134
  * naming it, not a new request shape.
4135
- *
4136
- * ⛔⛔ W42-T09 — **`viaField` IS LOAD-BEARING NOW, NOT ADVISORY.** It has always been sent, and
4137
- * until the hop existed the server could resolve the relation from `source` and `target` alone,
4138
- * so dropping it would have cost nothing visible. It cannot be dropped any more: a link field
4139
- * carrying a `via` is the ONLY thing that says which governed topic to travel through, and the
4140
- * server reads that bag off the field this key names. Two link columns may point at the same
4141
- * target through different topics, so `target` no longer identifies the relation on its own.
4142
  */
4143
  export function buildPivotRequest(
4144
  source: string,
@@ -4200,65 +3733,6 @@ export function pivotResponse(body: unknown): PivotResponse | null {
4200
  };
4201
  }
4202
 
4203
- /**
4204
- * ⭐⭐ W42-T09 — READ THE SERVER'S OWN REASON OFF A NON-2xx BODY, or answer `null`.
4205
- *
4206
- * ⛔⛔ THE DEFECT THIS CLOSES, AND IT IS HALF OF WHY D-484 READ AS "NOTHING WORKS". The grid's
4207
- * pivot fetch collapsed **every** non-2xx into `absent` and printed one generic sentence, so a
4208
- * server that had walled the reader out, refused the route, or found more related records than
4209
- * one answer can carry was indistinguishable on screen from a feature that had never been built.
4210
- * The server authored a reason every time and nobody read it.
4211
- *
4212
- * ⛔ IT IS THE SERVER'S WORDS OR NOTHING. `null` means the body carries no usable reason at all
4213
- * (an HTML error page, a proxy, a session redirect), and the caller then falls back to the
4214
- * generic "not available yet" line — which stays TRUE for exactly that case. Authoring a
4215
- * sentence here instead would make this client guess at a wall it did not hit, which is the rule
4216
- * `PivotRefusal` has carried since W41-T43.
4217
- *
4218
- * ⚠ EVERY SPELLING THE ANSWER CAN ARRIVE IN IS READ, because three of them are live at once and
4219
- * the ticket named a fourth. In order:
4220
- * • `refusal: {reason, subject}` — C10's own channel, if a refusal ever rides a non-2xx;
4221
- * • `error: {message, code}` — X2, THE shape this app's `main.py::_error_shape` returns for
4222
- * every non-2xx (`deps.err` raises the detail and the handler unwraps it), so this is the
4223
- * arm that actually fires today for `no_pivot_route`, `pivot_unavailable`, `pivot_truncated`
4224
- * and `forbidden`. Its `code` is NOT carried onto the screen — see the clause at that arm;
4225
- * • bare `reason` / `detail` / `message`, with `subject` beside it — FastAPI's own unwrapped
4226
- * `detail` and the two keys the ticket named.
4227
- * The subject is only ever a NAME the reader can go and ask for, never a machine code and never
4228
- * a second authored sentence.
4229
- */
4230
- export function pivotRefusalFromBody(body: unknown): PivotRefusal | null {
4231
- if (!body || typeof body !== "object" || Array.isArray(body)) return null;
4232
- const b = body as Record<string, unknown>;
4233
- const text = (v: unknown): string => (typeof v === "string" ? v.trim() : "");
4234
-
4235
- const nested = b.refusal;
4236
- if (nested && typeof nested === "object" && !Array.isArray(nested)) {
4237
- const r = nested as Record<string, unknown>;
4238
- if (text(r.reason)) return { reason: text(r.reason), subject: text(r.subject) };
4239
- }
4240
- const wrapped = b.error;
4241
- if (wrapped && typeof wrapped === "object" && !Array.isArray(wrapped)) {
4242
- const e = wrapped as Record<string, unknown>;
4243
- /* ⛔ THE `code` IS DELIBERATELY NOT CARRIED INTO `subject`, and this is a copy decision, not
4244
- an oversight. The renderer prints `${subject}: ${reason}`, and `subject` has only ever held
4245
- a DATABASE NAME there ("product_data: you may not open this database"). X2's `code` is a
4246
- snake_case machine token, so carrying it would put "no_pivot_route: there is no declared
4247
- way…" on a user's screen — developer vocabulary in the one sentence a walled-out reader
4248
- gets, against DESIGN.md §2's sentence case and §4's "say what stopped it and what to do".
4249
- Every message `routes_grid` authors already names its own subject inside the sentence, so
4250
- nothing actionable is lost. The code stays in the response for anyone reading the network
4251
- tab, which is where a machine token belongs. */
4252
- if (text(e.message)) return { reason: text(e.message), subject: "" };
4253
- }
4254
- /* ⚠ `detail` is read as a STRING ONLY. FastAPI hands back whatever was raised, and this app
4255
- raises a DICT — already handled by the `error` arm above — so an object here is a shape
4256
- nobody declared and stating it would print `[object Object]` at a reader. */
4257
- const flat = text(b.reason) || text(b.detail) || text(b.message);
4258
- if (flat) return { reason: flat, subject: text(b.subject) };
4259
- return null;
4260
- }
4261
-
4262
  /**
4263
  * wave17 R1 / contract C-LOCKV — **`"locked"` joins the vocabulary, and it is the whole of the
4264
  * client's model of a locked view.**
 
102
  /** What `_ai_<colId>` can say. `empty` is never stamped: an absent key IS empty. */
103
  export type AiCellState = "agent" | "human" | "stale" | "error";
104
 
105
+ export type FieldSource = "odoo" | "overlay";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
  /**
108
  * R13 — the languages a `code` column may declare. Mirrors `aios_grid.CODE_LANGUAGES`
 
227
  * asymmetry is honest rather than an oversight, and it is the reason the exported set below is
228
  * `string[]` while its first half is not.
229
  */
230
+ const ADVANCED_FIELD_KINDS: readonly FieldType[] = ["automation", "json", "code", "ai_enrich"];
 
 
 
 
 
 
 
 
 
 
 
231
 
232
  /** The advanced set the picker groups on: the four real types above plus the geocode pseudo-kind,
233
  * which joins by VALUE because it cannot join by type. */
 
241
  */
242
  export const ADVANCED_TYPES_HEADING = "Advanced";
243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  /** A run of field-type picker rows under an optional heading. `heading: null` is the ordinary
245
  * group, deliberately unlabelled: naming the majority case is chrome nobody reads, and the
246
  * divider under it already says where the ordinary list ends. */
 
331
  }
332
 
333
  /**
334
+ * One choice per line, blanks dropped, duplicates collapsed, order preserved, capped at 50.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
  * Case-INSENSITIVE dedupe: "Blocked" and "blocked" are one choice to a human, so the first
336
  * spelling wins rather than the column growing two pills that look like a typo.
337
  *
338
  * Lives here, not in ColumnMenu.tsx — a component file that also exports plain functions
339
  * breaks React fast refresh (the same reason counts.ts is its own module).
340
  */
341
+ export function parseOptions(text: string): string[] {
342
  const seen = new Set<string>();
343
  const out: string[] = [];
344
  for (const raw of text.split("\n")) {
 
349
  seen.add(k);
350
  out.push(v);
351
  }
352
+ return out.slice(0, 50);
 
 
 
 
 
 
 
 
 
 
 
 
353
  }
354
 
355
  /**
 
385
  * condition on it reads as a fact about the customer. It still displays and still sorts.
386
  */
387
  export function filterableFields(fields: Field[]): Field[] {
388
+ return fields.filter((f) => f.filterable !== false);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
  }
390
 
391
  /** Wave-5 item 10 — per-field display format. One optional bag; each type reads its half. */
 
2062
  * "(empty)" group every other type uses.
2063
  */
2064
  export function isGroupableField(field: Field, lockedKey: string): boolean {
 
 
 
 
 
2065
  return (
2066
  field.type === "status" ||
2067
  field.type === "select" ||
 
2105
  * reason (see `runPipeline`).
2106
  */
2107
  multi?: boolean;
 
 
 
 
 
 
 
 
 
 
 
2108
  /** header pin hint from the API (unused in Inc 0) */
2109
  pinned?: boolean;
2110
  /** default-visible unless explicitly false */
 
2145
  preset?: boolean;
2146
  /** Choices for a `select` / `multiselect` field. Ignored for every other type. */
2147
  options?: string[];
2148
+ /**
2149
+ * Calendar recurrence belongs to the DATE FIELD definition, not to a browser-only picker.
2150
+ * The host may add calendar-specific keys over time; this small, forward-compatible core is
2151
+ * enough for the editor to describe the next occurrence without inventing a second cell value.
2152
+ */
2153
+ recurrence?: {
2154
+ frequency?: "none" | "daily" | "weekly" | "monthly" | "yearly";
2155
+ interval?: number;
2156
+ weekdays?: number[];
2157
+ skipHolidays?: boolean;
2158
+ holidayCalendar?: "us";
2159
+ /** Server-computed next dates win over the browser preview when supplied. */
2160
+ preview?: string[];
2161
+ };
2162
+ /** The server-authoritative next date for a recurring Date field. */
2163
+ nextDate?: string;
2164
  /**
2165
  * Whether select-family choices render with coloured pills. Absent means true so legacy
2166
  * fields keep their existing appearance; an explicit false is the user's opt-out.
 
2409
  reciprocal?: string;
2410
  /** Airtable's `prefersSingleRecordLink` */
2411
  single?: boolean;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2412
  };
2413
  /**
2414
  * ⭐ 2026-08-07 — an AGGREGATE over the rows a `link` column resolves (Airtable's `rollup`).
 
2548
  ] as const;
2549
  export type RollupFn = (typeof ROLLUP_FNS)[number];
2550
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2551
  /** The rollup functions whose RESULT is a number — the render/align/sort family. */
2552
  export const ROLLUP_NUMERIC_FNS: ReadonlySet<string> =
2553
  new Set(["sum", "average", "stdev", "min", "max", "count", "counta", "countall"]);
 
3074
  id?: string;
3075
  }
3076
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3077
  /**
3078
  * Is this rule doing any work? A half-typed condition is INACTIVE and gets IGNORED by the
3079
  * combinator — not treated as `true`, which under `or` would show every record.
 
3371
  return tree?.conj === "or" ? "or" : "and";
3372
  }
3373
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3374
  export type RowHeightMode = "short" | "medium" | "tall";
3375
  export type ThemeMode = "light" | "dark";
3376
 
 
3405
  /** Wave-6 item 11 — freeze the first N visible columns (host-clamped 1..8). Absent = 1,
3406
  * the locked identity column — every legacy view's behavior. */
3407
  frozenCount?: number;
3408
+ /** Per-view presentation state. False/absent is the ordinary saved layout. */
3409
+ fullscreen?: boolean;
3410
  /**
3411
  * Item 12 (contract C-LOCK, 2026-08-02) — this view is LOCKED to a cohort: the id of the
3412
  * set whose members are the only rows it can ever show.
 
3460
  * the primary filter carried across. Absent = the ordinary view of its own table, which is
3461
  * every view saved before this wave (no migration, the `memberPids` precedent).
3462
  *
3463
+ * ⛔ **THE CLIENT HALF OF C6 IS ONLY HALF THE ROUND TRIP, AND THE OTHER HALF IS NOT IN THIS
3464
+ * WAVE.** `normalizeConfig` spreads, so this key survives the read; `sameConfig` is a whole
3465
+ * object compare, so it is picked up free. But the SERVER rebuilds the stored config from a
3466
+ * name allowlist in `platform/core/grid_events.py::handle_one` (`kind == 'view_upsert'`), and
3467
+ * that literal's own comment says a key it does not name is silently dropped while the write
3468
+ * still answers 200. No wave-41 ticket names that file. Until one does, a pivot renders and
3469
+ * does not persist [[two-lanes-one-contract-dead-feature]].
 
 
 
 
 
 
 
3470
  */
3471
  secondaryView?: SecondaryView;
3472
  }
 
3598
  *
3599
  * ⚠ AN EMPTY LIST IS A TRUTHFUL ANSWER, not a failure: it means this table has no link field
3600
  * yet. The control says so rather than offering a pivot that cannot be resolved.
 
 
 
 
 
 
 
3601
  */
3602
  export function relationalTargets(fields: Field[]): RelationalTarget[] {
3603
  const out: RelationalTarget[] = [];
 
3672
  * ⚠ `filters` is the SOURCE view's tree, passed straight through. That is how the primary filter
3673
  * is carried across (owner instruction 23) and it is also T44's door: one record is one filter
3674
  * naming it, not a new request shape.
 
 
 
 
 
 
 
3675
  */
3676
  export function buildPivotRequest(
3677
  source: string,
 
3733
  };
3734
  }
3735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3736
  /**
3737
  * wave17 R1 / contract C-LOCKV — **`"locked"` joins the vocabulary, and it is the whole of the
3738
  * client's model of a locked view.**
web/src/customer-grid/useVisibleRows.ts CHANGED
@@ -23,8 +23,8 @@ import type {
23
  VisibleRow,
24
  } from "./types";
25
  import { FILTER_OPS, cohortIds, isCohortRule, isFilterGroup, isMeasureRule, isRankOp,
26
- isViewRule, normalizeViewOp, viewRuleId, ROUTE_PROJECTION_KEY, routeStopPosition,
27
- singleRouteScope, isRuleActive, normalizeCohortOp, rhsColId } from "./types";
28
  import { resolveAnchor, resolveWindow } from "./windows";
29
  import { computeAggs } from "./aggregations";
30
  import { NO_RANKING, hasRankLeaf, resolveRankLeaves, stripRankLeaves } from "./rankOps";
@@ -278,44 +278,6 @@ function cmpText(op: FilterRule["op"], a: string, v: string): boolean {
278
  * A group's own conjunction (`and`/`or`) combines only its ACTIVE children; a
279
  * group with no active children is itself inactive. This is what keeps a
280
  * half-built group from either zeroing the grid (`and`) or disabling it (`or`).
281
- *
282
- * ⭐⭐ W42-T27 — `ctx.strict` is the PERMISSION mode, and it is the exact mirror of
283
- * `platform/harness/filter_eval.py::_eval`'s `strict` parameter (wave 15). Read the two files
284
- * side by side: `ignore` below is that file's line 296, and EVERY `return ignore` here answers one
285
- * of its SEVEN — derive the list from the file (`grep -n "return ignore"`), never from a summary,
286
- * because two successive summaries of it were short:
287
- * `:313` group, no active children `:317` node is not an object at all
288
- * `:323` cohort leaf, inactive `:346` measure leaf, inactive
289
- * `:356` unknown colId `:361` unknown rhs col `:363` plain leaf, inactive
290
- * Every `null` this function would return becomes `false` instead, so a viewer who CANNOT RESOLVE
291
- * a leaf is narrowed by it rather than widened.
292
- *
293
- * ⚠ TS has EIGHT sites to Python's seven. The extra is the VIEW leaf's `!isRuleActive`, which has
294
- * no Python counterpart because `filter_eval.py` has no view branch at all — see that branch.
295
- *
296
- * ⛔ THE MIRROR MUST BE COMPLETE, AND A PARTIAL ONE LOOKS FINISHED. Converting only the group and
297
- * the three PLAIN-leaf sites leaves the cohort and measure `isRuleActive` guards returning
298
- * `null`, and then `and` [half-built cohort, state is FL] lets the plain leaf carry the group to
299
- * TRUE under strict — the receiver sees every FL row the wall meant to withhold, while
300
- * `filter_eval.permits` on the identical tree returns False. The two engines disagreeing under
301
- * strict destroys the parity this design rests on. A tree of ONLY inactive rules does not expose
302
- * it (the group site rescues those); it takes a MIXED tree, which is why the fixture pins one.
303
- *
304
- * ⛔ THE GROUP SITE IS LOAD-BEARING AND IS THE ONE THAT LOOKS OPTIONAL. With only the leaf sites
305
- * flipped, a tree whose single leaf is unresolvable already returns `false` — the leaf sets
306
- * `sawActive` and clears `allTrue` — so the obvious negative control passes without it. What it
307
- * does NOT cover is a tree of only genuinely-INACTIVE rules, an EMPTY group, or a nested group
308
- * whose children are all inactive: those still return `null`, and `matchFilterTree`'s
309
- * `v === null ? true : v` then shows EVERY row, with the flag reading as correct.
310
- *
311
- * ⚠ ONE site has no Python counterpart at all: the VIEW leaf's `!isRuleActive`. `filter_eval.py`
312
- * has no view branch (C4 is TS-only and postdates it), so it is decided from the principle and
313
- * the reasoning is written at the branch itself rather than left to be re-derived.
314
- *
315
- * ⚠ Everything a receiver cannot RESOLVE — a missing cohort, view, measure or rank set — already
316
- * returned `false` before this change, via its own `if (!set) return false`. Those leaves are
317
- * untouched here and stay refusals in BOTH modes; `strict` governs only the leaves that used to
318
- * stand aside.
319
  */
320
  function evalNode(
321
  node: FilterNode,
@@ -323,11 +285,6 @@ function evalNode(
323
  fieldByKey: Map<string, Field>,
324
  ctx?: EvalCtx
325
  ): boolean | null {
326
- // `filter_eval.py:296`. In DISPLAY mode this is literally `null`, which makes every `return
327
- // ignore` below a `return null` — so display semantics are byte-identical by CONSTRUCTION,
328
- // not by test.
329
- const ignore = ctx?.strict ? false : null;
330
-
331
  if (isFilterGroup(node)) {
332
  let sawActive = false;
333
  let allTrue = true;
@@ -339,30 +296,10 @@ function evalNode(
339
  allTrue = allTrue && v;
340
  anyTrue = anyTrue || v;
341
  }
342
- // `filter_eval.py:309-313`. A group with no active children is itself inactive. In strict
343
- // mode an empty or wholly-unanswerable permission group DENIES: a wall that evaluates to
344
- // "nothing to say" must not mean "let them through".
345
- if (!sawActive) return ignore;
346
  return node.conj === "or" ? anyTrue : allTrue;
347
  }
348
 
349
- // `filter_eval.py:317` — A NODE THAT IS NOT AN OBJECT AT ALL, and it is NOT unreachable on a
350
- // typing argument. Filter trees are STORED JSON, so this is a runtime shape rather than a
351
- // type-system impossibility: a truncated write, a hand-edited view or an older saved shape can
352
- // put `null` in a `children` array, and `{"conj":"and","children":[null]}` is valid JSON.
353
- //
354
- // ⛔ TODAY THAT THROWS, it does not merely diverge. `isFilterGroup` is null-safe
355
- // (`node != null && Array.isArray(...)`), but `isCohortRule` immediately below reads
356
- // `(node as FilterRule).colId` on the raw node — `null.colId` is a TypeError out of the render
357
- // path. Other non-objects (`42`, `"str"`) fall through harmlessly to the colId guard. So this
358
- // line converts a live crash into defined behaviour: display IGNORES the junk node, which is
359
- // what `filter_eval.matches` has always done, and strict DENIES it, because a node we cannot
360
- // even parse must not be a node we let the reader past.
361
- //
362
- // ⚠ This is the ONE place the change touches DISPLAY mode — from throwing to ignoring. A crash
363
- // is not a row set, so no fixture case can have covered it and nothing that passes today moves.
364
- if (node == null || typeof node !== "object") return ignore;
365
-
366
  // --- owner item 5: a COHORT leaf, also before the column lookup ------------------------
367
  // Same trap as the measure leaf below: `__cohort__` is not a column, so `fieldByKey.has`
368
  // would say INACTIVE, and inactive means every row on screen under a count nobody doubts.
@@ -370,12 +307,7 @@ function evalNode(
370
  // `is not` as well as for `is`. The host drops rules naming a cohort the user does not
371
  // have (see aios_grid.clean_filter_tree), so this is a backstop, not the behaviour.
372
  if (isCohortRule(node)) {
373
- // `filter_eval.py:322-323`. Under strict an INACTIVE cohort rule DENIES rather than standing
374
- // aside, and the case that forces it is a MIXED tree: `and` [half-built cohort, state is FL]
375
- // would otherwise let the plain leaf carry the group to TRUE, showing the receiver every FL
376
- // row the sharer's wall meant to withhold — the widening sin arriving through the leaf next
377
- // door. Display mode is unmoved: `ignore` is `null` there.
378
- if (!isRuleActive(node)) return ignore;
379
  // A SET of cohorts since 2026-07-27 (`is any of` / `is all of` / `is none of`). A single id
380
  // parses to a one-element list, so the shipped `is part of` is the same code path.
381
  const ids = cohortIds(node.value);
@@ -401,16 +333,7 @@ function evalNode(
401
  // names. `unresolvedConditions` counts the same case, so the toolbar's "Filter unresolved"
402
  // chip explains the empty table instead of leaving it a mystery (D-124's shape, one leaf over).
403
  if (isViewRule(node)) {
404
- // ⚠ NO PYTHON LINE TO MIRROR — `filter_eval.py` has no view branch at all (C4 is a TS-only
405
- // construct that postdates it), so this one is decided from the PRINCIPLE rather than the
406
- // table, and the reasoning is recorded here so the next reader does not read it as drift.
407
- // A view leaf is a MEMBERSHIP test, exactly like the cohort leaf above and the rank leaf
408
- // below: its unresolvable case already `return false`s, byte-for-byte the cohort posture.
409
- // Its INACTIVE case therefore belongs with its neighbours — leaving it `null` would make
410
- // `View is [nothing chosen] AND state is FL` behave differently under strict from
411
- // `Cohort is [nothing chosen] AND state is FL`, an asymmetry with no principle under it and
412
- // one no user could predict.
413
- if (!isRuleActive(node)) return ignore;
414
  const set = ctx?.viewSets?.[viewRuleId(node.value)];
415
  if (!set) return false;
416
  return normalizeViewOp(node.op) === "notInView" ? !set.has(r.pid) : set.has(r.pid);
@@ -426,18 +349,14 @@ function evalNode(
426
  // half-typed rule is inactive exactly as a column rule is. An ACTIVE rule with no set yet is
427
  // PENDING and matches NOTHING — never everything (see types.ts `Measure`).
428
  if (isMeasureRule(node)) {
429
- // `filter_eval.py:345-346` — same rule, same reason as the cohort leaf above.
430
- if (!isRuleActive(node)) return ignore;
431
  const set = node.id ? ctx?.measureSets?.[node.id] : undefined;
432
  if (!set) return false;
433
  return set.has(r.pid);
434
  }
435
 
436
  // leaf
437
- // `filter_eval.py:353-356` — THE LEAF THE `strict` FLAG EXISTS FOR. Display: ignore it, so a
438
- // view that outlived one of its columns still paints. Permission: DENY, so a shared view whose
439
- // filter names a field the RECEIVER cannot see shows fewer rows, never more.
440
- if (!fieldByKey.has(node.colId)) return ignore; // unknown column -> ignored (display) / denied (strict)
441
  // An rhs naming a column this table does not have is ignored for the SAME reason and by the
442
  // SAME rule as an unknown LEFT column — a condition whose comparand does not exist is not a
443
  // condition. Consistency here is the point: treating one side as "ignore" and the other as
@@ -447,10 +366,8 @@ function evalNode(
447
  // as a deleted column.
448
  // A STATISTIC names no column — it is server-resolved on a measure leaf, which was
449
  // handled above, so one reaching here is as unusable as a deleted column.
450
- // `filter_eval.py:357-361`
451
- if (node.rhs && !fieldByKey.has(rhsColId(node.rhs) ?? "")) return ignore;
452
- // `filter_eval.py:362-363`
453
- if (!isRuleActive(node)) return ignore;
454
 
455
  // --- C-OPS: a RANK leaf is a MEMBERSHIP test, like a cohort or a measure ------------------
456
  // The set was computed in a prior pass over the residue-filtered domain (see rankOps.ts),
@@ -534,19 +451,11 @@ export interface EvalCtx {
534
  * nothing anywhere says so. Supplying this map is what lets `unresolvedConditions` say it.
535
  * ⚠ OPTIONAL BY DESIGN. Absent = the old behaviour exactly, so every existing caller and every
536
  * stored fixture is byte-identical; the pipeline and the grid supply it.
537
- * ⚠ W42-T27 REWROTE THE SENTENCE THAT USED TO SIT HERE. It said this map is "deliberately NOT
538
- * used to change what `evalNode` RETURNS", because flipping these leaves to `false` would empty
539
- * every grid holding a view that outlived one of its columns. That worry was right and it is
540
- * exactly why the flip is CONDITIONAL rather than global: in DISPLAY mode (no `strict`) nothing
541
- * moved — an unresolvable leaf is still ignored, still counted here, and the deletion case still
542
- * paints. Under `strict` the same leaf DENIES. Two semantics, one evaluator; the difference
543
- * between them IS the security property.
544
  */
545
  fieldByKey?: Map<string, Field>;
546
- /** PERMISSION mode. Mirrors `platform/harness/filter_eval.py`'s `strict`: every `null` this
547
- * evaluator would return becomes `false` instead. Absent or false = today's DISPLAY semantics,
548
- * byte-identical. True = a viewer who may not resolve a leaf is NARROWED by it, never widened. */
549
- strict?: boolean;
550
  }
551
 
552
  /**
@@ -620,27 +529,25 @@ export function activeMeasureRuleIds(nodes: FilterNode[]): string[] {
620
  * Detectable without the field map: `within` and `dateMode` are shapes only a DATE condition
621
  * has, and `__cohort__` is a reserved key.
622
  */
623
- export function unresolvedConditionReasons(nodes: FilterNode[], ctx?: EvalCtx): string[] {
624
- const reasons: string[] = [];
625
  for (const node of nodes ?? []) {
626
  if (isFilterGroup(node)) {
627
- reasons.push(...unresolvedConditionReasons(node.children, ctx));
628
  continue;
629
  }
630
  if (!isRuleActive(node)) continue;
631
  if (isCohortRule(node)) {
632
  // Any unresolvable member of the set makes the whole condition unanswerable — the same
633
  // all-or-nothing rule evalNode applies, so the marker and the rows agree on WHY.
634
- const unavailable = cohortIds(node.value).find((id) => !ctx?.cohortSets?.[id]);
635
- if (unavailable) reasons.push(`The cohort "${unavailable}" used by this filter is unavailable.`);
636
  continue;
637
  }
638
  // C4 — a view leaf naming a view we cannot resolve (deleted, or not visible to this caller)
639
  // is unanswerable, so it is COUNTED and the toolbar says so. Without this line the grid would
640
  // empty with no explanation, which is D-124 exactly, arriving one leaf over.
641
  if (isViewRule(node)) {
642
- const viewId = viewRuleId(node.value);
643
- if (!ctx?.viewSets?.[viewId]) reasons.push(`The view "${viewId}" used by this filter is unavailable.`);
644
  continue;
645
  }
646
  // ⭐⭐ D-229 — a leaf whose COLUMN, or whose rhs COLUMN, this table no longer has. `evalNode`
@@ -650,27 +557,18 @@ export function unresolvedConditionReasons(nodes: FilterNode[], ctx?: EvalCtx):
650
  if (ctx?.fieldByKey && !isMeasureRule(node)) {
651
  const rhsKey = node.rhs ? rhsColId(node.rhs) ?? "" : null;
652
  if (!ctx.fieldByKey.has(node.colId) || (rhsKey !== null && !ctx.fieldByKey.has(rhsKey))) {
653
- const missing = !ctx.fieldByKey.has(node.colId) ? node.colId : rhsKey;
654
- reasons.push(`This filter uses the field "${missing}", which you cannot access.`);
655
  continue;
656
  }
657
  }
658
  if (isMeasureRule(node)) continue; // that is `pendingMeasures`' job
659
  if (node.op === "within") {
660
- if (!ctx?.today || !resolveWindow(node.dateWindow, ctx.today)) {
661
- reasons.push("This date-range condition cannot be resolved.");
662
- }
663
  } else if (node.dateMode) {
664
- if (!ctx?.today || resolveAnchor(node.dateMode, node.value, ctx.today) == null) {
665
- reasons.push("This date condition cannot be resolved.");
666
- }
667
  }
668
  }
669
- return reasons;
670
- }
671
-
672
- export function unresolvedConditions(nodes: FilterNode[], ctx?: EvalCtx): number {
673
- return unresolvedConditionReasons(nodes, ctx).length;
674
  }
675
 
676
  /** Root-level evaluation: the whole tree as one implicit group. Exported for
@@ -699,29 +597,9 @@ export function matchFilterTree(
699
  * numerics coerced to 0 and outranked real negatives. A blank is only a
700
  * tie-breaker skip, so later sort keys still decide between two blanks.
701
  */
702
- export function makeComparator(
703
- sorts: SortSpec,
704
- fieldByKey: Map<string, Field>,
705
- routeLabel?: string,
706
- ) {
707
  return (a: Row, b: Row): number => {
708
  for (const s of sorts) {
709
- // W42 R22: `routes` carries prose such as "North - 10, South - 2". It is not a
710
- // sortable text value. The pipeline supplies `routeLabel` only after it has proved that
711
- // the whole view is inside one named route; a stale stored sort otherwise becomes a
712
- // no-op here instead of a confident lexical wrong answer.
713
- if (s.colId === ROUTE_PROJECTION_KEY) {
714
- if (!routeLabel) continue;
715
- const av = routeStopPosition(a[s.colId], routeLabel);
716
- const bv = routeStopPosition(b[s.colId], routeLabel);
717
- const aBlank = av === null;
718
- const bBlank = bv === null;
719
- if (aBlank !== bBlank) return aBlank ? 1 : -1;
720
- if (aBlank && bBlank) continue;
721
- const c = (av ?? 0) - (bv ?? 0);
722
- if (c !== 0) return s.dir === "asc" ? c : -c;
723
- continue;
724
- }
725
  const f = fieldByKey.get(s.colId);
726
  const numeric = f ? isNumericType(f.type) : false;
727
  const av = a[s.colId];
@@ -992,26 +870,15 @@ export interface PipelineInput {
992
  /** The TENANT'S today, from the payload. Required by every relative-date condition and
993
  * never defaulted to the browser clock — see CustomersPayload.today. */
994
  today?: string;
995
- /**
996
- * ⭐⭐ W42-T27 — PERMISSION mode for this whole run. Forwarded verbatim onto `EvalCtx.strict`
997
- * (read its docstring for the semantics); absent or false = today's DISPLAY behaviour,
998
- * byte-identical.
999
- *
1000
- * ⛔ IT HAS TO LIVE HERE, and that is the point of the field existing. `runPipeline` builds its
1001
- * OWN `EvalCtx` below rather than accepting one, so a caller setting `strict` on some other ctx
1002
- * literal — the one `CustomerGrid` hands `unresolvedConditions`, say — would move a COUNT and
1003
- * not a single row: the flag reads as wired, the wall is open, and every gate stays green.
1004
- */
1005
- strict?: boolean;
1006
  }
1007
 
1008
  export function runPipeline(input: PipelineInput): VisibleRowsResult {
1009
  const {
1010
  rawRows, fields, filters, search, sorts, groupBy, collapsed,
1011
  memberPids = [], filterConj = "and", serverWindowed = false, measureSets,
1012
- cohortSets, viewSets, today, cohortLock, strict,
1013
  } = input;
1014
- const ctx: EvalCtx = { measureSets, cohortSets, today, viewSets, strict };
1015
 
1016
  let unresolvedRank = 0;
1017
 
@@ -1127,13 +994,7 @@ export function runPipeline(input: PipelineInput): VisibleRowsResult {
1127
  const q = search.trim().toLowerCase();
1128
  if (q) out = out.filter((r) => matchSearch(q, r, fields));
1129
 
1130
- // A route stop number is an ordinal only within one route. `singleRouteScope` is also the
1131
- // builder's refusal decision, so persisted sorts take the same fail-closed path as new ones.
1132
- // A missing label deliberately leaves the projection rule as a no-op; raw CSV text is never
1133
- // used as a fallback comparator.
1134
- const routeScope = singleRouteScope({ nodes: filters, conj: filterConj }, fields);
1135
- const routeLabel = routeScope.ok ? fieldByKey.get(routeScope.routeKey)?.label : undefined;
1136
- if (sorts.length) out = [...out].sort(makeComparator(sorts, fieldByKey, routeLabel));
1137
 
1138
  if (!groupBy) return asRows(out);
1139
 
@@ -1168,15 +1029,12 @@ export function useVisibleRows(
1168
  measureSets?: MeasureSets,
1169
  cohortSets?: CohortSets,
1170
  today?: string,
1171
- cohortLock?: string,
1172
- /** ⭐⭐ W42-T27 — PERMISSION mode; see `EvalCtx.strict` and `PipelineInput.strict`. LAST and
1173
- * OPTIONAL, so every existing call site is unchanged and defaults to DISPLAY semantics. */
1174
- strict?: boolean
1175
  ): VisibleRowsResult {
1176
  return useMemo(
1177
  () => runPipeline({ rawRows, fields, filters, search, sorts, groupBy, collapsed,
1178
  memberPids, filterConj, serverWindowed, measureSets,
1179
- cohortSets, today, cohortLock, strict }),
1180
  [rawRows, fields, filters, filterConj, search, sorts, groupBy, collapsed,
1181
- memberPids, serverWindowed, measureSets, cohortSets, today, cohortLock, strict]);
1182
  }
 
23
  VisibleRow,
24
  } from "./types";
25
  import { FILTER_OPS, cohortIds, isCohortRule, isFilterGroup, isMeasureRule, isRankOp,
26
+ isViewRule, normalizeViewOp, viewRuleId,
27
+ isRuleActive, normalizeCohortOp, rhsColId } from "./types";
28
  import { resolveAnchor, resolveWindow } from "./windows";
29
  import { computeAggs } from "./aggregations";
30
  import { NO_RANKING, hasRankLeaf, resolveRankLeaves, stripRankLeaves } from "./rankOps";
 
278
  * A group's own conjunction (`and`/`or`) combines only its ACTIVE children; a
279
  * group with no active children is itself inactive. This is what keeps a
280
  * half-built group from either zeroing the grid (`and`) or disabling it (`or`).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  */
282
  function evalNode(
283
  node: FilterNode,
 
285
  fieldByKey: Map<string, Field>,
286
  ctx?: EvalCtx
287
  ): boolean | null {
 
 
 
 
 
288
  if (isFilterGroup(node)) {
289
  let sawActive = false;
290
  let allTrue = true;
 
296
  allTrue = allTrue && v;
297
  anyTrue = anyTrue || v;
298
  }
299
+ if (!sawActive) return null;
 
 
 
300
  return node.conj === "or" ? anyTrue : allTrue;
301
  }
302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
  // --- owner item 5: a COHORT leaf, also before the column lookup ------------------------
304
  // Same trap as the measure leaf below: `__cohort__` is not a column, so `fieldByKey.has`
305
  // would say INACTIVE, and inactive means every row on screen under a count nobody doubts.
 
307
  // `is not` as well as for `is`. The host drops rules naming a cohort the user does not
308
  // have (see aios_grid.clean_filter_tree), so this is a backstop, not the behaviour.
309
  if (isCohortRule(node)) {
310
+ if (!isRuleActive(node)) return null;
 
 
 
 
 
311
  // A SET of cohorts since 2026-07-27 (`is any of` / `is all of` / `is none of`). A single id
312
  // parses to a one-element list, so the shipped `is part of` is the same code path.
313
  const ids = cohortIds(node.value);
 
333
  // names. `unresolvedConditions` counts the same case, so the toolbar's "Filter unresolved"
334
  // chip explains the empty table instead of leaving it a mystery (D-124's shape, one leaf over).
335
  if (isViewRule(node)) {
336
+ if (!isRuleActive(node)) return null;
 
 
 
 
 
 
 
 
 
337
  const set = ctx?.viewSets?.[viewRuleId(node.value)];
338
  if (!set) return false;
339
  return normalizeViewOp(node.op) === "notInView" ? !set.has(r.pid) : set.has(r.pid);
 
349
  // half-typed rule is inactive exactly as a column rule is. An ACTIVE rule with no set yet is
350
  // PENDING and matches NOTHING — never everything (see types.ts `Measure`).
351
  if (isMeasureRule(node)) {
352
+ if (!isRuleActive(node)) return null;
 
353
  const set = node.id ? ctx?.measureSets?.[node.id] : undefined;
354
  if (!set) return false;
355
  return set.has(r.pid);
356
  }
357
 
358
  // leaf
359
+ if (!fieldByKey.has(node.colId)) return null; // unknown column -> ignored
 
 
 
360
  // An rhs naming a column this table does not have is ignored for the SAME reason and by the
361
  // SAME rule as an unknown LEFT column — a condition whose comparand does not exist is not a
362
  // condition. Consistency here is the point: treating one side as "ignore" and the other as
 
366
  // as a deleted column.
367
  // A STATISTIC names no column — it is server-resolved on a measure leaf, which was
368
  // handled above, so one reaching here is as unusable as a deleted column.
369
+ if (node.rhs && !fieldByKey.has(rhsColId(node.rhs) ?? "")) return null;
370
+ if (!isRuleActive(node)) return null;
 
 
371
 
372
  // --- C-OPS: a RANK leaf is a MEMBERSHIP test, like a cohort or a measure ------------------
373
  // The set was computed in a prior pass over the residue-filtered domain (see rankOps.ts),
 
451
  * nothing anywhere says so. Supplying this map is what lets `unresolvedConditions` say it.
452
  * ⚠ OPTIONAL BY DESIGN. Absent = the old behaviour exactly, so every existing caller and every
453
  * stored fixture is byte-identical; the pipeline and the grid supply it.
454
+ * ⚠ And it is deliberately NOT used to change what `evalNode` RETURNS. Flipping these leaves to
455
+ * `false` would empty every grid holding a view that outlived one of its columns, which is a
456
+ * far larger and much worse behaviour change than the silence it would cure.
 
 
 
 
457
  */
458
  fieldByKey?: Map<string, Field>;
 
 
 
 
459
  }
460
 
461
  /**
 
529
  * Detectable without the field map: `within` and `dateMode` are shapes only a DATE condition
530
  * has, and `__cohort__` is a reserved key.
531
  */
532
+ export function unresolvedConditions(nodes: FilterNode[], ctx?: EvalCtx): number {
533
+ let n = 0;
534
  for (const node of nodes ?? []) {
535
  if (isFilterGroup(node)) {
536
+ n += unresolvedConditions(node.children, ctx);
537
  continue;
538
  }
539
  if (!isRuleActive(node)) continue;
540
  if (isCohortRule(node)) {
541
  // Any unresolvable member of the set makes the whole condition unanswerable — the same
542
  // all-or-nothing rule evalNode applies, so the marker and the rows agree on WHY.
543
+ if (cohortIds(node.value).some((id) => !ctx?.cohortSets?.[id])) n += 1;
 
544
  continue;
545
  }
546
  // C4 — a view leaf naming a view we cannot resolve (deleted, or not visible to this caller)
547
  // is unanswerable, so it is COUNTED and the toolbar says so. Without this line the grid would
548
  // empty with no explanation, which is D-124 exactly, arriving one leaf over.
549
  if (isViewRule(node)) {
550
+ if (!ctx?.viewSets?.[viewRuleId(node.value)]) n += 1;
 
551
  continue;
552
  }
553
  // ⭐⭐ D-229 — a leaf whose COLUMN, or whose rhs COLUMN, this table no longer has. `evalNode`
 
557
  if (ctx?.fieldByKey && !isMeasureRule(node)) {
558
  const rhsKey = node.rhs ? rhsColId(node.rhs) ?? "" : null;
559
  if (!ctx.fieldByKey.has(node.colId) || (rhsKey !== null && !ctx.fieldByKey.has(rhsKey))) {
560
+ n += 1;
 
561
  continue;
562
  }
563
  }
564
  if (isMeasureRule(node)) continue; // that is `pendingMeasures`' job
565
  if (node.op === "within") {
566
+ if (!ctx?.today || !resolveWindow(node.dateWindow, ctx.today)) n += 1;
 
 
567
  } else if (node.dateMode) {
568
+ if (!ctx?.today || resolveAnchor(node.dateMode, node.value, ctx.today) == null) n += 1;
 
 
569
  }
570
  }
571
+ return n;
 
 
 
 
572
  }
573
 
574
  /** Root-level evaluation: the whole tree as one implicit group. Exported for
 
597
  * numerics coerced to 0 and outranked real negatives. A blank is only a
598
  * tie-breaker skip, so later sort keys still decide between two blanks.
599
  */
600
+ export function makeComparator(sorts: SortSpec, fieldByKey: Map<string, Field>) {
 
 
 
 
601
  return (a: Row, b: Row): number => {
602
  for (const s of sorts) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603
  const f = fieldByKey.get(s.colId);
604
  const numeric = f ? isNumericType(f.type) : false;
605
  const av = a[s.colId];
 
870
  /** The TENANT'S today, from the payload. Required by every relative-date condition and
871
  * never defaulted to the browser clock — see CustomersPayload.today. */
872
  today?: string;
 
 
 
 
 
 
 
 
 
 
 
873
  }
874
 
875
  export function runPipeline(input: PipelineInput): VisibleRowsResult {
876
  const {
877
  rawRows, fields, filters, search, sorts, groupBy, collapsed,
878
  memberPids = [], filterConj = "and", serverWindowed = false, measureSets,
879
+ cohortSets, viewSets, today, cohortLock,
880
  } = input;
881
+ const ctx: EvalCtx = { measureSets, cohortSets, today, viewSets };
882
 
883
  let unresolvedRank = 0;
884
 
 
994
  const q = search.trim().toLowerCase();
995
  if (q) out = out.filter((r) => matchSearch(q, r, fields));
996
 
997
+ if (sorts.length) out = [...out].sort(makeComparator(sorts, fieldByKey));
 
 
 
 
 
 
998
 
999
  if (!groupBy) return asRows(out);
1000
 
 
1029
  measureSets?: MeasureSets,
1030
  cohortSets?: CohortSets,
1031
  today?: string,
1032
+ cohortLock?: string
 
 
 
1033
  ): VisibleRowsResult {
1034
  return useMemo(
1035
  () => runPipeline({ rawRows, fields, filters, search, sorts, groupBy, collapsed,
1036
  memberPids, filterConj, serverWindowed, measureSets,
1037
+ cohortSets, today, cohortLock }),
1038
  [rawRows, fields, filters, filterConj, search, sorts, groupBy, collapsed,
1039
+ memberPids, serverWindowed, measureSets, cohortSets, today, cohortLock]);
1040
  }
web/src/customer-grid/viewEcho.ts CHANGED
@@ -38,7 +38,7 @@
38
  // that re-associates the server's answers — never by position.
39
  // ---------------------------------------------------------------------------
40
 
41
- import type { FilterNode, FilterRule, GridFolder, SavedView } from "./types";
42
  import { isFilterGroup, isMeasureRule, isRuleActive } from "./types";
43
 
44
  /**
@@ -270,161 +270,3 @@ export function reconcileEchoView(
270
  },
271
  };
272
  }
273
-
274
- // ── WAVE 42 · T15 (contract C5): the workspace half of the views resolver ───────────────────
275
- //
276
- // ⭐⭐ WHY THIS IS SPLIT ACROSS TWO FILES. C5 asks for ONE named resolver answering "the views
277
- // and folders for THIS DATABASE KEY", called from outside `CustomerGrid`. Two questions hide in
278
- // that sentence, and they belong to two layers: which payload does a database key name (the
279
- // SHELL's question, answered by `shell/nav.ts::viewsForDb`), and what does a workspace-bearing
280
- // payload hold (the GRID's question, answered here). That is the same split T41 made for the
281
- // path model, where `folders.ts::levelAt` is the resolver and `nav.ts::navLevelAt` supplies the
282
- // one thing that genuinely differs.
283
- //
284
- // ⛔ IT READS, IT NEVER FETCHES. The page payload already carries `workspace.views` — the grid
285
- // reads exactly these two paths at `CustomerGrid.tsx:1516` (`payload.workspace?.views ?? []`)
286
- // and `:5159` (`payload?.workspace?.folders`). A second fetch from the shell would ask the
287
- // server for bytes the browser is already holding, and would answer at a different instant from
288
- // the grid rendering beside it.
289
- //
290
- // ⛔ WHAT THIS RETURNS IS THE PERSISTED LIST (wave 42, AMENDMENT A6). T15's done-when originally
291
- // said "the same list `CustomerGrid` renders"; that is unsatisfiable from a pure module, so A6
292
- // amended it to the persisted `SavedView[]` / `GridFolder[]` for the key, on condition that the
293
- // exclusions are NAMED here rather than left as a silent shortfall. They are:
294
- //
295
- // ⛔ THREE TRANSFORMS ARE DELIBERATELY NOT REPRODUCED, and none of them is reachable from a pure
296
- // module — they are one browser's localStorage layered onto a MOUNTED grid's state:
297
- // · the synthesized "All records" tab (`CustomerGrid.tsx::allRecordsView`, module-private and
298
- // therefore unimportable, and it needs the grid's resolved `fields`);
299
- // · `seedLocalViews` + the tombstone/`viewWrites` pruning that keeps an optimistic create alive;
300
- // · `reconcileFolders`' optimistic-create layer over `workspace.folders`.
301
- // What is returned is the HOST list — the same list the grid starts from, and the only one that
302
- // exists outside a mounted grid.
303
-
304
- /** The two lists a database's view rail is drawn from. Both ALWAYS present, `[]` when empty:
305
- * a key a consumer has to test for is a key a consumer forgets to test for. */
306
- export interface WorkspaceViews {
307
- views: SavedView[];
308
- folders: GridFolder[];
309
- }
310
-
311
- /**
312
- * The minimum shape this resolver reads. Structural on purpose rather than `CustomersPayload`:
313
- * the caller is the SHELL, which must be able to hand over whatever workspace-bearing object it
314
- * is holding without importing the grid's payload type.
315
- */
316
- export interface WorkspaceHolder {
317
- workspace?: { views?: SavedView[]; folders?: GridFolder[] } | null;
318
- }
319
-
320
- /**
321
- * One workspace-bearing payload to its rail lists. Nothing throws: an absent payload, an absent
322
- * `workspace`, an absent `views` and an absent `folders` are all legal shapes on this wire
323
- * (`GridWorkspace.folders` is documented as "Absent = no folders, the pre-wave-8 shape"), and
324
- * each answers `[]`. `Array.isArray` rather than `?? []` because a drifted host sending a
325
- * non-array must not be handed to a renderer that will call `.map` on it.
326
- */
327
- export function viewsOfWorkspace(payload: WorkspaceHolder | null | undefined): WorkspaceViews {
328
- const ws = payload?.workspace;
329
- return {
330
- views: Array.isArray(ws?.views) ? ws!.views : [],
331
- folders: Array.isArray(ws?.folders) ? ws!.folders : [],
332
- };
333
- }
334
-
335
- // ── WAVE 42 · T45 (ruling R12, contract C9): THE PATH IS WHERE I LEFT IT AFTER A RELOAD ──────
336
- //
337
- // R12.6 chose PER-BROWSER persistence of the rail's current folder over always resetting to the
338
- // top level, and over putting the path in the URL. The URL option was judged more useful and is
339
- // booked as O4; it is deliberately NOT built here.
340
- //
341
- // ⛔⛔ THIS FILE HOLDS THE PURE HALF ONLY, AND THE REASON IS A GATE, NOT AN AESTHETIC.
342
- // `verify_view_echo.py` compiles `_test/viewEcho.test.ts` and runs it under BARE NODE
343
- // (`subprocess.run(["node", str(built)], cwd=WEB)`) — no jsdom, no `window`, no `localStorage`,
344
- // and the test file installs no shim. So anything in here that touched `window` would be
345
- // UNTESTABLE BY ITS OWN GATE: under node both databases fall into the same `catch` and answer
346
- // identically, and "two databases keep separate positions" would go green over nothing.
347
- // Therefore the browser half — the hash read, `getItem`, `setItem`, `removeItem` — lives in
348
- // `ViewSidebar.tsx`, beside the `aios-views-rail` try/catch it already owns (`:762`/`:771`), and
349
- // what stays here is what node can execute and the gate can therefore prove:
350
- //
351
- // 1. `pathStorageKey` — TWO DIFFERENT DATABASE KEYS PRODUCE TWO DIFFERENT STORAGE KEYS. That
352
- // is the per-database clause in its node-runnable form, which is why it is exported.
353
- // 2. `resolveStoredPath` — THE STORED ID IS NEVER TRUSTED. A folder deleted by another session
354
- // (or by this account on another machine) leaves a stored id pointing at nothing. Restoring
355
- // it blind renders an empty list inside a folder that does not exist, with no way back
356
- // except a manual reset. So it is resolved against the live standable set on every read,
357
- // and anything that does not resolve falls back to the top level (`null`).
358
- //
359
- // ⚠ THE DEFENSIVE RULE THE OTHER HALF CARRIES, recorded here because this is where the reader
360
- // looks: in a private window, with site data cleared, or in a browser configured to block
361
- // storage, `window.localStorage` throws on PROPERTY ACCESS — not on `getItem`. So the usual
362
- // `typeof window !== "undefined" && window.localStorage` feature test IS the throwing
363
- // expression and must sit INSIDE the try. A nav that throws on mount is a blank shell.
364
- //
365
- // Absent, malformed, wrong type and empty string all mean THE TOP LEVEL. Never an error, never a
366
- // guess at some other folder.
367
-
368
- /** Namespace for the per-database stored path. Sibling of the rail's existing `aios-views-rail`
369
- * fold-state key, which is GLOBAL rather than per database and is not touched from here. */
370
- const VIEW_PATH_KEY_PREFIX = "aios-views-at";
371
-
372
- /**
373
- * The storage key this browser remembers ONE database's open folder under. Lower-case and
374
- * hyphenated like its `aios-views-rail` sibling, and STABLE: changing it silently forgets every
375
- * viewer's position.
376
- *
377
- * ⭐ EXPORTED SO THE GATE CAN PROVE THE PER-DATABASE CLAUSE. "Two databases keep separate
378
- * positions" reduces, without a browser, to `pathStorageKey(a) !== pathStorageKey(b)` — which is
379
- * the whole of that clause that a node process can observe, and the reason this string builder
380
- * is a named export rather than a template literal inlined at the call site.
381
- *
382
- * Total by construction: a non-string key degrades to the empty key rather than throwing, so an
383
- * unidentifiable route loses its memory instead of taking the rail down.
384
- */
385
- export function pathStorageKey(dbKey: string): string {
386
- return `${VIEW_PATH_KEY_PREFIX}-${typeof dbKey === "string" ? dbKey : ""}`;
387
- }
388
-
389
- /**
390
- * ⛔ THE CLAUSE THAT SHIPS BROKEN IF IT IS SKIPPED. Answers `stored` only when it is one of the
391
- * ids the caller says are STANDABLE RIGHT NOW, and `null` otherwise — so a folder deleted by
392
- * another session lands the viewer at that database's top level instead of inside a folder that
393
- * no longer exists.
394
- *
395
- * ⛔⛔ THE ARGUMENT IS A SET OF VALID IDS, NOT THE `GridFolder[]` LIST, AND THAT IS THE WHOLE
396
- * POINT. This module deliberately does not know what a valid destination is, because the rail
397
- * ALREADY has exactly one definition of it and a second one here is the drift contract C9 exists
398
- * to prevent. The existing definition is W42-T43's `ViewSidebar.tsx::atId`, which validates
399
- * against the rendered GROUPS rather than against `folders` — on purpose, because a SYNTHESISED
400
- * group ("Shared with me", and one per shared folder via `sharedFolderGroupId`) owns a head on
401
- * this rail while having NO record in the stored `folders` list. Validating a stored path
402
- * against `folders` would therefore call a live shared folder deleted and bounce the viewer
403
- * straight out of a folder they had just opened — the stale-path guard MISFIRING on a real
404
- * place, which reads to a user as "reload sometimes forgets where I was" and is close to
405
- * unreportable. So the caller passes the same standable set `atId` derives, and there is ONE
406
- * answer to "is this a place I can stand", not two.
407
- *
408
- * ⚠ ONE ID IS ENOUGH, ANCESTORS NEED NO WALK, and that is scouted rather than assumed: folder
409
- * delete does NOT cascade (`folders.ts:17-23` — `folder_delete` moves contents to the top level
410
- * instead), and `folders.ts::folderNesting` re-roots any `parent` pointing at an unknown id to
411
- * `null`. So a folder whose ancestor was deleted is still a real, standable place at the root,
412
- * and checking the leaf is checking the whole chain.
413
- *
414
- * Run on EVERY read, not once at mount: the standable set arrives and changes over a session's
415
- * life, and a path resolved against an earlier set is the same untrusted id one tick later.
416
- * Absent or drifted input answers the top level rather than throwing.
417
- */
418
- export function resolveStoredPath(
419
- stored: string | null | undefined,
420
- validIds: Iterable<string> | null | undefined
421
- ): string | null {
422
- if (typeof stored !== "string" || stored === "") return null;
423
- if (!validIds || typeof (validIds as Iterable<string>)[Symbol.iterator] !== "function") {
424
- return null;
425
- }
426
- for (const id of validIds) {
427
- if (id === stored) return stored;
428
- }
429
- return null;
430
- }
 
38
  // that re-associates the server's answers — never by position.
39
  // ---------------------------------------------------------------------------
40
 
41
+ import type { FilterNode, FilterRule, SavedView } from "./types";
42
  import { isFilterGroup, isMeasureRule, isRuleActive } from "./types";
43
 
44
  /**
 
270
  },
271
  };
272
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/customer-grid/viewModes.tsx CHANGED
@@ -106,23 +106,22 @@ function IconDayCells() {
106
  mode-independent: `<ViewSidebar>` renders under `!hideViews` and never consults `displayMode`,
107
  so it is reachable from Map exactly as it is from Grid. Verified before removal, not assumed. */
108
 
109
- /**
110
- * ⭐⭐ W42-T19 — CALENDAR'S THREE SUB-CONTROLS NO LONGER DESTRUCTURE HERE, and the props they used
111
- * deliberately STAY in the type below rather than being deleted with them. `CustomerGrid.tsx` is
112
- * another lane's file this wave and still passes all eight; narrowing the type would turn that
113
- * untouchable call site into a compile error. So the contract is unchanged and only the BODY moved
114
- * (to `CalendarSettings`). ⚠ `noUnusedLocals` is on, which is why the names come out of the
115
- * destructuring pattern instead of being left bound and unread.
116
- */
117
  export function ModeSwitch({
118
  mode,
119
  onMode,
120
  locked = false,
 
 
121
  stackField,
122
  stackChoices,
123
  onPickField,
124
  clamped = true,
125
  onClamp,
 
 
 
 
 
126
  }: {
127
  mode: DisplayMode;
128
  onMode: (m: DisplayMode) => void;
@@ -252,10 +251,15 @@ export function ModeSwitch({
252
  date field and a board without a stack field are not modes, so the picker is never
253
  in its placeholder state here unless the view names a field the table has lost —
254
  which it now SHOWS rather than silently replacing with the first choice. */}
255
- {/* ⛔ W42-T19 — the CALENDAR date-field button that stood here now lives in
256
- `CalendarSettings`, on the second row. The kanban one below stays: only Calendar was
257
- named by owner instruction 11, and moving Kanban's too would be a scope the owner did
258
- not ask for. */}
 
 
 
 
 
259
  {mode === "kanban" && stackChoices.length > 0 && (
260
  <FieldSelectButton
261
  className="cg-mode-field"
@@ -289,82 +293,6 @@ export function ModeSwitch({
289
  {clamped ? "Short cards" : "Full cards"}
290
  </button>
291
  )}
292
- {/* ⛔ W42-T19 — the Day cells records/summaries popover AND the summary-mode Totals picker
293
- that stood here now live in `CalendarSettings`, on the second row, beside the date-field
294
- button. Nothing calendar-only is left in `cg-modes`; what remains is the universal
295
- "View · mode" trigger plus Kanban's two controls. */}
296
- </span>
297
- );
298
- }
299
-
300
- /** Map-only settings live in their own row beneath the main Filter / Sort / Group navigation. */
301
- /**
302
- * ⭐⭐ WAVE 42 · W42-T19 (owner instruction 11) — CALENDAR'S OWN CONTROLS, ON THEIR OWN ROW.
303
- *
304
- * Owner: *"Under Calendar View, I see that the toggle navigation for Choose dates and
305
- * Records/Summaries still live at the same line as Filter/Sort/Group. Move this downward exactly
306
- * how Time-series and Map view has it."*
307
- *
308
- * ⛔ THIS COMPONENT LANDED EMPTY IN THE WAVE'S BASELINE COMMIT, AND THAT WAS THE WHOLE POINT. IT IS
309
- * NOW FILLED (lane D), and the mount was never touched. It was already MOUNTED in
310
- * `CustomerGrid.tsx` beside `MapSettings` under `displayMode === "calendar" && !pivotOn`, so the
311
- * lane that filled it never had to open that file. `CustomerGrid.tsx` is another lane's, and a
312
- * cross-lane mount is exactly how wave 41 shipped a whole feature that nothing ever rendered.
313
- *
314
- * ⛔ WHAT THE FILLING LANE MUST NOT DO, AND DID NOT: relocate the whole `modeControl` prop out of
315
- * `<Toolbar>`.
316
- * `ModeSwitch` bundles the UNIVERSAL "View · mode" trigger together with Calendar's sub-controls in
317
- * one `<span className="cg-modes">`, so moving the lot deletes the mode switcher from row one for
318
- * EVERY view, not just Calendar. Extract only the three `mode === "calendar"` blocks: the date
319
- * field button, the `Day cells` records/summary toggle, and the summary-mode totals picker.
320
- *
321
- * ⭐ COPY MAP'S MECHANISM, NOT TIME-SERIES'. `MapSettings` is a sibling of `<Toolbar>` in
322
- * `CustomerGrid.tsx`, rendered after it and before `.cg-grid-box`. `TimeSeriesPanel`'s `.cg-ts-bar`
323
- * only LOOKS the same: it lives inside the view component and mounts inside `.cg-grid-box`.
324
- *
325
- * ⚠ AND SAY THIS OUT LOUD WHEN IT LANDS, because it is a behaviour change rather than a move:
326
- * leaving `.cg-toolbar` leaves the `cgtoolbar` container query, so these controls stop collapsing
327
- * to icons at 1080px and 480px. `.cg-map-settings` never had that collapse, so this matches Map.
328
- */
329
- export function CalendarSettings({
330
- dateField,
331
- dateChoices,
332
- onPickField,
333
- calendarMode = "records",
334
- onCalendarMode,
335
- calendarMetrics = [],
336
- metricChoices = [],
337
- onCalendarMetrics,
338
- }: {
339
- dateField?: Field;
340
- dateChoices: Field[];
341
- onPickField: (k: "dateField" | "stackField", key: string) => void;
342
- calendarMode?: "records" | "summary";
343
- onCalendarMode?: (next: "records" | "summary") => void;
344
- calendarMetrics?: { id: string; field: string; agg: string }[];
345
- metricChoices?: Field[];
346
- onCalendarMetrics?: (next: { id: string; field: string; agg: string }[]) => void;
347
- }) {
348
- /* ⚠ The HOST already guards on `displayMode === "calendar" && !pivotOn`, so there is no mode
349
- test in here: repeating it would be a second place to get the condition wrong. What is kept is
350
- each control's OWN precondition, unchanged from where it used to live in `ModeSwitch`. */
351
- if (dateChoices.length === 0 && !onCalendarMode) return null;
352
- return (
353
- <div className="cg-cal-settings" aria-label="Calendar settings">
354
- <span className="cg-cal-settings-label">Calendar</span>
355
- {/* Item 20 (C-FLDSEL) — the date picker wears the type mark, same control as the filter and
356
- sort rows. It has no "none" state: a calendar without a date field is not a mode, so the
357
- picker sits in its placeholder state only when the view names a field the table has lost,
358
- which it now SHOWS rather than silently replacing with the first choice. */}
359
- {dateChoices.length > 0 && (
360
- <FieldSelectButton
361
- className="cg-mode-field"
362
- ariaLabel="Calendar date field"
363
- value={dateField?.key}
364
- onChange={(key) => onPickField("dateField", key)}
365
- fields={dateChoices.map((f) => ({ key: f.key, label: f.label, type: f.type }))}
366
- />
367
- )}
368
  {/* Owner item 4 (C-DISP) — records vs summaries.
369
  wave17 owner item 8 — it WAS a bare toggle whose label was its own state, sitting in a
370
  bar where every other control opens a panel. Two things were wrong with that beyond
@@ -375,7 +303,7 @@ export function CalendarSettings({
375
  A `Popover` with radio rows fixes both — the trigger keeps ONE name and both choices
376
  are visible with the current one marked — and it is the same component Filter / Sort /
377
  Group / Totals mount, which is what item 8 asks for. */}
378
- {onCalendarMode && (
379
  <Popover
380
  label={`Day cells · ${calendarMode === "summary" ? "Summaries" : "Records"}`}
381
  icon={<IconDayCells />}
@@ -422,7 +350,7 @@ export function CalendarSettings({
422
  the feature would be half-delivered.
423
 
424
  Only shown in summary mode: a picker for a thing that is not on screen is noise. */}
425
- {calendarMode === "summary" && onCalendarMetrics && (
426
  <Popover
427
  label={`Totals · ${calendarMetrics.length + 1}`}
428
  icon={<ModeIcon mode="chart" />}
@@ -492,11 +420,52 @@ export function CalendarSettings({
492
  )}
493
  </Popover>
494
  )}
495
-
496
- </div>
497
  );
498
  }
499
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
500
  export function MapSettings({
501
  coordField,
502
  coordChoices,
@@ -518,27 +487,7 @@ export function MapSettings({
518
  selectedCount: number;
519
  onToggleRoute: () => void;
520
  }) {
521
- /**
522
- * ⭐⭐ W42-T24 (instruction 10) — THE ROW NO LONGER SELF-HIDES, and that is the whole
523
- * reachability half of the route navigation.
524
- *
525
- * The old guard returned null on a database with no coordinate or size columns and nothing
526
- * selected. That was right while the Route button opened a PLANNER, which needs stops to plan
527
- * over; it is wrong now that the button opens a NAVIGATION, whose entire job is to list routes
528
- * a colleague already saved. A rep opening the map to drive somebody else's Monday has nothing
529
- * selected by definition, so the old guard hid the control precisely when it was needed.
530
- *
531
- * ⚠ THE ROW IS NEVER EMPTY, so nothing is traded away: the Route toggle below renders
532
- * unconditionally, and it was the only reason the guard's other two clauses were ever checked.
533
- *
534
- * ⛔ WHERE THIS RAIL LIVES WHEN THE VIEW IS NOT MAP: IT DOES NOT, DELIBERATELY.
535
- * Opening a route SELECTS records and DRAWS a sequence, and neither has a referent on a grid,
536
- * a calendar or a kanban board; a listing whose one-click action could not do the thing it
537
- * names would be a menu of dead rows. A route's non-map identity is a COLUMN of visit numbers,
538
- * and that is already reachable in every display mode through the grid's own column header
539
- * menu, which is where its share dialog lives too. So the navigation is Map's, the column is
540
- * everywhere, and neither is a copy of the other.
541
- */
542
  return (
543
  <div className="cg-map-settings" aria-label="Map settings">
544
  <span className="cg-map-settings-label">Map</span>
@@ -548,7 +497,7 @@ export function MapSettings({
548
  aria-expanded={routeOpen}
549
  aria-controls="cg-route-popover"
550
  onClick={onToggleRoute}
551
- title="Show or hide the route navigation and planner"
552
  >
553
  Route{selectedCount >= 2 ? ` · ${selectedCount} selected` : ""}
554
  </button>
 
106
  mode-independent: `<ViewSidebar>` renders under `!hideViews` and never consults `displayMode`,
107
  so it is reachable from Map exactly as it is from Grid. Verified before removal, not assumed. */
108
 
 
 
 
 
 
 
 
 
109
  export function ModeSwitch({
110
  mode,
111
  onMode,
112
  locked = false,
113
+ dateField,
114
+ dateChoices,
115
  stackField,
116
  stackChoices,
117
  onPickField,
118
  clamped = true,
119
  onClamp,
120
+ calendarMode = "records",
121
+ onCalendarMode,
122
+ calendarMetrics = [],
123
+ metricChoices = [],
124
+ onCalendarMetrics,
125
  }: {
126
  mode: DisplayMode;
127
  onMode: (m: DisplayMode) => void;
 
251
  date field and a board without a stack field are not modes, so the picker is never
252
  in its placeholder state here unless the view names a field the table has lost —
253
  which it now SHOWS rather than silently replacing with the first choice. */}
254
+ {mode === "calendar" && dateChoices.length > 0 && (
255
+ <FieldSelectButton
256
+ className="cg-mode-field"
257
+ ariaLabel="Calendar date field"
258
+ value={dateField?.key}
259
+ onChange={(key) => onPickField("dateField", key)}
260
+ fields={dateChoices.map((f) => ({ key: f.key, label: f.label, type: f.type }))}
261
+ />
262
+ )}
263
  {mode === "kanban" && stackChoices.length > 0 && (
264
  <FieldSelectButton
265
  className="cg-mode-field"
 
293
  {clamped ? "Short cards" : "Full cards"}
294
  </button>
295
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
  {/* Owner item 4 (C-DISP) — records vs summaries.
297
  wave17 owner item 8 — it WAS a bare toggle whose label was its own state, sitting in a
298
  bar where every other control opens a panel. Two things were wrong with that beyond
 
303
  A `Popover` with radio rows fixes both — the trigger keeps ONE name and both choices
304
  are visible with the current one marked — and it is the same component Filter / Sort /
305
  Group / Totals mount, which is what item 8 asks for. */}
306
+ {mode === "calendar" && onCalendarMode && (
307
  <Popover
308
  label={`Day cells · ${calendarMode === "summary" ? "Summaries" : "Records"}`}
309
  icon={<IconDayCells />}
 
350
  the feature would be half-delivered.
351
 
352
  Only shown in summary mode: a picker for a thing that is not on screen is noise. */}
353
+ {mode === "calendar" && calendarMode === "summary" && onCalendarMetrics && (
354
  <Popover
355
  label={`Totals · ${calendarMetrics.length + 1}`}
356
  icon={<ModeIcon mode="chart" />}
 
420
  )}
421
  </Popover>
422
  )}
423
+ </span>
 
424
  );
425
  }
426
 
427
+ /** Map-only settings live in their own row beneath the main Filter / Sort / Group navigation. */
428
+ /**
429
+ * ⭐⭐ WAVE 42 · W42-T19 (owner instruction 11) — CALENDAR'S OWN CONTROLS, ON THEIR OWN ROW.
430
+ *
431
+ * Owner: *"Under Calendar View, I see that the toggle navigation for Choose dates and
432
+ * Records/Summaries still live at the same line as Filter/Sort/Group. Move this downward exactly
433
+ * how Time-series and Map view has it."*
434
+ *
435
+ * ⛔ THIS COMPONENT IS LANDED EMPTY IN THE WAVE'S BASELINE COMMIT, AND THAT IS THE WHOLE POINT.
436
+ * It is already MOUNTED in `CustomerGrid.tsx` beside `MapSettings`, so the lane that fills it never
437
+ * has to open that file. `CustomerGrid.tsx` is another lane's, and a cross-lane mount is exactly
438
+ * how wave 41 shipped a whole feature that nothing ever rendered.
439
+ *
440
+ * ⛔ WHAT THE FILLING LANE MUST NOT DO: relocate the whole `modeControl` prop out of `<Toolbar>`.
441
+ * `ModeSwitch` bundles the UNIVERSAL "View · mode" trigger together with Calendar's sub-controls in
442
+ * one `<span className="cg-modes">`, so moving the lot deletes the mode switcher from row one for
443
+ * EVERY view, not just Calendar. Extract only the three `mode === "calendar"` blocks: the date
444
+ * field button, the `Day cells` records/summary toggle, and the summary-mode totals picker.
445
+ *
446
+ * ⭐ COPY MAP'S MECHANISM, NOT TIME-SERIES'. `MapSettings` is a sibling of `<Toolbar>` in
447
+ * `CustomerGrid.tsx`, rendered after it and before `.cg-grid-box`. `TimeSeriesPanel`'s `.cg-ts-bar`
448
+ * only LOOKS the same: it lives inside the view component and mounts inside `.cg-grid-box`.
449
+ *
450
+ * ⚠ AND SAY THIS OUT LOUD WHEN IT LANDS, because it is a behaviour change rather than a move:
451
+ * leaving `.cg-toolbar` leaves the `cgtoolbar` container query, so these controls stop collapsing
452
+ * to icons at 1080px and 480px. `.cg-map-settings` never had that collapse, so this matches Map.
453
+ */
454
+ export function CalendarSettings(_props: {
455
+ dateField?: Field;
456
+ dateChoices: Field[];
457
+ onPickField: (k: "dateField" | "stackField", key: string) => void;
458
+ calendarMode?: "records" | "summary";
459
+ onCalendarMode?: (next: "records" | "summary") => void;
460
+ calendarMetrics?: { id: string; field: string; agg: string }[];
461
+ metricChoices?: Field[];
462
+ onCalendarMetrics?: (next: { id: string; field: string; agg: string }[]) => void;
463
+ }) {
464
+ // Empty by design until W42-T19 fills it. Renders nothing, so the calendar's controls keep
465
+ // working from `ModeSwitch` in the meantime and no intermediate state is broken for a user.
466
+ return null;
467
+ }
468
+
469
  export function MapSettings({
470
  coordField,
471
  coordChoices,
 
487
  selectedCount: number;
488
  onToggleRoute: () => void;
489
  }) {
490
+ if (coordChoices.length === 0 && sizeChoices.length === 0 && selectedCount < 1) return null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
491
  return (
492
  <div className="cg-map-settings" aria-label="Map settings">
493
  <span className="cg-map-settings-label">Map</span>
 
497
  aria-expanded={routeOpen}
498
  aria-controls="cg-route-popover"
499
  onClick={onToggleRoute}
500
+ title="Show or hide route planning"
501
  >
502
  Route{selectedCount >= 2 ? ` · ${selectedCount} selected` : ""}
503
  </button>
web/src/filter-kit/FieldsHidePanel.tsx CHANGED
@@ -13,7 +13,7 @@
13
  // happens to store the other polarity.
14
  // ---------------------------------------------------------------------------
15
 
16
- import { useMemo, useState } from "react";
17
  // ⚠ W40-T16 — the bare `Field` type import is GONE, not misplaced: the prop below is
18
  // `PermsField[]` now, which extends it, so importing both would leave one unread and
19
  // `tsconfig.app.json`'s `noUnusedLocals` reds the build on exactly that.
@@ -27,22 +27,9 @@ import { useMemo, useState } from "react";
27
  // miniature, where what a user searches and what they read answer the same question
28
  // differently. It lives in `types.ts` so the node harness can run it: this panel is JSX and
29
  // its search path only fires once somebody types, which no static render can do.
30
- import { fieldEditMode, fieldLabel, isOfferableField, isPresetField,
31
- FIELD_EDIT_BLURBS, FIELD_EDIT_LABELS }
32
- from "../customer-grid/types";
33
  import { FieldTypeIcon } from "../customer-grid/icons";
34
  import { TYPE_LABELS } from "../customer-grid/iconShapes";
35
- // ⭐⭐ W42-T38 — THE FORMULA HALF OF THE BROKEN-FIELD MARK, CONSUMED RATHER THAN RESPELLED.
36
- // `validateFormula` already owns "does every {ref} this source names exist on this table", and it
37
- // is the rule the column menu validates a formula WITH; a second copy here would be the shape
38
- // [[two-enumerations-from-different-anchors]] describes, where one of the two later learns
39
- // something the other does not. `parseFormula` comes with it only to tell a SOURCE THAT CANNOT BE
40
- // READ apart from a source that reads a column this table is not offering, because those two
41
- // deserve different sentences and `validateFormula` returns one `error` string for both.
42
- // ⚠ SAFE FOR THE KIT'S MODULE GRAPH: `formulaEngine.ts` has NO imports at all (it is the leaf the
43
- // Python port mirrors), so nothing here can close a cycle and `verify_ui.py`'s render smoke,
44
- // which reaches this file by mounting `PermsEditor` under bare node, still resolves.
45
- import { parseFormula, validateFormula } from "../customer-grid/formulaEngine";
46
  // ⭐⭐ W40-T16 (owner instruction 13) — A METRIC IS A ROW LIKE ANY OTHER, and the ONE thing that
47
  // makes it read differently is its NAME. `metricLabel` is that rule, declared once beside the
48
  // flag it depends on, and it is a pure string function so this panel does not acquire a runtime
@@ -70,9 +57,7 @@ import {
70
  bulkOutcomeLine,
71
  deleteImpactTitle,
72
  deleteRefusalReason,
73
- fieldAuthorBadge,
74
  fieldClassOf,
75
- fieldSectionOf,
76
  fieldUsageOf,
77
  fieldUsageTitle,
78
  fieldUsageTotal,
@@ -81,21 +66,14 @@ import {
81
  originBadge,
82
  permRuleWarningTitle,
83
  shareMarkTitle,
84
- supersededNoteOf,
85
  valuesBadge,
86
- FIELD_SECTION_TITLES,
87
  LOCKED_HIDE_REFUSAL,
88
  PRESET_BADGE_TITLE,
89
  REMOVE_FIELD_HINT,
90
  REMOVE_FIELD_LABEL,
91
  } from "./fieldClass";
92
 
93
- /**
94
- * ⭐⭐ W42-T12 — THE BASE ARM. Everything a mount may pass, with the six manager doors still
95
- * OPTIONAL here, because the two permission rooms genuinely have no version of them. What makes
96
- * the manager mount unable to drop one is the union at the bottom of this block, not this shape.
97
- */
98
- interface FieldsHidePanelBase {
99
  /** Owner item 23 — in the view's COLUMN ORDER, not definition order. Dragging a row here
100
  * rewrites `config.order`, so a list showing a different sequence from the one it edits
101
  * would move a field to a position the user never pointed at.
@@ -121,6 +99,8 @@ interface FieldsHidePanelBase {
121
  * affordance renders for them at all. */
122
  deletableKeys?: ReadonlySet<string>;
123
  onDeleteField?: (key: string) => void;
 
 
124
  /**
125
  * ⭐⭐ W41-T29 (R6, contract C2) — WHO IS LOOKING, so C2's rights pair can be asked at all.
126
  *
@@ -130,10 +110,7 @@ interface FieldsHidePanelBase {
130
  * colleague owns is in the set and looks deletable to a non-owner today. The narrowing has to
131
  * happen here, against C1's classification, because the set cannot express who is asking.
132
  *
133
- * ⭐ W42-T12 CORRECTS THE PARAGRAPH BELOW: the grid's mount passes one now, and the manager arm
134
- * of this file's props union makes it unable to stop. The render below is still built for an
135
- * absent viewer, because the two permission rooms match the plain arm and pass nothing.
136
- * ⚠ WHEN THIS WAS WRITTEN, NO MOUNT PASSED ONE. All four call sites
137
  * (`customer-grid/Toolbar.tsx`, `settings/DatabasePermsPane.tsx`, `settings/ModulePermsList.tsx`
138
  * and the `web_grid_ux` render) are outside this ticket's fence. See the row map for the split
139
  * that keeps an unwired viewer from silently withdrawing a delete that ships today.
@@ -146,21 +123,19 @@ interface FieldsHidePanelBase {
146
  * a destructive act, which is the one thing this ticket must not ship, so the affordance
147
  * renders only where a host supplied this door.
148
  *
149
- * ⭐ W42-T12 — THE GRID'S MOUNT PASSES ONE NOW (`CustomerGrid::useFieldBulkDoors`); the
150
- * sentence below records what was true before it.
151
- * ⚠ NO ENDPOINT EXISTS FOR IT STILL (searched: nothing in
152
  * `aios-web/api` unshares a field). The half of R6(b) that IS enforced today is the refusal:
153
  * a shared-with-me field loses its Delete whether or not this handler arrives.
154
  */
155
- onRemoveField?: ((key: string) => void) | null;
156
  /**
157
  * ⭐⭐ W41-T30 (R3, R8) - THE TWO BULK ACTS THAT HAVE NO CALLER YET, and they take the
158
  * WHOLE selection rather than one key, because that is what makes them one act: a share
159
  * dialog opened once over five fields is the feature; five dialogs is the thing R3 asked
160
  * to be replaced.
161
  *
162
- * ⛔ OPTIONAL ON THE BASE, REQUIRED ON THE MANAGER ARM (W42-T12), AND ABSENT STILL MEANS THE
163
- * BUTTON IS NOT THERE. When this was written, all four mount sites were outside the fence (see `viewer`'s JSDoc for the list), so no host can supply
164
  * either door today. R8 forbids the alternative outright: an affordance that renders and does
165
  * nothing is worse than one that is missing, because a missing one is visibly missing. The
166
  * house posture this file already states for `onShowAll` / `onHideAll` applies unchanged -
@@ -170,8 +145,8 @@ interface FieldsHidePanelBase {
170
  * for an admin viewer, because "an admin can reassign a field's owner" is the whole of the
171
  * ruling and a non-admin has no version of the act to offer.
172
  */
173
- onShareFields?: ((keys: string[]) => void) | null;
174
- onReassignFields?: ((keys: string[]) => void) | null;
175
  /**
176
  * ⭐⭐ W41-T30 - BULK HIDE AND SHOW NEED A PLURAL DOOR, AND THIS IS THE TICKET'S BIGGEST
177
  * MEASURED FINDING. The wave board's premise was that bulk visibility "can be wired for real:
@@ -192,7 +167,7 @@ interface FieldsHidePanelBase {
192
  * builds `onShowAll` out of `onColumnsVisible(keys: string[])`. Wiring this prop to it is the
193
  * whole of the caller change, and it is outside this ticket's fence.
194
  */
195
- onSetFieldsHidden?: ((keys: string[], hidden: boolean) => void) | null;
196
  /**
197
  * THE BATCH DELETE DOOR, AND BULK DELETE IS ABSENT WITHOUT IT, ON PURPOSE.
198
  *
@@ -215,7 +190,7 @@ interface FieldsHidePanelBase {
215
  * offers no bulk delete at all, which is the posture this file already keeps for every other
216
  * handler ("a missing prop makes the action ABSENT, never present-and-inert").
217
  */
218
- onDeleteFields?: ((keys: string[]) => void) | null;
219
  /**
220
  * ⭐⭐ W40-T17 (owner instruction 15) — DOES THIS MOUNT FILE ROWS UNDER "Shared with me" AND
221
  * "Shared with everyone"? Absent means YES, which is the grid's behaviour and every behaviour
@@ -256,198 +231,6 @@ interface FieldsHidePanelBase {
256
  manager?: boolean;
257
  }
258
 
259
- /**
260
- * ⭐⭐ W42-T12 (D-485) — THE MANAGER ARM, AND ITS SIX MEMBERS ARE REQUIRED ON PURPOSE.
261
- *
262
- * Six optional doors degrade to "the feature does not exist", which reads on screen exactly like
263
- * "nobody built it" — a Fields manager offering Share, Reassign, Hide, Show and Delete over a
264
- * ticked selection, and doing none of them. That is the defect this arm ends: a mount that says
265
- * `manager` and then forgets one door does not compile.
266
- *
267
- * ⛔ THE DISCRIMINANT HAS TO BE PASSED, NOT DEFAULTED. `manager` defaults to `sharedSections`
268
- * below, and TypeScript cannot narrow a union on a runtime default, so the grid's mount states
269
- * `manager` explicitly. The two permission rooms (`settings/DatabasePermsPane.tsx`,
270
- * `settings/ModulePermsList.tsx`) pass no `manager` at all and therefore match the plain arm,
271
- * untouched — which is what lets this land without editing a file outside the fence.
272
- *
273
- * ⚠ REQUIRED KEY, NULLABLE VALUE, AND THE TWO ARE DIFFERENT PROPERTIES. What D-485 costs is the
274
- * host that never DECIDED; `| null` still forces the decision to be written down, and a mount
275
- * that genuinely has no version of an act says so in one greppable word instead of in silence.
276
- * `null` and absent behave identically in the body below — every use is truthiness-guarded — so
277
- * the house posture holds: a door nobody supplied makes the control ABSENT, never inert.
278
- * `viewer` takes `undefined` rather than `null` because that is the value the grid already holds
279
- * for "not signed in / not told", and inventing one would invent the rights answer itself.
280
- */
281
- export interface FieldsHidePanelManagerProps extends FieldsHidePanelBase {
282
- manager: true;
283
- viewer: FieldViewer | undefined;
284
- onRemoveField: ((key: string) => void) | null;
285
- onShareFields: ((keys: string[]) => void) | null;
286
- onReassignFields: ((keys: string[]) => void) | null;
287
- onSetFieldsHidden: ((keys: string[], hidden: boolean) => void) | null;
288
- onDeleteFields: ((keys: string[]) => void) | null;
289
- }
290
-
291
- /** Every mount that is NOT the field manager: the bulk bar never renders, so the six doors stay
292
- * as optional as they have always been and an absent one still means the act is ABSENT. */
293
- export interface FieldsHidePanelPlainProps extends FieldsHidePanelBase {
294
- manager?: false;
295
- }
296
-
297
- export type FieldsHidePanelProps =
298
- | FieldsHidePanelManagerProps
299
- | FieldsHidePanelPlainProps;
300
-
301
- /**
302
- * ⭐⭐ W42-T38 — **A COMPUTED COLUMN WHOSE CONFIGURATION NO LONGER RESOLVES, AND WHY.** Returns the
303
- * REASON as a finished sentence, or `null` for every ordinary column. Pure and exported, so the
304
- * answer can be exercised directly instead of being read out of a rendered row: `gridUx.test.ts`
305
- * already imports this panel under bare node, which is what makes an export here reachable at all.
306
- *
307
- * ⛔⛔ IT NAMES NON-RESOLUTION AND NEVER DELETION, and that is the whole of the wording rule.
308
- * `fields` is the list the server sent THIS VIEWER: a column narrowed away by a permission rule,
309
- * a column dropped since this definition was written, and a definition that never pointed
310
- * anywhere all arrive here as the same absent key. W41-T43 hit this exact fork on the pivot note
311
- * (`CustomerGrid.tsx`) and refused a cause for the same reason: a sentence naming any one of the
312
- * three is a false claim on the other two. So every sentence below says what is observable, which
313
- * is that the table is not offering the column the configuration names.
314
- *
315
- * ⛔ AND IT MARKS A REFERENCE THAT DOES NOT RESOLVE, NEVER A BAG THAT IS ABSENT. A `link` column
316
- * carrying no `link` bag is UNCONFIGURED, which is a different fact with a different remedy, and
317
- * the fixture `gridUx.test.ts` renders this panel with is exactly that shape (`customer_link`,
318
- * typed `link`, no bag) — marking it would put new markup inside a row that test reads.
319
- *
320
- * ⚠ EVERY READ IS GUARDED, because none of this arrives typed: `type`, `label`, and every key
321
- * inside the three bags are `string` by declaration and whatever the wire sent in fact. The early
322
- * return also keeps the cost off the ordinary column, which is all but a handful of them.
323
- *
324
- * ⚠ WHAT THIS CANNOT SEE, stated rather than guessed at. Four references resolve against THIS
325
- * table and are answered here: a formula's `{ref}`s, `rollup.link`, `rollup.source.on` and
326
- * `link.from`. The rest name things this panel is never passed — `rollup.field`, `rollup.sortBy`
327
- * and the rollup conditions live in the LINKED table; `link.table`, `link.reciprocal` and
328
- * `link.inverse` name another database; `rollup.source.topic|measure|groupBy` and every key of
329
- * `link.via` name the governed topic catalogue. Answering those needs a table list and a topic
330
- * catalogue, and inventing either would be this panel asserting a wall it did not hit.
331
- *
332
- * ⚠ NO `selfKey` IS PASSED TO `validateFormula`, deliberately. Its two other refusals (a formula
333
- * referencing itself, a loop between formulas) are states the WRITE DOOR already refuses, so a
334
- * chip claiming one on a saved column asserts something unreachable, and the cycle walk it costs
335
- * would run per column per keystroke to say so.
336
- */
337
- export function brokenFieldReason(
338
- field: PermsField,
339
- fields: readonly PermsField[]
340
- ): string | null {
341
- const formula = typeof field.formula === "string" ? field.formula : "";
342
- const rollup = field.rollup;
343
- const link = field.link;
344
- if (!formula && !rollup && !link) return null;
345
- const known = new Set<string>();
346
- for (const f of fields) if (typeof f?.key === "string") known.add(f.key);
347
- // ⚠ AN ABSENT COLUMN IS QUOTED BY ITS KEY, and there is no softer option: every sentence below
348
- // that names one has already established the key is not in `fields`, so there is no label
349
- // anywhere on this payload to borrow. The one branch that HAS the field quotes it by name.
350
- if (formula) {
351
- const parsed = parseFormula(formula);
352
- if (!parsed.ok) return "This formula cannot be read as written, so it computes nothing.";
353
- const sources = new Map<string, string>();
354
- for (const f of fields) {
355
- if (typeof f?.key === "string" && typeof f.formula === "string" && f.formula)
356
- sources.set(f.key, f.formula);
357
- }
358
- const checked = validateFormula(formula, known, sources);
359
- if (!checked.ok && checked.error)
360
- return `This formula cannot be resolved: ${checked.error}.`;
361
- }
362
- if (rollup) {
363
- // The READ-THROUGH kind. `source.on` is the column on THIS table whose value matches the group
364
- // key, and it is the one half of a source rollup this panel can answer for.
365
- const on = rollup.source?.on;
366
- if (typeof on === "string" && on && !known.has(on))
367
- return `This rollup matches on the column "${on}", which this table is not `
368
- + "offering, so it folds nothing.";
369
- // The LINK FOLD. Two ways it stops resolving, and they are different facts: the link column is
370
- // not on this table at all, or it is here and is no longer a link.
371
- const via = rollup.link;
372
- if (typeof via === "string" && via) {
373
- const hit = fields.find((f) => f?.key === via);
374
- if (!hit)
375
- return `This rollup folds the link column "${via}", which this table is not `
376
- + "offering, so it has no records to summarise.";
377
- if (hit.type !== "link")
378
- return `This rollup folds "${rowLabelOf(hit)}", which is not a link column any more, so `
379
- + "it has no records to summarise.";
380
- }
381
- }
382
- if (link) {
383
- // `from` is the column on THIS table supplying the join value. Absent is not broken: the
384
- // profile or pinned column is the documented default, so only a NAMED missing one is a fault.
385
- const from = link.from;
386
- if (typeof from === "string" && from && !known.has(from))
387
- return `This link joins on the column "${from}", which this table is not offering, `
388
- + "so it matches no records.";
389
- }
390
- return null;
391
- }
392
-
393
- /**
394
- * ⭐ W42-T38 — HOW A ROW IS NAMED, hoisted out of the component so `brokenFieldReason` can quote a
395
- * column by the name the reader sees without either of them growing a second naming rule. The
396
- * component's own `rowLabel` is this function, and wave 30's R5 plus W40-T16's metric prefix are
397
- * still the only two things in it.
398
- */
399
- function rowLabelOf(f: PermsField): string {
400
- return f.isMetric ? metricLabel(fieldLabel(f)) : fieldLabel(f);
401
- }
402
-
403
- /**
404
- * ⭐⭐ W42-T48 (R14) - EDITABILITY IS A BADGE NOW, NOT A SECTION, and this is where that
405
- * fact moved to. The panel used to answer "who may change this column" BY POSITION: a row
406
- * sat under "Shared with everyone" because `fieldEditMode(field)` answered `collaborative`.
407
- * R14 gives the position to OWNERSHIP instead (`fieldSectionOf`), so the same fact now
408
- * rides the row as a chip and NOTHING about it is lost.
409
- *
410
- * ⛔⛔ THIS IS THE PANEL HALF `verify_map.py`'s `private-by-default-is-anchored` LEG READS.
411
- * Its subject is unchanged and is worth restating: a route column is stored with
412
- * `permissions: {edit: "personal"}` and `types.ts::fieldEditMode` falls back to
413
- * `cleanFieldPermissions(field.permissions, "collaborative")` for a definition carrying no
414
- * bag at all, so the stamp is what keeps a route reading as private BY RULE rather than by
415
- * luck. The leg follows that fact HERE rather than dying with the section it used to live in.
416
- *
417
- * ⛔ THE STAMP, NEVER THE FALLBACK, IS WHAT EARNS A CHIP. A definition with no `permissions`
418
- * bag would take `collaborative` from the fallback, and painting `Collaborative` on every
419
- * unstamped column in the product would be a claim derived from a default - the same failure
420
- * C8 refuses for `class`. No bag, no badge; the row then says nothing rather than something
421
- * wrong.
422
- */
423
- export function fieldEditBadge(field: PermsField): { text: string; title: string } | null {
424
- const bag: unknown = field.permissions;
425
- if (typeof bag !== "object" || bag === null) return null;
426
- if (typeof (bag as { edit?: unknown }).edit !== "string") return null;
427
- const mode = fieldEditMode(field);
428
- return { text: FIELD_EDIT_LABELS[mode], title: FIELD_EDIT_BLURBS[mode] };
429
- }
430
-
431
- /**
432
- * ⭐ W42-T38 — WHAT A PERSON WOULD TYPE FOR A TYPE, as one lower-cased haystack.
433
- *
434
- * BOTH the human name and the raw kind, deliberately. `TYPE_LABELS[f.type]` is the word this
435
- * product shows for the kind — the icon's own tooltip on the row two hundred lines below reads it,
436
- * and so does the column menu — so it is what somebody hunting "every currency column" will type.
437
- * The raw kind is the second spelling the SAME user meets, in a formula's `{ref}` vocabulary, in a
438
- * saved view's payload and in the API; matching it costs one token and cannot produce a hit the
439
- * label would not, since every kind is a single lower-case word.
440
- *
441
- * ⚠ GUARDED THE WAY `rowLabel` IS, and for the same reported crash: `TYPE_LABELS` is declared
442
- * `Record<FieldType, string>`, so `tsc` sees a `string` where an off-union wire value gives
443
- * `undefined`, and `.toLowerCase()` on that is the throw wave 30's R5 fixed for labels.
444
- */
445
- function typeTerms(f: PermsField): string {
446
- const label = TYPE_LABELS[f?.type] ?? "";
447
- const kind = typeof f?.type === "string" ? f.type : "";
448
- return `${label} ${kind}`.toLowerCase();
449
- }
450
-
451
  /**
452
  * The Fields show/hide panel (owner item 7 remainder, wave 2 2026-07-27): a SEARCH box over the
453
  * field list, and a small muted `Pre-set` chip on every Odoo-precomputed field. The chip's
@@ -456,8 +239,23 @@ function typeTerms(f: PermsField): string {
456
  * the table. Show all / Hide all keep acting on ALL fields, not the searched subset — their
457
  * labels say "all", and a narrowed meaning under an active search would be a quiet lie.
458
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
  export function FieldsHidePanel({
460
- fields: allFields,
461
  hidden,
462
  onToggle,
463
  onHideAll,
@@ -466,6 +264,7 @@ export function FieldsHidePanel({
466
  onFieldOrder,
467
  deletableKeys,
468
  onDeleteField,
 
469
  // ⭐⭐ W41-T29 — NO DEFAULT ON EITHER, deliberately. `undefined` here is not a preference a
470
  // default could stand in for: it is "nobody has told this panel who is looking", and inventing
471
  // a viewer would be inventing the rights answer C2 is meant to derive.
@@ -484,26 +283,6 @@ export function FieldsHidePanel({
484
  // already made: swap the two lines and this is `undefined` on every mount.
485
  manager = sharedSections,
486
  }: FieldsHidePanelProps) {
487
- /**
488
- * ⭐⭐ WAVE-42 C11 (W42-T54) — THE FIELDS MANAGER IS A FIELD PICKER, so it lists the OFFERABLE
489
- * columns. The prop is shadowed once, here, rather than narrowed at each of the four places
490
- * below that partition, search, order, tick and render it: this panel derives its list five
491
- * ways and a filter added to four of them is the fifth one still offering ~64 route columns.
492
- *
493
- * ⛔ PRESENTATION ONLY. Nothing is deleted and nothing is walled: the payload still carries
494
- * every withheld field, the grid still renders any that are visible, and a route column's own
495
- * doors (its column menu, `patchRouteOrderField`, `deleteRouteOrderField`) are untouched.
496
- *
497
- * R1's narrow exception is a route field whose host has already offered a delete affordance.
498
- * It stays in THIS manager only so that affordance remains reachable; it remains absent from
499
- * every picker. `deletableKeys` is a ceiling supplied by the host, so this cannot make a
500
- * withheld field deletable or offer any field outside the Fields manager.
501
- */
502
- const fields = useMemo(
503
- () => allFields.filter((field) =>
504
- isOfferableField(field) || !!deletableKeys?.has(field.key)),
505
- [allFields, deletableKeys]
506
- );
507
  /** W41-T27 - one name for "this mount is the Fields manager", so the title, the width class
508
  * and anything a later ticket adds all key off the same answer instead of re-deriving it. */
509
  const managerMode = manager;
@@ -553,10 +332,8 @@ export function FieldsHidePanel({
553
  * A field with no metric flag comes back byte-identical to `fieldLabel(f)` — which is what
554
  * keeps the GRID's mount of this panel unchanged, since grid fields never carry the flag.
555
  */
556
- // ⭐ W42-T38 — the rule MOVED to module scope (`rowLabelOf`) and did not change: the broken-field
557
- // reason quotes a column by the name a reader sees, and a helper outside the component cannot
558
- // reach a binding declared inside it. This name stays because six call sites below spell it.
559
- const rowLabel = rowLabelOf;
560
  /**
561
  * ⭐⭐ W41-T30 (contract C2) - EVERY RIGHT THIS PANEL ASKS ABOUT ONE FIELD, ASKED IN ONE
562
  * PLACE, so the ROW and the BULK BAR cannot answer the same question differently.
@@ -589,56 +366,35 @@ export function FieldsHidePanel({
589
  return { fc, presetRefusal, canRemove, deletable, removable, hideable };
590
  };
591
  const q = query.trim().toLowerCase();
592
- // ⭐⭐ W42-T38 — BY LABEL **AND BY TYPE NAME**. "currency" now finds every currency column on a
593
- // table where none of them says so in its label, which is the search a person actually runs when
594
- // they are looking for a kind rather than a name. See `typeTerms` for which spellings count and
595
- // for the guard, which is wave 30's R5 guard applied to the second field this line now reads.
596
- // ⚠ `shown` STILL FEEDS THE SECTIONS AND NOTHING ELSE. Show all / Hide all keep acting on
597
- // `fields` (see this function's own doc comment): their labels say "all", and a wider search
598
- // must not quietly widen or narrow what a bulk button touches.
599
- const shown = q
600
- ? fields.filter((f) => rowLabel(f).toLowerCase().includes(q) || typeTerms(f).includes(q))
601
- : fields;
602
  /**
603
  * ⭐⭐ W40-T17 (owner instruction 15) — TWO MOUNTS, TWO QUESTIONS, ONE PANEL.
604
  *
605
  * The GRID asks "whose column is this?" and answers it with three sections, because a person
606
- * looking at their own table needs to tell their columns from their colleagues' and from the
607
- * tenant's. The PERMISSION EDITOR asks "which columns may an admin set a rule on?", and AM-2
608
- * answers that with `metric || !custom` — the database's own pre-set columns, plus every bound
609
- * measure. They are not the same list narrowed; they are different questions with different
610
- * answers.
611
  *
612
- * ⭐⭐ W42-T48 (R14) — AND THE THREE SECTIONS ARE CUT ON OWNERSHIP, not on who may edit.
613
- * `My fields` / `From my colleagues` / `Built in`, decided by `fieldClass::fieldSectionOf`,
614
- * which is C1/C10's `class` first and the shipped stratum stamps (`custom`, `shared`,
615
- * `createdBy`) as the C8 fallback while the server half is late. What LEFT the layout is
616
- * `fieldEditMode`: who may CHANGE a column and who may SEE it are BADGES on the row now
617
- * (`fieldEditBadge`, `audienceBadge`), so neither fact is lost and neither one decides where a
618
- * row sits. A colleague's route column therefore reads as theirs, with their name on the row,
619
- * instead of sitting untitled at the top because its stamp happened to say `personal`.
620
- *
621
- * ⛔ THE TWO-MOUNT SEAM IS UNTOUCHED BY THAT RE-CUT. `sharedSections` still declares the
622
- * question, still defaults to true so the grid needs no edit, and still selects between the
623
- * wide arm and AM-2's narrow one. `verify_ui.py::hide_panel_is_mount_scoped` checks each of
624
- * those separately and every one of them is still correct after R14.
625
- *
626
- * ⛔ THE MEMBERSHIP IS A PURE, EXPORTED FUNCTION AND THAT IS DELIBERATE. Nobody can click this
627
- * panel on a branch whose store is tenant #0's production data, so the sectioning has to be
628
- * executable directly, on a hand-built field, without React and without a server.
629
  *
630
  * ⚠ THE NARROW ARM RENDERS ONE UNTITLED SECTION, which is what the first section has always
631
- * been. `section.title` is falsy there, so the rows sit directly under the search box exactly
632
- * as they do in the two permission rooms today.
633
  */
634
  const sections = sharedSections
635
  ? [
636
- { key: "mine", title: FIELD_SECTION_TITLES.mine,
637
- fields: shown.filter((field) => fieldSectionOf(field, viewer) === "mine") },
638
- { key: "colleagues", title: FIELD_SECTION_TITLES.colleagues,
639
- fields: shown.filter((field) => fieldSectionOf(field, viewer) === "colleagues") },
640
- { key: "builtin", title: FIELD_SECTION_TITLES.builtin,
641
- fields: shown.filter((field) => fieldSectionOf(field, viewer) === "builtin") },
642
  ]
643
  : [{ key: "personal", title: "", fields: presetHideFields(shown) }];
644
  /**
@@ -804,14 +560,7 @@ export function FieldsHidePanel({
804
  onChange={(e) => setQuery(e.target.value)}
805
  />
806
  <div className="cg-pop-list">
807
- {/* ⭐⭐ W42-T48 (R14) - AN EMPTY SECTION DOES NOT RENDER ITS HEADING. Three titled
808
- sections where one used to be untitled means the common account, with no columns of
809
- its own and none from a colleague, would open this panel on two empty headings and
810
- have to scroll past them to reach the rows. The heading earns its line by having
811
- something under it.
812
- ⚠ THE PANEL-WIDE EMPTY STATE IS A DIFFERENT QUESTION and is untouched: it asks
813
- whether EVERY section is empty, which is the search-matched-nothing case. */}
814
- {sections.filter((section) => section.fields.length > 0).map((section) => (
815
  <div key={section.key} className="cg-fields-section">
816
  {section.title && <div className="cg-fields-section-title">{section.title}</div>}
817
  {section.fields.map((f) => {
@@ -835,25 +584,11 @@ export function FieldsHidePanel({
835
  // `fieldRights` above). The row used to derive C2's terms inline, where no
836
  // footer button could reach them.
837
  const rights = fieldRights(f);
838
- /** ⭐⭐ W42-T38 — the reason this computed column resolves against nothing, or null for
839
- * every ordinary one. Asked here, per row, from the SAME `fields` list the panel is
840
- * rendering: `shown` is a search narrowing and would make the mark blink on and off as
841
- * a query hid the very column a rollup reads. */
842
- const brokenReason = brokenFieldReason(f, fields);
843
  const fc = rights.fc;
844
  const originText = fc && originBadge(fc);
845
  const audienceText = fc && audienceBadge(fc);
846
  const valuesText = fc && valuesBadge(fc);
847
  const shareTitle = fc && shareMarkTitle(fc);
848
- // ⭐⭐ W42-T48 (R14, R16) - THE THREE FACTS THE SECTION NO LONGER CARRIES.
849
- // `authorBadge` is the name on a colleague's row, worded by which fact was read
850
- // (`Shared by` off C1, `Added by` off the `createdBy` stamp); `editBadge` is the
851
- // editability stamp that used to decide the section; `supersededNote` is R16's
852
- // sentence, which paints nothing until a producer marks the collision (see
853
- // `supersededNoteOf`, and the handoff, for the wire key nobody sends yet).
854
- const authorBadge = fieldAuthorBadge(f, viewer);
855
- const editBadge = fieldEditBadge(f);
856
- const supersededNote = supersededNoteOf(f);
857
  // ⭐⭐ W41-T28 (R3, R8) - WHERE THIS FIELD IS USED, read off C8's `usage`
858
  // block and NEVER counted here. This component can see one user's field list
859
  // and nothing else: not the other users' saved views, not the automations, not
@@ -1081,26 +816,23 @@ export function FieldsHidePanel({
1081
  vocabulary is learned. */}
1082
  <FieldTypeIcon type={f.type} title={TYPE_LABELS[f.type]} />
1083
  <span className="cg-check-label">{rowLabel(f)}</span>
1084
- {/* ⭐⭐ W42-T38 — THE BROKEN COMPUTED COLUMN SAYS SO, AND SAYS WHY. A mark plus a
1085
- tooltip, never a sentence laid across the row (DESIGN §4) — the same shape the
1086
- share mark above uses, so a list of forty columns does not become forty
1087
- paragraphs. The chip word is the JUDGEMENT and the title is the REASON, which is
1088
- what makes the mark worth trusting: "Broken" on its own is the kind of badge a
1089
- reader learns to ignore.
1090
- ⚠ `aria-label` CARRIES THE REASON, not the word. A tooltip is a hover, and a
1091
- reader who cannot hover would otherwise get the judgement with none of the
1092
- evidence behind it.
1093
- ⛔ THE SENTENCE IS `brokenFieldReason`'s AND IS COMPOSED NOWHERE ELSE, so the one
1094
- place that knows which reference failed is the one place that words it. */}
1095
- {brokenReason && (
1096
- <span
1097
- className="cg-preset-tag cg-field-broken"
1098
- role="img"
1099
- aria-label={brokenReason}
1100
- title={brokenReason}
1101
  >
1102
- Broken
1103
- </span>
 
 
 
1104
  )}
1105
  {/* ⭐ OWNER ITEM 3 (2026-08-06): *"it doesn't show pre-set when I hide fields just
1106
  like how Odoo fields are. This is always the standard label."* Right — the chip
@@ -1118,15 +850,8 @@ export function FieldsHidePanel({
1118
  `Pre-set` is the pre-set-FIELD lock and it locks the COLUMN's definition; it
1119
  must never be read as "you cannot type here", which is a locked database. */}
1120
  {fc
1121
- ? originText && (
1122
- <span
1123
- className="cg-preset-tag cg-field-origin"
1124
- title={PRESET_BADGE_TITLE}
1125
- >
1126
- {originText}
1127
- </span>
1128
- )
1129
- : isPresetField(f) && <span className="cg-preset-tag">Pre-set</span>}
1130
  {/* ⭐ W41-T27 (R5, badge 2 of 3) — AUDIENCE: who can see this column. Sentence case
1131
  per DESIGN §2 (`Private`, `Shared by Karen`, `Everyone`), worded once in
1132
  `fieldClass.ts` so the four C1 surfaces cannot drift apart on it.
@@ -1137,36 +862,7 @@ export function FieldsHidePanel({
1137
  read as unshared under the old inference and reports `Everyone` under this one,
1138
  and the panel needed no new plumbing for it: the derivation moved to the side
1139
  that can see the grants. */}
1140
- {audienceText && (
1141
- <span className="cg-preset-tag cg-field-audience">{audienceText}</span>
1142
- )}
1143
- {/* ⭐⭐ W42-T48 (R14) - WHOSE COLUMN THIS IS, ON THE ROW. The section already
1144
- says a colleague put it in your list; the row says WHICH colleague, which is
1145
- the half a section title cannot carry. Rendered only under `From my
1146
- colleagues`, because a name on your own row would be chrome. */}
1147
- {authorBadge && (
1148
- <span className="cg-preset-tag cg-field-author" title={authorBadge.title}>
1149
- {authorBadge.text}
1150
- </span>
1151
- )}
1152
- {/* ⭐⭐ W42-T48 (R14) - EDITABILITY, AS A BADGE. This is the fact that used to
1153
- BE the section ("Shared with everyone" was `fieldEditMode` answering
1154
- `collaborative`). It is a chip now, it reads the STAMP and never the fallback,
1155
- and the blurb under `title` is the same sentence the column menu shows. */}
1156
- {editBadge && (
1157
- <span className="cg-preset-tag cg-field-edit" title={editBadge.title}>
1158
- {editBadge.text}
1159
- </span>
1160
- )}
1161
- {/* ⛔ W42-T48 (R16) - THE SUPERSEDED LOCAL COLUMN SAYS SO. Null on every field
1162
- on today's wire, by C8: no producer marks a key collision yet, and inventing
1163
- the state client side would be asserting a second definition the server never
1164
- sent. The reader is here so the sentence lands the day one does. */}
1165
- {supersededNote && (
1166
- <span className="cg-preset-tag cg-field-superseded" title={supersededNote}>
1167
- Superseded
1168
- </span>
1169
- )}
1170
  {/* ⭐⭐ W41-T27 (owner instruction 8) — THE HOVER CHIP. A shared row carries a small
1171
  share mark whose title names WHO shared it and to whom. A mark and a tooltip,
1172
  never a sentence on the row (DESIGN §4); inline SVG in the house vocabulary,
@@ -1204,9 +900,7 @@ export function FieldsHidePanel({
1204
  `Shared values` means one value everyone reads, which is why Supplier behaves
1205
  unlike a column you made. Blank is the other half, so a personal column earns
1206
  no chip rather than a `Personal` one that says what every column used to be. */}
1207
- {valuesText && (
1208
- <span className="cg-preset-tag cg-field-values">{valuesText}</span>
1209
- )}
1210
  {/* ⭐ W41-T27 (R3) — THE OWNER, which is the half of instruction 2 the three badges
1211
  do not carry: a classification says what KIND of column this is, and R3 asks the
1212
  manager row to say WHOSE it is.
@@ -1218,11 +912,7 @@ export function FieldsHidePanel({
1218
  swaps source the day the server half lands, with no diff to show it.
1219
  ⚠ A name, muted, with a `title` saying what it is. Not "Owned by Karen" — that
1220
  is a sentence, and every row would carry one. */}
1221
- {fc?.owner && (
1222
- <span className="cg-field-owner" title="Field owner">
1223
- {fc.owner}
1224
- </span>
1225
- )}
1226
  {/* ⭐⭐ W41-T28 (R3) - THE USAGE COUNT. One mark, one digit, and the
1227
  breakdown in `title`/`aria-label`: DESIGN §4 asks for a count and a
1228
  mark, so "used in 2 views, 1 filter and 3 rollups" is what this row
 
13
  // happens to store the other polarity.
14
  // ---------------------------------------------------------------------------
15
 
16
+ import { useState } from "react";
17
  // ⚠ W40-T16 — the bare `Field` type import is GONE, not misplaced: the prop below is
18
  // `PermsField[]` now, which extends it, so importing both would leave one unread and
19
  // `tsconfig.app.json`'s `noUnusedLocals` reds the build on exactly that.
 
27
  // miniature, where what a user searches and what they read answer the same question
28
  // differently. It lives in `types.ts` so the node harness can run it: this panel is JSX and
29
  // its search path only fires once somebody types, which no static render can do.
30
+ import { fieldEditMode, fieldLabel, isPresetField } from "../customer-grid/types";
 
 
31
  import { FieldTypeIcon } from "../customer-grid/icons";
32
  import { TYPE_LABELS } from "../customer-grid/iconShapes";
 
 
 
 
 
 
 
 
 
 
 
33
  // ⭐⭐ W40-T16 (owner instruction 13) — A METRIC IS A ROW LIKE ANY OTHER, and the ONE thing that
34
  // makes it read differently is its NAME. `metricLabel` is that rule, declared once beside the
35
  // flag it depends on, and it is a pure string function so this panel does not acquire a runtime
 
57
  bulkOutcomeLine,
58
  deleteImpactTitle,
59
  deleteRefusalReason,
 
60
  fieldClassOf,
 
61
  fieldUsageOf,
62
  fieldUsageTitle,
63
  fieldUsageTotal,
 
66
  originBadge,
67
  permRuleWarningTitle,
68
  shareMarkTitle,
 
69
  valuesBadge,
 
70
  LOCKED_HIDE_REFUSAL,
71
  PRESET_BADGE_TITLE,
72
  REMOVE_FIELD_HINT,
73
  REMOVE_FIELD_LABEL,
74
  } from "./fieldClass";
75
 
76
+ export interface FieldsHidePanelProps {
 
 
 
 
 
77
  /** Owner item 23 — in the view's COLUMN ORDER, not definition order. Dragging a row here
78
  * rewrites `config.order`, so a list showing a different sequence from the one it edits
79
  * would move a field to a position the user never pointed at.
 
99
  * affordance renders for them at all. */
100
  deletableKeys?: ReadonlySet<string>;
101
  onDeleteField?: (key: string) => void;
102
+ /** Opens the ordinary field editor; this panel deliberately remains mounted underneath it. */
103
+ onEditField?: (key: string, anchor: DOMRect) => void;
104
  /**
105
  * ⭐⭐ W41-T29 (R6, contract C2) — WHO IS LOOKING, so C2's rights pair can be asked at all.
106
  *
 
110
  * colleague owns is in the set and looks deletable to a non-owner today. The narrowing has to
111
  * happen here, against C1's classification, because the set cannot express who is asking.
112
  *
113
+ * ⚠ NO MOUNT PASSES ONE YET, and the render below is built for that. All four call sites
 
 
 
114
  * (`customer-grid/Toolbar.tsx`, `settings/DatabasePermsPane.tsx`, `settings/ModulePermsList.tsx`
115
  * and the `web_grid_ux` render) are outside this ticket's fence. See the row map for the split
116
  * that keeps an unwired viewer from silently withdrawing a delete that ships today.
 
123
  * a destructive act, which is the one thing this ticket must not ship, so the affordance
124
  * renders only where a host supplied this door.
125
  *
126
+ * ⚠ NO MOUNT PASSES ONE YET EITHER, and no endpoint exists for it (searched: nothing in
 
 
127
  * `aios-web/api` unshares a field). The half of R6(b) that IS enforced today is the refusal:
128
  * a shared-with-me field loses its Delete whether or not this handler arrives.
129
  */
130
+ onRemoveField?: (key: string) => void;
131
  /**
132
  * ⭐⭐ W41-T30 (R3, R8) - THE TWO BULK ACTS THAT HAVE NO CALLER YET, and they take the
133
  * WHOLE selection rather than one key, because that is what makes them one act: a share
134
  * dialog opened once over five fields is the feature; five dialogs is the thing R3 asked
135
  * to be replaced.
136
  *
137
+ * ⛔ OPTIONAL, AND ABSENT MEANS THE BUTTON IS NOT THERE. This panel's four mount sites are
138
+ * all outside this ticket's fence (see `viewer`'s JSDoc for the list), so no host can supply
139
  * either door today. R8 forbids the alternative outright: an affordance that renders and does
140
  * nothing is worse than one that is missing, because a missing one is visibly missing. The
141
  * house posture this file already states for `onShowAll` / `onHideAll` applies unchanged -
 
145
  * for an admin viewer, because "an admin can reassign a field's owner" is the whole of the
146
  * ruling and a non-admin has no version of the act to offer.
147
  */
148
+ onShareFields?: (keys: string[]) => void;
149
+ onReassignFields?: (keys: string[]) => void;
150
  /**
151
  * ⭐⭐ W41-T30 - BULK HIDE AND SHOW NEED A PLURAL DOOR, AND THIS IS THE TICKET'S BIGGEST
152
  * MEASURED FINDING. The wave board's premise was that bulk visibility "can be wired for real:
 
167
  * builds `onShowAll` out of `onColumnsVisible(keys: string[])`. Wiring this prop to it is the
168
  * whole of the caller change, and it is outside this ticket's fence.
169
  */
170
+ onSetFieldsHidden?: (keys: string[], hidden: boolean) => void;
171
  /**
172
  * THE BATCH DELETE DOOR, AND BULK DELETE IS ABSENT WITHOUT IT, ON PURPOSE.
173
  *
 
190
  * offers no bulk delete at all, which is the posture this file already keeps for every other
191
  * handler ("a missing prop makes the action ABSENT, never present-and-inert").
192
  */
193
+ onDeleteFields?: (keys: string[]) => void;
194
  /**
195
  * ⭐⭐ W40-T17 (owner instruction 15) — DOES THIS MOUNT FILE ROWS UNDER "Shared with me" AND
196
  * "Shared with everyone"? Absent means YES, which is the grid's behaviour and every behaviour
 
231
  manager?: boolean;
232
  }
233
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  /**
235
  * The Fields show/hide panel (owner item 7 remainder, wave 2 2026-07-27): a SEARCH box over the
236
  * field list, and a small muted `Pre-set` chip on every Odoo-precomputed field. The chip's
 
239
  * the table. Show all / Hide all keep acting on ALL fields, not the searched subset — their
240
  * labels say "all", and a narrowed meaning under an active search would be a quiet lie.
241
  */
242
+ function FieldMetaIcon({ detail, kind }: { detail: string; kind: "origin" | "audience" | "values" | "owner" }) {
243
+ const shape = kind === "values"
244
+ ? <><path d="M3 5.1 8 2.8l5 2.3L8 7.4 3 5.1Z" /><path d="M3 8.2 8 10.5l5-2.3M3 11.2 8 13.5l5-2.3" /></>
245
+ : kind === "origin"
246
+ ? <><path d="M8 2.5 13 8 8 13.5 3 8 8 2.5Z" /><path d="M6.3 8h3.4" /></>
247
+ : <><circle cx="8" cy="5.6" r="2.1" /><path d="M3.6 13.3c.5-2.4 2.1-3.7 4.4-3.7s3.9 1.3 4.4 3.7" /></>;
248
+ return (
249
+ <span className="cg-field-meta" role="img" tabIndex={0} aria-label={detail} data-meta-detail={detail}>
250
+ <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden focusable="false" stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round">
251
+ {shape}
252
+ </svg>
253
+ </span>
254
+ );
255
+ }
256
+
257
  export function FieldsHidePanel({
258
+ fields,
259
  hidden,
260
  onToggle,
261
  onHideAll,
 
264
  onFieldOrder,
265
  deletableKeys,
266
  onDeleteField,
267
+ onEditField,
268
  // ⭐⭐ W41-T29 — NO DEFAULT ON EITHER, deliberately. `undefined` here is not a preference a
269
  // default could stand in for: it is "nobody has told this panel who is looking", and inventing
270
  // a viewer would be inventing the rights answer C2 is meant to derive.
 
283
  // already made: swap the two lines and this is `undefined` on every mount.
284
  manager = sharedSections,
285
  }: FieldsHidePanelProps) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  /** W41-T27 - one name for "this mount is the Fields manager", so the title, the width class
287
  * and anything a later ticket adds all key off the same answer instead of re-deriving it. */
288
  const managerMode = manager;
 
332
  * A field with no metric flag comes back byte-identical to `fieldLabel(f)` — which is what
333
  * keeps the GRID's mount of this panel unchanged, since grid fields never carry the flag.
334
  */
335
+ const rowLabel = (f: PermsField): string =>
336
+ f.isMetric ? metricLabel(fieldLabel(f)) : fieldLabel(f);
 
 
337
  /**
338
  * ⭐⭐ W41-T30 (contract C2) - EVERY RIGHT THIS PANEL ASKS ABOUT ONE FIELD, ASKED IN ONE
339
  * PLACE, so the ROW and the BULK BAR cannot answer the same question differently.
 
366
  return { fc, presetRefusal, canRemove, deletable, removable, hideable };
367
  };
368
  const q = query.trim().toLowerCase();
369
+ const shown = q ? fields.filter((f) => rowLabel(f).toLowerCase().includes(q)) : fields;
 
 
 
 
 
 
 
 
 
370
  /**
371
  * ⭐⭐ W40-T17 (owner instruction 15) — TWO MOUNTS, TWO QUESTIONS, ONE PANEL.
372
  *
373
  * The GRID asks "whose column is this?" and answers it with three sections, because a person
374
+ * looking at their own table needs to tell their columns from the tenant's. The PERMISSION
375
+ * EDITOR asks "which columns may an admin set a rule on?", and AM-2 answers that with
376
+ * `metric || !custom` — the database's own pre-set columns, plus every bound measure. They are
377
+ * not the same list narrowed; they are different questions with different answers.
 
378
  *
379
+ * ⛔ THE THREE-SECTION ARM IS UNCHANGED AND MUST STAY SPELLED EXACTLY THIS WAY.
380
+ * `verify_map.py`'s `private-by-default-is-anchored` leg reads this file for the literal
381
+ * `fieldEditMode(field) === "collaborative"`: it is what pins "Shared with everyone" to the
382
+ * `collaborative` answer, so a route column stamped `edit: personal` is filed as private by
383
+ * rule rather than by luck. Rename the parameter or move the predicate and that gate reports a
384
+ * fact about route columns going stale, one surface away from here.
 
 
 
 
 
 
 
 
 
 
 
385
  *
386
  * ⚠ THE NARROW ARM RENDERS ONE UNTITLED SECTION, which is what the first section has always
387
+ * been. No heading appears and no heading disappears: `section.title` is falsy, so the rows sit
388
+ * directly under the search box exactly as the personal rows do on the grid today.
389
  */
390
  const sections = sharedSections
391
  ? [
392
+ { key: "personal", title: "", fields: shown.filter((field) =>
393
+ (!field.custom && !field.shared) || fieldEditMode(field) === "personal") },
394
+ { key: "me", title: "Shared with me", fields: shown.filter((field) =>
395
+ (field.custom || field.shared) && fieldEditMode(field) === "users") },
396
+ { key: "everyone", title: "Shared with everyone", fields: shown.filter((field) =>
397
+ (field.custom || field.shared) && fieldEditMode(field) === "collaborative") },
398
  ]
399
  : [{ key: "personal", title: "", fields: presetHideFields(shown) }];
400
  /**
 
560
  onChange={(e) => setQuery(e.target.value)}
561
  />
562
  <div className="cg-pop-list">
563
+ {sections.map((section) => (
 
 
 
 
 
 
 
564
  <div key={section.key} className="cg-fields-section">
565
  {section.title && <div className="cg-fields-section-title">{section.title}</div>}
566
  {section.fields.map((f) => {
 
584
  // `fieldRights` above). The row used to derive C2's terms inline, where no
585
  // footer button could reach them.
586
  const rights = fieldRights(f);
 
 
 
 
 
587
  const fc = rights.fc;
588
  const originText = fc && originBadge(fc);
589
  const audienceText = fc && audienceBadge(fc);
590
  const valuesText = fc && valuesBadge(fc);
591
  const shareTitle = fc && shareMarkTitle(fc);
 
 
 
 
 
 
 
 
 
592
  // ⭐⭐ W41-T28 (R3, R8) - WHERE THIS FIELD IS USED, read off C8's `usage`
593
  // block and NEVER counted here. This component can see one user's field list
594
  // and nothing else: not the other users' saved views, not the automations, not
 
816
  vocabulary is learned. */}
817
  <FieldTypeIcon type={f.type} title={TYPE_LABELS[f.type]} />
818
  <span className="cg-check-label">{rowLabel(f)}</span>
819
+ {onEditField && (
820
+ <button
821
+ type="button"
822
+ className="cg-field-edit-trigger"
823
+ aria-label={`Edit field ${rowLabel(f)}`}
824
+ title="Edit field"
825
+ onClick={(event) => {
826
+ event.preventDefault();
827
+ event.stopPropagation();
828
+ onEditField(f.key, event.currentTarget.getBoundingClientRect());
829
+ }}
 
 
 
 
 
 
830
  >
831
+ <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden focusable="false">
832
+ <path d="m3.2 11.9.7-2.8 6.5-6.5 2.5 2.5-6.5 6.5-2.7.8Z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" />
833
+ <path d="m9.1 4 2.5 2.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" />
834
+ </svg>
835
+ </button>
836
  )}
837
  {/* ⭐ OWNER ITEM 3 (2026-08-06): *"it doesn't show pre-set when I hide fields just
838
  like how Odoo fields are. This is always the standard label."* Right — the chip
 
850
  `Pre-set` is the pre-set-FIELD lock and it locks the COLUMN's definition; it
851
  must never be read as "you cannot type here", which is a locked database. */}
852
  {fc
853
+ ? originText && <FieldMetaIcon kind="origin" detail={`${PRESET_BADGE_TITLE}: ${originText}`} />
854
+ : isPresetField(f) && <FieldMetaIcon kind="origin" detail={PRESET_BADGE_TITLE} />}
 
 
 
 
 
 
 
855
  {/* ⭐ W41-T27 (R5, badge 2 of 3) — AUDIENCE: who can see this column. Sentence case
856
  per DESIGN §2 (`Private`, `Shared by Karen`, `Everyone`), worded once in
857
  `fieldClass.ts` so the four C1 surfaces cannot drift apart on it.
 
862
  read as unshared under the old inference and reports `Everyone` under this one,
863
  and the panel needed no new plumbing for it: the derivation moved to the side
864
  that can see the grants. */}
865
+ {audienceText && <FieldMetaIcon kind="audience" detail={audienceText} />}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
866
  {/* ⭐⭐ W41-T27 (owner instruction 8) — THE HOVER CHIP. A shared row carries a small
867
  share mark whose title names WHO shared it and to whom. A mark and a tooltip,
868
  never a sentence on the row (DESIGN §4); inline SVG in the house vocabulary,
 
900
  `Shared values` means one value everyone reads, which is why Supplier behaves
901
  unlike a column you made. Blank is the other half, so a personal column earns
902
  no chip rather than a `Personal` one that says what every column used to be. */}
903
+ {valuesText && <FieldMetaIcon kind="values" detail={valuesText} />}
 
 
904
  {/* ⭐ W41-T27 (R3) — THE OWNER, which is the half of instruction 2 the three badges
905
  do not carry: a classification says what KIND of column this is, and R3 asks the
906
  manager row to say WHOSE it is.
 
912
  swaps source the day the server half lands, with no diff to show it.
913
  ⚠ A name, muted, with a `title` saying what it is. Not "Owned by Karen" — that
914
  is a sentence, and every row would carry one. */}
915
+ {fc?.owner && <FieldMetaIcon kind="owner" detail={`Field owner: ${fc.owner}`} />}
 
 
 
 
916
  {/* ⭐⭐ W41-T28 (R3) - THE USAGE COUNT. One mark, one digit, and the
917
  breakdown in `title`/`aria-label`: DESIGN §4 asks for a count and a
918
  mark, so "used in 2 views, 1 filter and 3 rollups" is what this row
web/src/filter-kit/fieldClass.ts CHANGED
@@ -710,180 +710,3 @@ export const PRESET_DESCRIPTION_ONLY_HINT =
710
 
711
  /** R19's undo, in the words the rest of the product uses for the same act. */
712
  export const DESCRIPTION_RESET_LABEL = "Reset to default";
713
-
714
- // ---------------------------------------------------------------------------
715
- // W42-T48 (R14, R15, R16 / contract C10) - WHOSE FIELD IS THIS, and it is the
716
- // question the Fields panel now sections on.
717
- //
718
- // R14 re-cuts the panel's three sections on OWNERSHIP: `My fields`, `From my
719
- // colleagues`, `Built in`. What a section NEVER says again is who may SEE the
720
- // column or who may CHANGE it: those two are BADGES on the row (`audienceBadge`
721
- // above, and the panel's own edit-stamp badge), because a person reading their
722
- // field list is asking "is this mine" first and "who else sees it" second, and
723
- // one list cannot answer both by position.
724
- //
725
- // ⛔ ONE PRODUCER, THEN ONE C8 FALLBACK, IN THAT ORDER. C1/C10's `class` is the
726
- // authority the moment it answers; while it is absent this reads the SHIPPED
727
- // stratum stamps (`custom`, `shared`, `createdBy`) and nothing else. That is
728
- // exactly the shape W41-T27 sanctioned for the origin badge, where
729
- // `isPresetField` answers only while `class` is absent. It is NOT a defaulted
730
- // class: no origin, audience or values is invented for a field the server has
731
- // not classified, and every badge those three drive still paints nothing.
732
- //
733
- // ⚠ THE VIEWER IS THE MISSING HALF AND IT IS SAID OUT LOUD RATHER THAN GUESSED.
734
- // No mount passes `viewer` today (`customer-grid/Toolbar.tsx`,
735
- // `settings/DatabasePermsPane.tsx`, `settings/ModulePermsList.tsx` all pass
736
- // none, and all three are outside this ticket's fence). With no viewer, "is
737
- // this author me?" has no answer, so a definition read from the TENANT-WIDE
738
- // stratum and stamped with a person's name files under `From my colleagues`.
739
- // That is the honest reading of "somebody put this in my list" without an
740
- // identity to compare against; wire one mount's `viewer` and the same function
741
- // files that person's own shared column back under `My fields` with no other
742
- // change. Stated, not papered over.
743
- //
744
- // STILL NO RUNTIME IMPORTS (see this file's header): the stratum stamps are
745
- // read STRUCTURALLY off an `unknown`, exactly as `fieldClassOf` reads `class`.
746
- // ---------------------------------------------------------------------------
747
-
748
- /** R14's three sections, as keys. The titles are `FIELD_SECTION_TITLES`. */
749
- export const FIELD_SECTIONS = ["mine", "colleagues", "builtin"] as const;
750
- export type FieldSection = (typeof FIELD_SECTIONS)[number];
751
-
752
- /**
753
- * The words on screen. Sentence case, DESIGN section 2 (no ALL-CAPS chrome),
754
- * and no em dash or en dash anywhere in them (standing rule 2).
755
- */
756
- export const FIELD_SECTION_TITLES: Record<FieldSection, string> = {
757
- mine: "My fields",
758
- colleagues: "From my colleagues",
759
- builtin: "Built in",
760
- };
761
-
762
- /** Where a name may come from, so a caller can word the row honestly. */
763
- export interface FieldAuthor {
764
- name: string;
765
- /** `owner` and `sharedBy` are C1's; `createdBy` is the C8 fallback stamp. */
766
- from: "owner" | "sharedBy" | "createdBy";
767
- }
768
-
769
- /**
770
- * WHO PUT THIS COLUMN HERE, or nothing.
771
- *
772
- * ⛔ THE SOURCE TRAVELS WITH THE NAME, because the three do not mean the same
773
- * thing and the row must not claim one while reading another. W41-T27 refused
774
- * `field.createdBy` as a producer of the OWNER badge and that refusal stands:
775
- * C1 derives `owner` from grants plus the shared stratum, and the two disagree
776
- * on a transferred, an admin-seeded or a shared-values column. What this adds
777
- * is a DIFFERENT claim with its own word: while `class` is absent, `createdBy`
778
- * says who CREATED the definition, which is all the row then asserts.
779
- */
780
- export function fieldAuthorOf(field: unknown): FieldAuthor | null {
781
- const fc = fieldClassOf(field);
782
- if (fc) {
783
- if (fc.owner) return { name: fc.owner, from: "owner" };
784
- if (fc.sharedBy) return { name: fc.sharedBy, from: "sharedBy" };
785
- return null;
786
- }
787
- if (typeof field !== "object" || field === null) return null;
788
- const made = nameOrNull((field as { createdBy?: unknown }).createdBy);
789
- return made ? { name: made, from: "createdBy" } : null;
790
- }
791
-
792
- /** Was this definition read from the TENANT-WIDE stratum rather than yours? */
793
- function fromSharedStratum(field: unknown, fc: FieldClass | null): boolean {
794
- if (fc) return fc.audience !== "private";
795
- if (typeof field !== "object" || field === null) return false;
796
- return (field as { shared?: unknown }).shared === true;
797
- }
798
-
799
- /**
800
- * ⭐⭐ R14 IN ONE PURE FUNCTION, exported so it can be executed directly rather
801
- * than inferred from a screenshot nobody can take on this branch.
802
- *
803
- * The order of the branches IS the rule:
804
- * 1. C1 says the platform made the column, and that beats every stamp below.
805
- * 2. a named author who IS this viewer: yours, wherever it lives.
806
- * 3. a named author on a definition read from the tenant-wide stratum:
807
- * somebody else put it in your list. A route column is this case
808
- * (`shared: true`, stamped with the person who solved the route), which
809
- * is why a colleague's route reads as theirs rather than as the
810
- * database's own.
811
- * 4. an overlay column created from the table UI lives in YOUR workspace
812
- * document, so it is yours even with no name on it.
813
- * 5. a named author with no stratum stamp is still a person's column.
814
- * 6. nobody authored it and you did not add it: the database's own.
815
- *
816
- * ⛔ A NULL `class` NEVER LANDS A ROW NOWHERE. Every field the panel holds is
817
- * placed by branch 3, 4, 5 or 6 off the shipped stamps, so today's wire renders
818
- * a complete list: custom columns under `My fields`, shared columns carrying a
819
- * creator under `From my colleagues`, and the database's own contract columns
820
- * under `Built in`. The C10 half only makes the same answer authoritative.
821
- */
822
- export function fieldSectionOf(
823
- field: unknown,
824
- viewer?: FieldViewer | null
825
- ): FieldSection {
826
- const fc = fieldClassOf(field);
827
- if (fc && fc.origin === "preset") return "builtin";
828
- const author = fieldAuthorOf(field);
829
- if (author && sameUser(author.name, viewer?.name)) return "mine";
830
- if (author && fromSharedStratum(field, fc)) return "colleagues";
831
- if (typeof field === "object" && field !== null
832
- && (field as { custom?: unknown }).custom === true) return "mine";
833
- if (author) return "colleagues";
834
- return "builtin";
835
- }
836
-
837
- /**
838
- * THE NAME ON THE ROW, in the ONE case where nothing else on the row carries it.
839
- *
840
- * ⛔⛔ NEVER BESIDE A C1 CHIP THAT ALREADY SAYS IT, which is the whole of the
841
- * guard below. The moment `class` ships, the row already names the person twice
842
- * over: `audienceBadge` renders `Shared by Karen` for an `audience: "users"`
843
- * column, and the panel's own `cg-field-owner` chip renders `class.owner`
844
- * verbatim. A third chip repeating that name is what "nothing else derives a
845
- * badge independently" looks like on screen, and it would appear on the exact
846
- * deployed build this ticket is observed against rather than on this branch.
847
- *
848
- * So this fires ONLY on the C8 fallback: no `class`, no C1 chip, nobody named,
849
- * and a `createdBy` stamp that says who CREATED the definition. `Added by` is
850
- * that weaker claim worded as itself, never as an ownership or a share claim.
851
- * Null on your own rows and on the database's own columns, where there is no
852
- * whose to name.
853
- */
854
- export function fieldAuthorBadge(
855
- field: unknown,
856
- viewer?: FieldViewer | null
857
- ): { text: string; title: string } | null {
858
- if (fieldSectionOf(field, viewer) !== "colleagues") return null;
859
- const author = fieldAuthorOf(field);
860
- if (!author || author.from !== "createdBy") return null;
861
- return { text: `Added by ${author.name}`, title: "Who created this column" };
862
- }
863
-
864
- /**
865
- * ⛔⛔ R16, AND THE PAYLOAD EXPRESSES IT UNDER THE SERVER'S OWN KEY. The ruling: a SHARED
866
- * definition wins a key collision, the local one is superseded rather than
867
- * deleted, and the field manager says so. The first two halves are real
868
- * server-side facts (`core.field_permissions.migrate_legacy_fields` re-promotes
869
- * a per-user fork of a key on every read, and `routes_tables`' delete door
870
- * clears both strata precisely because a fork survives), but NOTHING ON THE
871
- * WIRE MARKS THE ROW: `routes_customers._merge_shared_fields` projects the shared
872
- * definition in place and carries its thin `{ superseded: { stratum: "personal" } }`
873
- * marker. The local definition stays in the workspace member, but nothing needs to
874
- * copy it back onto the served field to tell the person what happened.
875
- *
876
- * This is a C8 reader, not an invented state: it returns the sentence only for
877
- * that explicit personal-stratum marker. Any absent, malformed, or other-stratum
878
- * payload stays null rather than turning an unrelated field into a collision.
879
- */
880
- export const SUPERSEDED_NOTE =
881
- "Superseded: the shared version of this column is the one in use, and your own copy is kept rather than deleted.";
882
-
883
- export function supersededNoteOf(field: unknown): string | null {
884
- if (typeof field !== "object" || field === null) return null;
885
- const marker = (field as { superseded?: { stratum?: unknown } }).superseded;
886
- return marker?.stratum === "personal"
887
- ? SUPERSEDED_NOTE
888
- : null;
889
- }
 
710
 
711
  /** R19's undo, in the words the rest of the product uses for the same act. */
712
  export const DESCRIPTION_RESET_LABEL = "Reset to default";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/index.css CHANGED
@@ -110,10 +110,6 @@
110
  paint underneath its own dialog — which is precisely the failure the paragraph above
111
  records, re-created one modal later. */
112
  --cg-z-overlay: 110;
113
- /* Field-access is a true modal opened FROM the Fields portal overlay. It is the one
114
- intentional exception to the usual "overlay over dialog" order: it must cover the
115
- picker it was opened from, or its own controls are visible but unreachable. */
116
- --cg-z-dialog: 120;
117
 
118
  /* --- Loopable C1 tokens (wave-8 I7c) ------------------------------------
119
  ADDITIVE on purpose. The `--cg-*` tokens above are NOT redefined because
@@ -605,18 +601,6 @@ body {
605
  text-overflow: ellipsis;
606
  white-space: nowrap;
607
  }
608
- .cg-type-info {
609
- display: inline-flex;
610
- align-items: center;
611
- justify-content: center;
612
- flex: 0 0 auto;
613
- width: 16px;
614
- height: 16px;
615
- color: var(--lp-muted);
616
- cursor: help;
617
- }
618
- .cg-type-row:hover .cg-type-info,
619
- .cg-type-row:focus-visible .cg-type-info { color: var(--lp-blue-deep); }
620
  .cg-type-check { color: var(--lp-blue-deep); flex: 0 0 auto; }
621
  /* W40-T29 (owner instruction 31) - the create picker's Advanced group: a hairline, then a quiet
622
  one-word heading, then the three kinds most people never want. Same typographic weight as
@@ -1323,15 +1307,7 @@ body {
1323
  the owner's "the Route one is the only one with smaller font". The row now declares the SAME
1324
  size the controls in it use, so a control written with `font: inherit` lands on it by
1325
  construction rather than by being told twice. */
1326
- /* ⭐⭐ W42-T19 (owner instruction 11) — CALENDAR'S SECOND ROW SHARES THIS RULE RATHER THAN COPYING
1327
- IT. `.cg-cal-settings` is a selector added to Map's own declaration block, not a duplicate set of
1328
- values beside it, so the two rows cannot drift: one change moves both. The owner asked for
1329
- "exactly how Time-series and Map view has it", and identical-by-construction is the only spelling
1330
- of that which survives a later spacing tweak.
1331
- ⚠ `.cg-cal-bar` is NOT this and must not be reused: it is the month navigator INSIDE `.cg-calview`
1332
- (see its rule further down), a different row in a different box. */
1333
- .cg-map-settings,
1334
- .cg-cal-settings {
1335
  flex: 0 0 auto;
1336
  min-height: 40px;
1337
  display: flex;
@@ -1345,8 +1321,7 @@ body {
1345
  font-size: var(--lp-fs-xs);
1346
  line-height: 1.3;
1347
  }
1348
- .cg-map-settings-label,
1349
- .cg-cal-settings-label {
1350
  margin-right: 2px;
1351
  font-weight: 600;
1352
  letter-spacing: 0.02em;
@@ -5734,14 +5709,8 @@ a.cg-map-ctl-b { text-decoration: none; }
5734
  measured numbers on `padding` below. */
5735
  gap: 8px;
5736
  min-width: 0;
5737
- /* ⭐ W42-T43 / R12.2 — `position: relative` REMOVED WITH THE CHEVRON IT ANCHORED. Its comment
5738
- read "the disclosure chevron is positioned against this box", and `.cg-fold-chev` was the ONLY
5739
- absolutely-positioned descendant of this button (checked: the three rules naming
5740
- `.cg-fold-toggle` are this one, `:hover`, and `.cg-folder-mark`, which is `flex: 0 0 auto`).
5741
- With the chevron gone it anchored nothing and created a stacking context nothing used.
5742
- ⛔ The comment goes WITH it rather than being left behind: a comment naming a deleted element
5743
- is a tombstone that reads as intent, which is how T43's own ticket came to call this button
5744
- "the twisty" when it is the folder header. */
5745
  border: none;
5746
  background: transparent;
5747
  font: inherit;
@@ -5773,15 +5742,18 @@ a.cg-map-ctl-b { text-decoration: none; }
5773
  cursor: pointer;
5774
  }
5775
  .cg-fold-toggle:hover { background: var(--lp-blue-tint); color: var(--lp-ink); }
5776
- /* ⭐⭐ W42-T43 / R12.2 — `.cg-fold-chev` AND `.cg-fold-chev.is-shut` ARE DELETED. The disclosure
5777
- chevron is gone: R12 replaced expand/collapse with a PATH, so `.cg-fold-toggle` is now the DRILL
5778
- button and there is no open/shut state left to rotate. Lane C removed the `<span>` and the whole
5779
- `opened`/`collapsed` machinery from `ViewSidebar.tsx` (commit `7f6a1c0`); this is the CSS half of
5780
- that one change, landed second by ruling so the rule never outlives its markup.
5781
- ⭐ THE MEASURED INDENT FIX ABOVE IS UNAFFECTED, and that is a fact about the box model rather
5782
- than care taken: the chevron was `position: absolute; left: -8px`, i.e. already OUT OF FLOW, so
5783
- removing it moves the folder mark and the name by ZERO pixels and the `7 + 2 + 8 = 17px`
5784
- arithmetic in `.cg-fold-toggle`'s padding still holds. */
 
 
 
5785
  .cg-fold-name {
5786
  flex: 1 1 auto;
5787
  overflow: hidden;
@@ -10654,11 +10626,6 @@ a.cg-map-ctl-b { text-decoration: none; }
10654
  padding-top: 18vh;
10655
  z-index: 80;
10656
  }
10657
- /* Do not raise every shell confirmation. Only field access is opened from the
10658
- body-portal'd Fields panel and therefore has to sit above that panel. */
10659
- .cg-field-access-scrim {
10660
- z-index: var(--cg-z-dialog);
10661
- }
10662
  .shell-newdb {
10663
  width: 400px;
10664
  max-width: calc(100vw - 48px);
@@ -13493,3 +13460,29 @@ input.conn-odoo-v:disabled { background: var(--lp-surface-2); color: var(--lp-mu
13493
  font-size: var(--lp-fs-2xs);
13494
  color: var(--lp-muted);
13495
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  paint underneath its own dialog — which is precisely the failure the paragraph above
111
  records, re-created one modal later. */
112
  --cg-z-overlay: 110;
 
 
 
 
113
 
114
  /* --- Loopable C1 tokens (wave-8 I7c) ------------------------------------
115
  ADDITIVE on purpose. The `--cg-*` tokens above are NOT redefined because
 
601
  text-overflow: ellipsis;
602
  white-space: nowrap;
603
  }
 
 
 
 
 
 
 
 
 
 
 
 
604
  .cg-type-check { color: var(--lp-blue-deep); flex: 0 0 auto; }
605
  /* W40-T29 (owner instruction 31) - the create picker's Advanced group: a hairline, then a quiet
606
  one-word heading, then the three kinds most people never want. Same typographic weight as
 
1307
  the owner's "the Route one is the only one with smaller font". The row now declares the SAME
1308
  size the controls in it use, so a control written with `font: inherit` lands on it by
1309
  construction rather than by being told twice. */
1310
+ .cg-map-settings {
 
 
 
 
 
 
 
 
1311
  flex: 0 0 auto;
1312
  min-height: 40px;
1313
  display: flex;
 
1321
  font-size: var(--lp-fs-xs);
1322
  line-height: 1.3;
1323
  }
1324
+ .cg-map-settings-label {
 
1325
  margin-right: 2px;
1326
  font-weight: 600;
1327
  letter-spacing: 0.02em;
 
5709
  measured numbers on `padding` below. */
5710
  gap: 8px;
5711
  min-width: 0;
5712
+ /* the disclosure chevron is positioned against this box */
5713
+ position: relative;
 
 
 
 
 
 
5714
  border: none;
5715
  background: transparent;
5716
  font: inherit;
 
5742
  cursor: pointer;
5743
  }
5744
  .cg-fold-toggle:hover { background: var(--lp-blue-tint); color: var(--lp-ink); }
5745
+ .cg-fold-chev {
5746
+ position: absolute;
5747
+ left: -8px;
5748
+ top: 50%;
5749
+ transform: translateY(-50%);
5750
+ transition: transform 0.12s ease;
5751
+ font-size: var(--lp-fs-4xs);
5752
+ }
5753
+ /* ⚠ the translate MUST be repeated, not appended: `transform` is ONE property, so a bare
5754
+ `rotate(-90deg)` here would drop the centring and the collapsed chevron would jump half its
5755
+ own height. Measured both states in the harness. */
5756
+ .cg-fold-chev.is-shut { transform: translateY(-50%) rotate(-90deg); }
5757
  .cg-fold-name {
5758
  flex: 1 1 auto;
5759
  overflow: hidden;
 
10626
  padding-top: 18vh;
10627
  z-index: 80;
10628
  }
 
 
 
 
 
10629
  .shell-newdb {
10630
  width: 400px;
10631
  max-width: calc(100vw - 48px);
 
13460
  font-size: var(--lp-fs-2xs);
13461
  color: var(--lp-muted);
13462
  }
13463
+
13464
+ /* Wave 43 — compact date/recurrence editor, filtered bulk update, and view-local fullscreen. */
13465
+ .cg-date-picker { width: min(328px, calc(100vw - 24px)); padding: 10px; }
13466
+ .cg-date-picker-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; font-size: var(--lp-fs-xs); }
13467
+ .cg-icon-button { width: 26px; height: 26px; border: 0; border-radius: var(--lp-r-sm); background: transparent; color: var(--lp-ink); cursor: pointer; font: inherit; font-size: 20px; line-height: 1; }
13468
+ .cg-icon-button:hover, .cg-icon-button:focus-visible { background: var(--lp-surface-2); outline: none; }
13469
+ .cg-date-weekdays, .cg-date-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; text-align: center; }
13470
+ .cg-date-weekdays { margin-top: 8px; color: var(--lp-muted); font-size: var(--lp-fs-3xs); }
13471
+ .cg-date-grid { margin-top: 3px; }
13472
+ .cg-date-day { min-height: 27px; border: 0; border-radius: var(--lp-r-sm); background: transparent; color: var(--lp-ink); cursor: pointer; font: inherit; font-size: var(--lp-fs-2xs); }
13473
+ .cg-date-day:hover, .cg-date-day:focus-visible { background: var(--lp-surface-2); outline: none; }
13474
+ .cg-date-day.is-selected { background: var(--lp-blue-solid); color: var(--lp-on-blue, #fff); }
13475
+ .cg-date-recurrence, .cg-date-preview { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 10px; padding-top: 8px; border-top: 1px solid var(--lp-line); font-size: var(--lp-fs-2xs); }
13476
+ .cg-date-recurrence .cg-pop-title, .cg-date-preview .cg-pop-title { width: 100%; }
13477
+ .cg-date-interval { width: 42px; padding: 3px; }
13478
+ .cg-date-holidays { width: 100%; color: var(--lp-muted); }
13479
+ .cg-date-preview span { padding: 2px 4px; border-radius: var(--lp-r-sm); background: var(--lp-surface-2); color: var(--lp-muted); font-variant-numeric: tabular-nums; }
13480
+ .cg-bulk-update-pop { display: flex; flex-direction: column; gap: 8px; min-width: 240px; }
13481
+ .cg-fullscreen-toggle { align-self: flex-end; margin: 6px 8px -2px 0; border: 1px solid var(--lp-line); border-radius: var(--lp-r-sm); background: var(--lp-surface); color: var(--lp-muted); cursor: pointer; font: inherit; font-size: var(--lp-fs-3xs); padding: 4px 7px; }
13482
+ .cg-fullscreen-toggle:hover, .cg-fullscreen-toggle:focus-visible { color: var(--lp-ink); border-color: var(--lp-muted); outline: none; }
13483
+ .cg-shell.is-view-fullscreen { position: fixed; inset: 0; z-index: var(--cg-z-overlay); width: auto; height: auto; background: var(--lp-surface); }
13484
+ .cg-shell.is-view-fullscreen .cg-views, .cg-shell.is-view-fullscreen .cg-chat-dock { display: none; }
13485
+ .cg-shell.is-view-fullscreen .cg-main { min-height: 100vh; }
13486
+ .cg-grid-box { overflow: hidden; }
13487
+ .cg-column-drop-shadow { position: absolute; top: 0; bottom: 0; width: 2px; pointer-events: none; background: var(--lp-blue-solid); box-shadow: 0 0 12px color-mix(in srgb, var(--lp-blue-solid) 45%, transparent); opacity: 0; transform: translateX(-1px); transition: opacity 140ms ease, transform 140ms ease; }
13488
+ .cg-column-drop-shadow.is-visible { opacity: 1; transform: translateX(0); }
web/src/shell/NavExtras.tsx CHANGED
@@ -735,8 +735,9 @@ export function CreateNewRow({
735
  export function FolderHead({
736
  folder,
737
  count,
 
738
  collapsed,
739
- onOpen,
740
  onRename,
741
  onDelete,
742
  isDrop,
@@ -747,18 +748,9 @@ export function FolderHead({
747
  /* ⛔ WAVE 35 · T07 (owner item 9) — the `important?: NavImportant` prop is DELETED. It carried
748
  wave-34 R1's per-folder SUM of mark-important numbers; item 9 retires that badge, and `tsc`'s
749
  unused-locals check is what named this prop the moment its only reader went. */
750
- /* ⛔⛔ W42-T42 (ruling R12.2) — `open` and `onToggle` are DELETED, and so is the
751
- `aria-expanded` they fed. A nav folder no longer expands in place: it is a step on a path, and
752
- pressing it walks INTO it. Announcing an expanded or collapsed state for a list that has
753
- neither is the wrong sentence read aloud, and the views half of the rail (W42-T43) removed the
754
- same line, so the two folder systems now read the same way to a screen reader. R12 exists to
755
- end that difference.
756
- ⚠ `collapsed` IS A DIFFERENT QUESTION AND IT STAYS. It asks whether the RAIL is folded to its
757
- narrow strip, not whether this folder is shut, and it was never part of the expand state. */
758
  collapsed: boolean;
759
- /** Walk into this folder. Named for the walk rather than reusing `onToggle`, so a reader cannot
760
- * mistake a drill for a state flip that no longer exists. */
761
- onOpen: () => void;
762
  onRename: (name: string) => void;
763
  onDelete: () => void;
764
  /** Wave 14 C-NAVFOLD — a database row is being dragged over this folder. */
@@ -785,16 +777,13 @@ export function FolderHead({
785
  className={"shell-nav-folder" + (isDrop ? " is-drop" : "")}
786
  {...(dropProps ?? {})}
787
  >
788
- {/* R3: no chevron — the Views-rail folder look; the mark + bold label ARE the row.
789
- ⭐ W42-T42 (R12.2) — and no twisty was ever drawn here, so there is nothing left to
790
- remove: what went is the expand STATE behind it. The accessible name says what the press
791
- does, in the same words the views rail uses, because one gesture read aloud two ways is
792
- the difference R12 is closing. */}
793
  <button
794
  type="button"
795
  className="shell-nav-folderbtn"
796
- aria-label={`Open folder ${folder.name}`}
797
- onClick={onOpen}
798
  >
799
  <FolderIcon />
800
  <span className="shell-nav-label">{folder.name}</span>
 
735
  export function FolderHead({
736
  folder,
737
  count,
738
+ open,
739
  collapsed,
740
+ onToggle,
741
  onRename,
742
  onDelete,
743
  isDrop,
 
748
  /* ⛔ WAVE 35 · T07 (owner item 9) — the `important?: NavImportant` prop is DELETED. It carried
749
  wave-34 R1's per-folder SUM of mark-important numbers; item 9 retires that badge, and `tsc`'s
750
  unused-locals check is what named this prop the moment its only reader went. */
751
+ open: boolean;
 
 
 
 
 
 
 
752
  collapsed: boolean;
753
+ onToggle: () => void;
 
 
754
  onRename: (name: string) => void;
755
  onDelete: () => void;
756
  /** Wave 14 C-NAVFOLD — a database row is being dragged over this folder. */
 
777
  className={"shell-nav-folder" + (isDrop ? " is-drop" : "")}
778
  {...(dropProps ?? {})}
779
  >
780
+ {/* R3: no chevron — the Views-rail folder look. Open state reads from the members
781
+ below it (and aria-expanded says it aloud); the mark + bold label ARE the row. */}
 
 
 
782
  <button
783
  type="button"
784
  className="shell-nav-folderbtn"
785
+ aria-expanded={open}
786
+ onClick={onToggle}
787
  >
788
  <FolderIcon />
789
  <span className="shell-nav-label">{folder.name}</span>
web/src/shell/ShareDialog.tsx CHANGED
@@ -66,78 +66,6 @@ const ROLE_BLURB: Record<ShareKind, Record<ShareRole, string>> = {
66
  },
67
  };
68
 
69
- /**
70
- * ⭐⭐ W42-T26 (owner instruction 8, R9, contract C7) — THE SHARER IS TOLD WHICH FIELDS TRAVEL.
71
- * Sharing a view grants every field the view NAMES, and until this landed the dialog said nothing
72
- * about fields at all. The trap the ticket names: T25 makes the behaviour correct and nothing on
73
- * screen changes, so the disclosure is the half that gets dropped.
74
- *
75
- * ⛔ THESE ARE CONSTANTS, NOT INLINE JSX TEXT, FOR TWO REASONS. (1) `verify_prose`'s JSX pass skips
76
- * any run containing a newline [[web-prose-blind-to-wrapped-jsx]], and this file's own comments
77
- * record that blind spot twice; a `const` string literal is seen by the gate whatever prettier does
78
- * to the markup around it. (2) `wiring_rows/wave42_g.py` pins this copy by regex, and a regex
79
- * cannot span a JSX line wrap. Standing rule 2: no em dash and no en dash below.
80
- */
81
- const VIEW_FIELD_TRAVEL =
82
- "Sharing a view also shares the fields it uses: the columns it shows, and the columns it groups by, colors by and sorts by.";
83
- /** ⚠ ITS OWN SENTENCE ON PURPOSE, and the non-obvious half of the disclosure. A sharer reasons
84
- * about the columns they can SEE; a condition may name one they never put on screen, and the
85
- * grant covers it all the same. The done-when calls this clause out separately, so it has to be
86
- * readable on its own rather than being a word inside a list.
87
- * ⛔ Do NOT restate the literal below in prose here: `wave42_g.py` pins it, and the WIRINGS loop
88
- * matches raw file text (comments included), so a paraphrase close enough to match would let the
89
- * row pass off its own explanation. */
90
- const VIEW_FILTER_FIELDS =
91
- "The filters count too. A filter can test a column that is not on screen, and sharing this view hands that column over as well.";
92
- /** ⚠ The grant is TOPIC-WIDE by construction (C7), so the dialog has to say so in the reader's
93
- * terms rather than let them assume it stops at this view. */
94
- const VIEW_FIELD_TOPIC_WIDE =
95
- "Each of those fields then shows on every view of this database, not only on this one.";
96
- const SHARED_FIELDS_LEAD = "Fields shared with this view:";
97
- const REFUSED_FIELDS_LEAD = "These fields could not be included:";
98
-
99
- /** One field the server named in its answer, with the reason it gave for refusing it. */
100
- type FieldNote = { key: string; reason: string };
101
-
102
- /**
103
- * `sharedFieldKeys` / `refusedFieldKeys` off the RAW PUT body, normalised.
104
- *
105
- * ⛔ BOTH KEYS ARE OPTIONAL AND ABSENT TODAY. C7 splits this feature across two lanes and the
106
- * server half is not this fence; a grep for either name has zero code hits at the time of writing.
107
- * So the contract here is: render NOTHING when the key is missing or unusable, never throw, and
108
- * light up unchanged the moment the server starts answering. `shareModel.parseShare` cannot carry
109
- * these (it builds a new object with five fixed keys and drops the rest) and is out of fence, so
110
- * the raw body is the door.
111
- *
112
- * ⚠ The shape is read defensively rather than assumed: `string[]`, `{key|colId|field, reason|why}[]`
113
- * and `Record<key, string | {reason}>` all normalise. The REASON TEXT IS THE SERVER'S, never
114
- * invented here, so a new refusal cause needs no client change.
115
- */
116
- function fieldNotes(raw: unknown): FieldNote[] {
117
- const out: FieldNote[] = [];
118
- const push = (key: unknown, reason: unknown) => {
119
- const k = typeof key === "string" ? key.trim() : "";
120
- if (!k) return;
121
- out.push({ key: k, reason: typeof reason === "string" ? reason.trim() : "" });
122
- };
123
- if (Array.isArray(raw)) {
124
- for (const item of raw) {
125
- if (typeof item === "string") {
126
- push(item, "");
127
- } else if (item && typeof item === "object") {
128
- const rec = item as Record<string, unknown>;
129
- push(rec.key ?? rec.colId ?? rec.field, rec.reason ?? rec.why);
130
- }
131
- }
132
- } else if (raw && typeof raw === "object") {
133
- for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
134
- if (v && typeof v === "object") push(k, (v as Record<string, unknown>).reason);
135
- else push(k, typeof v === "string" ? v : "");
136
- }
137
- }
138
- return out;
139
- }
140
-
141
  export default function ShareDialog({
142
  kind,
143
  id,
@@ -172,10 +100,6 @@ export default function ShareDialog({
172
  const [busy, setBusy] = useState(false);
173
  const [pick, setPick] = useState("");
174
  const [pickRole, setPickRole] = useState<ShareRole>("view");
175
- // W42-T26 — the RESULT half: what the last successful save actually granted, and what it
176
- // refused. Empty until a save answers, and empty again whenever one answers without the keys.
177
- const [sharedFields, setSharedFields] = useState<FieldNote[]>([]);
178
- const [refusedFields, setRefusedFields] = useState<FieldNote[]>([]);
179
 
180
  const path = `${API_V1}/share/${encodeURIComponent(kind)}/${encodeURIComponent(id)}`;
181
 
@@ -247,10 +171,6 @@ export default function ShareDialog({
247
  const body = (await res.json().catch(() => null)) as
248
  | { error?: { message?: string } }
249
  | null;
250
- // ⛔ CLEARED ON FAILURE TOO. A refusal list left standing beside a change that did not
251
- // happen describes a grant nobody made.
252
- setSharedFields([]);
253
- setRefusedFields([]);
254
  setError(
255
  res.status >= 500
256
  ? "Something went wrong on our side. Try again in a moment."
@@ -270,11 +190,6 @@ export default function ShareDialog({
270
  // promote anybody, and this line must never be the reason it looks like it can.
271
  const saved = parseShare({ ...(body as object), mayAdminister: true });
272
  setEntries(saved.entries);
273
- // ⭐ W42-T26 / C7 — read STRAIGHT OFF THE RAW BODY, because `parseShare` keeps five keys
274
- // and drops everything else, and `shareModel.ts` is another lane's file this wave.
275
- const answered = (body ?? null) as Record<string, unknown> | null;
276
- setSharedFields(fieldNotes(answered?.sharedFieldKeys));
277
- setRefusedFields(fieldNotes(answered?.refusedFieldKeys));
278
  return true;
279
  } catch {
280
  setError("Cannot reach the server.");
@@ -327,20 +242,10 @@ export default function ShareDialog({
327
  : "Sharing never widens past this workspace: everyone here can already open the surface it lives on."}
328
  </p>
329
  {kind === "view" ? (
330
- <>
331
- <p className="shell-share-note">
332
- View access is the general rule. A field's own Share field access takes precedence, so
333
- a field shared as Can view stays read-only even inside an editable view.
334
- </p>
335
- {/* ⭐⭐ W42-T26 / C7 — WHICH FIELDS TRAVEL, and how far. Two paragraphs, not one and
336
- not four: the done-when reads for three statements (what travels, the FILTER's
337
- fields by name, and the topic-wide reach), and a sharer must be able to point at a
338
- sentence for each without reading an essay in a dialog subtitle. */}
339
- <p className="shell-share-note">
340
- {VIEW_FIELD_TRAVEL} {VIEW_FIELD_TOPIC_WIDE}
341
- </p>
342
- <p className="shell-share-note">{VIEW_FILTER_FIELDS}</p>
343
- </>
344
  ) : kind === "field" ? (
345
  <p className="shell-share-note">
346
  Field access takes precedence over the view. Can view keeps values and field settings
@@ -361,31 +266,6 @@ export default function ShareDialog({
361
  one-line answer above it, since the fact that changes everything
362
  ("Everyone can edit") is the one a list of rows buries. */}
363
  <p className="shell-share-summary">{shareSummary(entries)}</p>
364
- {/* ⭐⭐ W42-T26 / C7 — THE RESULT: which fields actually travelled, and which could not,
365
- each with the reason the SERVER gave. Absent both keys this renders nothing at all
366
- and the dialog looks exactly as it did before the ticket, which is today's state:
367
- the server half is lane A's and has not landed.
368
- ⚠ NO NEW CLASSES. `index.css` is another lane's file this wave and a lane sheet
369
- loses every equal-specificity fight with it [[a-lane-stylesheet-cannot-override-index-css]],
370
- so a refusal reuses the row/who/role anatomy the entries list already paints. */}
371
- {kind === "view" && sharedFields.length > 0 ? (
372
- <p className="shell-share-note">
373
- {SHARED_FIELDS_LEAD} {sharedFields.map((f) => f.key).join(", ")}
374
- </p>
375
- ) : null}
376
- {kind === "view" && refusedFields.length > 0 ? (
377
- <>
378
- <p className="shell-share-note">{REFUSED_FIELDS_LEAD}</p>
379
- <div className="shell-share-list">
380
- {refusedFields.map((f) => (
381
- <div className="shell-share-row" key={f.key}>
382
- <span className="shell-share-who">{f.key}</span>
383
- {f.reason ? <span className="shell-share-role">{f.reason}</span> : null}
384
- </div>
385
- ))}
386
- </div>
387
- </>
388
- ) : null}
389
  <div className="shell-share-list">
390
  {state.owner ? (
391
  <div className="shell-share-row is-owner">
 
66
  },
67
  };
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  export default function ShareDialog({
70
  kind,
71
  id,
 
100
  const [busy, setBusy] = useState(false);
101
  const [pick, setPick] = useState("");
102
  const [pickRole, setPickRole] = useState<ShareRole>("view");
 
 
 
 
103
 
104
  const path = `${API_V1}/share/${encodeURIComponent(kind)}/${encodeURIComponent(id)}`;
105
 
 
171
  const body = (await res.json().catch(() => null)) as
172
  | { error?: { message?: string } }
173
  | null;
 
 
 
 
174
  setError(
175
  res.status >= 500
176
  ? "Something went wrong on our side. Try again in a moment."
 
190
  // promote anybody, and this line must never be the reason it looks like it can.
191
  const saved = parseShare({ ...(body as object), mayAdminister: true });
192
  setEntries(saved.entries);
 
 
 
 
 
193
  return true;
194
  } catch {
195
  setError("Cannot reach the server.");
 
242
  : "Sharing never widens past this workspace: everyone here can already open the surface it lives on."}
243
  </p>
244
  {kind === "view" ? (
245
+ <p className="shell-share-note">
246
+ View access is the general rule. A field's own Share field access takes precedence, so
247
+ a field shared as Can view stays read-only even inside an editable view.
248
+ </p>
 
 
 
 
 
 
 
 
 
 
249
  ) : kind === "field" ? (
250
  <p className="shell-share-note">
251
  Field access takes precedence over the view. Can view keeps values and field settings
 
266
  one-line answer above it, since the fact that changes everything
267
  ("Everyone can edit") is the one a list of rows buries. */}
268
  <p className="shell-share-summary">{shareSummary(entries)}</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
  <div className="shell-share-list">
270
  {state.owner ? (
271
  <div className="shell-share-row is-owner">
web/src/shell/Shell.tsx CHANGED
@@ -64,7 +64,7 @@ const AutomationSurface = lazy(() => import("../automation/AutomationSurface"));
64
  // ⚠ IT JOINS `Lazily`, NOT A BARE `Suspense`: the shared wrapper carries the ErrorBoundary, so a
65
  // chunk that fails to load names the surface it was for instead of blanking the frame.
66
  const CustomerGrid = lazy(() => import("../customer-grid/CustomerGrid"));
67
- import { clearCustomersCache, currentSurfaceScope, peekWorkspace } from "../customer-grid/apiBridge";
68
  import { OverlayProvider } from "../customer-grid/OverlaySurface";
69
  // ROWS_STALE_EVENT left with `addRecord` (wave 20 item 4): the shell no longer writes rows,
70
  // so it no longer has to tell the grid that it did.
@@ -76,14 +76,8 @@ import type { SettingsSection } from "../settings/SettingsModal";
76
  import { Brand } from "./Brand";
77
  import { ErrorBoundary } from "./ErrorBoundary";
78
  import LoginPage from "./LoginPage";
79
- import { ASSISTANT_ROUTE, CONNECTORS_ROUTE, EMPTY_NAV_PREFS, ENVELOPE_KEYS, FEEDBACK_ROUTE, HOME_ROUTE, INBOX_ROUTE, NO_SUBSCRIPTION_TENANT, STARRED_ROUTE, SUBSCRIPTION_ROUTE, USAGE_ROUTE, MAX_NAV_FOLDERS, NAV_TIMEOUT_STATUS, appLink, canonicalRoute, databaseEntries, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchTableFootprint, navFolderIdOf, navLevelAt, postOpened, QUERY_ROUTE, resolveRoute, rewrittenHash, routeKeyOf, saveNavMeta, saveNavPrefs, shapeNav, splitChrome, viewsForDb } from "./nav";
80
- import type { DbWorkspaces, NavEntry, NavFolder, NavMetaPatch, NavPage, NavPrefs, Recent } from "./nav";
81
- // ⭐⭐ WAVE 42 · T16 (contract C5) — the rail's views level walks the SAME path resolver the
82
- // grid's view rail walks (W42-T41). One walk, two callers: a level here and a level there can
83
- // never disagree about what is filed where, because neither of them re-derives it.
84
- import { levelAt } from "../customer-grid/folders";
85
- import type { GridFolder, SavedView } from "../customer-grid/types";
86
- import type { WorkspaceHolder } from "../customer-grid/viewEcho";
87
  // ⭐ 2026-08-14 — the database frame, extracted so the Query module can wear the SAME one.
88
  import { DbIcon, gridScopeFor } from "./dbFrame";
89
  /* ⭐ W35-T09 — the app's own star (B-3): one mark, one meaning (DESIGN.md §4). */
@@ -339,12 +333,6 @@ type Nav =
339
  const NO_UTILITY: NavPage[] = [];
340
  /** Stable identity, like `NO_ENTRIES` — a fresh `[]` per render would re-run Home's memo. */
341
  const NO_RECENTS: Recent[] = [];
342
- /** W42-T42 — the rail's folder heads while a search needle is live: none, flattened away. Same
343
- * stable-identity rule as the two above. */
344
- const NO_NAV_FOLDERS: NavFolder[] = [];
345
- /** The same, for the rail's VIEW folders — a flattened search shows no folder heads on either
346
- * level, because the two levels answer the search box one way (W42-T42). */
347
- const NO_VIEW_FOLDERS: GridFolder[] = [];
348
 
349
  /**
350
  * ⭐⭐ W33-T22 (owner item 1) — THE TWO ROWS THE PAYLOAD DECIDES, FOUND IN ONE PLACE.
@@ -1214,24 +1202,7 @@ function ShellFrame() {
1214
  // route has to join, and a route that joins it must also RENDER something. A drill is a rail
1215
  // STATE: the content pane keeps showing whatever it was showing, which is also the honest
1216
  // answer to "I opened the navigation, I did not leave the page".
1217
- // ⭐⭐ WAVE 42 · T16 (owner instructions 4 + 16, contract C5, amendment A1) — THE KINDS ARE
1218
- // ONE CONTINUOUS PATH, AND EACH STEP CARRIES WHERE IT STANDS INSIDE ITSELF.
1219
- //
1220
- // ⛔ `{kind:"db"}` IS REPLACED BY `{kind:"views"}`, and that is the contract rather than
1221
- // tidying. A `db` step was a DESTINATION the rail recorded and then re-navigated to, which is
1222
- // why `stepRail` used to write the hash; a `views` step is a place the rail STANDS, drawing
1223
- // that database's view folders and saved views in the rail itself. The old kind was named in
1224
- // exactly four places, all in this file, so nothing outside it has to learn a new word.
1225
- //
1226
- // ⭐ `at` IS THE PATH VARIANT W42-T41's MODEL ASKS FOR. `folders.ts::levelAt` answers "what is
1227
- // at this path" from a FOLDER ID, `null` meaning the top of that level, so a step that means to
1228
- // be walked has to be able to say which folder it is in. On `views` it is a view folder
1229
- // (`GridFolder.id`) and is walked below; on `data` it is a NAV folder, declared here so both
1230
- // halves of the path share ONE shape, and walked by W42-T42, which owns that generalisation.
1231
- type RailLevel =
1232
- | { kind: "root" }
1233
- | { kind: "data"; at: string | null }
1234
- | { kind: "views"; dbKey: string; at: string | null };
1235
  const [rail, setRail] = useState<{ hist: RailLevel[]; at: number }>(
1236
  () => ({ hist: [{ kind: "root" }], at: 0 })
1237
  );
@@ -1258,40 +1229,18 @@ function ShellFrame() {
1258
  setRail((s) =>
1259
  s.hist.length > 1
1260
  ? { ...s, at: 1 }
1261
- : { hist: [s.hist[0], { kind: "data", at: null }], at: 1 }
1262
  );
1263
  }, []);
1264
- /** Take ONE step along the path, whatever the step is.
 
1265
  * ⚠ It TRUNCATES anything ahead of the cursor, which is what a browser's forward button does
1266
  * after you take a new branch: a forward entry you can no longer reach by going back is a
1267
- * destination the history is lying about.
1268
- * ⭐ W42-T16 — one pusher for every kind of step. Two of them would be two places to remember
1269
- * the truncation rule, and the second one is where it gets forgotten. */
1270
- const pushLevel = useCallback((level: RailLevel) => {
1271
- setRail((s) => ({ hist: [...s.hist.slice(0, s.at + 1), level], at: s.at + 1 }));
1272
  setDbQuery("");
1273
  }, []);
1274
- /** Step from the database list into ONE database's VIEWS. The row's own `href` still opens the
1275
- * database in the content pane; this moves the RAIL to that database's views, which is what
1276
- * makes the click one step along a path rather than a departure from it (W42-T16, C5). */
1277
- const pushDb = useCallback(
1278
- (key: string) => pushLevel({ kind: "views", dbKey: key, at: null }),
1279
- [pushLevel]
1280
- );
1281
- /** Step INTO a view folder, staying in the same database. `at` is a `GridFolder.id`, exactly
1282
- * what `levelAt` reads, and `<` walks back out of it like any other step. */
1283
- const pushViewFolder = useCallback(
1284
- (dbKey: string, at: string | null) => pushLevel({ kind: "views", dbKey, at }),
1285
- [pushLevel]
1286
- );
1287
- /** Step INTO a DATABASE folder, staying in the database half of the path. `at` is a
1288
- * `NavFolder.id`, the same shape `navLevelAt` reads, and `<` walks back out of it like every
1289
- * other step (W42-T42, R12.1). It is the third caller of the ONE pusher rather than a second
1290
- * history: the truncation rule lives in exactly one place. */
1291
- const pushNavFolder = useCallback(
1292
- (at: string | null) => pushLevel({ kind: "data", at }),
1293
- [pushLevel]
1294
- );
1295
  // ⚠ Declared here and READ inside the Escape effect below, because that effect must not
1296
  // re-subscribe on every drag state change — and because the guard it needs is "a drag is in
1297
  // flight", which is state this component already holds (`dragKey`, declared further down with
@@ -1486,12 +1435,7 @@ function ShellFrame() {
1486
  const [navPrefs, setNavPrefs] = useState<NavPrefs>(EMPTY_NAV_PREFS);
1487
  const navPrefsRef = useRef(navPrefs);
1488
  navPrefsRef.current = navPrefs;
1489
- // ⛔⛔ W42-T42 (ruling R12.2) — THE `closedFolders` SET IS DELETED, AND SO IS THE TREE IT DREW.
1490
- // A nav folder used to expand in place: a twisty, an open/closed set, and its members drawn
1491
- // underneath it. R12 replaces expand and collapse with a PATH in both folder systems, so a
1492
- // folder is a step you walk into and there is no open state left for anything to hold. It was
1493
- // local `useState` and reached neither `saveNavPrefs` nor `postOpened`, so nothing persisted
1494
- // goes with it and no migration is owed.
1495
  const [schemaFor, setSchemaFor] = useState<string | null>(null);
1496
  useEffect(() => {
1497
  if (who === null) {
@@ -1551,8 +1495,14 @@ function ShellFrame() {
1551
  },
1552
  [commitPrefs]
1553
  );
1554
- // ⛔ W42-T42 (R12.2) — `toggleFolder` is deleted with `closedFolders`. A folder head opens a
1555
- // LEVEL now (`pushNavFolder`); there is no second state for it to flip.
 
 
 
 
 
 
1556
  // ── Wave 14 C-NAVFOLD (items 4/6): drag replaces the menu's Move-to-folder. A PRIVATE
1557
  // dataTransfer MIME so a drop anywhere text-editable types nothing (the wave-13 C-LAYOUT
1558
  // scar); `dropTarget` is a folder id or "__root__" (drag out = drop on the list itself).
@@ -2166,22 +2116,14 @@ function ShellFrame() {
2166
  // most a few dozen rows, so anything cleverer (fuzzy, ranked) would be a scoring function
2167
  // nobody can predict over a set small enough to read.
2168
  //
2169
- // ⛔⛔ W42-T42 (R12) — A LIVE QUERY FLATTENS ACROSS EVERY FOLDER, AND THAT IS THE WHOLE POINT.
2170
- // The path decides what the list shows only while the search box is EMPTY. The moment a needle
2171
- // is live the level stops deciding: the list is every matching database from every folder, with
2172
- // no folder heads and no level, because a search that quietly saw only the folder you happen to
2173
- // be standing in would answer "no such database" about a database that exists.
2174
- // ⛔ IT MIRRORS `customer-grid/ViewSidebar.tsx::levelGroups`, WHICH DOES EXACTLY THIS FOR VIEWS
2175
- // (W42-T43, same lane) — R12 asks the two folder systems to behave identically, and a rail whose
2176
- // two halves searched differently would breach it inside one wave. An earlier draft of this
2177
- // ticket scoped the search to the level and justified it by claiming parity with the views
2178
- // level; the views level does the OPPOSITE, and the claim was simply false. It was also a
2179
- // REGRESSION: the tree this replaced passed `EMPTY_NAV_PREFS` to `foldNav` precisely so a query
2180
- // flattened it, so scoping would have removed a behaviour that already worked.
2181
- // ⚠ THE PATH SURVIVES THE SEARCH. Typing never touches `rail`, so clearing the box puts the
2182
- // reader back on the level they were standing on rather than at the top — the third thing T43
2183
- // does, for the same reason.
2184
  const dbQ = dbQuery.trim().toLowerCase();
 
 
 
2185
  // WAVE 23 C10 — what Home draws: the server's recents plus this session's own stamps.
2186
  const recents = mergeRecents(nav.phase === "ready" ? nav.recents : NO_RECENTS, opened);
2187
 
@@ -2198,98 +2140,6 @@ function ShellFrame() {
2198
  // from `rail.at`, and everything reads it.
2199
  const railLevel: RailLevel = rail.hist[rail.at] ?? { kind: "root" };
2200
  const dbAt = railLevel.kind !== "root";
2201
- // ── W42-T16 (contract C5) — WHAT VIEWS IS THE RAIL STANDING IN? ───────────────────────────
2202
- //
2203
- // `viewsForDb` is a LOOKUP over payloads the client already holds, never a fetch — C5 forbids a
2204
- // second read. `peekWorkspace` exposes that existing cache without reading through it: absence
2205
- // stays absent, so an unvisited database renders PENDING rather than an untrue "no views".
2206
- const dbWorkspaces: DbWorkspaces = (() => {
2207
- const out: Record<string, WorkspaceHolder> = {};
2208
- for (const e of dbEntries) {
2209
- const ws = peekWorkspace(e.key);
2210
- if (ws) out[e.key] = { workspace: ws }; // ABSENT, never null
2211
- }
2212
- return out;
2213
- })();
2214
- // ⚠ CALLED UNCONDITIONALLY, with an empty key off the views level. Both resolvers answer a
2215
- // well-formed empty result for a key that names nothing, so there is no branch here to get
2216
- // wrong and no hook rule to trip over — the render simply ignores them anywhere else.
2217
- const railViewsLevel = railLevel.kind === "views" ? railLevel : null;
2218
- const railViews = viewsForDb(dbWorkspaces, railViewsLevel?.dbKey ?? "");
2219
- const viewLevel = levelAt<GridFolder, SavedView>(
2220
- railViewsLevel?.at ?? null,
2221
- railViews.folders,
2222
- railViews.views,
2223
- (v) => v.folderId
2224
- );
2225
- // ⛔⛔ W42-T42 EDIT, INSIDE W42-T16's BLOCK, AND THE ATTRIBUTION IS DELIBERATE. T16 owns this
2226
- // level and is still open; what it has left to do is the `dbWorkspaces` wiring above, which is
2227
- // untouched here. Only the SEARCH changed, and it changed because T42 changed the database
2228
- // level's search three lines down. Whoever finishes T16 must be able to see that.
2229
- //
2230
- // ⭐⭐ T16 WROTE HERE: "a level is one anatomy, so its search behaves one way." That sentence was
2231
- // TRUE when it was written and T42's first draft made it FALSE, by flattening the database
2232
- // level's search while this one still filtered its own level. The sentence is kept, because the
2233
- // principle is right and it is the reason for this edit; what changed is that the ONE WAY is now
2234
- // FLATTENING, on both levels, matching `customer-grid/ViewSidebar.tsx::levelGroups` on the views
2235
- // rail. Three surfaces, one meaning for the search box, which is what R12's "both folder systems
2236
- // behave identically" asks for.
2237
- //
2238
- // ⛔ THE FILTER RUNS OVER `railViews`, THE WHOLE DATABASE'S SET, NOT OVER `viewLevel`. Filtering
2239
- // the level's own arrays is the level-scoped search R12 forbids: it answers "no such view" about
2240
- // a view that exists one folder away. `viewsForDb` already handed us every folder and every view
2241
- // for this database, so the whole population is in hand and no second read is needed (C5).
2242
- // ⚠ NO FOLDER HEADS WHILE A NEEDLE IS LIVE, the same rule the database level applies: a
2243
- // flattened list has no levels in it, and a head sitting above matches drawn from other folders
2244
- // would imply they were its members.
2245
- //
2246
- // ⚠ UNOBSERVABLE ON THIS TREE, AND THAT IS THE REASON TO WRITE IT NOW RATHER THAN A REASON TO
2247
- // WAIT. `dbWorkspaces` is empty until T16 is wired, so `railViews` is empty, so no screen, gate
2248
- // or probe can tell this version from the one it replaces. It becomes visible the moment the
2249
- // integrator lands that wiring, which is exactly when nobody is looking for it.
2250
- const shownViewFolders = dbQ ? NO_VIEW_FOLDERS : viewLevel.folders;
2251
- const shownViews = dbQ
2252
- ? railViews.views.filter((v) => v.name.toLowerCase().includes(dbQ))
2253
- : viewLevel.leaves;
2254
- // ── W42-T42 (ruling R12, contracts C5 + C9) — THE DATABASE LEVEL IS A PATH TOO ─────────────
2255
- //
2256
- // ⭐⭐ ONE RESOLVER, TWO FOLDER SYSTEMS. `navLevelAt` is W42-T41's adapter over the SAME
2257
- // `levelAt` the views level three lines up calls; the two halves of the rail therefore answer
2258
- // "what is at this path" with one piece of code and one shape, which is the whole of C9.
2259
- // ⛔ RAW `entries`, NOT a pre-filtered list: `navLevelAt` calls `databaseEntries` itself, so
2260
- // handing it a filtered list would filter twice and, worse, would decide a folder's membership
2261
- // from a list the level is not drawing.
2262
- // ⚠ CALLED UNCONDITIONALLY with `null` off a `data` level, the same way the views resolvers
2263
- // above are: a well-formed top level for a path nobody is standing on costs one pass over a few
2264
- // dozen rows and saves a hook-order branch.
2265
- const navLevel = navLevelAt(
2266
- railLevel.kind === "data" ? railLevel.at : null,
2267
- entries,
2268
- navPrefs
2269
- );
2270
- // ⛔ NO FOLDER HEADS WHILE A NEEDLE IS LIVE. A flattened list has no levels in it, so a head
2271
- // would be a step into a place the list is already showing you the contents of — and it would
2272
- // sit above matches drawn from OTHER folders, implying they were its members.
2273
- const shownNavFolders = dbQ ? NO_NAV_FOLDERS : navLevel.folders;
2274
- // ⛔⛔ `dbEntries`, THE WHOLE SET — NOT `navLevel.leaves`. This is the flatten. Filtering the
2275
- // level's own leaves is the level-scoped search R12 forbids and reads as "no such database"
2276
- // over a database sitting one folder away. `dbEntries` is every database the viewer is granted,
2277
- // which is exactly the population a search should answer over, and `databaseEntries` has
2278
- // already removed the surfaces that are not databases (D-54).
2279
- const shownDbs = dbQ
2280
- ? dbEntries.filter((e) => e.label.toLowerCase().includes(dbQ))
2281
- : navLevel.leaves;
2282
- // ⛔ A FOLDER HEAD COUNTS **BLOCKS**, AND IT MUST KEEP DOING SO. `.shell-nav-foldercount` has
2283
- // meant "how many databases are filed here" since wave 14 (`verify_ui.py` W35-T07 pins that it
2284
- // survives), and `foldNav` counted a BLOCK — a family head, its depth-1 children riding with
2285
- // it. `navFolderIdOf` mirrors that same block rule, so counting depth-0 heads through it gives
2286
- // the number the head has always shown.
2287
- // ⚠ COUNTED OVER THE UNFILTERED LIST ON PURPOSE. The folder's members are not rendered at this
2288
- // level at all, so a search over THIS level's rows says nothing about how many things are
2289
- // inside the folder; filtering the count would make the head lie about the place it leads to.
2290
- const navFolderIdFor = navFolderIdOf(entries, navPrefs);
2291
- const navFolderCount = (id: string) =>
2292
- dbEntries.filter((e) => e.depth === 0 && navFolderIdFor(e) === id).length;
2293
  const canRailBack = rail.at > 0;
2294
  const canRailForward = rail.at < rail.hist.length - 1;
2295
  /**
@@ -2297,17 +2147,10 @@ function ShellFrame() {
2297
  * Connectors back on screen — a level replaces the rail's rows, so this is the way out, not a
2298
  * convenience.
2299
  *
2300
- * ⛔⛔ W42-T16 (contract C5) — A STEP NEVER NAVIGATES NOW, AND THE ARGUMENT THAT SAID IT MUST
2301
- * IS RETIRED RATHER THAN DELETED. W41-T32 wrote here that a `db` step had to re-navigate
2302
- * "because that is what the entry MEANS": for a database the path WAS the open surface, so
2303
- * moving the rail without moving the grid would have shown a path nobody was standing on. That
2304
- * held only while a level had nothing of the database in it. It no longer does. A `views` level
2305
- * RENDERS that database's view folders and saved views in the rail, so the rail is showing the
2306
- * place the reader is standing in, and `<` walking out of it is a walk out of a level rather
2307
- * than a lie about the content pane. Re-navigating would now be the defect: it would throw the
2308
- * grid to another table every time somebody backed out of a folder.
2309
- * ⚠ And a step that writes `window.location.hash` is a real browser navigation — a page load
2310
- * on the way to a rail render, which is what the owner asked this level not to be.
2311
  * ⚠ A plain function, not a `useCallback`: it reads `rail` from this render and every click
2312
  * gets a fresh one, so there is no stale-cursor window between two human clicks — and a hook
2313
  * here would have to be declared 900 lines up, away from the thing it walks.
@@ -2318,32 +2161,13 @@ function ShellFrame() {
2318
  if (!dest) return;
2319
  setRail({ hist: rail.hist, at });
2320
  setDbQuery("");
2321
- // ⛔ NOTHING ELSE. See the note above: the walk moves the RAIL and only the rail.
2322
  };
2323
  /** The level's own name, and the only header a level gets (DESIGN §2: a short plain noun). */
2324
- // ⭐ W42-T16 — a view FOLDER is a level of its own and says its own name; the database names
2325
- // the level at the top of its views. Falling back to the key's label keeps the header honest
2326
- // for a database whose row is filtered out of the list behind it.
2327
- // ⭐ W42-T42 — a DATABASE folder is a level of its own too, and says its own name. The header is
2328
- // the only thing on screen that answers "where am I", so a level standing inside a nav folder
2329
- // reading "Data" would be the same word for every step of the walk. `navLevel.folder` is `null`
2330
- // at the top, which is the one place that word is right.
2331
  const railLevelName =
2332
- railLevel.kind === "views"
2333
- // ⛔ THE VIEW FOLDER'S NAME GOES AWAY WHILE A SEARCH IS LIVE, exactly as the folder name
2334
- // does on the database arm below. The list is flattened across every folder of this
2335
- // database then, so naming the folder you walked into would be the claim the scope note
2336
- // denies. The DATABASE's own label is the honest word here, because the database is the
2337
- // population being searched, the way "Data" is on the other arm.
2338
- ? ((dbQ ? undefined : viewLevel.folder?.name) ??
2339
- dbEntries.find((e) => e.key === railLevel.dbKey)?.label ??
2340
- "Data")
2341
- // ⛔ AND IT STOPS NAMING THE FOLDER WHILE A SEARCH IS LIVE. The list is flattened across
2342
- // every folder then, so a header reading the folder's name would be the exact claim the
2343
- // scope note below exists to deny. "Data" is the honest word for the whole database half,
2344
- // which is what is being searched; the path itself is untouched, so clearing the box brings
2345
- // the folder's name straight back.
2346
- : (dbQ ? "Data" : (navLevel.folder?.name ?? "Data"));
2347
  /**
2348
  * ⭐ OWNER INSTRUCTION 4 — `Loopable / Odoo customer`, the topbar path.
2349
  *
@@ -2795,20 +2619,8 @@ function ShellFrame() {
2795
  exact 12x12 box for the Data row's disclosure; one mark, one meaning
2796
  (DESIGN §4). The buttons wear the quiet-button register `.shell-newfolder`
2797
  established, per DESIGN §4's "new nav joins the existing rhythm".
2798
- ⛔⛔ W42-T42 (ruling R13) — THE FORWARD CARET HIDES WHEN THERE IS NOTHING
2799
- AHEAD, AND THIS NOTE REPLACES THE ONE R13 OVERTURNS BY NAME. The old rule
2800
- here was "a disabled end of the walk, not a hidden one", on the reasoning
2801
- that a vanishing control moves its neighbour under the reader's cursor. R13
2802
- rules the other way: a control that cannot act does not render. It costs
2803
- nothing to obey, because the geometry the old note worried about does not
2804
- arise — BACK is the LEADING caret and never moves, so removing the trailing
2805
- one leaves every remaining control exactly where it was.
2806
- ⚠ THE BACK CARET IS UNCHANGED, and the asymmetry is the point rather than an
2807
- oversight. Inside a rendered level there is ALWAYS somewhere back to go: the
2808
- level only exists when the cursor has left the root, so back can always act
2809
- and hiding it would be hiding a live control. Forward is the only one that
2810
- runs out of path, and it comes back the moment going back gives it a
2811
- destination again. */}
2812
  <div className="shell-path">
2813
  <button
2814
  type="button"
@@ -2820,109 +2632,18 @@ function ShellFrame() {
2820
  >
2821
  <PathCaret back />
2822
  </button>
2823
- {canRailForward ? (
2824
- <button
2825
- type="button"
2826
- className="shell-path-step"
2827
- aria-label="Forward"
2828
- title="Forward"
2829
- onClick={() => stepRail(1)}
2830
- >
2831
- <PathCaret />
2832
- </button>
2833
- ) : null}
2834
  <span className="shell-path-here">{railLevelName}</span>
2835
  </div>
2836
- {/* ⭐⭐ WAVE 42 · T16 (owner instructions 4 + 16, contract C5, amendment A1) —
2837
- ONE LEVEL, TWO CONTENTS, AND THE SECOND IS THE NEXT STEP OF THE SAME PATH.
2838
- Clicking a database no longer leaves the rail behind: the level stays, the
2839
- caret still walks out of it, and what it lists is that database's view
2840
- folders and saved views.
2841
- ⛔⛔ THE VIEW ROWS ARE `.shell-rail-view`, NOT `.shell-nav-item`, AND THAT IS
2842
- A GATE CONTRACT RATHER THAN A STYLE CHOICE. `verify_live.py` waits on
2843
- `.shell-dbfly .shell-nav-item, .shell-level .shell-nav-item` and then CLICKS
2844
- the first match expecting a DATABASE to open, on its own documented
2845
- invariant that every such row beneath this container is a database by
2846
- construction. A view wearing that class would keep the selector matching and
2847
- break the invariant instead, which is the worse of the two failures. The
2848
- database branch below keeps every one of its rows, so the selector still
2849
- matches; a probe that stalls 120 s on a healthy build is what that costs.
2850
- ⚠ SAME ANATOMY, DIFFERENT CONTENTS (DESIGN §4): the header, one search box,
2851
- rows. No new control shape, and no second create footer — making a view is
2852
- the database's own rail's door, and a second one here would be a second
2853
- answer to one question. */}
2854
- {railLevel.kind === "views" ? (
2855
- <>
2856
- <div className="shell-dbfly-head">
2857
- <input
2858
- autoFocus
2859
- className="shell-dbfly-search"
2860
- placeholder="Search views"
2861
- value={dbQuery}
2862
- maxLength={60}
2863
- onChange={(e) => setDbQuery(e.target.value)}
2864
- onKeyDown={(e) => {
2865
- if (e.key === "Escape") closeDbFly();
2866
- }}
2867
- />
2868
- </div>
2869
- <div className="shell-nav-list">
2870
- {railViews.known ? (
2871
- <>
2872
- {/* ⛔ THE SCOPE IS STATED HERE TOO — same sentence, same class, same
2873
- place above the rows as the database level and as `ViewSidebar`'s
2874
- views rail. A live search flattens across every folder of this
2875
- database, so the list below is not the level the path names. Three
2876
- surfaces, one sentence, because a reader who learns what the box does
2877
- on one level must not have to learn it again on another. */}
2878
- {dbQ ? (
2879
- <p className="shell-dbfly-empty">Showing matches in every folder</p>
2880
- ) : null}
2881
- {shownViewFolders.map((f) => (
2882
- <button
2883
- key={`viewfolder:${f.id}`}
2884
- type="button"
2885
- className="shell-rail-view is-folder"
2886
- onClick={() => pushViewFolder(railLevel.dbKey, f.id)}
2887
- >
2888
- <span className="shell-nav-mark" aria-hidden="true">
2889
- <FolderMark {...(f.icon ? { icon: f.icon } : {})} size={16} />
2890
- </span>
2891
- <span className="shell-nav-label">{f.name}</span>
2892
- </button>
2893
- ))}
2894
- {shownViews.map((v) => (
2895
- <button
2896
- key={v.id}
2897
- type="button"
2898
- className="shell-rail-view"
2899
- /* The one forward door this ticket owns: opening a view is what the
2900
- level is FOR. `openViewInDatabase` is the shell's existing opener,
2901
- scope-mapped and retry-laddered — a second way to open a view is a
2902
- second way to get the scope spelling wrong. */
2903
- onClick={() => openViewInDatabase(railLevel.dbKey, v.id)}
2904
- >
2905
- <span className="shell-nav-label">{v.name}</span>
2906
- </button>
2907
- ))}
2908
- {shownViewFolders.length === 0 && shownViews.length === 0 ? (
2909
- <p className="shell-dbfly-empty">
2910
- {dbQuery
2911
- ? "No view matches that."
2912
- : "No saved views here yet."}
2913
- </p>
2914
- ) : null}
2915
- </>
2916
- ) : (
2917
- /* ⛔ PENDING, NOT EMPTY, and `known` is the field that tells them apart. An
2918
- empty list drawn over a payload nobody has read yet is a confident zero
2919
- for a database with ten views, and nothing downstream could tell. */
2920
- <p className="shell-dbfly-empty">Reading this database's views.</p>
2921
- )}
2922
- </div>
2923
- </>
2924
- ) : (
2925
- <>
2926
  <div className="shell-dbfly-head">
2927
  <input
2928
  autoFocus
@@ -2950,13 +2671,6 @@ function ShellFrame() {
2950
  if (e.currentTarget.contains(e.relatedTarget as Node)) return;
2951
  setDropTarget(null);
2952
  }}
2953
- // ⚠ W42-T42 — DELIBERATELY STILL `null`, INSIDE A FOLDER TOO. The background of the
2954
- // list is the "drag it out" target and has been since wave 14. Now that a level can BE
2955
- // a folder, an alternative reading appears — drop on the background means "file it
2956
- // here" — and it was rejected: taking it would leave a database filed in a folder with
2957
- // no drag gesture at all for getting it out again, because the row is not visible from
2958
- // the level above. Unfiling makes the row leave this level, which is exactly what the
2959
- // gesture looks like it is doing.
2960
  onDrop={(e) => {
2961
  const key = e.dataTransfer.getData(NAV_DRAG_TYPE);
2962
  setDropTarget(null);
@@ -2966,95 +2680,58 @@ function ShellFrame() {
2966
  movePage(key, null);
2967
  }}
2968
  >
2969
- {/* ⭐⭐ W42-T42 (ruling R12, contracts C5 + C9) — THE DATABASE LIST IS A LEVEL OF A
2970
- PATH, AND THE TREE THAT USED TO BE HERE IS GONE. `foldNav` drew folder heads with
2971
- their members underneath and an open or closed state per head; R12 replaces expand
2972
- and collapse with a walk, in BOTH folder systems, so this list draws only what is
2973
- AT the current path. Clicking a folder takes a step into it; the back caret above
2974
- walks out again. `foldNav` itself stays exported and unit-tested in `nav.ts` — this
2975
- ticket removes its CALL, not the function.
2976
-
2977
- ⭐ FOLDERS FIRST, THEN THE DATABASES (R12.4). They arrive as two arrays from
2978
- `navLevelAt` for exactly that reason, so the order is a property of the render and
2979
- never a sort over a mixed list that a later edit can quietly disturb.
2980
-
2981
- ⛔⛔ EVERY DATABASE ROW BENEATH THIS CONTAINER IS A DATABASE, AND A DEPLOY PROBE
2982
- RESTS ON IT. The live verification script waits on the database row class scoped to
2983
- this level, then CLICKS the first one expecting a grid to open, on its own written
2984
- invariant that the class cannot appear here on anything but a database. Folder heads
2985
- wear the folder classes `FolderHead` renders and must NEVER be given the row class:
2986
- that would keep the probe matching while breaking what it matches, which is worse
2987
- than not matching at all. The needles are described here, never spelled — prose
2988
- about a pattern IS the pattern to a text scan.
2989
- ⚠ AND AFTER THIS TICKET THE COUNT OF THOSE ROWS CAN LEGITIMATELY BE ZERO at the
2990
- top level, because a viewer who has filed every database into folders should see
2991
- folders there and nothing else. That is the instruction working, not a defect; it
2992
- is a known hazard for a probe that assumes at least one row and it is booked with
2993
- the integrator, who owns the deploy. Do not code around it here. */}
2994
- {/* ⛔ THE SCOPE IS STATED, never implied — W42-T42, mirroring W42-T43's line on the
2995
- views rail. A live search flattens across every folder, so the list below is NOT
2996
- the level the path names, and leaving that unsaid while the header still names a
2997
- folder would claim otherwise. It rides ABOVE the rows, where it is read before
2998
- them rather than as a footnote to them. Clearing the box is the action that
2999
- resolves it, so it is a note in the list's own note class and not a control. */}
3000
- {dbQ ? (
3001
- <p className="shell-dbfly-empty">Showing matches in every folder</p>
3002
- ) : null}
3003
- {shownNavFolders.map((f) => (
3004
- <FolderHead
3005
- key={`folder:${f.id}`}
3006
- folder={f}
3007
- // ⛔ BLOCKS, not rendered rows, and counted over the whole list — see
3008
- // `navFolderCount`. The head names a place you have not walked into yet.
3009
- count={navFolderCount(f.id)}
3010
- // WAVE 23 C10 — always false here: the panel has full width in either rail state,
3011
- // so folder chrome is never the thing being squeezed. It asks whether the RAIL is
3012
- // folded to its narrow strip, which is a different question from anything R12
3013
- // retired.
3014
- collapsed={false}
3015
- // ⭐ R12.2 — the head DRILLS. It used to flip an open state; there is no open
3016
- // state left, and the prop is named for the walk so the two cannot be confused.
3017
- onOpen={() => pushNavFolder(f.id)}
3018
- onRename={(name) => renameFolder(f.id, name)}
3019
- onDelete={() => deleteFolder(f.id)}
3020
- isDrop={dropTarget === f.id}
3021
- // ⛔ A FOLDER YOU CAN WALK INTO IS STILL A FOLDER YOU CAN DROP A DATABASE ONTO.
3022
- // The drag keys off the folder ID exactly as it always has (C9: the path model is
3023
- // ADDED over the placement data, it does not replace it), so filing by drag and
3024
- // walking by click are two things one row does.
3025
- dropProps={{
3026
- onDragOver: (e) => {
3027
- if (!e.dataTransfer.types.includes(NAV_DRAG_TYPE)) return;
3028
- e.preventDefault();
3029
- e.stopPropagation();
3030
- e.dataTransfer.dropEffect = "move";
3031
- setDropTarget(f.id);
3032
- },
3033
- onDrop: (e) => {
3034
- const key = e.dataTransfer.getData(NAV_DRAG_TYPE);
3035
- setDropTarget(null);
3036
- setDragKey(null);
3037
- if (!key) return;
3038
- e.preventDefault();
3039
- e.stopPropagation();
3040
- movePage(key, f.id);
3041
- },
3042
- }}
3043
- />
3044
- ))}
3045
- {shownDbs.map(
3046
- (item) => {
3047
  // Wave 17 item 12 — ONE answer, read by the row AND the link.
3048
  // The row paints the tint (so it reaches under the ⋯, matching
3049
  // the Views rail); the link keeps the class because the weight
3050
  // and the full-strength icon hang off `.shell-nav-item.is-active`.
3051
  const isActive = !!active && active.key === item.key;
3052
- // ⛔⛔ `is-child` IS NOT THE INDENTATION R12.2 DELETES, and the next reader greps
3053
- // "indent", lands here, and needs this sentence. It marks a database's own
3054
- // SUB-PAGE — `NavEntry.depth`, a family the server sends as a head plus its
3055
- // children — and it has never had anything to do with folder nesting: even under
3056
- // the old tree a folder's members were drawn flush. R12.2 removes the twisty and
3057
- // the expand state; a family staying visibly a family is untouched by it.
3058
  const cls =
3059
  "shell-nav-item" +
3060
  (item.depth > 0 ? " is-child" : "") +
@@ -3162,19 +2839,7 @@ function ShellFrame() {
3162
  className={
3163
  "shell-nav-row" +
3164
  (isActive ? " is-active" : "") +
3165
- // ⛔⛔ W42-T42 (R12.2) — `is-foldered` IS GONE, AND IT IS THE INDENTATION
3166
- // THE RULING DELETES. It was set for a row drawn UNDERNEATH its folder's
3167
- // head and `navExtras.css` pays it as `padding-left: 30px` — a row stepped
3168
- // in to say "I belong to the head above me". A level has no head above it:
3169
- // the folder is the header of the whole screen, every row on it is inside
3170
- // that folder, and indenting all of them would step the entire list in
3171
- // against nothing. Translating the flag to "this level IS a folder" was the
3172
- // mechanical move and it is the wrong one — it keeps the indent and merely
3173
- // widens it. `is-child` below is a different flag for a different fact and
3174
- // stays; see its note.
3175
- // ⚠ The rule in `navExtras.css` is now unrendered. That file is off this
3176
- // ticket's fence, so its deletion is BOOKED rather than taken: an orphan
3177
- // rule is an invitation to re-add the class it styles.
3178
  (dragKey === item.key ? " is-dragging" : "")
3179
  }
3180
  // WAVE 23 C10 — `!navCollapsed &&` dropped from both gates below: the panel
@@ -3264,20 +2929,13 @@ function ShellFrame() {
3264
  );
3265
  }
3266
  )}
3267
- {/* The level's own empty state: ONE line, and it is different from "this
3268
  workspace has none" — a search that matched nothing is not a workspace
3269
  with nothing in it, and saying the second when the first is true is how a
3270
- reader concludes their data is gone.
3271
- ⭐ W42-T42 — a THIRD sentence, because a level can now be empty for a third
3272
- reason: you walked into a folder and it holds nothing. Saying "no databases
3273
- yet" there would tell somebody with twenty databases that they have none. */}
3274
- {shownNavFolders.length === 0 && shownDbs.length === 0 ? (
3275
  <p className="shell-dbfly-empty">
3276
- {dbQuery
3277
- ? "No database matches that."
3278
- : navLevel.folder
3279
- ? "This folder is empty."
3280
- : "No databases yet."}
3281
  </p>
3282
  ) : null}
3283
  </div>
@@ -3319,8 +2977,6 @@ function ShellFrame() {
3319
  canFolder={entries.length > 0}
3320
  />
3321
  </div>
3322
- </>
3323
- )}
3324
  </div>
3325
  ) : null}
3326
  {/* W33-T75: loading is represented only by the two row-local slots above. A separate
 
64
  // ⚠ IT JOINS `Lazily`, NOT A BARE `Suspense`: the shared wrapper carries the ErrorBoundary, so a
65
  // chunk that fails to load names the surface it was for instead of blanking the frame.
66
  const CustomerGrid = lazy(() => import("../customer-grid/CustomerGrid"));
67
+ import { clearCustomersCache, currentSurfaceScope } from "../customer-grid/apiBridge";
68
  import { OverlayProvider } from "../customer-grid/OverlaySurface";
69
  // ROWS_STALE_EVENT left with `addRecord` (wave 20 item 4): the shell no longer writes rows,
70
  // so it no longer has to tell the grid that it did.
 
76
  import { Brand } from "./Brand";
77
  import { ErrorBoundary } from "./ErrorBoundary";
78
  import LoginPage from "./LoginPage";
79
+ import { ASSISTANT_ROUTE, CONNECTORS_ROUTE, EMPTY_NAV_PREFS, ENVELOPE_KEYS, FEEDBACK_ROUTE, HOME_ROUTE, INBOX_ROUTE, NO_SUBSCRIPTION_TENANT, STARRED_ROUTE, SUBSCRIPTION_ROUTE, USAGE_ROUTE, MAX_NAV_FOLDERS, NAV_TIMEOUT_STATUS, appLink, canonicalRoute, databaseEntries, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchTableFootprint, foldNav, postOpened, QUERY_ROUTE, resolveRoute, rewrittenHash, routeKeyOf, saveNavMeta, saveNavPrefs, shapeNav, splitChrome } from "./nav";
80
+ import type { NavEntry, NavMetaPatch, NavPage, NavPrefs, Recent } from "./nav";
 
 
 
 
 
 
81
  // ⭐ 2026-08-14 — the database frame, extracted so the Query module can wear the SAME one.
82
  import { DbIcon, gridScopeFor } from "./dbFrame";
83
  /* ⭐ W35-T09 — the app's own star (B-3): one mark, one meaning (DESIGN.md §4). */
 
333
  const NO_UTILITY: NavPage[] = [];
334
  /** Stable identity, like `NO_ENTRIES` — a fresh `[]` per render would re-run Home's memo. */
335
  const NO_RECENTS: Recent[] = [];
 
 
 
 
 
 
336
 
337
  /**
338
  * ⭐⭐ W33-T22 (owner item 1) — THE TWO ROWS THE PAYLOAD DECIDES, FOUND IN ONE PLACE.
 
1202
  // route has to join, and a route that joins it must also RENDER something. A drill is a rail
1203
  // STATE: the content pane keeps showing whatever it was showing, which is also the honest
1204
  // answer to "I opened the navigation, I did not leave the page".
1205
+ type RailLevel = { kind: "root" } | { kind: "data" } | { kind: "db"; key: string };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1206
  const [rail, setRail] = useState<{ hist: RailLevel[]; at: number }>(
1207
  () => ({ hist: [{ kind: "root" }], at: 0 })
1208
  );
 
1229
  setRail((s) =>
1230
  s.hist.length > 1
1231
  ? { ...s, at: 1 }
1232
+ : { hist: [s.hist[0], { kind: "data" }], at: 1 }
1233
  );
1234
  }, []);
1235
+ /** Drill from the list into ONE database. The row's own `href` does the navigating; this records
1236
+ * where the click went, so `<` and `>` can walk back to it.
1237
  * ⚠ It TRUNCATES anything ahead of the cursor, which is what a browser's forward button does
1238
  * after you take a new branch: a forward entry you can no longer reach by going back is a
1239
+ * destination the history is lying about. */
1240
+ const pushDb = useCallback((key: string) => {
1241
+ setRail((s) => ({ hist: [...s.hist.slice(0, s.at + 1), { kind: "db", key }], at: s.at + 1 }));
 
 
1242
  setDbQuery("");
1243
  }, []);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1244
  // ⚠ Declared here and READ inside the Escape effect below, because that effect must not
1245
  // re-subscribe on every drag state change — and because the guard it needs is "a drag is in
1246
  // flight", which is state this component already holds (`dragKey`, declared further down with
 
1435
  const [navPrefs, setNavPrefs] = useState<NavPrefs>(EMPTY_NAV_PREFS);
1436
  const navPrefsRef = useRef(navPrefs);
1437
  navPrefsRef.current = navPrefs;
1438
+ const [closedFolders, setClosedFolders] = useState<ReadonlySet<string>>(new Set());
 
 
 
 
 
1439
  const [schemaFor, setSchemaFor] = useState<string | null>(null);
1440
  useEffect(() => {
1441
  if (who === null) {
 
1495
  },
1496
  [commitPrefs]
1497
  );
1498
+ const toggleFolder = useCallback((id: string) => {
1499
+ setClosedFolders((prev) => {
1500
+ const next = new Set(prev);
1501
+ if (next.has(id)) next.delete(id);
1502
+ else next.add(id);
1503
+ return next;
1504
+ });
1505
+ }, []);
1506
  // ── Wave 14 C-NAVFOLD (items 4/6): drag replaces the menu's Move-to-folder. A PRIVATE
1507
  // dataTransfer MIME so a drop anywhere text-editable types nothing (the wave-13 C-LAYOUT
1508
  // scar); `dropTarget` is a folder id or "__root__" (drag out = drop on the list itself).
 
2116
  // most a few dozen rows, so anything cleverer (fuzzy, ranked) would be a scoring function
2117
  // nobody can predict over a set small enough to read.
2118
  //
2119
+ // ⚠ SEARCHING RENDERS FLAT. `foldNav` is called with EMPTY prefs while a query is live,
2120
+ // because a folder head whose members were filtered out would report a count it is not
2121
+ // showing — the same "count derived from one list, rows from another" defect the R10
2122
+ // relocation note two blocks up already documents.
 
 
 
 
 
 
 
 
 
 
 
2123
  const dbQ = dbQuery.trim().toLowerCase();
2124
+ const shownEntries = dbQ
2125
+ ? dbEntries.filter((e) => e.label.toLowerCase().includes(dbQ))
2126
+ : dbEntries;
2127
  // WAVE 23 C10 — what Home draws: the server's recents plus this session's own stamps.
2128
  const recents = mergeRecents(nav.phase === "ready" ? nav.recents : NO_RECENTS, opened);
2129
 
 
2140
  // from `rail.at`, and everything reads it.
2141
  const railLevel: RailLevel = rail.hist[rail.at] ?? { kind: "root" };
2142
  const dbAt = railLevel.kind !== "root";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2143
  const canRailBack = rail.at > 0;
2144
  const canRailForward = rail.at < rail.hist.length - 1;
2145
  /**
 
2147
  * Connectors back on screen — a level replaces the rail's rows, so this is the way out, not a
2148
  * convenience.
2149
  *
2150
+ * ⚠ A `db` step RE-NAVIGATES, because that is what the entry MEANS. The owner asked to *"go to
2151
+ * the previous path"*, and for a database the path IS the open surface; a back button that
2152
+ * changed the rail while leaving the grid on another table would be showing a path nobody is
2153
+ * standing on.
 
 
 
 
 
 
 
2154
  * ⚠ A plain function, not a `useCallback`: it reads `rail` from this render and every click
2155
  * gets a fresh one, so there is no stale-cursor window between two human clicks — and a hook
2156
  * here would have to be declared 900 lines up, away from the thing it walks.
 
2161
  if (!dest) return;
2162
  setRail({ hist: rail.hist, at });
2163
  setDbQuery("");
2164
+ if (dest.kind === "db") window.location.hash = `#/${dest.key}`;
2165
  };
2166
  /** The level's own name, and the only header a level gets (DESIGN §2: a short plain noun). */
 
 
 
 
 
 
 
2167
  const railLevelName =
2168
+ railLevel.kind === "db"
2169
+ ? (dbEntries.find((e) => e.key === railLevel.key)?.label ?? "Data")
2170
+ : "Data";
 
 
 
 
 
 
 
 
 
 
 
 
2171
  /**
2172
  * ⭐ OWNER INSTRUCTION 4 — `Loopable / Odoo customer`, the topbar path.
2173
  *
 
2619
  exact 12x12 box for the Data row's disclosure; one mark, one meaning
2620
  (DESIGN §4). The buttons wear the quiet-button register `.shell-newfolder`
2621
  established, per DESIGN §4's "new nav joins the existing rhythm".
2622
+ ⚠ A DISABLED END OF THE WALK, not a hidden one: a control that vanishes when
2623
+ it cannot act moves the other one under the reader's cursor. */}
 
 
 
 
 
 
 
 
 
 
 
 
2624
  <div className="shell-path">
2625
  <button
2626
  type="button"
 
2632
  >
2633
  <PathCaret back />
2634
  </button>
2635
+ <button
2636
+ type="button"
2637
+ className="shell-path-step"
2638
+ aria-label="Forward"
2639
+ title="Forward"
2640
+ disabled={!canRailForward}
2641
+ onClick={() => stepRail(1)}
2642
+ >
2643
+ <PathCaret />
2644
+ </button>
 
2645
  <span className="shell-path-here">{railLevelName}</span>
2646
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2647
  <div className="shell-dbfly-head">
2648
  <input
2649
  autoFocus
 
2671
  if (e.currentTarget.contains(e.relatedTarget as Node)) return;
2672
  setDropTarget(null);
2673
  }}
 
 
 
 
 
 
 
2674
  onDrop={(e) => {
2675
  const key = e.dataTransfer.getData(NAV_DRAG_TYPE);
2676
  setDropTarget(null);
 
2680
  movePage(key, null);
2681
  }}
2682
  >
2683
+ {/* C-SCHEMA: the list folds under the user's folders.
2684
+ ⭐ WAVE 23 C10 — the `navCollapsed ? EMPTY_NAV_PREFS :` gate is GONE with the band
2685
+ it belonged to. It existed because the 44px strip had no room for folder chrome;
2686
+ this panel is 268px wide whatever the rail is doing, so the folders always render
2687
+ and the reason for the gate no longer exists. A SEARCH still flattens (see
2688
+ `shownEntries`) — that is a different fact about a different state. */}
2689
+ {foldNav(shownEntries, dbQ ? EMPTY_NAV_PREFS : navPrefs, closedFolders).map(
2690
+ (row) => {
2691
+ if (row.kind === "folder") {
2692
+ return (
2693
+ <FolderHead
2694
+ key={`folder:${row.folder.id}`}
2695
+ folder={row.folder}
2696
+ count={row.count}
2697
+ // ⭐ W34-T11 / C1 — `foldNav` sets this only for a CLOSED folder, so the
2698
+ // "an expanded one does not double-count" clause is decided where the
2699
+ // members are known rather than re-derived here.
2700
+ open={row.open}
2701
+ // WAVE 23 C10 — always false in the flyout: the panel has full width in
2702
+ // either rail state, so folder chrome is never the thing being squeezed.
2703
+ collapsed={false}
2704
+ onToggle={() => toggleFolder(row.folder.id)}
2705
+ onRename={(name) => renameFolder(row.folder.id, name)}
2706
+ onDelete={() => deleteFolder(row.folder.id)}
2707
+ isDrop={dropTarget === row.folder.id}
2708
+ dropProps={{
2709
+ onDragOver: (e) => {
2710
+ if (!e.dataTransfer.types.includes(NAV_DRAG_TYPE)) return;
2711
+ e.preventDefault();
2712
+ e.stopPropagation();
2713
+ e.dataTransfer.dropEffect = "move";
2714
+ setDropTarget(row.folder.id);
2715
+ },
2716
+ onDrop: (e) => {
2717
+ const key = e.dataTransfer.getData(NAV_DRAG_TYPE);
2718
+ setDropTarget(null);
2719
+ setDragKey(null);
2720
+ if (!key) return;
2721
+ e.preventDefault();
2722
+ e.stopPropagation();
2723
+ movePage(key, row.folder.id);
2724
+ },
2725
+ }}
2726
+ />
2727
+ );
2728
+ }
2729
+ const item = row.entry;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2730
  // Wave 17 item 12 — ONE answer, read by the row AND the link.
2731
  // The row paints the tint (so it reaches under the ⋯, matching
2732
  // the Views rail); the link keeps the class because the weight
2733
  // and the full-strength icon hang off `.shell-nav-item.is-active`.
2734
  const isActive = !!active && active.key === item.key;
 
 
 
 
 
 
2735
  const cls =
2736
  "shell-nav-item" +
2737
  (item.depth > 0 ? " is-child" : "") +
 
2839
  className={
2840
  "shell-nav-row" +
2841
  (isActive ? " is-active" : "") +
2842
+ (row.folderId ? " is-foldered" : "") +
 
 
 
 
 
 
 
 
 
 
 
 
2843
  (dragKey === item.key ? " is-dragging" : "")
2844
  }
2845
  // WAVE 23 C10 — `!navCollapsed &&` dropped from both gates below: the panel
 
2929
  );
2930
  }
2931
  )}
2932
+ {/* The panel's own empty state: ONE line, and it is different from "this
2933
  workspace has none" — a search that matched nothing is not a workspace
2934
  with nothing in it, and saying the second when the first is true is how a
2935
+ reader concludes their data is gone. */}
2936
+ {shownEntries.length === 0 ? (
 
 
 
2937
  <p className="shell-dbfly-empty">
2938
+ {dbQuery ? "No database matches that." : "No databases yet."}
 
 
 
 
2939
  </p>
2940
  ) : null}
2941
  </div>
 
2977
  canFolder={entries.length > 0}
2978
  />
2979
  </div>
 
 
2980
  </div>
2981
  ) : null}
2982
  {/* W33-T75: loading is represented only by the two row-local slots above. A separate
web/src/shell/nav.ts CHANGED
@@ -30,19 +30,6 @@ import { API_V1, CREDENTIALS } from "../apiContract";
30
  // `appBase` being a parameter for exactly that reason).
31
  import { FOLDER_SHAPES, FOLDER_TONES } from "../customer-grid/types";
32
  import type { FolderIcon } from "../customer-grid/types";
33
- // ⭐⭐ WAVE 42 · T41 (R12 / C9) — the ONE path model, imported rather than re-spelled. See the
34
- // adapter block at the foot of this file. `customer-grid/folders` is pure and React-free by its
35
- // own header (it exists so `verify_folders.py` can run it under node) and its only imports are
36
- // `./viewEcho` and `./types`, both of which bottom out in `./windows`; so this import keeps
37
- // nav.ts runnable under plain node, which `verify_login.py` depends on.
38
- import { folderPath, levelAt } from "../customer-grid/folders";
39
- import type { FolderLevel } from "../customer-grid/folders";
40
- // ⭐⭐ WAVE 42 · T15 (C5) — the workspace-to-rail-lists resolver, imported rather than re-spelled.
41
- // See the `viewsForDb` block at the foot of this file. `customer-grid/viewEcho` is pure by its own
42
- // header and imports only `./types`, which bottoms out in `./windows`, so this keeps nav.ts
43
- // runnable under plain node the way `verify_login.py` depends on.
44
- import { viewsOfWorkspace } from "../customer-grid/viewEcho";
45
- import type { WorkspaceHolder, WorkspaceViews } from "../customer-grid/viewEcho";
46
 
47
  /** One entry of X2's nav payload. `source` is the registry's connector fact
48
  * (wave-9 I8: "Sales · Odoo"); `parent` names a sub-module's family head. */
@@ -1378,150 +1365,3 @@ export function resolveRoute(entries: NavEntry[], route: string): NavEntry | und
1378
  const fallback = defaultRoute(entries);
1379
  return entries.find((e) => e.key === fallback);
1380
  }
1381
-
1382
- // ── ⭐⭐ WAVE 42 · T41 (ruling R12, contract C9) — THE DATABASE FOLDERS, ON THE ONE PATH MODEL ──
1383
- //
1384
- // ⛔ THIS IS AN ADAPTER, NOT A SECOND MODEL. `foldNav` above is untouched and every one of its
1385
- // callers keeps working: it still answers "draw me the rail as rows". What was missing is the
1386
- // OTHER question, the one R12 turns the navigation into — "what is at this path, and what is one
1387
- // step out" — and answering it here in nav's own spelling would have rebuilt the very duplication
1388
- // R12.3 exists to end. So the answer comes from `customer-grid/folders.ts::levelAt`, the single
1389
- // resolver, and this file supplies only the two things that genuinely differ.
1390
- //
1391
- // ⚠ WHAT DIFFERS IS EXACTLY ONE THING: WHERE MEMBERSHIP IS STORED. A view carries its own
1392
- // `folderId`; a database's placement lives in the per-user `NavPrefs.placement` map, keyed by page
1393
- // key. {@link navFolderIdOf} closes over that map and hands `levelAt` the same
1394
- // item-to-folder-id function a view rail hands it. Nothing else about a database folder is
1395
- // special, which is the claim R12.3 makes and this adapter is how it becomes true.
1396
- //
1397
- // ⚠ NAV FOLDERS ARE FLAT AND STAY FLAT. `NavFolder` has no `parent` and must not grow one here:
1398
- // `parseNavPrefs` mirrors the server's `_clean_nav_prefs`, which builds a strict `{id, name}` row,
1399
- // so the value would be dropped on the next save. A parentless folder resolves through
1400
- // `folderNesting` at level 1 with a `null` parent, so `levelAt` drills it with the same code that
1401
- // drills a ten-deep view folder — it simply never has subfolders to list. `MAX_NAV_FOLDERS` (16,
1402
- // a COUNT) and `FOLDER_DEPTH_MAX` (10, a DEPTH) are different numbers and neither bounds the other.
1403
-
1404
- /**
1405
- * Where a nav entry is filed, in the shape {@link levelAt} asks for.
1406
- *
1407
- * ⛔ IT MIRRORS `foldNav`'s BLOCK RULE rather than reading `placement` raw, and that is the whole
1408
- * of its correctness. A depth-1 entry is a sub-module of the entry above it, `foldNav` moves the
1409
- * two as ONE unit ("filing a family head files the family"), and `placement` only ever names the
1410
- * head. Reading the map directly would leave every child at the top level while its parent sat in
1411
- * a folder — the family split in half, on a rail that has never shown one.
1412
- *
1413
- * ⚠ A placement naming a folder that no longer exists returns `null`, the same dangling rule
1414
- * `foldNav` applies (`ids.has(fid)`) and the same one `levelAt` applies one layer down.
1415
- */
1416
- export function navFolderIdOf(
1417
- entries: NavEntry[],
1418
- prefs: NavPrefs
1419
- ): (entry: NavEntry) => string | null {
1420
- const ids = new Set(prefs.folders.map((f) => f.id));
1421
- const owner = new Map<string, string | null>();
1422
- let headKey: string | null = null;
1423
- for (const e of entries) {
1424
- if (e.depth > 0 && headKey) {
1425
- owner.set(e.key, owner.get(headKey) ?? null);
1426
- continue;
1427
- }
1428
- headKey = e.key;
1429
- const fid = prefs.placement[e.key];
1430
- owner.set(e.key, fid && ids.has(fid) ? fid : null);
1431
- }
1432
- return (entry: NavEntry) => owner.get(entry.key) ?? null;
1433
- }
1434
-
1435
- /**
1436
- * ⭐⭐ WHAT IS AT THIS PATH, for the DATABASE half of the navigation — the same
1437
- * `{folders, leaves, parent}` a view folder answers with, from the same resolver.
1438
- *
1439
- * `at` is the nav folder the user has drilled into, absent/`null` being the top level. Leaves are
1440
- * {@link DatabaseEntry}s, so the surfaces that are not databases (D-54's `SURFACE_KEYS`) are
1441
- * already out: a path that drills into folders of databases must not hand back a row that is not
1442
- * one, and `databaseEntries` is the only supported way to obtain that list.
1443
- */
1444
- export function navLevelAt(
1445
- at: string | null | undefined,
1446
- entries: NavEntry[],
1447
- prefs: NavPrefs
1448
- ): FolderLevel<NavFolder, DatabaseEntry> {
1449
- const folderIdOf = navFolderIdOf(entries, prefs);
1450
- return levelAt<NavFolder, DatabaseEntry>(
1451
- at,
1452
- prefs.folders,
1453
- databaseEntries(entries),
1454
- folderIdOf
1455
- );
1456
- }
1457
-
1458
- /**
1459
- * The breadcrumb trail to a nav folder, outermost first — R12.1's "one continuous path", the
1460
- * database half of it. Flat today, so it is at most one folder long; it is the shared walk rather
1461
- * than a `[folder]` literal so that the day nav folders nest, this needs no second thought.
1462
- */
1463
- export function navFolderPath(
1464
- at: string | null | undefined,
1465
- prefs: NavPrefs
1466
- ): NavFolder[] {
1467
- return folderPath<NavFolder>(at, prefs.folders);
1468
- }
1469
-
1470
- // ── WAVE 42 · T15 (contract C5): the rail's views level, from OUTSIDE the grid ──────────────
1471
- //
1472
- // ⭐⭐ THE ONE RESOLVER FOR "WHAT VIEWS DOES THIS DATABASE HAVE?". C5's views level puts a
1473
- // database's `SavedView[]`/`GridFolder[]` on the rail, where no `CustomerGrid` is mounted to be
1474
- // asked. Before this there was NO db-key-to-views symbol anywhere: the lists were a `useState`
1475
- // seeded from the page payload inside the grid's content component, reachable only by being that
1476
- // component.
1477
- //
1478
- // ⛔ IT IS A LOOKUP, NOT A FETCH, and that is the trap this ticket names by name. The data
1479
- // already arrives with the page; a second `GET` issued from the shell would re-download bytes the
1480
- // browser holds and would answer at a different instant from the grid rendering beside it. So the
1481
- // caller passes what it is already holding and this narrows it.
1482
- //
1483
- // The workspace-to-lists half lives in `customer-grid/viewEcho.ts::viewsOfWorkspace`, beside the
1484
- // other SavedView-shaped resolution and beside the reads it mirrors. Same split as T41's
1485
- // `levelAt`/`navLevelAt`: the generic in the grid, the adapter here, and what differs is only
1486
- // where the thing is keyed from.
1487
-
1488
- /** What the shell holds: a workspace-bearing payload per database key, whatever it has so far.
1489
- * A key with no entry is not an error — see {@link DbViews.known}. */
1490
- export type DbWorkspaces = Readonly<Record<string, WorkspaceHolder | null | undefined>>;
1491
-
1492
- /**
1493
- * ⛔ `known` IS THE LOAD-BEARING FIELD, exactly as `NavPage.important`'s absence is one level up:
1494
- * an empty list must not be reported for a database whose payload has simply not been read yet.
1495
- * `false` means THIS SOURCE HOLDS NO WORKSPACE FOR THAT KEY — the caller draws a pending state,
1496
- * never "no views". `true` with `views: []` is a real, checkable claim that the database has no
1497
- * saved views. Conflating the two would put a confident zero on screen for a database with ten,
1498
- * and nothing downstream could tell the difference.
1499
- */
1500
- export interface DbViews extends WorkspaceViews {
1501
- known: boolean;
1502
- }
1503
-
1504
- /**
1505
- * ⭐⭐ THE VIEWS AND FOLDERS OF ONE DATABASE, from the payload the page already carries.
1506
- *
1507
- * The lists are the HOST's — `payload.workspace.views` / `.folders`, the same two reads
1508
- * `CustomerGrid` starts from (`CustomerGrid.tsx:1516` and `:5159`). A mounted grid then layers
1509
- * this browser's own localStorage over them (an optimistic create, a tombstoned delete, the
1510
- * synthesized "All records" tab); that layer is per-browser state owned by a mounted component
1511
- * and is not reproducible — nor desirable — from here.
1512
- *
1513
- * Nothing throws. An absent source, an absent payload, an absent `workspace`, an absent `views`,
1514
- * an absent `folders` and a key naming nothing all answer a well-formed empty result.
1515
- */
1516
- export function viewsForDb(source: DbWorkspaces | null | undefined, dbKey: string): DbViews {
1517
- const held =
1518
- source && typeof source === "object" && dbKey
1519
- ? (Object.prototype.hasOwnProperty.call(source, dbKey) ? source[dbKey] : undefined)
1520
- : undefined;
1521
- // ⚠ `hasOwnProperty`, not a truthiness test on the value: a key present with an explicit
1522
- // `null` (a payload that was read and came back empty) is KNOWN, and it is the one case a
1523
- // truthiness test would misfile as pending for ever.
1524
- const known = !!source && typeof source === "object" && !!dbKey &&
1525
- Object.prototype.hasOwnProperty.call(source, dbKey);
1526
- return { ...viewsOfWorkspace(held), known };
1527
- }
 
30
  // `appBase` being a parameter for exactly that reason).
31
  import { FOLDER_SHAPES, FOLDER_TONES } from "../customer-grid/types";
32
  import type { FolderIcon } from "../customer-grid/types";
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  /** One entry of X2's nav payload. `source` is the registry's connector fact
35
  * (wave-9 I8: "Sales · Odoo"); `parent` names a sub-module's family head. */
 
1365
  const fallback = defaultRoute(entries);
1366
  return entries.find((e) => e.key === fallback);
1367
  }