fsanyoto commited on
Commit
19aed6d
·
verified ·
1 Parent(s): 3db2baa

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 +13 -1
  2. VERSION +1 -1
  3. api/automation_control.py +17 -1
  4. api/automation_engine.py +54 -11
  5. api/routes_admin.py +43 -4
  6. api/routes_automation.py +183 -1
  7. api/routes_customers.py +982 -138
  8. api/routes_geo.py +81 -9
  9. api/routes_grid.py +177 -15
  10. api/routes_nav.py +4 -1
  11. api/routes_shares.py +430 -13
  12. api/routes_tables.py +221 -20
  13. api/voice_control_plane.py +745 -0
  14. api/voice_provider_adapters.py +189 -0
  15. platform/aios_grid.py +143 -14
  16. platform/aios_grid_fields.json +2 -0
  17. platform/core/field_permissions.py +225 -21
  18. platform/core/grid_events.py +43 -8
  19. platform/core/route_system.py +886 -0
  20. platform/core/shared_overlay.py +100 -3
  21. platform/core/store_pg.py +22 -7
  22. platform/core/table_store.py +31 -9
  23. platform/core/user_tables.py +249 -8
  24. platform/harness/semantic.py +68 -5
  25. platform/model/topics/sales_lines.yml +12 -0
  26. web/public/sample_customers.json +1 -0
  27. web/src/automation/AutomationBuilder.tsx +132 -49
  28. web/src/automation/AutomationDetail.tsx +38 -19
  29. web/src/automation/AutomationSurface.tsx +104 -1
  30. web/src/automation/VoiceAgentProperties.tsx +542 -0
  31. web/src/automation/automationApi.ts +228 -0
  32. web/src/automation/voiceAgentTypes.ts +101 -0
  33. web/src/customer-grid/CatalogView.tsx +3 -2
  34. web/src/customer-grid/ColumnMenu.tsx +458 -69
  35. web/src/customer-grid/CustomerGrid.tsx +648 -91
  36. web/src/customer-grid/FieldProperties.tsx +49 -0
  37. web/src/customer-grid/FormInterface.tsx +4 -3
  38. web/src/customer-grid/MapView.tsx +0 -0
  39. web/src/customer-grid/RecordDetail.tsx +2 -2
  40. web/src/customer-grid/RouteNav.tsx +555 -0
  41. web/src/customer-grid/ScriptViewPanel.tsx +3 -2
  42. web/src/customer-grid/TimeSeriesPanel.tsx +4 -3
  43. web/src/customer-grid/Toolbar.tsx +133 -16
  44. web/src/customer-grid/ViewSidebar.tsx +803 -83
  45. web/src/customer-grid/apiBridge.ts +140 -0
  46. web/src/customer-grid/dataPath.ts +184 -0
  47. web/src/customer-grid/export.ts +47 -0
  48. web/src/customer-grid/formulaEngine.ts +434 -9
  49. web/src/customer-grid/map.css +85 -22
  50. web/src/customer-grid/navFold.ts +19 -0
RELEASES.json CHANGED
@@ -1,6 +1,18 @@
1
  {
2
- "current": "v54 (6a8e99a)",
3
  "releases": [
 
 
 
 
 
 
 
 
 
 
 
 
4
  {
5
  "version": "v54",
6
  "sha": "6a8e99a",
 
1
  {
2
+ "current": "v56 (2970b72)",
3
  "releases": [
4
+ {
5
+ "version": "v56",
6
+ "sha": "2970b72",
7
+ "date": "2026-08-28",
8
+ "subject": "release v56"
9
+ },
10
+ {
11
+ "version": "v55",
12
+ "sha": "b766b90",
13
+ "date": "2026-08-28",
14
+ "subject": "release v55"
15
+ },
16
  {
17
  "version": "v54",
18
  "sha": "6a8e99a",
VERSION CHANGED
@@ -1 +1 @@
1
- v54 (6a8e99a)
 
1
+ v56 (2970b72)
api/automation_control.py CHANGED
@@ -19,6 +19,7 @@ import os
19
  import re
20
  import time
21
  import uuid
 
22
 
23
  import requests
24
 
@@ -124,6 +125,21 @@ def _base_job(tenant: str, defn: dict, mode: str) -> dict:
124
  "scheduledTime": "<aws.scheduler.scheduled-time>"}
125
 
126
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  def recurring_specs(tenant: str, defn: dict) -> list[dict]:
128
  scope = schedule_scope(tenant, defn.get("id"))
129
  specs: list[dict] = []
@@ -131,7 +147,7 @@ def recurring_specs(tenant: str, defn: dict) -> list[dict]:
131
  if schedule.get("enabled"):
132
  for index, expression in enumerate(aws_cron_expressions(schedule.get("cron") or "")):
133
  specs.append({"name": f"{scope}-schedule-{index}", "mode": "schedule",
134
- "expression": expression, "timezone": "UTC",
135
  "job": _base_job(tenant, defn, "schedule")})
136
  trigger = defn.get("trigger") or {}
137
  if (trigger.get("key") == "email" and trigger.get("enabled", True)
 
19
  import re
20
  import time
21
  import uuid
22
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
23
 
24
  import requests
25
 
 
125
  "scheduledTime": "<aws.scheduler.scheduled-time>"}
126
 
127
 
128
+ def _recurring_timezone(defn: dict) -> str:
129
+ """Use a Route's frozen wall-clock Zone; every other automation remains UTC."""
130
+ if str(defn.get("kind") or "") != "route_delivery":
131
+ return "UTC"
132
+ schedule = defn.get("schedule") if isinstance(defn.get("schedule"), dict) else {}
133
+ config = defn.get("config") if isinstance(defn.get("config"), dict) else {}
134
+ snapshot = config.get("routeSnapshot") if isinstance(config.get("routeSnapshot"), dict) else {}
135
+ timezone = str(schedule.get("timezone") or snapshot.get("timezone") or "").strip()
136
+ try:
137
+ ZoneInfo(timezone)
138
+ except (ZoneInfoNotFoundError, ValueError):
139
+ raise ValueError("a scheduled route needs a recognized IANA timezone") from None
140
+ return timezone
141
+
142
+
143
  def recurring_specs(tenant: str, defn: dict) -> list[dict]:
144
  scope = schedule_scope(tenant, defn.get("id"))
145
  specs: list[dict] = []
 
147
  if schedule.get("enabled"):
148
  for index, expression in enumerate(aws_cron_expressions(schedule.get("cron") or "")):
149
  specs.append({"name": f"{scope}-schedule-{index}", "mode": "schedule",
150
+ "expression": expression, "timezone": _recurring_timezone(defn),
151
  "job": _base_job(tenant, defn, "schedule")})
152
  trigger = defn.get("trigger") or {}
153
  if (trigger.get("key") == "email" and trigger.get("enabled", True)
api/automation_engine.py CHANGED
@@ -35,6 +35,7 @@ import socket
35
  import threading
36
  import time
37
  from urllib.parse import urljoin, urlparse
 
38
 
39
  import requests
40
 
@@ -1481,8 +1482,14 @@ def field_def(text_key, label, ftype="text", **extra):
1481
  """
1482
  description = " ".join(str(extra.pop(
1483
  "description", IG_FIELD_DESCRIPTIONS.get(text_key, "")) or "").split())
1484
- out = {"key": text_key, "label": label, "type": ftype, "source": "overlay",
1485
- "editRole": "admins"}
 
 
 
 
 
 
1486
  if description:
1487
  out["description"] = description
1488
  out.update(extra)
@@ -1664,14 +1671,19 @@ def clean_config(kind, raw, previous=None):
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()
@@ -1694,6 +1706,7 @@ def clean_config(kind, raw, previous=None):
1694
  return {
1695
  "recipient": recipient,
1696
  "routeSnapshot": {
 
1697
  "sourceViewId": source_view,
1698
  "sourceViewRevision": revision,
1699
  "sourceViewName": source_name or source_view,
@@ -2334,6 +2347,10 @@ def clean_definition(raw, previous=None, username="", notes=None, rt=None):
2334
  else prev.get("schedule"), prev.get("schedule"))
2335
  except ValueError as e:
2336
  return None, str(e)
 
 
 
 
2337
  # (`clean_trigger` ran at the top — law 1 needs the trigger before the kind.)
2338
  flow_raw = raw.get("flow") if "flow" in raw else prev.get("flow")
2339
  # ⭐ EVERY CLEAN, NOT ONLY THE EDGE (owner ruling 6 — see `_ensure_ig_action`). The edge-only
@@ -9259,6 +9276,7 @@ WEB_REQUIRED = {
9259
  #: run-time refusal rather than becoming a store read on the automations LIST path (W30-T12 took
9260
  #: that read off this route; putting it back to draw a label would undo the wave before this one).
9261
  ACTION_REQUIRED = dict(WEB_REQUIRED)
 
9262
  #: ⭐ W31-T38 (C5) — the web step's own clamps. `20000` matches the default E's seam documents;
9263
  #: the ceiling exists because this blocks the record walk (~9-32 s of cold start ALREADY), and an
9264
  #: automation that can be configured to wait ten minutes per record is a stalled run, not a slow one.
@@ -9268,7 +9286,7 @@ WEB_READ_TIMEOUT_MAX_MS = 120000
9268
  #: and never by a literal list of group names: a client-side ordering is a second copy of this
9269
  #: table, and the way it fails is that a group added here renders last, or not at all, with
9270
  #: nothing red anywhere.
9271
- ACTION_GROUP_ORDER = {"Web action": 1, "Database": 2, "Connected": 3, "Advanced logic": 4}
9272
  ACTION_CATALOG = [
9273
  # ── 1. WEB ACTION (owner rulings R1-R5) — DECLARED HERE, NOT YET BUILT (DEBT D-51). ────────
9274
  # ⛔ NOT A TEASE. `clean_actions` refuses an unready kind with a sentence, so the faded row
@@ -9326,16 +9344,19 @@ ACTION_CATALOG = [
9326
  # hidden row's label is still rendered on a STORED step's card, so leaving the six captions in
9327
  # place would have kept them on screen for exactly the people who already use them. They now
9328
  # name the mechanism instead, and no old caption survives as a substring in any case.
9329
- {"kind": "ai_agent", "label": "Web agent", "group": "Web action", "ready": True,
9330
  "detail": "Describe a job on a website in words; the agent works out the steps, runs them in "
9331
  "a browser and reports what it actually did"},
9332
- {"kind": "web_goto", "label": "Web agent step (navigate)", "group": "Web action",
 
 
 
9333
  "ready": True, "menu": False,
9334
  "detail": "Opens a page in a browser job and reports the title it landed on"},
9335
- {"kind": "web_fill", "label": "Web agent step (type)", "group": "Web action",
9336
  "ready": True, "menu": False,
9337
  "detail": "Types a value into a field. Mark it secret and the value is masked in the log"},
9338
- {"kind": "web_click", "label": "Web agent step (click)", "group": "Web action",
9339
  "ready": True, "menu": False,
9340
  "detail": "Clicks the element a selector names, and reports where it landed"},
9341
  # ⚠ `"kind": "web_read"` AND `"ready": True` STAY ON ONE LINE. `verify_wiring`'s C5 row matches
@@ -9345,9 +9366,9 @@ ACTION_CATALOG = [
9345
  # the client can add must be one the runner will execute); the layout is what it happens to
9346
  # depend on, so the layout is preserved here rather than the assertion weakened there.
9347
  {"kind": "web_read", "ready": True, "label": "Web agent step (extract)",
9348
- "group": "Web action", "menu": False,
9349
  "detail": "Reads one value off a live page in a browser job. Expect ~10-30 s per step"},
9350
- {"kind": "web_repair", "label": "Web agent step (relocate)", "group": "Web action",
9351
  "ready": True, "menu": False,
9352
  "detail": "Follows a label to its control when a selector has gone stale, and proposes one"},
9353
  # ── 2. DATABASE ──────────────────────────────────────────────────────────────────────────
@@ -9432,7 +9453,7 @@ ACTION_CATALOG = [
9432
  "ready": True, "menu": False,
9433
  "detail": "Pull the connected Odoo databases on a schedule. Configured on the connector, not "
9434
  "here"},
9435
- {"kind": "ai_enrich", "label": "Enrich this column with AI", "group": "Connected",
9436
  "ready": True, "menu": False,
9437
  "detail": "Fill an AI column for the records this flow walks. Configured on the column, not "
9438
  "here"},
@@ -10027,6 +10048,15 @@ def _clean_action_config(kind, cfg, depth, seen, count, notes=None, rt=None):
10027
  if limit < 1 or limit > FIND_LIMIT_MAX:
10028
  return None, f"the find records limit is between 1 and {FIND_LIMIT_MAX}"
10029
  return {"table": table, "cond": cond, "limit": limit}, None
 
 
 
 
 
 
 
 
 
10030
  if kind == "ai_agent":
10031
  # ⭐⭐ W33-T56 — THE FUZZY STEP'S CONFIG. Same posture as the web arm below in every
10032
  # respect that matters: an ALLOWLIST, a shape test on the url, a clamped timeout, and an
@@ -11101,6 +11131,19 @@ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print
11101
  "editor, not from this canvas. Nothing was done")
11102
  counts["webBlocked"] += 1
11103
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
11104
  elif kind == "ai_agent":
11105
  # ⭐⭐ W33-T56 (owner item 7, ruling R3) — THE FUZZY STEP, AT RUN TIME.
11106
  #
 
35
  import threading
36
  import time
37
  from urllib.parse import urljoin, urlparse
38
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
39
 
40
  import requests
41
 
 
1482
  """
1483
  description = " ".join(str(extra.pop(
1484
  "description", IG_FIELD_DESCRIPTIONS.get(text_key, "")) or "").split())
1485
+ # W44 C3: machine-spawned columns must declare the same full field contract emitted by the
1486
+ # user-table validator. A generic engine field is source-owned; the two derived kinds are
1487
+ # computed. Keeping this in the one constructor keeps every preset family exact under
1488
+ # `_clean_field` instead of letting a new contract key drift across hundreds of declarations.
1489
+ value_authority = "computed" if ftype in {"formula", "rollup"} else "source"
1490
+ out = {"key": text_key, "label": "Table" if ftype == "json" else label,
1491
+ "type": ftype, "source": "overlay", "kind": ftype, "origin": "automation",
1492
+ "valueAuthority": value_authority, "scope": "tenant", "editRole": "admins"}
1493
  if description:
1494
  out["description"] = description
1495
  out.update(extra)
 
1671
  revision = str(snap.get("sourceViewRevision") or "").strip()[:128]
1672
  recipient = str(raw.get("recipient") or "").strip()[:120]
1673
  timezone = str(snap.get("timezone") or raw.get("timezone") or "UTC").strip()[:80]
1674
+ try:
1675
+ ZoneInfo(timezone)
1676
+ except (ZoneInfoNotFoundError, ValueError):
1677
+ return None, "a scheduled route needs a recognized IANA timezone"
1678
  source_name = " ".join(str(snap.get("sourceViewName") or "").split())[:120]
1679
+ route_id = str(snap.get("routeId") or "").strip()[:96]
1680
  route_field = str(snap.get("routeField") or "").strip()[:120]
1681
  try:
1682
  links_per_map = int(snap.get("mapsPerLink", raw.get("mapsPerLink", 10)))
1683
  except (TypeError, ValueError):
1684
  links_per_map = 10
1685
  # R5: Google directions requires at least an origin and destination. The map UI exposes
1686
+ # the same 2-10 bound; this server normalisation is the wall for hand-written bodies too.
1687
  links_per_map = max(2, min(10, links_per_map))
1688
  ordered = []
1689
  seen = set()
 
1706
  return {
1707
  "recipient": recipient,
1708
  "routeSnapshot": {
1709
+ "routeId": route_id,
1710
  "sourceViewId": source_view,
1711
  "sourceViewRevision": revision,
1712
  "sourceViewName": source_name or source_view,
 
2347
  else prev.get("schedule"), prev.get("schedule"))
2348
  except ValueError as e:
2349
  return None, str(e)
2350
+ if kind == "route_delivery":
2351
+ # Native cron interprets this wall clock in the exact validated Zone frozen beside the
2352
+ # Route. Ordinary automations intentionally retain their historical UTC default.
2353
+ schedule["timezone"] = config["routeSnapshot"]["timezone"]
2354
  # (`clean_trigger` ran at the top — law 1 needs the trigger before the kind.)
2355
  flow_raw = raw.get("flow") if "flow" in raw else prev.get("flow")
2356
  # ⭐ EVERY CLEAN, NOT ONLY THE EDGE (owner ruling 6 — see `_ensure_ig_action`). The edge-only
 
9276
  #: run-time refusal rather than becoming a store read on the automations LIST path (W30-T12 took
9277
  #: that read off this route; putting it back to draw a label would undo the wave before this one).
9278
  ACTION_REQUIRED = dict(WEB_REQUIRED)
9279
+ ACTION_REQUIRED["voice_agent"] = (("a Voice agent", "voiceAgentId"),)
9280
  #: ⭐ W31-T38 (C5) — the web step's own clamps. `20000` matches the default E's seam documents;
9281
  #: the ceiling exists because this blocks the record walk (~9-32 s of cold start ALREADY), and an
9282
  #: automation that can be configured to wait ten minutes per record is a stalled run, not a slow one.
 
9286
  #: and never by a literal list of group names: a client-side ordering is a second copy of this
9287
  #: table, and the way it fails is that a group added here renders last, or not at all, with
9288
  #: nothing red anywhere.
9289
+ ACTION_GROUP_ORDER = {"Agent": 1, "Database": 2, "Connected": 3, "Advanced logic": 4}
9290
  ACTION_CATALOG = [
9291
  # ── 1. WEB ACTION (owner rulings R1-R5) — DECLARED HERE, NOT YET BUILT (DEBT D-51). ────────
9292
  # ⛔ NOT A TEASE. `clean_actions` refuses an unready kind with a sentence, so the faded row
 
9344
  # hidden row's label is still rendered on a STORED step's card, so leaving the six captions in
9345
  # place would have kept them on screen for exactly the people who already use them. They now
9346
  # name the mechanism instead, and no old caption survives as a substring in any case.
9347
+ {"kind": "ai_agent", "label": "Web agent", "group": "Agent", "ready": True,
9348
  "detail": "Describe a job on a website in words; the agent works out the steps, runs them in "
9349
  "a browser and reports what it actually did"},
9350
+ {"kind": "voice_agent", "label": "Voice agent", "group": "Agent", "ready": True,
9351
+ "detail": "Use a configured Loopable Voice agent. Production calls remain unavailable; "
9352
+ "the no-dial harness is the only executable Voice path"},
9353
+ {"kind": "web_goto", "label": "Web agent step (navigate)", "group": "Agent",
9354
  "ready": True, "menu": False,
9355
  "detail": "Opens a page in a browser job and reports the title it landed on"},
9356
+ {"kind": "web_fill", "label": "Web agent step (type)", "group": "Agent",
9357
  "ready": True, "menu": False,
9358
  "detail": "Types a value into a field. Mark it secret and the value is masked in the log"},
9359
+ {"kind": "web_click", "label": "Web agent step (click)", "group": "Agent",
9360
  "ready": True, "menu": False,
9361
  "detail": "Clicks the element a selector names, and reports where it landed"},
9362
  # ⚠ `"kind": "web_read"` AND `"ready": True` STAY ON ONE LINE. `verify_wiring`'s C5 row matches
 
9366
  # the client can add must be one the runner will execute); the layout is what it happens to
9367
  # depend on, so the layout is preserved here rather than the assertion weakened there.
9368
  {"kind": "web_read", "ready": True, "label": "Web agent step (extract)",
9369
+ "group": "Agent", "menu": False,
9370
  "detail": "Reads one value off a live page in a browser job. Expect ~10-30 s per step"},
9371
+ {"kind": "web_repair", "label": "Web agent step (relocate)", "group": "Agent",
9372
  "ready": True, "menu": False,
9373
  "detail": "Follows a label to its control when a selector has gone stale, and proposes one"},
9374
  # ── 2. DATABASE ──────────────────────────────────────────────────────────────────────────
 
9453
  "ready": True, "menu": False,
9454
  "detail": "Pull the connected Odoo databases on a schedule. Configured on the connector, not "
9455
  "here"},
9456
+ {"kind": "ai_enrich", "label": "AI field agent", "group": "Agent",
9457
  "ready": True, "menu": False,
9458
  "detail": "Fill an AI column for the records this flow walks. Configured on the column, not "
9459
  "here"},
 
10048
  if limit < 1 or limit > FIND_LIMIT_MAX:
10049
  return None, f"the find records limit is between 1 and {FIND_LIMIT_MAX}"
10050
  return {"table": table, "cond": cond, "limit": limit}, None
10051
+ if kind == "voice_agent":
10052
+ # Voice configuration lives in the dedicated, permissioned control plane. The action
10053
+ # stores one Loopable-local reference only: never a provider id, phone number, SIP route,
10054
+ # or credential. An empty draft is addable and is then named Unconfigured by
10055
+ # ACTION_REQUIRED; the runner arm below still refuses every ordinary dispatch.
10056
+ voice_id = _s(cfg.get("voiceAgentId"), 120).strip()
10057
+ if voice_id and not re.fullmatch(r"va_[A-Za-z0-9_\-]{4,110}", voice_id):
10058
+ return None, "select a Voice agent from Loopable rather than entering a provider id"
10059
+ return {"voiceAgentId": voice_id}, None
10060
  if kind == "ai_agent":
10061
  # ⭐⭐ W33-T56 — THE FUZZY STEP'S CONFIG. Same posture as the web arm below in every
10062
  # respect that matters: an ALLOWLIST, a shape test on the url, a clamped timeout, and an
 
11131
  "editor, not from this canvas. Nothing was done")
11132
  counts["webBlocked"] += 1
11133
  continue
11134
+ elif kind == "voice_agent":
11135
+ # Voice has a dedicated no-dial harness and no ordinary automation dispatcher.
11136
+ # Keeping the refusal in the walk is load-bearing: this dispatcher has no final
11137
+ # unknown-kind else, so a catalog row without an arm would otherwise report a
11138
+ # successful run that silently did nothing. A future activation must replace this
11139
+ # wall only after consent, capacity lease, callback route, webhook verification,
11140
+ # provider tests, and an explicit owner authorization all exist.
11141
+ if "voice_agent_not_activated" not in web_notes:
11142
+ web_notes.append("voice_agent_not_activated")
11143
+ log("[aios-auto] voice_agent: production Voice dispatch is not activated. "
11144
+ "Use the no-dial harness; no call was created")
11145
+ counts["webBlocked"] += 1
11146
+ continue
11147
  elif kind == "ai_agent":
11148
  # ⭐⭐ W33-T56 (owner item 7, ruling R3) — THE FUZZY STEP, AT RUN TIME.
11149
  #
api/routes_admin.py CHANGED
@@ -843,7 +843,7 @@ def _module_fields(key, session=None):
843
  if isinstance(_uf, dict) and _uf.get("key") and _uf["key"] not in _have:
844
  _have.add(_uf["key"])
845
  src.append(_uf)
846
- known = _server_side_vocabularies()
847
  out = []
848
  for f in src:
849
  if not isinstance(f, dict) or not f.get("key"):
@@ -1019,7 +1019,7 @@ BLANK = "(none)"
1019
  _VOCAB_CACHE = None
1020
 
1021
 
1022
- def _server_side_vocabularies():
1023
  """`{field key: [choice, …]}` for choice columns whose vocabulary is CLOSED and known here,
1024
  but which the grid contract does not declare.
1025
 
@@ -1090,8 +1090,36 @@ def _server_side_vocabularies():
1090
  it. Recorded because the ask, not a guess, is what settled it.
1091
  """
1092
  global _VOCAB_CACHE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1093
  if _VOCAB_CACHE is not None:
1094
- return dict(_VOCAB_CACHE)
 
 
 
 
 
 
 
 
1095
 
1096
  out = {}
1097
 
@@ -1199,6 +1227,10 @@ def _server_side_vocabularies():
1199
  _agents, _salespeople)])
1200
  if complete:
1201
  _VOCAB_CACHE = dict(out)
 
 
 
 
1202
  return out
1203
 
1204
 
@@ -2029,7 +2061,14 @@ def _store_binding(session):
2029
  import core.store as store # noqa: PLC0415
2030
  bound = getattr(session.runtime, "store_handle", None)
2031
  repo = getattr(bound, "repo", None) or store.REPO
2032
- return data_binding.describe(repo)
 
 
 
 
 
 
 
2033
  except Exception as e: # noqa: BLE001
2034
  return {"deployment": "unknown", "production": False, "repo": "",
2035
  "writable": False, "refusal": f"could not resolve the store binding: {e}",
 
843
  if isinstance(_uf, dict) and _uf.get("key") and _uf["key"] not in _have:
844
  _have.add(_uf["key"])
845
  src.append(_uf)
846
+ known = _server_side_vocabularies(session=session)
847
  out = []
848
  for f in src:
849
  if not isinstance(f, dict) or not f.get("key"):
 
1019
  _VOCAB_CACHE = None
1020
 
1021
 
1022
+ def _server_side_vocabularies(session=None):
1023
  """`{field key: [choice, …]}` for choice columns whose vocabulary is CLOSED and known here,
1024
  but which the grid contract does not declare.
1025
 
 
1090
  it. Recorded because the ask, not a guess, is what settled it.
1091
  """
1092
  global _VOCAB_CACHE
1093
+
1094
+ def _product_shared_choices():
1095
+ """Tenant-owned options for the editable Product taxonomy columns.
1096
+
1097
+ These nine fields are ordinary shared Product fields. Their vocabulary is admitted by
1098
+ the same atomic cell+choice write that stores an edit, so the permission editor must read
1099
+ the tenant's shared definition rather than inventing a global list or loading the whole
1100
+ Product pool. A missing runtime honestly supplies nothing; a value from another tenant
1101
+ must never be borrowed from the process cache below.
1102
+ """
1103
+ if session is None:
1104
+ return {}
1105
+ import core.shared_overlay as shared_overlay
1106
+ import modules.product_data as product_data
1107
+
1108
+ stored = shared_overlay.fields(product_data.TABLE_KEY, st=session.runtime) or {}
1109
+ keys = ("collection", "color", "finish", "main_category", "material",
1110
+ "occassion", "shape_style", "size", "sub_category")
1111
+ return {key: (stored.get(key) or {}).get("options") or () for key in keys}
1112
+
1113
  if _VOCAB_CACHE is not None:
1114
+ out = dict(_VOCAB_CACHE)
1115
+ try:
1116
+ for key, values in _product_shared_choices().items():
1117
+ clean = sorted({str(v) for v in values if str(v or "").strip()})
1118
+ if clean:
1119
+ out[key] = clean
1120
+ except Exception: # noqa: BLE001
1121
+ pass
1122
+ return out
1123
 
1124
  out = {}
1125
 
 
1227
  _agents, _salespeople)])
1228
  if complete:
1229
  _VOCAB_CACHE = dict(out)
1230
+ # Tenant-owned choices are deliberately added AFTER the process cache is stamped. Caching
1231
+ # them beside Odoo's shared Royal vocabulary would leak one tenant's Product taxonomy into
1232
+ # another tenant's permission editor for the life of the worker.
1233
+ arm(_product_shared_choices)
1234
  return out
1235
 
1236
 
 
2061
  import core.store as store # noqa: PLC0415
2062
  bound = getattr(session.runtime, "store_handle", None)
2063
  repo = getattr(bound, "repo", None) or store.REPO
2064
+ result = data_binding.describe(repo)
2065
+ if result.get("backend") == "pg":
2066
+ import core.store_pg as store_pg # noqa: PLC0415
2067
+ slug = getattr(bound, "tenant_slug", None) or session.tenant
2068
+ refusal = store_pg.write_refusal(slug)
2069
+ result.update(writable=refusal is None, refusal=refusal,
2070
+ allowlist=sorted(store_pg.sandbox_tenants()))
2071
+ return result
2072
  except Exception as e: # noqa: BLE001
2073
  return {"deployment": "unknown", "production": False, "repo": "",
2074
  "writable": False, "refusal": f"could not resolve the store binding: {e}",
api/routes_automation.py CHANGED
@@ -19,6 +19,7 @@ from fastapi import APIRouter, Body, Depends, Header, Request
19
  import ai_review
20
  import automation_control
21
  import automation_engine as engine
 
22
  import oauth_connect
23
  import routes_oauth
24
  import scope_cache
@@ -53,6 +54,186 @@ MODULE = "automation"
53
  _GATE = module_gate(MODULE)
54
 
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  def _sync_schedule_or_503(tenant, defn):
57
  """Apply the exact native schedules after a definition write, never silently drift."""
58
  try:
@@ -1037,7 +1218,8 @@ def _table_views(session, key):
1037
  return None
1038
  merged = {**shared, **own} # a view lives in ONE home; the merge is belt-and-braces
1039
  return sorted(
1040
- ({"id": str(vid), "label": str((v or {}).get("name") or vid)}
 
1041
  for vid, v in merged.items() if isinstance(v, dict)),
1042
  key=lambda r: r["label"].lower())
1043
 
 
19
  import ai_review
20
  import automation_control
21
  import automation_engine as engine
22
+ import voice_control_plane as voice
23
  import oauth_connect
24
  import routes_oauth
25
  import scope_cache
 
54
  _GATE = module_gate(MODULE)
55
 
56
 
57
+ def _voice_view_revision(view):
58
+ """One stable revision string for a server-owned saved View choice."""
59
+ if not isinstance(view, dict):
60
+ return ""
61
+ cfg = view.get("config") if isinstance(view.get("config"), dict) else {}
62
+ for key in ("revision", "version", "updatedAt", "updated_at"):
63
+ value = view.get(key, cfg.get(key))
64
+ if value not in (None, ""):
65
+ return str(value)[:120]
66
+ return ""
67
+
68
+
69
+ def _voice_option(key, label, fields, views):
70
+ phone = [{"key": str(field.get("key") or ""),
71
+ "label": str(field.get("label") or field.get("key") or "")}
72
+ for field in (fields or []) if isinstance(field, dict)
73
+ and field.get("key") and field.get("type") == "phone"]
74
+ saved = [{"id": str(view.get("id") or ""),
75
+ "label": str(view.get("name") or view.get("label") or view.get("id") or ""),
76
+ "revision": _voice_view_revision(view)}
77
+ for view in (views or []) if isinstance(view, dict) and view.get("id")]
78
+ if not phone or not saved:
79
+ return None
80
+ return {"key": str(key), "label": str(label), "views": saved, "phoneFields": phone}
81
+
82
+
83
+ def _voice_options(session):
84
+ """Compose only databases, saved Views, and phone fields this session may already open."""
85
+ tables = []
86
+ # Built-in customer data has its own module wall. An Automation grant is not permission to
87
+ # enumerate its schema, so failure simply withholds this choice.
88
+ try:
89
+ session.require("customer_data")
90
+ from routes_customers import grid_assembly
91
+ customer = grid_assembly(session, consume_corrections=False)
92
+ option = _voice_option("customer_data", "Customers", customer.get("fields"),
93
+ customer.get("views"))
94
+ if option:
95
+ tables.append(option)
96
+ except Exception: # noqa: BLE001 - permission/absence.
97
+ pass
98
+ # User tables are permissioned by their own object wall inside automation_tables().
99
+ for table in automation_tables(session).get("tables") or []:
100
+ option = _voice_option(table.get("key"), table.get("label") or table.get("key"),
101
+ table.get("fields"), table.get("views"))
102
+ if option:
103
+ tables.append(option)
104
+ return {"tables": tables}
105
+
106
+
107
+ def _voice_rows_from_user_table(session, table_key):
108
+ import aios_grid
109
+ from routes_tables import ut_assembly
110
+
111
+ g = ut_assembly(session, table_key, consume_corrections=False, with_rows=True)
112
+ overlays = (g.get("ws") or {}).get("overlays") or {}
113
+ merged = {}
114
+ for row in g.get("rows_src") or []:
115
+ pid = str(row.get("pid"))
116
+ cells = dict(overlays.get(pid) or overlays.get(row.get("pid")) or {})
117
+ shared = (g.get("shared_cells") or {}).get(pid)
118
+ if isinstance(shared, dict):
119
+ cells.update(shared)
120
+ merged[pid] = cells
121
+ rows = aios_grid.rows_from_pool(g.get("rows_src") or [], g.get("fields") or [], merged,
122
+ derived=g.get("derived") or {})
123
+ return g, rows
124
+
125
+
126
+ def _voice_rows_from_customers(session):
127
+ import aios_grid
128
+ from core import route_system
129
+ from routes_customers import grid_assembly
130
+
131
+ session.require("customer_data")
132
+ g = grid_assembly(session, consume_corrections=False)
133
+ rows = aios_grid.rows_from_pool(g["rows_src"], g["fields"], g["ws"].get("overlays"),
134
+ derived=g["derived"])
135
+ return g, route_system.apply_customer_projections(rows, g["routes"], g["zones"])
136
+
137
+
138
+ def _voice_view_input(session, audience):
139
+ """Resolve an authorized saved View to redacted recipient counts, never phone values."""
140
+ from harness import filter_eval
141
+
142
+ table_key = str((audience or {}).get("tableKey") or "")
143
+ if table_key == "customer_data":
144
+ g, rows = _voice_rows_from_customers(session)
145
+ elif table_key.startswith("ut_"):
146
+ g, rows = _voice_rows_from_user_table(session, table_key)
147
+ else:
148
+ raise voice.VoiceRefusal("select a database available to this account")
149
+ view_id = str((audience or {}).get("viewId") or "")
150
+ phone_key = str((audience or {}).get("phoneFieldKey") or "")
151
+ view = next((row for row in (g.get("views") or []) if isinstance(row, dict)
152
+ and str(row.get("id") or "") == view_id), None)
153
+ if not isinstance(view, dict):
154
+ raise voice.VoiceRefusal("select a saved View you are authorized to open")
155
+ revision = _voice_view_revision(view)
156
+ requested_revision = str((audience or {}).get("viewRevision") or "")
157
+ if requested_revision and revision and requested_revision != revision:
158
+ raise voice.VoiceRefusal("that saved View changed; review the audience before running")
159
+ field = next((row for row in (g.get("fields") or []) if isinstance(row, dict)
160
+ and str(row.get("key") or "") == phone_key), None)
161
+ if not isinstance(field, dict) or field.get("type") != "phone":
162
+ raise voice.VoiceRefusal("select a phone-type field")
163
+ cfg = dict(view.get("config") or {})
164
+ cohorts = {str(item.get("id")): set(item.get("pids") or [])
165
+ for item in (g.get("lists") or []) if isinstance(item, dict) and item.get("id")}
166
+ context = filter_eval.EvalCtx(cohort_sets=cohorts,
167
+ measure_sets=g.get("measure_sets") or {},
168
+ today=g.get("today") or time.strftime("%Y-%m-%d"))
169
+ tree = {"nodes": cfg.get("filters") or [], "conj": cfg.get("filterConj") or "and"}
170
+ pids = set(filter_eval.visible_pids(tree, rows, g.get("fields") or [], context,
171
+ member_pids=cfg.get("memberPids") or [],
172
+ group_by=cfg.get("groupBy")))
173
+ selected = [row for row in rows if row.get("pid") in pids]
174
+ eligible = [row for row in selected if row.get(phone_key) not in (None, "")]
175
+ return {"tableKey": table_key, "viewId": view_id, "viewRevision": revision,
176
+ "phoneFieldKey": phone_key, "selectedCount": len(selected),
177
+ "recipientCount": len(eligible), "rawPhoneValuesReturned": False}
178
+
179
+
180
+ @router.get("/voice-agents")
181
+ def list_voice_agents(session: Session = Depends(_GATE)):
182
+ options = _voice_options(session)
183
+ rows = voice.list_browser_dtos(session.runtime)
184
+ for row in rows:
185
+ row["audienceOptions"] = options
186
+ return {"voiceAgents": rows}
187
+
188
+
189
+ @router.get("/voice-agents/options")
190
+ def voice_agent_options(session: Session = Depends(_GATE)):
191
+ return {**voice.browser_options(session.runtime), "audienceOptions": _voice_options(session)}
192
+
193
+
194
+ @router.post("/voice-agents")
195
+ def create_voice_agent(body: dict = Body(default=None), session: Session = Depends(_GATE)):
196
+ try:
197
+ saved = voice.save_draft(session.runtime, body or {}, session.uname)
198
+ row = voice.get_browser_dto(session.runtime, saved["id"])
199
+ row["audienceOptions"] = _voice_options(session)
200
+ return {"voiceAgent": row}
201
+ except voice.VoiceRefusal as exc:
202
+ raise err(400, "voice_refused", str(exc))
203
+
204
+
205
+ @router.patch("/voice-agents/{voice_id}")
206
+ def patch_voice_agent(voice_id: str, body: dict = Body(default=None), session: Session = Depends(_GATE)):
207
+ try:
208
+ voice.patch_draft(session.runtime, voice_id, body or {}, session.uname)
209
+ row = voice.get_browser_dto(session.runtime, voice_id)
210
+ row["audienceOptions"] = _voice_options(session)
211
+ return {"voiceAgent": row}
212
+ except voice.VoiceRefusal as exc:
213
+ raise err(400 if "unknown" not in str(exc) else 404, "voice_refused", str(exc))
214
+
215
+
216
+ @router.post("/voice-agents/{voice_id}/harness/dry-run")
217
+ def voice_dry_run(voice_id: str, body: dict = Body(default=None), session: Session = Depends(_GATE)):
218
+ body = body or {}
219
+ try:
220
+ if isinstance(body.get("audience"), dict):
221
+ audience = body.get("audience")
222
+ else:
223
+ audience = {}
224
+ for source, target in (("table", "tableKey"), ("viewId", "viewId"),
225
+ ("viewRevision", "viewRevision"),
226
+ ("phoneField", "phoneFieldKey"),
227
+ ("emptyPolicy", "emptyPolicy"),
228
+ ("maxRecipients", "maxRecipients")):
229
+ if source in body:
230
+ audience[target] = body.get(source)
231
+ return voice.dry_run(session.runtime, voice_id, audience,
232
+ lambda selected: _voice_view_input(session, selected))
233
+ except voice.VoiceRefusal as exc:
234
+ raise err(400 if "unknown" not in str(exc) else 404, "voice_refused", str(exc))
235
+
236
+
237
  def _sync_schedule_or_503(tenant, defn):
238
  """Apply the exact native schedules after a definition write, never silently drift."""
239
  try:
 
1218
  return None
1219
  merged = {**shared, **own} # a view lives in ONE home; the merge is belt-and-braces
1220
  return sorted(
1221
+ ({"id": str(vid), "label": str((v or {}).get("name") or vid),
1222
+ "revision": _voice_view_revision(v)}
1223
  for vid, v in merged.items() if isinstance(v, dict)),
1224
  key=lambda r: r["label"].lower())
1225
 
api/routes_customers.py CHANGED
@@ -190,7 +190,11 @@ def shared_fields(st=None):
190
  try:
191
  field_permissions.migrate_legacy_fields(
192
  _shared_key(), st=st, grant_topic="customer_data", shared_key=_shared_key())
193
- return shared_overlay.fields(_shared_key(), st=st)
 
 
 
 
194
  except Exception: # noqa: BLE001
195
  # Lenient like every other display read: an unreachable store degrades to "nothing is
196
  # shared yet", never to a 500 on a grid that would otherwise render. The WALL does not
@@ -198,6 +202,11 @@ def shared_fields(st=None):
198
  return {}
199
 
200
 
 
 
 
 
 
201
  def shared_cells(pids, st=None):
202
  """`{"<pid>": {key: value}}` for the rows named by `pids`, and ONLY those.
203
 
@@ -213,7 +222,14 @@ def shared_cells(pids, st=None):
213
  return {}
214
 
215
 
216
- def _merge_shared_fields(fields, defs, session=None):
 
 
 
 
 
 
 
217
  """`fields` PLUS the tenant-wide columns this topic declares — `routes_tables._ut_shared_fields`
218
  on the customer topic.
219
 
@@ -225,12 +241,33 @@ def _merge_shared_fields(fields, defs, session=None):
225
  ⚠ A key the canonical contract already declares WINS. A shared column is an ADDITION to this
226
  database's contract, never a redefinition of a column it already has.
227
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
  if not defs:
229
  return fields
230
- have = {f.get("key") for f in (fields or ()) if isinstance(f, dict)}
231
  projected = []
232
  for k, f in defs.items():
233
- if k in have:
 
 
 
 
 
 
 
 
234
  continue
235
  item = dict(f, source="overlay", shared=True)
236
  if session is not None:
@@ -240,8 +277,29 @@ def _merge_shared_fields(fields, defs, session=None):
240
  is_admin=session.admin, st=session.runtime)
241
  if role:
242
  item["sharedRole"] = role
243
- projected.append(item)
244
- return list(fields or ()) + projected
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
 
247
  def grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
@@ -305,9 +363,10 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
305
  # dict on one request (the write ctx's wall, the read merge, and the closure), and letting each
306
  # take its own copy is the shape D-214 spent a whole ticket removing one document over.
307
  _defs = shared_fields(st=rt)
 
308
  ws = grid_events.table_workspace(
309
- _ctx_for(session, pids, defs=_defs), allowed_pids=pids,
310
- consume_corrections=consume_corrections)
311
  # ⭐⭐ W38-T20 / D-425 — THE TENANT-WIDE CELLS, LAYERED OVER THE PER-USER ONES, IN THE
312
  # ASSEMBLY SO EVERY CONSUMER SEES ONE TRUTH. `routes_grid`'s /workspace route serves
313
  # `workspace["overlays"] = g["ws"].get("overlays")` verbatim and `_payload` hands the same
@@ -333,7 +392,18 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
333
  # ⭐⭐ W38-T20 — AND THE COLUMN DEFINITIONS, BEFORE THE WALL. See `_merge_shared_fields`: this
334
  # position is load-bearing twice, once for the transitive closure and once because it is the
335
  # only order in which the per-field grant marker is ever presented to `hidden_keys`.
336
- fields = _merge_shared_fields(fields, _defs, session=session)
 
 
 
 
 
 
 
 
 
 
 
337
  # ⭐⭐ W41-T01 / RULING R5 / CONTRACTS C1 + C8 — **THE THREE BADGES, STAMPED ONCE, HERE.**
338
  #
339
  # C1 makes `field_permissions.field_class` the ONE producer of `{origin, audience, sharedBy,
@@ -377,7 +447,8 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
377
  try:
378
  from core import field_permissions as _fp
379
  _classes = _fp.field_classes(fields, session.uname, table_key=_shared_key(),
380
- grant_topic=SHARE_TOPIC, values_shared=set(_defs), st=rt)
 
381
  fields = [dict(f, **{"class": _classes[f["key"]]})
382
  if isinstance(f, dict) and _classes.get(f.get("key")) else f
383
  for f in fields]
@@ -399,6 +470,22 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
399
  # makes this degrade safe: a client renders NOTHING for a missing `class` rather than a
400
  # wrong badge, so a registry that will not open costs the badges and not the grid.
401
  pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
402
  # THE FIELD WALL — a TRANSITIVE closure (C-PERM amendment 5), so hiding a field also hides
403
  # every formula computed FROM it. Formulas evaluate in the browser from `{ref}`s, so
404
  # shipping a dependent formula while withholding its input either leaks the input through
@@ -474,14 +561,19 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
474
  on_error=_measure_err) if may_metrics else {}).items():
475
  derived.setdefault(pid, {}).update(cells)
476
 
477
- # Zones are table-scoped tenant data, surfaced as the established comma-joined multiselect
478
- # contract so saved Views and FilterBuilder evaluate them like every other membership field.
479
- from core import user_tables as _zones
480
- fields = _zones.with_zone_field("customer_data", fields, st=rt)
 
 
 
 
 
481
  return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
482
  "fields": fields, "views": views, "lists": lists, "derived": derived,
483
  "measures": measures, "measure_sets": measure_sets, "today": today,
484
- "team_id": team_id}
485
 
486
 
487
  def _payload(session: Session):
@@ -501,9 +593,8 @@ def _payload(session: Session):
501
  g = grid_assembly(session)
502
  rows = aios_grid.rows_from_pool(
503
  g["rows_src"], g["fields"], g["ws"].get("overlays"), derived=g["derived"])
504
- from core import user_tables as _zones
505
- rows = _zones.zone_cells("customer_data", rows, allowed_row_ids=g["pids"],
506
- st=session.runtime)
507
  # ⭐ C4 / D-138 (W30-T37) — THE DOCUMENTS PRODUCER FOR THE CUSTOMER SCOPE. The write door
508
  # (`doc_add`/`doc_fetch`/`doc_delete`) never stopped working and every client half is
509
  # complete; what vanished with `app.py` at EXIT-6 was the only thing that ever set this key.
@@ -604,6 +695,673 @@ def customers(session: Session = Depends(module_gate(MODULE))):
604
  return _payload(session)
605
 
606
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607
  def _split_route_updates(session, updates):
608
  """Split a cell PATCH into `(route order updates, everything else)`.
609
 
@@ -614,7 +1372,9 @@ def _split_route_updates(session, updates):
614
  route, rest = {}, {}
615
  for key, value in (updates or {}).items():
616
  defn = defs.get(key)
617
- if isinstance(defn, dict) and defn.get("kind") == ROUTE_KIND:
 
 
618
  route[key] = value
619
  else:
620
  rest[key] = value
@@ -652,9 +1412,10 @@ def _patch_route_ranks(session, ctx, pid, pool, updates):
652
  `patch_customer` routes everything else through `grid_events` rather than writing the store.
653
 
654
  ⚠ UNIQUENESS IS MAINTAINED OVER THE ROWS THIS CALLER CAN SEE, and that is a limit worth
655
- stating rather than hiding. `shared_overlay.cells` takes the scoped pool BY SIGNATURE (there is
656
- deliberately no "every shared cell in the tenant" call), so the holder of a displaced number is
657
- looked for inside this session's book. In practice the whole column lives there anyway --
 
658
  `route_order_write` REFUSES a body carrying a pid outside the writer's pool, so every number in
659
  a route order was written by somebody whose book contained all of them.
660
  """
@@ -670,49 +1431,30 @@ def _patch_route_ranks(session, ctx, pid, pool, updates):
670
  #: value the caller did NOT ask for.
671
  taken, swaps = set(), []
672
 
673
- def _held():
674
- """`{pid: rank}` for this column, over the rows this caller can see.
675
 
676
- Re-read per key rather than hoisted, because a multi-key patch writes between iterations
677
- and the second key must see the first one's result.
 
678
  """
679
- out = {}
680
- for raw_pid, cells in (shared_cells(pool, st=session.runtime) or {}).items():
681
- if not isinstance(cells, dict):
682
- continue
683
- cell = cells.get(key)
684
- if cell in (None, ""):
685
- continue
686
- try:
687
- out[int(raw_pid)] = int(str(cell).strip())
688
- except (TypeError, ValueError):
689
- continue
690
- return out
691
 
692
  for key, raw in updates.items():
693
  defn = defs.get(key) or {}
694
- held = _held()
695
-
696
- def _stored():
697
- """⛔⛔ A REFUSAL REPORTS WHAT THE CELL ACTUALLY HOLDS, AND THAT IS NOT TIDINESS.
698
-
699
- `patchTopicRow` adopts `body.updates` into the browser's optimistic copy and rolls
700
- back only on a non-2xx. A refused key that is simply ABSENT from `updates` is a key
701
- the client never hears about: the response is 200, the rollback never fires, `adopt`
702
- has nothing to write, and the typed text goes on painting a value the store rejected
703
- until something unrelated forces a refetch. On a `select` the option normaliser made
704
- this unreachable; item 7 made the column an `int`, so `14.5` or a stray letter is now
705
- an ordinary typo away. `patchTopicRow`'s own docstring already states the rule —
706
- keep only what the server actually took — and this is that rule with its hole closed.
707
- """
708
- n = held.get(pid)
709
- return "" if n is None else str(n)
710
 
711
  if key in hidden:
712
- accepted[key] = _stored()
713
  continue
714
  if not grid_events._may_edit_field_value(ctx, key, defn):
715
- accepted[key] = _stored()
716
  continue
717
  # An empty cell is "not on this route". Legal, and the only way to take a stop off the
718
  # day without re-solving the whole column.
@@ -724,30 +1466,22 @@ def _patch_route_ranks(session, ctx, pid, pool, updates):
724
  # ⛔ A BOOL IS AN `int` IN PYTHON, so `True` would store as visit number 1. Excluded by
725
  # name here exactly as `route_order_write` excludes it, rather than by hoping.
726
  if isinstance(raw, bool):
727
- accepted[key] = _stored()
728
  continue
729
  try:
730
  want = int(str(raw).strip())
731
  except (TypeError, ValueError):
732
- accepted[key] = _stored()
733
  continue
734
  if want < 1:
735
- accepted[key] = _stored()
736
  continue
737
 
738
- prior = held.get(pid)
739
- if prior == want:
740
- accepted[key] = str(want)
741
- taken.add(key)
742
- continue
743
- writes = {pid: {key: str(want)}}
744
- holder = next((p for p, n in held.items() if n == want and p != pid), None)
745
- if holder is not None:
746
- moved = prior if prior is not None else max(held.values()) + 1
747
- writes[holder] = {key: str(moved)}
748
- swaps.append({"pid": holder, "field": key, "value": str(moved)})
749
- shared_overlay.put_rows(_shared_key(), writes, st=session.runtime)
750
- accepted[key] = str(want)
751
  taken.add(key)
752
  return accepted, swaps, taken
753
 
@@ -768,6 +1502,12 @@ def patch_customer(pid: int, body: dict = Body(default=None),
768
  updates = dict(body or {})
769
  if not updates:
770
  raise err(400, "empty_patch", "no fields to update")
 
 
 
 
 
 
771
  pool = allowed_pids(session)
772
  if pid not in pool:
773
  # 403, not 404: the pid may well exist — it is simply not in this session's book, and
@@ -875,6 +1615,8 @@ ROUTE_KEY_PREFIX = "route_"
875
  #: the client; never inferred from the key, because a prefix is a naming convention and a
876
  #: convention is not a declaration.
877
  ROUTE_KIND = "route_order"
 
 
878
 
879
  #: ⭐⭐ W41-T05 / CONTRACT C3 — THE DESCRIPTION EVERY ROUTE COLUMN IS BORN WITH.
880
  #:
@@ -991,8 +1733,11 @@ def _route_defs(session: Session):
991
  import core.perm_scope as perm_scope
992
 
993
  all_defs = shared_fields(st=session.runtime) or {}
 
 
994
  defs = {k: v for k, v in all_defs.items()
995
- if isinstance(v, dict) and v.get("kind") == ROUTE_KIND}
 
996
  if not defs:
997
  return {}
998
  hide = perm_scope.hidden_keys(
@@ -1254,6 +1999,9 @@ def route_order_write(body: dict = Body(default=None),
1254
  "source": "overlay",
1255
  "shared": True,
1256
  "kind": ROUTE_KIND,
 
 
 
1257
  # ⭐⭐ W41-T05 — THE DESCRIPTION, CARRIED BY **PRESENCE** AND NOT BY TRUTHINESS.
1258
  # `ROUTE_FIELD_NOTE` says why the column cannot be born without one and why `""` has to
1259
  # survive a re-solve: `route_order_rename` clears a description by storing exactly that,
@@ -1585,6 +2333,7 @@ def _route_delivery_wire(defn):
1585
  "recipient": str(cfg.get("recipient") or ""),
1586
  "schedule": dict(defn.get("schedule") or {}),
1587
  "snapshot": {
 
1588
  "sourceViewId": str(snap.get("sourceViewId") or ""),
1589
  "sourceViewRevision": str(snap.get("sourceViewRevision") or ""),
1590
  "sourceViewName": str(snap.get("sourceViewName") or ""),
@@ -1598,11 +2347,19 @@ def _route_delivery_wire(defn):
1598
  }
1599
 
1600
 
1601
- def _route_delivery_recipient_or_400(raw):
 
 
 
 
 
 
1602
  recipient = str(raw or "").strip()
1603
  try:
1604
- import core.users as users
1605
- user = (users.registry() or {}).get(recipient)
 
 
1606
  except Exception: # registry unavailable is not permission to queue a phantom Inbox delivery
1607
  user = None
1608
  if not recipient or not isinstance(user, dict) or not user.get("active", True):
@@ -1624,89 +2381,141 @@ def _route_view_revision(view_id, config):
1624
  return "view-config-v2-" + hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:24]
1625
 
1626
 
1627
- def _route_snapshot_for_view_or_409(snapshot, source_view):
1628
- """Accept a route only when the caller's View config is the View visible at this request.
 
1629
 
1630
- Ordered stops remain the actual frozen work list. The source View is its separately auditable
1631
- provenance, so a forged revision must never be stored beside an otherwise valid View id.
1632
- Copy only canonical server facts forward; the submitted config is a compare-and-discard
1633
- concurrency guard, not another persisted configuration copy.
1634
  """
1635
- source_view_id = str(source_view.get("id") or "").strip()
1636
- source_config = source_view.get("config")
1637
- submitted_config = snapshot.get("sourceViewConfig")
1638
- if not source_view_id or not isinstance(source_config, dict):
1639
- raise err(409, "stale_route_source_view",
1640
- "the saved route View changed; refresh it before scheduling this route")
1641
- if not isinstance(submitted_config, dict) or submitted_config != source_config:
1642
- raise err(409, "stale_route_source_view",
1643
- "the saved route View changed; refresh it before scheduling this route")
1644
- return {
1645
- **snapshot,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1646
  "sourceViewId": source_view_id,
1647
  "sourceViewRevision": _route_view_revision(source_view_id, source_config),
1648
  "sourceViewName": str(source_view.get("name") or source_view_id),
 
 
 
 
1649
  }
1650
 
1651
 
1652
- @router.get("/customers/route-deliveries")
1653
- def route_delivery_list(session: Session = Depends(module_gate(MODULE))):
1654
- """Saved C2 route deliveries owned by the caller (or all for an administrator)."""
1655
  import automation_engine as engine
1656
  out = []
1657
  for defn in (engine.all_definitions(session.runtime) or {}).values():
1658
  if not isinstance(defn, dict) or defn.get("kind") != "route_delivery":
1659
  continue
1660
- # A recipient can see the delivery arriving in their Inbox; the edit index is the owner's
1661
- # configuration surface. Admins can support either one.
1662
  if not session.admin and str(defn.get("createdBy") or "") != session.uname:
1663
  continue
1664
- out.append(_route_delivery_wire(defn))
1665
- return {"deliveries": sorted(out, key=lambda row: (row["name"].casefold(), row["id"]))}
 
 
 
1666
 
1667
 
1668
- @router.post("/customers/route-deliveries")
1669
- def route_delivery_create(body: dict = Body(default=None),
1670
- session: Session = Depends(module_gate(MODULE))):
1671
- """Save a daily route delivery as an immutable C2 snapshot and arm its native schedule."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1672
  import automation_control
1673
  import automation_engine as engine
1674
 
1675
  if not session.runtime.available():
1676
  raise err(503, "store_unavailable", "the tenant store is unavailable. Nothing was saved")
1677
- body = body if isinstance(body, dict) else {}
1678
- recipient = _route_delivery_recipient_or_400(body.get("recipient"))
1679
- snapshot = body.get("routeSnapshot") if isinstance(body.get("routeSnapshot"), dict) else {}
1680
- # A route snapshot is allowed to freeze its *stops*, never to invent its View provenance.
1681
- # `map-current`/a route-plan fingerprint were a synthetic fallback that made an automation
1682
- # impossible to audit back to the actual filtered View. Resolve the submitted id against
1683
- # this reader's visible View contract, compare the complete config, and mint its revision
1684
- # server-side; a valid View id with a forged/stale revision is still not an honest snapshot.
1685
- source_view_id = str(snapshot.get("sourceViewId") or "").strip()
1686
- if not source_view_id or source_view_id == "map-current":
1687
- raise err(400, "invalid_route_source_view",
1688
- "choose an active saved View for this frozen route")
1689
- source_views = {str(view.get("id") or ""): view for view in
1690
- (grid_assembly(session, consume_corrections=False).get("views") or [])
1691
- if isinstance(view, dict) and view.get("id")}
1692
- source_view = source_views.get(source_view_id)
1693
- if source_view is None:
1694
- raise err(400, "unknown_route_source_view",
1695
- "the route source View is no longer visible to this account")
1696
- snapshot = _route_snapshot_for_view_or_409(snapshot, source_view)
1697
  raw = {
1698
- "name": " ".join(str(body.get("name") or snapshot.get("sourceViewName") or "Scheduled route").split())[:120],
1699
  "kind": "route_delivery",
1700
  "trigger": {"key": "manual"},
1701
- "schedule": body.get("schedule") if isinstance(body.get("schedule"), dict)
1702
- else {"cron": "0 8 * * *", "enabled": True},
1703
- "config": {
1704
- "recipient": recipient,
1705
- "routeSnapshot": {
1706
- **snapshot,
1707
- "mapsPerLink": snapshot.get("mapsPerLink", body.get("mapsPerLink", 10)),
1708
- },
1709
- },
1710
  "flow": {"actions": []},
1711
  }
1712
  defn, problem = engine.create(session.runtime, raw, username=session.uname)
@@ -1715,22 +2524,41 @@ def route_delivery_create(body: dict = Body(default=None),
1715
  try:
1716
  automation_control.sync_definition(session.tenant, defn)
1717
  except automation_control.ControlPlaneError as exc:
1718
- # The definition exists but is not allowed to read as armed if its native schedule did not.
1719
  raise err(503, "automation_control_unavailable",
1720
  f"the route was saved, but its daily schedule could not be armed: {exc}")
1721
  return {"delivery": _route_delivery_wire(defn)}
1722
 
1723
 
1724
- @router.delete("/customers/route-deliveries/{delivery_id}")
1725
- def route_delivery_delete(delivery_id: str,
 
 
 
 
 
 
 
 
1726
  session: Session = Depends(module_gate(MODULE))):
1727
- """Remove one scheduled delivery without touching its immutable route field or rows."""
 
 
 
 
 
 
 
 
 
1728
  import automation_control
1729
  import automation_engine as engine
1730
 
1731
  defn = (engine.all_definitions(session.runtime) or {}).get(str(delivery_id))
1732
  if not isinstance(defn, dict) or defn.get("kind") != "route_delivery":
1733
  raise err(404, "unknown_route_delivery", "no scheduled route with that id")
 
 
 
1734
  if not session.admin and str(defn.get("createdBy") or "") != session.uname:
1735
  raise err(403, "forbidden", "only the route creator or an administrator can remove its schedule")
1736
  engine.remove(session.runtime, str(delivery_id))
@@ -1740,3 +2568,19 @@ def route_delivery_delete(delivery_id: str,
1740
  raise err(503, "automation_control_unavailable",
1741
  f"the route schedule was removed, but its native schedule could not be removed: {exc}")
1742
  return {"deleted": str(delivery_id)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  try:
191
  field_permissions.migrate_legacy_fields(
192
  _shared_key(), st=st, grant_topic="customer_data", shared_key=_shared_key())
193
+ fields = shared_overlay.fields(_shared_key(), st=st)
194
+ # Normalized Routes use an invisible field-shaped bridge so the established Share dialog
195
+ # and grant registry can be reused. It is object metadata, never a customer column.
196
+ return {key: value for key, value in fields.items()
197
+ if not _is_route_share_bridge(value)}
198
  except Exception: # noqa: BLE001
199
  # Lenient like every other display read: an unreachable store degrades to "nothing is
200
  # shared yet", never to a 500 on a grid that would otherwise render. The WALL does not
 
202
  return {}
203
 
204
 
205
+ def _is_route_share_bridge(definition):
206
+ route = definition.get("route") if isinstance(definition, dict) else None
207
+ return bool(isinstance(route, dict) and route.get("normalizedId"))
208
+
209
+
210
  def shared_cells(pids, st=None):
211
  """`{"<pid>": {key: value}}` for the rows named by `pids`, and ONLY those.
212
 
 
222
  return {}
223
 
224
 
225
+ def _canonical_field_keys():
226
+ """Keys declared by the product contract, not by a user's workspace stratum."""
227
+ import aios_grid
228
+ return {str(field.get("key") or "").strip()
229
+ for field in (aios_grid.FIELDS or ()) if isinstance(field, dict)}
230
+
231
+
232
+ def _merge_shared_fields(fields, defs, session=None, strata=None):
233
  """`fields` PLUS the tenant-wide columns this topic declares — `routes_tables._ut_shared_fields`
234
  on the customer topic.
235
 
 
241
  ⚠ A key the canonical contract already declares WINS. A shared column is an ADDITION to this
242
  database's contract, never a redefinition of a column it already has.
243
  """
244
+ incoming = list(fields or ())
245
+ canonical = _canonical_field_keys()
246
+ lent = strata if isinstance(strata, dict) else None
247
+ have = {}
248
+ for index, field in enumerate(incoming):
249
+ if not isinstance(field, dict):
250
+ continue
251
+ key = str(field.get("key") or "").strip()
252
+ if not key or key in have:
253
+ continue
254
+ have[key] = index
255
+ if lent is not None:
256
+ lent[key] = "contract" if key in canonical else "personal"
257
+
258
  if not defs:
259
  return fields
 
260
  projected = []
261
  for k, f in defs.items():
262
+ if _is_route_share_bridge(f):
263
+ continue
264
+ k = str(k or "").strip()
265
+ if not k:
266
+ continue
267
+ index = have.get(k)
268
+ # A tenant-wide definition may never redefine a built-in contract field. For any other
269
+ # same-key collision (including a saved route), the shared definition wins in place.
270
+ if index is not None and k in canonical:
271
  continue
272
  item = dict(f, source="overlay", shared=True)
273
  if session is not None:
 
277
  is_admin=session.admin, st=session.runtime)
278
  if role:
279
  item["sharedRole"] = role
280
+ if index is None:
281
+ projected.append(item)
282
+ else:
283
+ local = incoming[index] if isinstance(incoming[index], dict) else {}
284
+ item["superseded"] = {
285
+ "stratum": "personal",
286
+ "owner": str(local.get("createdBy") or "").strip() or None,
287
+ "label": str(local.get("label") or "").strip() or None,
288
+ }
289
+ incoming[index] = item
290
+ if lent is not None:
291
+ lent[k] = "shared"
292
+ return incoming + projected
293
+
294
+
295
+ def _mark_offerability(fields):
296
+ """Withhold stored route-order fields from pickers without deleting them from the payload."""
297
+ return [dict(field, **{OFFERABLE_KEY: False})
298
+ if (isinstance(field, dict)
299
+ and field.get("kind") == ROUTE_KIND
300
+ and str(field.get("key") or "").strip() != ROUTE_PROJECTION_KEY)
301
+ else field
302
+ for field in (fields or ())]
303
 
304
 
305
  def grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
 
363
  # dict on one request (the write ctx's wall, the read merge, and the closure), and letting each
364
  # take its own copy is the shape D-214 spent a whole ticket removing one document over.
365
  _defs = shared_fields(st=rt)
366
+ _workspace_ctx = _ctx_for(session, pids, defs=_defs)
367
  ws = grid_events.table_workspace(
368
+ _workspace_ctx, allowed_pids=pids,
369
+ consume_corrections=consume_corrections, capture_document=True)
370
  # ⭐⭐ W38-T20 / D-425 — THE TENANT-WIDE CELLS, LAYERED OVER THE PER-USER ONES, IN THE
371
  # ASSEMBLY SO EVERY CONSUMER SEES ONE TRUTH. `routes_grid`'s /workspace route serves
372
  # `workspace["overlays"] = g["ws"].get("overlays")` verbatim and `_payload` hands the same
 
392
  # ⭐⭐ W38-T20 — AND THE COLUMN DEFINITIONS, BEFORE THE WALL. See `_merge_shared_fields`: this
393
  # position is load-bearing twice, once for the transitive closure and once because it is the
394
  # only order in which the per-field grant marker is ever presented to `hidden_keys`.
395
+ _strata = {}
396
+ fields = _merge_shared_fields(fields, _defs, session=session, strata=_strata)
397
+ # Legacy `Destination N` definitions remain in the shared document for rollback/audit, but
398
+ # once the dedicated migration recorded its independent parity proof they are display-hidden.
399
+ # This is intentionally a projection only: no field or cell is deleted here.
400
+ from core import route_system
401
+ _legacy_migrations = route_system.read(rt).get("legacyMigrations") or {}
402
+ fields = [field for field in fields if not (
403
+ isinstance(field, dict) and (_legacy_migrations.get(str(field.get("key"))) or {}).get("verified"))]
404
+ # Presentation only: legacy route-order definitions remain served/manageable where W44 has
405
+ # not migrated them, but no generic field picker may offer one as a data dimension.
406
+ fields = _mark_offerability(fields)
407
  # ⭐⭐ W41-T01 / RULING R5 / CONTRACTS C1 + C8 — **THE THREE BADGES, STAMPED ONCE, HERE.**
408
  #
409
  # C1 makes `field_permissions.field_class` the ONE producer of `{origin, audience, sharedBy,
 
447
  try:
448
  from core import field_permissions as _fp
449
  _classes = _fp.field_classes(fields, session.uname, table_key=_shared_key(),
450
+ grant_topic=SHARE_TOPIC, values_shared=set(_defs),
451
+ strata=_strata, st=rt)
452
  fields = [dict(f, **{"class": _classes[f["key"]]})
453
  if isinstance(f, dict) and _classes.get(f.get("key")) else f
454
  for f in fields]
 
470
  # makes this degrade safe: a client renders NOTHING for a missing `class` rather than a
471
  # wrong badge, so a registry that will not open costs the badges and not the grid.
472
  pass
473
+ # C4 parity: the topic grid reuses the same whole-workspace usage producer as user databases.
474
+ # The captured document avoids another store read; MODULE remains the memo/permission topic,
475
+ # while `_shared_key()` remains the independently named workspace document.
476
+ try:
477
+ from routes_tables import _field_usage as _fu
478
+ _usage_source = getattr(_workspace_ctx, "workspace_document", None)
479
+ if not isinstance(_usage_source, dict):
480
+ _usage_source = rt
481
+ _usage = _fu(session, MODULE, fields, None,
482
+ _usage_source, _shared_key(), st=rt)
483
+ except Exception: # noqa: BLE001
484
+ _usage = {}
485
+ if _usage:
486
+ fields = [dict(f, usage=dict(_usage[f["key"]]))
487
+ if isinstance(f, dict) and _usage.get(f.get("key")) else f
488
+ for f in fields]
489
  # THE FIELD WALL — a TRANSITIVE closure (C-PERM amendment 5), so hiding a field also hides
490
  # every formula computed FROM it. Formulas evaluate in the browser from `{ref}`s, so
491
  # shipping a dependent formula while withholding its input either leaks the input through
 
561
  on_error=_measure_err) if may_metrics else {}).items():
562
  derived.setdefault(pid, {}).update(cells)
563
 
564
+ # Route stops and Zone membership are normalized system relations. They project into two
565
+ # read-only customer fields; neither is a generic Link or an editable user-table cell.
566
+ # Route names and membership are object data too: a private Route must not leak through the
567
+ # derived customer column while its navigator correctly hides it.
568
+ normalized_routes = [route for route, _mark in _visible_normalized_routes(session)]
569
+ normalized_zones = route_system.list_zones(rt, rows_src)
570
+ fields = [field for field in fields if field.get("key") not in {"routes", "zone"}]
571
+ fields.extend(route_system.customer_projection_fields(normalized_routes, normalized_zones))
572
+ fields = [route_system.field_axes(field) for field in fields]
573
  return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
574
  "fields": fields, "views": views, "lists": lists, "derived": derived,
575
  "measures": measures, "measure_sets": measure_sets, "today": today,
576
+ "team_id": team_id, "routes": normalized_routes, "zones": normalized_zones}
577
 
578
 
579
  def _payload(session: Session):
 
593
  g = grid_assembly(session)
594
  rows = aios_grid.rows_from_pool(
595
  g["rows_src"], g["fields"], g["ws"].get("overlays"), derived=g["derived"])
596
+ from core import route_system
597
+ rows = route_system.apply_customer_projections(rows, g["routes"], g["zones"])
 
598
  # ⭐ C4 / D-138 (W30-T37) — THE DOCUMENTS PRODUCER FOR THE CUSTOMER SCOPE. The write door
599
  # (`doc_add`/`doc_fetch`/`doc_delete`) never stopped working and every client half is
600
  # complete; what vanished with `app.py` at EXIT-6 was the only thing that ever set this key.
 
695
  return _payload(session)
696
 
697
 
698
+ # ── Wave 44: normalized, Loopable-owned Route/Zone APIs ─────────────────────
699
+ # These are deliberately ahead of `/customers/{pid}`. Route stops are a protected relation;
700
+ # no generic Link field, generic table writer, or legacy Destination column is a write door.
701
+ def _route_view_can_edit(session, view_id):
702
+ """Route mutations inherit the source View editor wall, never an invented role."""
703
+ if not view_id:
704
+ return bool(session.admin)
705
+ try:
706
+ import core.table_store as table_store
707
+ ws = _customer_table(session).workspace(session.uname, consume_corrections=False)
708
+ view = (ws.get("views") or {}).get(str(view_id))
709
+ return bool(view and table_store._may_edit(view, session.uname, session.admin))
710
+ except Exception: # unavailable store is fail-closed
711
+ return False
712
+
713
+
714
+ def _route_input_pids(raw):
715
+ offered = []
716
+ for stop in (raw or {}).get("stops") or ():
717
+ candidate = stop.get("customerPid") if isinstance(stop, dict) else stop
718
+ if isinstance(candidate, bool):
719
+ raise err(400, "invalid_route_stop", "a route stop needs a customer id")
720
+ try:
721
+ offered.append(int(candidate))
722
+ except (TypeError, ValueError):
723
+ raise err(400, "invalid_route_stop", "a route stop needs a customer id")
724
+ return offered
725
+
726
+
727
+ def _reject_client_create_id(raw, subject):
728
+ """Keep POST as create-only; object identities are minted by the server.
729
+
730
+ ``route_system.put_*`` intentionally remains an upsert primitive for PATCH and migrations.
731
+ Passing any browser-supplied ``id`` key from POST into that primitive would turn the create
732
+ door into an undocumented update door, including across owners. Key presence is the wall:
733
+ null, false, zero, blank, whitespace, arrays, and objects are all refused. Refuse loudly
734
+ instead of silently stripping the id so a malformed caller learns to use PATCH.
735
+ """
736
+ if isinstance(raw, dict) and "id" in raw:
737
+ slug = str(subject or "object").strip().lower().replace(" ", "_") or "object"
738
+ raise err(400, f"server_managed_{slug}_id",
739
+ f"{subject} ids are server-managed; omit id when creating and use PATCH "
740
+ f"to update an existing {subject}")
741
+
742
+
743
+ def _legacy_route_defs_readonly(session):
744
+ """Visible legacy route definitions from the shared stratum, with no reconciliation write."""
745
+ import aios_grid
746
+ import core.perm_scope as perm_scope
747
+ from core import route_system, shared_overlay
748
+
749
+ try:
750
+ all_defs = shared_overlay.fields(_shared_key(), st=session.runtime) or {}
751
+ except Exception:
752
+ all_defs = {}
753
+ migrated = route_system.read(session.runtime).get("legacyMigrations") or {}
754
+ defs = {key: definition for key, definition in all_defs.items()
755
+ if isinstance(definition, dict) and definition.get("kind") == ROUTE_KIND
756
+ and not _is_route_share_bridge(definition)
757
+ and not bool((migrated.get(key) or {}).get("verified"))}
758
+ if not defs:
759
+ return {}
760
+ hidden = perm_scope.hidden_keys(
761
+ session.user, MODULE, _merge_shared_fields(list(aios_grid.FIELDS), all_defs),
762
+ st=session.runtime)
763
+ return {key: definition for key, definition in defs.items() if key not in hidden}
764
+
765
+
766
+ def _route_share_records(session):
767
+ """One normalized registry read for list visibility and every share mark."""
768
+ from core import field_permissions
769
+ return field_permissions.grant_records(SHARE_TOPIC, st=session.runtime) or {}
770
+
771
+
772
+ def _route_share_mark(session, route, records=None):
773
+ """C6's exact owner/shared/shared-out projection from the generic field registry."""
774
+ from core import route_system, shares
775
+ records = records if isinstance(records, dict) else _route_share_records(session)
776
+ key = str(route.get("shareKey") or route_system.route_share_key(route.get("id")))
777
+ rec = records.get(key) or {}
778
+ entries = rec.get("entries") or []
779
+ me = str(session.uname or "").strip().lower()
780
+ owner = (str(rec.get("owner") or "").strip().lower()
781
+ or str(route.get("createdBy") or "").strip().lower())
782
+ role = None
783
+ if me and owner != me:
784
+ for entry in entries:
785
+ if str(entry.get("user") or "").lower() not in (me, shares.EVERYONE):
786
+ continue
787
+ if entry.get("role") == "edit":
788
+ role = "edit"
789
+ break
790
+ role = role or "view"
791
+ mine = bool(me and owner == me)
792
+ return {"shareId": f"customer_data:{key}", "owner": owner,
793
+ "shared": role is not None, "sharedOut": bool(mine and entries),
794
+ "hasShares": bool(entries), "sharedRole": role,
795
+ "visible": bool(session.admin or mine or role)}
796
+
797
+
798
+ def _visible_normalized_routes(session, records=None):
799
+ from core import route_system
800
+ records = records if isinstance(records, dict) else _route_share_records(session)
801
+ visible = []
802
+ for route in route_system.list_routes(session.runtime):
803
+ mark = _route_share_mark(session, route, records)
804
+ if mark["visible"]:
805
+ visible.append((route, mark))
806
+ return visible
807
+
808
+
809
+ def _compatible_routes(session, permitted=None, records=None):
810
+ """Visible normalized Routes plus a read-only projection of legacy route-order fields.
811
+
812
+ Wave 44 introduced a normalized Route store while production already held saved route-order
813
+ columns. Requiring an administrator to run the migration before a GET made those existing
814
+ Routes disappear from the Map. This projection uses the same field and row walls as the old
815
+ route-order picker and performs no store update; the explicit migration remains a separate,
816
+ independently verified write operation.
817
+ """
818
+ from core import route_system
819
+ permitted = allowed_pids(session) if permitted is None else frozenset(permitted)
820
+ normalized = [route for route, _mark in _visible_normalized_routes(session, records)]
821
+ return route_system.compatible_routes(
822
+ normalized,
823
+ _legacy_route_defs_readonly(session),
824
+ shared_cells(permitted, st=session.runtime),
825
+ tenant_id=session.tenant,
826
+ created_by=session.uname,
827
+ )
828
+
829
+
830
+ def _legacy_route_navigation(session):
831
+ """Wave 42 per-reader Route folders, used only as a no-write migration fallback."""
832
+ try:
833
+ ws = _customer_table(session).workspace(session.uname, consume_corrections=False)
834
+ except Exception:
835
+ return [], {}
836
+ folders = ws.get("folders") or {}
837
+ return (list(folders.get("routes") or []) if isinstance(folders, dict) else [],
838
+ dict((ws.get("itemFolders") or {}).get("routes") or {}))
839
+
840
+
841
+ def _route_navigation(session, routes):
842
+ from core import route_system
843
+ folders, placements = _legacy_route_navigation(session)
844
+ return route_system.route_navigation(
845
+ session.runtime, session.uname, routes,
846
+ legacy_folders=folders, legacy_placements=placements)
847
+
848
+
849
+ def _route_dto(route, allowed, active, session, share_mark=None):
850
+ from core import route_system
851
+ allowed = {int(pid) for pid in allowed}
852
+ stops = [stop for stop in route_system.ordered_stops(route)
853
+ if int(stop.get("customerPid")) in allowed]
854
+ visible = [int(stop["customerPid"]) for stop in stops]
855
+ active = {int(pid) for pid in active if int(pid) in allowed}
856
+ compatibility = route.get("compatibility")
857
+ mark = share_mark if isinstance(share_mark, dict) else _route_share_mark(session, route)
858
+ owns_route = bool(session.admin or (
859
+ mark.get("owner") and mark.get("owner") == str(session.uname or "").strip().lower()))
860
+ dto = {"id": route["id"], "name": route["name"], "color": route["color"],
861
+ "number": route["number"], "visibleStopIds": visible,
862
+ "outsideFilter": bool(active) and not bool(active.intersection(visible)),
863
+ "permission": {"canEdit": (False if compatibility else owns_route and
864
+ _route_view_can_edit(session, route.get("sourceViewId"))),
865
+ "sourceViewId": route.get("sourceViewId")},
866
+ "source": {"viewId": route.get("sourceViewId"),
867
+ "revision": route.get("sourceViewRevision")},
868
+ "owner": mark["owner"], "shared": mark["shared"],
869
+ "sharedOut": mark["sharedOut"], "hasShares": mark["hasShares"],
870
+ "sharedRole": mark["sharedRole"], "shareId": mark["shareId"],
871
+ "folderId": route.get("folderId"), "navOrder": route.get("navOrder", 0)}
872
+ if compatibility == "legacy-route-order":
873
+ dto["compatibility"] = compatibility
874
+ if route.get("mapsUrl"):
875
+ dto["mapsUrl"] = route["mapsUrl"]
876
+ return dto
877
+
878
+
879
+ def _query_pids(raw):
880
+ values = []
881
+ for value in str(raw or "").split(","):
882
+ try:
883
+ values.append(int(value))
884
+ except (TypeError, ValueError):
885
+ continue
886
+ return values
887
+
888
+
889
+ def _route_or_404(session, route_id):
890
+ route = next((item for item, _mark in _visible_normalized_routes(session)
891
+ if item.get("id") == str(route_id)), None)
892
+ if route is None:
893
+ raise err(404, "route_not_found", "that Route does not exist")
894
+ return route
895
+
896
+
897
+ def _route_mutation_allowed(session, route, requested_source=None):
898
+ owner = str(_route_share_mark(session, route).get("owner") or "").strip().lower()
899
+ if not (session.admin or (owner and owner == str(session.uname or "").strip().lower())):
900
+ raise err(403, "route_not_owner", "only the Route owner or an administrator can change it")
901
+ source = requested_source if requested_source is not None else route.get("sourceViewId")
902
+ if not _route_view_can_edit(session, source):
903
+ raise err(403, "route_view_read_only", "only an editor of the Route source View can change it")
904
+
905
+
906
+ def _ensure_route_share_bridge(session, route):
907
+ """Materialize the invisible field-shaped object consumed by the existing Share dialog."""
908
+ from core import route_system, shared_overlay
909
+ key = str(route.get("shareKey") or route_system.route_share_key(route.get("id")))
910
+ shared_overlay.put_field(_shared_key(), key, {
911
+ "key": key, "label": route.get("name") or "Route", "type": "text",
912
+ "source": "overlay", "kind": ROUTE_KIND, "custom": True,
913
+ "createdBy": route.get("createdBy") or session.uname,
914
+ "note": "Access bridge for a saved Route.", "shared": True, "granted": True,
915
+ "route": {"normalizedId": route.get("id"), "routeObject": True},
916
+ }, st=session.runtime)
917
+ return key
918
+
919
+
920
+ def _drop_route_share_bridge(session, route):
921
+ from core import route_system, shared_overlay, shares
922
+ key = str(route.get("shareKey") or route_system.route_share_key(route.get("id")))
923
+ shared_overlay.drop_field(_shared_key(), key, st=session.runtime)
924
+ shares.drop_objects([("field", shares.field_oid(SHARE_TOPIC, key))], st=session.runtime)
925
+
926
+
927
+ def _route_nav_mutation_context(session):
928
+ routes = _compatible_routes(session)
929
+ folders, placements = _legacy_route_navigation(session)
930
+ return routes, folders, placements
931
+
932
+
933
+ @router.get("/customers/routes")
934
+ def routes(visiblePids: str = "", currentPids: str = "",
935
+ session: Session = Depends(module_gate(MODULE))):
936
+ """Route picker DTO consumed by C1/C3; only permitted stops ever leave the server."""
937
+ allowed = allowed_pids(session)
938
+ active = _query_pids(currentPids or visiblePids)
939
+ records = _route_share_records(session)
940
+ navigation = _route_navigation(session, _compatible_routes(session, allowed, records))
941
+ return {"routes": [_route_dto(
942
+ route, allowed, active, session,
943
+ _route_share_mark(session, route, records))
944
+ for route in navigation["routes"]],
945
+ "folders": navigation["folders"]}
946
+
947
+
948
+ @router.post("/customers/routes", status_code=201)
949
+ def create_route(body: dict = Body(default=None), session: Session = Depends(module_gate(MODULE))):
950
+ from core import route_system
951
+ raw = dict(body or {})
952
+ _reject_client_create_id(raw, "Route")
953
+ if not _route_view_can_edit(session, raw.get("sourceViewId")):
954
+ raise err(403, "route_view_read_only", "a Route requires an editable source View")
955
+ permitted = allowed_pids(session)
956
+ if any(pid not in permitted for pid in _route_input_pids(raw)):
957
+ raise err(403, "out_of_scope", "a Route stop must be in your customer book")
958
+ route = route_system.put_route(session.runtime, raw, tenant_id=session.tenant, created_by=session.uname)
959
+ if route is None:
960
+ raise err(400, "invalid_route", "a Route needs a name and an optional HTTPS Google Maps URL")
961
+ _ensure_route_share_bridge(session, route)
962
+ return {"route": _route_dto(route, permitted, (), session)}
963
+
964
+
965
+ @router.post("/customers/routes/{route_id}/duplicate", status_code=201)
966
+ def duplicate_route(route_id: str, body: dict = Body(default=None),
967
+ session: Session = Depends(module_gate(MODULE))):
968
+ from core import route_system
969
+ prior = _route_or_404(session, route_id)
970
+ if not _route_view_can_edit(session, prior.get("sourceViewId")):
971
+ raise err(403, "route_view_read_only", "an editable source View is required to duplicate this Route")
972
+ route = route_system.duplicate_route(
973
+ session.runtime, route_id, tenant_id=session.tenant, created_by=session.uname,
974
+ name=(body or {}).get("name"))
975
+ if route is None:
976
+ raise err(404, "route_not_found", "that Route does not exist")
977
+ _ensure_route_share_bridge(session, route)
978
+ return {"route": _route_dto(route, allowed_pids(session), (), session)}
979
+
980
+
981
+ @router.post("/customers/routes/{route_id}/share-ready")
982
+ def route_share_ready(route_id: str, session: Session = Depends(module_gate(MODULE))):
983
+ route = _route_or_404(session, route_id)
984
+ _route_mutation_allowed(session, route)
985
+ key = _ensure_route_share_bridge(session, route)
986
+ return {"kind": "field", "id": f"customer_data:{key}", "label": route.get("name")}
987
+
988
+
989
+ @router.patch("/customers/routes/{route_id}")
990
+ def update_route(route_id: str, body: dict = Body(default=None),
991
+ session: Session = Depends(module_gate(MODULE))):
992
+ from core import route_system
993
+ prior = _route_or_404(session, route_id)
994
+ raw = dict(body or {})
995
+ _route_mutation_allowed(session, prior, raw.get("sourceViewId", prior.get("sourceViewId")))
996
+ raw["id"] = prior["id"]
997
+ if "stops" in raw and any(pid not in allowed_pids(session) for pid in _route_input_pids(raw)):
998
+ raise err(403, "out_of_scope", "a Route stop must be in your customer book")
999
+ route = route_system.put_route(session.runtime, raw, tenant_id=session.tenant, created_by=session.uname)
1000
+ if route is None:
1001
+ raise err(400, "invalid_route", "a Route needs a name and an optional HTTPS Google Maps URL")
1002
+ _ensure_route_share_bridge(session, route)
1003
+ return {"route": _route_dto(route, allowed_pids(session), (), session)}
1004
+
1005
+
1006
+ @router.post("/customers/routes/{route_id}/stops/move")
1007
+ def move_route_stop(route_id: str, body: dict = Body(default=None),
1008
+ session: Session = Depends(module_gate(MODULE))):
1009
+ from core import route_system
1010
+ prior = _route_or_404(session, route_id)
1011
+ _route_mutation_allowed(session, prior)
1012
+ raw = dict(body or {})
1013
+ try:
1014
+ pid, order = int(raw.get("customerPid")), int(raw.get("order"))
1015
+ except (TypeError, ValueError):
1016
+ raise err(400, "invalid_route_stop", "customerPid and order are required")
1017
+ if pid not in allowed_pids(session):
1018
+ raise err(403, "out_of_scope", "that customer is not in your book")
1019
+ route = route_system.move_stop(session.runtime, route_id, pid, order,
1020
+ tenant_id=session.tenant, created_by=session.uname)
1021
+ if route is None:
1022
+ # A Route may intentionally have no stops. We never turn that harmless state into a
1023
+ # synthetic generic Link row; the caller can render the honest no-stop state.
1024
+ raise err(409, "no_route_stop", "that customer is not a stop on this Route")
1025
+ return {"route": _route_dto(route, allowed_pids(session), (), session)}
1026
+
1027
+
1028
+ @router.post("/customers/routes/{route_id}/stops/membership")
1029
+ def set_route_stop_membership(route_id: str, body: dict = Body(default=None),
1030
+ session: Session = Depends(module_gate(MODULE))):
1031
+ """Add or remove one permitted customer while preserving every other ordered stop."""
1032
+ from core import route_system
1033
+ prior = _route_or_404(session, route_id)
1034
+ _route_mutation_allowed(session, prior)
1035
+ raw = dict(body or {})
1036
+ candidate = raw.get("customerPid")
1037
+ present = raw.get("present")
1038
+ if isinstance(candidate, bool) or not isinstance(present, bool):
1039
+ raise err(400, "invalid_route_membership",
1040
+ "customerPid and a true or false present value are required")
1041
+ try:
1042
+ pid = int(candidate)
1043
+ except (TypeError, ValueError):
1044
+ raise err(400, "invalid_route_membership",
1045
+ "customerPid and a true or false present value are required")
1046
+ permitted = allowed_pids(session)
1047
+ if pid not in permitted:
1048
+ raise err(403, "out_of_scope", "that customer is not in your book")
1049
+ route = route_system.set_stop_membership(
1050
+ session.runtime, route_id, pid, present,
1051
+ tenant_id=session.tenant, created_by=session.uname)
1052
+ if route is None:
1053
+ raise err(404, "route_not_found", "that Route does not exist")
1054
+ return {"route": _route_dto(route, permitted, (), session)}
1055
+
1056
+
1057
+ @router.delete("/customers/routes/{route_id}")
1058
+ def remove_route(route_id: str, session: Session = Depends(module_gate(MODULE))):
1059
+ from core import route_system
1060
+ route = _route_or_404(session, route_id)
1061
+ _route_mutation_allowed(session, route)
1062
+ linked_delivery_ids = _linked_route_delivery_ids(session.runtime, route_id)
1063
+ if linked_delivery_ids:
1064
+ visible_delivery_ids = {
1065
+ str(delivery.get("id") or "")
1066
+ for delivery in _route_delivery_definitions(session, route_id)
1067
+ if isinstance(delivery, dict)
1068
+ }
1069
+ if not session.admin and not set(linked_delivery_ids).issubset(visible_delivery_ids):
1070
+ raise err(409, "route_deliveries_exist",
1071
+ "Ask an administrator to remove this Route's scheduled deliveries, "
1072
+ "then delete the Route")
1073
+ raise err(409, "route_deliveries_exist",
1074
+ "Remove this Route's scheduled deliveries first, then delete the Route")
1075
+ if not route_system.delete_route(session.runtime, route_id):
1076
+ raise err(404, "route_not_found", "that Route does not exist")
1077
+ _drop_route_share_bridge(session, route)
1078
+ return {"deleted": True}
1079
+
1080
+
1081
+ @router.patch("/customers/routes/{route_id}/folder")
1082
+ def move_route_to_folder(route_id: str, body: dict = Body(default=None),
1083
+ session: Session = Depends(module_gate(MODULE))):
1084
+ from core import route_system
1085
+ routes, legacy_folders, legacy_placements = _route_nav_mutation_context(session)
1086
+ if str(route_id) not in {str(route.get("id")) for route in routes}:
1087
+ raise err(404, "route_not_found", "that Route does not exist")
1088
+ folder_id = (body or {}).get("folderId")
1089
+ if folder_id is not None and not isinstance(folder_id, str):
1090
+ raise err(400, "invalid_route_folder", "folderId must be a folder id or null")
1091
+ if folder_id and not any(folder.get("id") == folder_id for folder in _route_navigation(session, routes)["folders"]):
1092
+ raise err(409, "route_folder_not_found", "that Route folder no longer exists")
1093
+ route_system.place_route(
1094
+ session.runtime, session.uname, route_id, folder_id, routes,
1095
+ legacy_folders=legacy_folders, legacy_placements=legacy_placements)
1096
+ navigation = _route_navigation(session, routes)
1097
+ moved = next(route for route in navigation["routes"] if route.get("id") == str(route_id))
1098
+ return {"route": _route_dto(moved, allowed_pids(session), (), session),
1099
+ "folders": navigation["folders"]}
1100
+
1101
+
1102
+ @router.post("/customers/routes/reorder")
1103
+ def reorder_route_navigation(body: dict = Body(default=None),
1104
+ session: Session = Depends(module_gate(MODULE))):
1105
+ from core import route_system
1106
+ routes, legacy_folders, legacy_placements = _route_nav_mutation_context(session)
1107
+ order = (body or {}).get("order")
1108
+ if not isinstance(order, list):
1109
+ raise err(400, "invalid_route_order", "order must be a list of visible Route ids")
1110
+ result = route_system.reorder_routes(
1111
+ session.runtime, session.uname, order, routes,
1112
+ legacy_folders=legacy_folders, legacy_placements=legacy_placements)
1113
+ if result is None:
1114
+ raise err(409, "invalid_route_order", "Route order contains an unknown or duplicate id")
1115
+ return {"order": result}
1116
+
1117
+
1118
+ @router.post("/customers/route-folders", status_code=201)
1119
+ def create_route_folder(body: dict = Body(default=None),
1120
+ session: Session = Depends(module_gate(MODULE))):
1121
+ from core import route_system
1122
+ routes, legacy_folders, legacy_placements = _route_nav_mutation_context(session)
1123
+ folder = route_system.put_route_folder(
1124
+ session.runtime, session.uname, body or {}, routes,
1125
+ legacy_folders=legacy_folders, legacy_placements=legacy_placements)
1126
+ if folder is None:
1127
+ raise err(400, "invalid_route_folder", "a Route folder needs a name and a valid parent")
1128
+ return {"folder": folder, "folders": _route_navigation(session, routes)["folders"]}
1129
+
1130
+
1131
+ @router.patch("/customers/route-folders/{folder_id}")
1132
+ def update_route_folder(folder_id: str, body: dict = Body(default=None),
1133
+ session: Session = Depends(module_gate(MODULE))):
1134
+ from core import route_system
1135
+ routes, legacy_folders, legacy_placements = _route_nav_mutation_context(session)
1136
+ current = next((folder for folder in _route_navigation(session, routes)["folders"]
1137
+ if folder.get("id") == folder_id), None)
1138
+ if current is None:
1139
+ raise err(404, "route_folder_not_found", "that Route folder does not exist")
1140
+ raw = dict(current)
1141
+ raw.update(body or {})
1142
+ raw["id"] = folder_id
1143
+ folder = route_system.put_route_folder(
1144
+ session.runtime, session.uname, raw, routes,
1145
+ legacy_folders=legacy_folders, legacy_placements=legacy_placements)
1146
+ if folder is None:
1147
+ raise err(409, "invalid_route_folder", "that folder move would create an invalid path")
1148
+ return {"folder": folder, "folders": _route_navigation(session, routes)["folders"]}
1149
+
1150
+
1151
+ @router.delete("/customers/route-folders/{folder_id}")
1152
+ def remove_route_folder(folder_id: str, session: Session = Depends(module_gate(MODULE))):
1153
+ from core import route_system
1154
+ routes, legacy_folders, legacy_placements = _route_nav_mutation_context(session)
1155
+ if not route_system.delete_route_folder(
1156
+ session.runtime, session.uname, folder_id, routes,
1157
+ legacy_folders=legacy_folders, legacy_placements=legacy_placements):
1158
+ raise err(404, "route_folder_not_found", "that Route folder does not exist")
1159
+ return {"deleted": True, "folders": _route_navigation(session, routes)["folders"]}
1160
+
1161
+
1162
+ @router.post("/customers/route-folders/reorder")
1163
+ def reorder_route_folder_navigation(body: dict = Body(default=None),
1164
+ session: Session = Depends(module_gate(MODULE))):
1165
+ from core import route_system
1166
+ routes, legacy_folders, legacy_placements = _route_nav_mutation_context(session)
1167
+ order = (body or {}).get("order")
1168
+ if not isinstance(order, list):
1169
+ raise err(400, "invalid_route_folder_order", "order must be a list of Route folder ids")
1170
+ result = route_system.reorder_route_folders(
1171
+ session.runtime, session.uname, order, routes,
1172
+ legacy_folders=legacy_folders, legacy_placements=legacy_placements)
1173
+ if result is None:
1174
+ raise err(409, "invalid_route_folder_order", "folder order contains an unknown or duplicate id")
1175
+ return {"order": result}
1176
+
1177
+
1178
+ @router.post("/customers/routes/selection")
1179
+ def route_selection(body: dict = Body(default=None), session: Session = Depends(module_gate(MODULE))):
1180
+ """Dedicated managed-OR mutation; user filter clauses are returned byte-for-byte intact."""
1181
+ from core import route_system
1182
+ raw = dict(body or {})
1183
+ chosen = [str(item) for item in raw.get("routeIds") or ()]
1184
+ compatible = _compatible_routes(session)
1185
+ known = {route["id"] for route in compatible}
1186
+ if any(route_id not in known for route_id in chosen):
1187
+ raise err(404, "route_not_found", "a selected Route does not exist")
1188
+ state = route_system.apply_managed_route_selection(
1189
+ raw.get("viewState"), chosen, compatible)
1190
+ return {"viewState": state, "managedBy": route_system.MANAGED_BY}
1191
+
1192
+
1193
+ def _export_sort_value(row, field):
1194
+ value = row.get(field.get("key"))
1195
+ if field.get("type") in {"currency", "int", "pct", "rating", "formula"}:
1196
+ try:
1197
+ return (value is None or value == "", float(value))
1198
+ except (TypeError, ValueError):
1199
+ return (True, 0.0)
1200
+ return (value is None or value == "", str(value or "").lower())
1201
+
1202
+
1203
+ @router.post("/customers/view-export")
1204
+ def selected_view_export(body: dict = Body(default=None),
1205
+ session: Session = Depends(module_gate(MODULE))):
1206
+ """Authoritative selected-View export data; the browser owns XLSX rendering, not selection.
1207
+
1208
+ The request names saved View ids only. Its field order/visibility, filter, sort and cohort
1209
+ membership are resolved independently per tab, so the caller cannot accidentally duplicate
1210
+ the active View's rows under several View names.
1211
+ """
1212
+ import aios_grid
1213
+ from core import route_system
1214
+ from harness import filter_eval
1215
+
1216
+ raw_ids = (body or {}).get("viewIds")
1217
+ if not isinstance(raw_ids, list) or not raw_ids or len(raw_ids) > 20:
1218
+ raise err(400, "invalid_view_ids", "viewIds must name between one and twenty visible Views")
1219
+ ids = [str(value).strip()[:120] for value in raw_ids]
1220
+ if any(not value for value in ids) or len(set(ids)) != len(ids):
1221
+ raise err(400, "invalid_view_ids", "viewIds must be unique non-empty View ids")
1222
+ g = grid_assembly(session)
1223
+ views = {str(view.get("id")): view for view in g["views"] if isinstance(view, dict)}
1224
+ if any(view_id not in views for view_id in ids):
1225
+ raise err(404, "view_not_found", "an export View is not visible to this account")
1226
+ rows = aios_grid.rows_from_pool(g["rows_src"], g["fields"], g["ws"].get("overlays"),
1227
+ derived=g["derived"])
1228
+ rows = route_system.apply_customer_projections(rows, g["routes"], g["zones"])
1229
+ by_key = {field["key"]: field for field in g["fields"] if isinstance(field, dict) and field.get("key")}
1230
+ cohort_sets = {str(item.get("id")): set(item.get("pids") or [])
1231
+ for item in g["lists"] if isinstance(item, dict) and item.get("id")}
1232
+ exports = []
1233
+ for view_id in ids:
1234
+ view, cfg = views[view_id], dict(views[view_id].get("config") or {})
1235
+ context = filter_eval.EvalCtx(cohort_sets=cohort_sets, measure_sets=g["measure_sets"],
1236
+ today=g["today"])
1237
+ tree = {"nodes": cfg.get("filters") or [], "conj": cfg.get("filterConj") or "and"}
1238
+ pids = set(filter_eval.visible_pids(tree, rows, g["fields"], context,
1239
+ member_pids=cfg.get("memberPids") or [],
1240
+ group_by=cfg.get("groupBy")))
1241
+ selected = [dict(row) for row in rows if row.get("pid") in pids]
1242
+ for sort in reversed(cfg.get("sorts") or []):
1243
+ field = by_key.get(sort.get("colId")) if isinstance(sort, dict) else None
1244
+ if field is not None:
1245
+ selected.sort(key=lambda row, f=field: _export_sort_value(row, f),
1246
+ reverse=sort.get("dir") == "desc")
1247
+ ordered = [key for key in cfg.get("order") or [] if key in by_key]
1248
+ ordered += [key for key in by_key if key not in ordered]
1249
+ visible = set(cfg.get("visible") or ordered)
1250
+ columns = [dict(by_key[key]) for key in ordered if key in visible]
1251
+ exports.append({"viewId": view_id, "name": view.get("name") or view_id,
1252
+ "columns": columns, "rows": selected,
1253
+ "view": {"filters": cfg.get("filters") or [],
1254
+ "filterConj": cfg.get("filterConj") or "and",
1255
+ "sorts": cfg.get("sorts") or [],
1256
+ "memberPids": cfg.get("memberPids") or []}})
1257
+ return {"today": g["today"], "exports": exports}
1258
+
1259
+
1260
+ @router.post("/customers/routes/migrate-legacy")
1261
+ def migrate_legacy_destination_fields(session: Session = Depends(module_gate(MODULE))):
1262
+ """Copy legacy Destination N ranks, prove parity, then hide the retained columns.
1263
+
1264
+ The explicit whole-book check is important: a partial manager scope may copy a useful subset,
1265
+ but it can never prove a tenant-wide route complete and therefore may not hide anything.
1266
+ """
1267
+ if not session.admin:
1268
+ raise err(403, "legacy_migration_admin_only", "only an administrator may migrate legacy Routes")
1269
+ from core import route_system
1270
+ raw_rows = _pool_rows(session)
1271
+ whole_book = {int(row["pid"]) for row in raw_rows if row.get("pid") is not None}
1272
+ if whole_book != set(allowed_pids(session)):
1273
+ raise err(409, "legacy_migration_scope_limited",
1274
+ "legacy Route migration needs an unrestricted customer scope to prove parity")
1275
+ defs = shared_fields(st=session.runtime)
1276
+ result = route_system.migrate_legacy_routes(
1277
+ session.runtime, defs, shared_cells(whole_book, st=session.runtime),
1278
+ tenant_id=session.tenant, created_by=session.uname,
1279
+ zones=route_system.list_zones(session.runtime, raw_rows))
1280
+ # `legacyMigrations` lives with the normalized system data. The source field definition and
1281
+ # every scalar rank cell are retained byte-for-byte; the persisted proof is the read-side
1282
+ # hide/read-only marker rather than a generic field rewrite or a delete.
1283
+ return result
1284
+
1285
+
1286
+ def _zone_can_edit(session, source_view_id):
1287
+ return bool(session.admin) or _route_view_can_edit(session, source_view_id)
1288
+
1289
+
1290
+ def _zone_dto(zone, allowed, session):
1291
+ return {"id": zone["id"], "name": zone["name"], "color": zone["color"],
1292
+ "geometryGeoJson": zone.get("geometryGeoJson"), "zipCodes": zone.get("zipCodes") or [],
1293
+ # MapView and the read-only Customer ``Zone`` field consume this same normalized
1294
+ # membership. Returning a second ``visibleMemberIds`` dialect made the map paint an
1295
+ # empty Zone while the grid projection named the customer as a member.
1296
+ "memberships": [int(pid) for pid in zone.get("memberPids") or [] if int(pid) in allowed],
1297
+ "membershipRevision": zone.get("membershipRevision", 0),
1298
+ "sourceViewId": zone.get("sourceViewId"),
1299
+ "geographicField": str(zone.get("geographicField") or ""),
1300
+ "createdBy": str(zone.get("createdBy") or ""),
1301
+ "createdAt": str(zone.get("createdAt") or ""),
1302
+ "visible": zone.get("visible", True),
1303
+ "permission": {
1304
+ "canEdit": _zone_can_edit(session, zone.get("sourceViewId")),
1305
+ "canDelete": bool(session.admin),
1306
+ }}
1307
+
1308
+
1309
+ @router.get("/customers/zones")
1310
+ def zones(session: Session = Depends(module_gate(MODULE))):
1311
+ from core import route_system
1312
+ rows = _pool_rows(session)
1313
+ allowed = allowed_pids(session)
1314
+ return {"zones": [_zone_dto(zone, allowed, session)
1315
+ for zone in route_system.list_zones(session.runtime, rows)]}
1316
+
1317
+
1318
+ @router.post("/customers/zones", status_code=201)
1319
+ def create_zone(body: dict = Body(default=None), session: Session = Depends(module_gate(MODULE))):
1320
+ from core import route_system
1321
+ raw = dict(body or {})
1322
+ _reject_client_create_id(raw, "Zone")
1323
+ if not _zone_can_edit(session, raw.get("sourceViewId")):
1324
+ raise err(403, "zone_view_read_only", "a Zone requires an editable source View")
1325
+ zone = route_system.put_zone(session.runtime, raw, rows=_pool_rows(session),
1326
+ tenant_id=session.tenant, created_by=session.uname)
1327
+ if zone is None:
1328
+ raise err(400, "invalid_zone", "a Zone needs a name and a polygon or ZIP code")
1329
+ return {"zone": _zone_dto(zone, allowed_pids(session), session)}
1330
+
1331
+
1332
+ @router.patch("/customers/zones/{zone_id}")
1333
+ def update_zone(zone_id: str, body: dict = Body(default=None),
1334
+ session: Session = Depends(module_gate(MODULE))):
1335
+ from core import route_system
1336
+ prior = next((zone for zone in route_system.list_zones(session.runtime)
1337
+ if zone.get("id") == str(zone_id)), None)
1338
+ if prior is None:
1339
+ raise err(404, "zone_not_found", "that Zone does not exist")
1340
+ raw = dict(body or {})
1341
+ # A Zone keeps the View it was authored from. Editing its colour or boundary is not a
1342
+ # second door for silently rebasing its permission wall onto another View.
1343
+ source_view_id = prior.get("sourceViewId") or raw.get("sourceViewId")
1344
+ if not _zone_can_edit(session, source_view_id):
1345
+ raise err(403, "zone_view_read_only", "a Zone requires an editable source View")
1346
+ raw["sourceViewId"] = source_view_id
1347
+ raw["id"] = prior["id"]
1348
+ zone = route_system.put_zone(session.runtime, raw, rows=_pool_rows(session),
1349
+ tenant_id=session.tenant, created_by=session.uname)
1350
+ if zone is None:
1351
+ raise err(400, "invalid_zone", "a Zone needs a name and a polygon or ZIP code")
1352
+ return {"zone": _zone_dto(zone, allowed_pids(session), session)}
1353
+
1354
+
1355
+ @router.delete("/customers/zones/{zone_id}")
1356
+ def remove_zone(zone_id: str, session: Session = Depends(module_gate(MODULE))):
1357
+ from core import route_system
1358
+ if not session.admin:
1359
+ raise err(403, "zone_view_read_only", "only an administrator can delete a Zone")
1360
+ if not route_system.delete_zone(session.runtime, zone_id):
1361
+ raise err(404, "zone_not_found", "that Zone does not exist")
1362
+ return {"deleted": True}
1363
+
1364
+
1365
  def _split_route_updates(session, updates):
1366
  """Split a cell PATCH into `(route order updates, everything else)`.
1367
 
 
1372
  route, rest = {}, {}
1373
  for key, value in (updates or {}).items():
1374
  defn = defs.get(key)
1375
+ from core import route_system
1376
+ migrated = bool((route_system.read(session.runtime).get("legacyMigrations") or {}).get(key, {}).get("verified"))
1377
+ if isinstance(defn, dict) and defn.get("kind") == ROUTE_KIND and not migrated:
1378
  route[key] = value
1379
  else:
1380
  rest[key] = value
 
1412
  `patch_customer` routes everything else through `grid_events` rather than writing the store.
1413
 
1414
  ⚠ UNIQUENESS IS MAINTAINED OVER THE ROWS THIS CALLER CAN SEE, and that is a limit worth
1415
+ stating rather than hiding. `shared_overlay.transpose_rank` requires the scoped pool BY
1416
+ SIGNATURE, then reads it inside the same store-update callback that writes both rows. The
1417
+ holder of a displaced number is therefore looked for inside this session's book, but never
1418
+ from a stale pre-write snapshot. In practice the whole column lives there anyway:
1419
  `route_order_write` REFUSES a body carrying a pid outside the writer's pool, so every number in
1420
  a route order was written by somebody whose book contained all of them.
1421
  """
 
1431
  #: value the caller did NOT ask for.
1432
  taken, swaps = set(), []
1433
 
1434
+ def _stored(key):
1435
+ """The current rank for a refused key, scoped to this one admitted row.
1436
 
1437
+ Valid nonblank assignments never use this read: ``transpose_rank`` reads the whole scoped
1438
+ column inside the atomic update that writes it. This helper exists only so a refusal can
1439
+ repaint the store's truth in the optimistic client.
1440
  """
1441
+ row = ((shared_cells([pid], st=session.runtime) or {}).get(str(pid)) or {})
1442
+ cell = row.get(key) if isinstance(row, dict) else None
1443
+ if cell in (None, ""):
1444
+ return ""
1445
+ try:
1446
+ return str(int(str(cell).strip()))
1447
+ except (TypeError, ValueError):
1448
+ return ""
 
 
 
 
1449
 
1450
  for key, raw in updates.items():
1451
  defn = defs.get(key) or {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1452
 
1453
  if key in hidden:
1454
+ accepted[key] = _stored(key)
1455
  continue
1456
  if not grid_events._may_edit_field_value(ctx, key, defn):
1457
+ accepted[key] = _stored(key)
1458
  continue
1459
  # An empty cell is "not on this route". Legal, and the only way to take a stop off the
1460
  # day without re-solving the whole column.
 
1466
  # ⛔ A BOOL IS AN `int` IN PYTHON, so `True` would store as visit number 1. Excluded by
1467
  # name here exactly as `route_order_write` excludes it, rather than by hoping.
1468
  if isinstance(raw, bool):
1469
+ accepted[key] = _stored(key)
1470
  continue
1471
  try:
1472
  want = int(str(raw).strip())
1473
  except (TypeError, ValueError):
1474
+ accepted[key] = _stored(key)
1475
  continue
1476
  if want < 1:
1477
+ accepted[key] = _stored(key)
1478
  continue
1479
 
1480
+ moved = shared_overlay.transpose_rank(
1481
+ _shared_key(), pid, key, want, pool, st=session.runtime)
1482
+ if moved.get("swap"):
1483
+ swaps.append(moved["swap"])
1484
+ accepted[key] = moved["value"]
 
 
 
 
 
 
 
 
1485
  taken.add(key)
1486
  return accepted, swaps, taken
1487
 
 
1502
  updates = dict(body or {})
1503
  if not updates:
1504
  raise err(400, "empty_patch", "no fields to update")
1505
+ from core import route_system
1506
+ retired = {str(key) for key, proof in (route_system.read(session.runtime).get("legacyMigrations") or {}).items()
1507
+ if isinstance(proof, dict) and proof.get("verified")}
1508
+ if retired.intersection(updates):
1509
+ raise err(403, "legacy_route_hidden",
1510
+ "this legacy Destination field was migrated; edit the named Route instead")
1511
  pool = allowed_pids(session)
1512
  if pid not in pool:
1513
  # 403, not 404: the pid may well exist — it is simply not in this session's book, and
 
1615
  #: the client; never inferred from the key, because a prefix is a naming convention and a
1616
  #: convention is not a declaration.
1617
  ROUTE_KIND = "route_order"
1618
+ OFFERABLE_KEY = "offerable"
1619
+ ROUTE_PROJECTION_KEY = "routes"
1620
 
1621
  #: ⭐⭐ W41-T05 / CONTRACT C3 — THE DESCRIPTION EVERY ROUTE COLUMN IS BORN WITH.
1622
  #:
 
1733
  import core.perm_scope as perm_scope
1734
 
1735
  all_defs = shared_fields(st=session.runtime) or {}
1736
+ from core import route_system
1737
+ migrated = route_system.read(session.runtime).get("legacyMigrations") or {}
1738
  defs = {k: v for k, v in all_defs.items()
1739
+ if isinstance(v, dict) and v.get("kind") == ROUTE_KIND
1740
+ and not bool((migrated.get(k) or {}).get("verified"))}
1741
  if not defs:
1742
  return {}
1743
  hide = perm_scope.hidden_keys(
 
1999
  "source": "overlay",
2000
  "shared": True,
2001
  "kind": ROUTE_KIND,
2002
+ # Stored as well as projected so every read door starts from the same explicit contract.
2003
+ # This is presentation metadata: the route stays visible/manageable and its values remain.
2004
+ OFFERABLE_KEY: False,
2005
  # ⭐⭐ W41-T05 — THE DESCRIPTION, CARRIED BY **PRESENCE** AND NOT BY TRUTHINESS.
2006
  # `ROUTE_FIELD_NOTE` says why the column cannot be born without one and why `""` has to
2007
  # survive a re-solve: `route_order_rename` clears a description by storing exactly that,
 
2333
  "recipient": str(cfg.get("recipient") or ""),
2334
  "schedule": dict(defn.get("schedule") or {}),
2335
  "snapshot": {
2336
+ "routeId": str(snap.get("routeId") or ""),
2337
  "sourceViewId": str(snap.get("sourceViewId") or ""),
2338
  "sourceViewRevision": str(snap.get("sourceViewRevision") or ""),
2339
  "sourceViewName": str(snap.get("sourceViewName") or ""),
 
2347
  }
2348
 
2349
 
2350
+ def _route_delivery_recipient_or_400(session, raw, directory=None):
2351
+ """Resolve one active Inbox account behind the narrow directory seam.
2352
+
2353
+ ``session`` is intentionally part of the seam even though the ordinary registry does not
2354
+ consume it yet. Staging-only identities can extend this one helper without leaking fixture
2355
+ logic into Route persistence or falling through to a different account plane.
2356
+ """
2357
  recipient = str(raw or "").strip()
2358
  try:
2359
+ if directory is None:
2360
+ import core.users as users
2361
+ directory = users.registry
2362
+ user = (directory() or {}).get(recipient)
2363
  except Exception: # registry unavailable is not permission to queue a phantom Inbox delivery
2364
  user = None
2365
  if not recipient or not isinstance(user, dict) or not user.get("active", True):
 
2381
  return "view-config-v2-" + hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:24]
2382
 
2383
 
2384
+ def _route_delivery_snapshot_for_route_or_400(
2385
+ session, route, body, *, source_views=None, permitted=None, recipient_directory=None):
2386
+ """Build the immutable delivery exclusively from a normalized Route and server reads.
2387
 
2388
+ The browser may choose the recipient, timezone, and bounded Maps chunk size. It cannot send
2389
+ View configuration, revision, Route name, or stop ids: all of those are resolved again here
2390
+ from the saved Route and its real source View at the moment the schedule is created.
 
2391
  """
2392
+ from core import route_system
2393
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
2394
+
2395
+ body = body if isinstance(body, dict) else {}
2396
+ recipient = _route_delivery_recipient_or_400(
2397
+ session, body.get("recipient"), directory=recipient_directory)
2398
+ source_view_id = str(route.get("sourceViewId") or "").strip()
2399
+ if not source_view_id:
2400
+ raise err(409, "route_source_view_missing",
2401
+ "this Route has no saved source View and cannot be scheduled")
2402
+
2403
+ if source_views is None:
2404
+ source_views = grid_assembly(session, consume_corrections=False).get("views") or []
2405
+ source_by_id = {str(view.get("id") or ""): view for view in source_views
2406
+ if isinstance(view, dict) and view.get("id")}
2407
+ source_view = source_by_id.get(source_view_id)
2408
+ source_config = source_view.get("config") if isinstance(source_view, dict) else None
2409
+ if not isinstance(source_config, dict):
2410
+ raise err(409, "route_source_view_unavailable",
2411
+ "the Route source View is no longer visible; restore it before scheduling")
2412
+
2413
+ ordered_stop_ids = [int(stop["customerPid"]) for stop in route_system.ordered_stops(route)]
2414
+ if len(ordered_stop_ids) < 2:
2415
+ raise err(400, "route_delivery_needs_stops",
2416
+ "add at least two ordered stops before scheduling this Route")
2417
+ permitted = allowed_pids(session) if permitted is None else frozenset(int(pid) for pid in permitted)
2418
+ if any(pid not in permitted for pid in ordered_stop_ids):
2419
+ raise err(409, "route_delivery_scope_changed",
2420
+ "one or more Route stops are outside your current customer book; update the Route first")
2421
+
2422
+ timezone = str(body.get("timezone") or "UTC").strip()[:80] or "UTC"
2423
+ try:
2424
+ ZoneInfo(timezone)
2425
+ except (ZoneInfoNotFoundError, ValueError):
2426
+ raise err(400, "invalid_route_timezone", "choose a recognized timezone for this delivery")
2427
+
2428
+ raw_maps_per_link = body.get("mapsPerLink", 10)
2429
+ if isinstance(raw_maps_per_link, bool):
2430
+ raise err(400, "invalid_route_maps_per_link", "Maps links must contain between 2 and 10 stops")
2431
+ try:
2432
+ maps_per_link = int(raw_maps_per_link)
2433
+ except (TypeError, ValueError):
2434
+ raise err(400, "invalid_route_maps_per_link", "Maps links must contain between 2 and 10 stops")
2435
+ if maps_per_link < 2 or maps_per_link > 10:
2436
+ raise err(400, "invalid_route_maps_per_link", "Maps links must contain between 2 and 10 stops")
2437
+
2438
+ return recipient, {
2439
+ "routeId": str(route.get("id") or ""),
2440
  "sourceViewId": source_view_id,
2441
  "sourceViewRevision": _route_view_revision(source_view_id, source_config),
2442
  "sourceViewName": str(source_view.get("name") or source_view_id),
2443
+ "timezone": timezone,
2444
+ "routeField": str(route.get("id") or ""),
2445
+ "orderedStopIds": ordered_stop_ids,
2446
+ "mapsPerLink": maps_per_link,
2447
  }
2448
 
2449
 
2450
+ def _route_delivery_definitions(session, route_id=None):
 
 
2451
  import automation_engine as engine
2452
  out = []
2453
  for defn in (engine.all_definitions(session.runtime) or {}).values():
2454
  if not isinstance(defn, dict) or defn.get("kind") != "route_delivery":
2455
  continue
 
 
2456
  if not session.admin and str(defn.get("createdBy") or "") != session.uname:
2457
  continue
2458
+ wire = _route_delivery_wire(defn)
2459
+ if route_id is not None and wire["snapshot"]["routeId"] != str(route_id):
2460
+ continue
2461
+ out.append(wire)
2462
+ return sorted(out, key=lambda row: (row["name"].casefold(), row["id"]))
2463
 
2464
 
2465
+ def _linked_route_delivery_ids(runtime, route_id):
2466
+ """Return every tenant delivery linked to a Route, regardless of its creator.
2467
+
2468
+ The user-facing delivery list is intentionally filtered by caller. A Route delete guard is a
2469
+ referential-integrity question instead: a collaborator-owned delivery is still a live link and
2470
+ must block deletion just like an owner-created one.
2471
+ """
2472
+ import automation_engine as engine
2473
+
2474
+ wanted = str(route_id or "")
2475
+ linked = []
2476
+ for definition_id, defn in (engine.all_definitions(runtime) or {}).items():
2477
+ if not isinstance(defn, dict) or defn.get("kind") != "route_delivery":
2478
+ continue
2479
+ snapshot = ((defn.get("config") or {}).get("routeSnapshot")
2480
+ if isinstance(defn.get("config"), dict) else None)
2481
+ if not isinstance(snapshot, dict) or str(snapshot.get("routeId") or "") != wanted:
2482
+ continue
2483
+ linked.append(str(defn.get("id") or definition_id))
2484
+ return sorted(set(linked))
2485
+
2486
+
2487
+ @router.get("/customers/route-deliveries")
2488
+ def route_delivery_list(session: Session = Depends(module_gate(MODULE))):
2489
+ """Saved C2 route deliveries owned by the caller (or all for an administrator)."""
2490
+ return {"deliveries": _route_delivery_definitions(session)}
2491
+
2492
+
2493
+ @router.get("/customers/routes/{route_id}/deliveries")
2494
+ def normalized_route_delivery_list(route_id: str,
2495
+ session: Session = Depends(module_gate(MODULE))):
2496
+ """Deliveries for the one normalized Route whose detail is open."""
2497
+ _route_or_404(session, route_id)
2498
+ return {"deliveries": _route_delivery_definitions(session, route_id)}
2499
+
2500
+
2501
+ def _create_route_delivery_for_route(session, route, body):
2502
+ """Persist and arm one server-authored snapshot; never execute its runner here."""
2503
  import automation_control
2504
  import automation_engine as engine
2505
 
2506
  if not session.runtime.available():
2507
  raise err(503, "store_unavailable", "the tenant store is unavailable. Nothing was saved")
2508
+ _route_mutation_allowed(session, route)
2509
+ recipient, snapshot = _route_delivery_snapshot_for_route_or_400(session, route, body)
2510
+ route_name = " ".join(str(route.get("name") or "Route").split())[:120] or "Route"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2511
  raw = {
2512
+ "name": f"{route_name} delivery"[:120],
2513
  "kind": "route_delivery",
2514
  "trigger": {"key": "manual"},
2515
+ # The normalized Route UI promises one deliberately boring cadence. A browser cannot
2516
+ # smuggle a different cron or an immediate run into this creation request.
2517
+ "schedule": {"cron": "0 8 * * *", "enabled": True},
2518
+ "config": {"recipient": recipient, "routeSnapshot": snapshot},
 
 
 
 
 
2519
  "flow": {"actions": []},
2520
  }
2521
  defn, problem = engine.create(session.runtime, raw, username=session.uname)
 
2524
  try:
2525
  automation_control.sync_definition(session.tenant, defn)
2526
  except automation_control.ControlPlaneError as exc:
 
2527
  raise err(503, "automation_control_unavailable",
2528
  f"the route was saved, but its daily schedule could not be armed: {exc}")
2529
  return {"delivery": _route_delivery_wire(defn)}
2530
 
2531
 
2532
+ @router.post("/customers/routes/{route_id}/deliveries", status_code=201)
2533
+ def normalized_route_delivery_create(route_id: str, body: dict = Body(default=None),
2534
+ session: Session = Depends(module_gate(MODULE))):
2535
+ """Schedule a named normalized Route from its server-resolved View and stop relation."""
2536
+ return _create_route_delivery_for_route(
2537
+ session, _route_or_404(session, route_id), body if isinstance(body, dict) else {})
2538
+
2539
+
2540
+ @router.post("/customers/route-deliveries")
2541
+ def route_delivery_create(body: dict = Body(default=None),
2542
  session: Session = Depends(module_gate(MODULE))):
2543
+ """Compatibility door: a normalized Route id is still mandatory and server-resolved."""
2544
+ body = body if isinstance(body, dict) else {}
2545
+ route_id = str(body.get("routeId") or "").strip()
2546
+ if not route_id:
2547
+ raise err(400, "normalized_route_required",
2548
+ "choose a saved Route before scheduling its delivery")
2549
+ return _create_route_delivery_for_route(session, _route_or_404(session, route_id), body)
2550
+
2551
+
2552
+ def _delete_route_delivery(session, delivery_id, route_id=None):
2553
  import automation_control
2554
  import automation_engine as engine
2555
 
2556
  defn = (engine.all_definitions(session.runtime) or {}).get(str(delivery_id))
2557
  if not isinstance(defn, dict) or defn.get("kind") != "route_delivery":
2558
  raise err(404, "unknown_route_delivery", "no scheduled route with that id")
2559
+ wire = _route_delivery_wire(defn)
2560
+ if route_id is not None and wire["snapshot"]["routeId"] != str(route_id):
2561
+ raise err(404, "unknown_route_delivery", "no scheduled delivery for this Route with that id")
2562
  if not session.admin and str(defn.get("createdBy") or "") != session.uname:
2563
  raise err(403, "forbidden", "only the route creator or an administrator can remove its schedule")
2564
  engine.remove(session.runtime, str(delivery_id))
 
2568
  raise err(503, "automation_control_unavailable",
2569
  f"the route schedule was removed, but its native schedule could not be removed: {exc}")
2570
  return {"deleted": str(delivery_id)}
2571
+
2572
+
2573
+ @router.delete("/customers/routes/{route_id}/deliveries/{delivery_id}")
2574
+ def normalized_route_delivery_delete(route_id: str, delivery_id: str,
2575
+ session: Session = Depends(module_gate(MODULE))):
2576
+ """Remove one delivery from the normalized Route detail that owns it."""
2577
+ route = _route_or_404(session, route_id)
2578
+ _route_mutation_allowed(session, route)
2579
+ return _delete_route_delivery(session, delivery_id, route_id)
2580
+
2581
+
2582
+ @router.delete("/customers/route-deliveries/{delivery_id}")
2583
+ def route_delivery_delete(delivery_id: str,
2584
+ session: Session = Depends(module_gate(MODULE))):
2585
+ """Compatibility removal for existing schedule links."""
2586
+ return _delete_route_delivery(session, delivery_id)
api/routes_geo.py CHANGED
@@ -123,7 +123,9 @@ _CACHE_MAX = 4096
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):
@@ -173,6 +175,25 @@ def _clean_geometry(raw):
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 {}
@@ -182,8 +203,13 @@ def _clean_zone(raw, previous=None, *, zone_id=""):
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 []
@@ -209,6 +235,7 @@ def _clean_zone(raw, previous=None, *, zone_id=""):
209
  "name": name,
210
  "color": color,
211
  "geometryGeoJson": geometry,
 
212
  "visible": bool(raw.get("visible")) if "visible" in raw else bool(previous.get("visible", True)),
213
  "geographicField": geographic,
214
  "memberships": member_ids,
@@ -217,7 +244,8 @@ def _clean_zone(raw, previous=None, *, zone_id=""):
217
 
218
  def _zone_wire(zone):
219
  wire = {key: zone.get(key) for key in ("id", "name", "color", "geometryGeoJson", "visible",
220
- "geographicField", "memberships", "createdBy", "createdAt")}
 
221
  # Storage keeps ids as strings because table records may originate in several backends; Map
222
  # selection is numeric `pid`s. The wire performs that one boundary conversion explicitly.
223
  members = []
@@ -229,9 +257,50 @@ def _zone_wire(zone):
229
  if pid > 0:
230
  members.append(pid)
231
  wire["memberships"] = members
 
232
  return wire
233
 
234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  def _zone_context(session, raw_table_key):
236
  """One table-scoped Zone context, using the existing grid assemblies as permission walls."""
237
  table_key = str(raw_table_key or "").strip()
@@ -250,7 +319,7 @@ def _zone_context(session, raw_table_key):
250
  raise err(400, "invalid_zone_table", "choose a database before working with Zones")
251
  fields = {str(field.get("key") or "") for field in (grid.get("fields") or [])
252
  if isinstance(field, dict) and field.get("key")}
253
- return table_key, fields, set(grid.get("pids") or ())
254
 
255
 
256
  def _zone_subject(session, table_key, zone_id):
@@ -437,13 +506,14 @@ def geo_providers(session: Session = Depends(require_session)):
437
  def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(require_session)):
438
  """The canonical table-scoped Zone DTOs a Map may draw or filter by."""
439
  from core import user_tables
440
- table_key, _fields, _pids = _zone_context(session, tableKey)
441
  zones = user_tables.zones(table_key, st=session.runtime)
442
  # A hidden Zone remains recoverable to its creator/admin, but cannot become visible through a
443
  # second table simply because row ids happen to collide there.
444
  visible = [zone for zone in zones if zone.get("visible", True)
445
  or session.admin or str(zone.get("createdBy") or "") == session.uname]
446
- return {"zones": [_zone_wire(zone) for zone in sorted(visible,
 
447
  key=lambda zone: (str(zone.get("name") or "").casefold(), str(zone.get("id") or "")))]}
448
 
449
 
@@ -452,9 +522,10 @@ def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(
452
  """Persist one Zone in the existing table-scoped Zone store and field/filter contract."""
453
  from core import user_tables
454
  body = body if isinstance(body, dict) else {}
455
- table_key, field_keys, pids = _zone_context(session, body.get("tableKey"))
456
  try:
457
  zone = _clean_zone(body)
 
458
  except ValueError as exc:
459
  raise err(400, "invalid_zone", str(exc))
460
  if not zone["id"]:
@@ -476,10 +547,11 @@ def geo_zone_update(zone_id: str, body: dict = Body(default=None),
476
  """Edit a table-scoped Zone while retaining creator, geometry and membership invariants."""
477
  from core import user_tables
478
  body = body if isinstance(body, dict) else {}
479
- table_key, field_keys, pids = _zone_context(session, body.get("tableKey"))
480
  previous = _zone_subject(session, table_key, zone_id)
481
  try:
482
  zone = _clean_zone(body, previous, zone_id=str(zone_id))
 
483
  except ValueError as exc:
484
  raise err(400, "invalid_zone", str(exc))
485
  saved = user_tables.upsert_zone(table_key, zone, field_keys=field_keys,
@@ -495,7 +567,7 @@ def geo_zone_delete(zone_id: str, body: dict = Body(default=None),
495
  session: Session = Depends(require_session)):
496
  """Delete exactly one table-scoped Zone; record values are never mutated here."""
497
  body = body if isinstance(body, dict) else {}
498
- table_key, _fields, _pids = _zone_context(session, body.get("tableKey"))
499
  _zone_subject(session, table_key, zone_id)
500
  from core import user_tables
501
  if not user_tables.delete_zone(table_key, zone_id, st=session.runtime):
 
123
  ZONES_KEY = "map_zones"
124
  MAX_ZONES = 200
125
  MAX_ZONE_MEMBERSHIPS = 10_000
126
+ MAX_ZONE_ZIP_CODES = 500
127
  _ZONE_COLORS = ("#9DBFF2", "#A5D8B4", "#F5D989", "#F0A8A0", "#C7B7E8")
128
+ _ZONE_ZIP_RE = re.compile(r"^\d{5}(?:-\d{4})?$")
129
 
130
 
131
  def _zone_id(raw):
 
175
  "type": "MultiPolygon", "coordinates": cleaned_polys}
176
 
177
 
178
+ def _clean_zip_codes(raw):
179
+ """A bounded US ZIP list. Invalid input is refused rather than silently losing a boundary."""
180
+ if raw is None:
181
+ return []
182
+ if not isinstance(raw, list):
183
+ raise ValueError("Zone ZIP codes must be a list")
184
+ if len(raw) > MAX_ZONE_ZIP_CODES:
185
+ raise ValueError(f"a Zone can contain at most {MAX_ZONE_ZIP_CODES:,} ZIP codes")
186
+ out, seen = [], set()
187
+ for value in raw:
188
+ zip_code = str(value or "").strip().upper()
189
+ if not _ZONE_ZIP_RE.fullmatch(zip_code):
190
+ raise ValueError("each Zone ZIP code must be five digits or ZIP+4")
191
+ if zip_code not in seen:
192
+ seen.add(zip_code)
193
+ out.append(zip_code)
194
+ return out
195
+
196
+
197
  def _clean_zone(raw, previous=None, *, zone_id=""):
198
  raw = raw if isinstance(raw, dict) else {}
199
  previous = previous if isinstance(previous, dict) else {}
 
203
  color = str(raw.get("color") if "color" in raw else previous.get("color") or _ZONE_COLORS[0]).upper()
204
  if not re.fullmatch(r"#[0-9A-F]{6}", color):
205
  raise ValueError("a Zone color is a six-digit hex color")
206
+ geometry_raw = (raw.get("geometryGeoJson") if "geometryGeoJson" in raw
207
+ else previous.get("geometryGeoJson"))
208
+ geometry = _clean_geometry(geometry_raw) if geometry_raw is not None else None
209
+ zip_codes = _clean_zip_codes(raw.get("zipCodes") if "zipCodes" in raw
210
+ else previous.get("zipCodes"))
211
+ if geometry is None and not zip_codes:
212
+ raise ValueError("a Zone needs GeoJSON Polygon or MultiPolygon geometry or a ZIP code")
213
  geographic = str(raw.get("geographicField") if "geographicField" in raw
214
  else previous.get("geographicField") or "").strip()[:80]
215
  memberships = raw.get("memberships") if "memberships" in raw else previous.get("memberships") or []
 
235
  "name": name,
236
  "color": color,
237
  "geometryGeoJson": geometry,
238
+ "zipCodes": zip_codes,
239
  "visible": bool(raw.get("visible")) if "visible" in raw else bool(previous.get("visible", True)),
240
  "geographicField": geographic,
241
  "memberships": member_ids,
 
244
 
245
  def _zone_wire(zone):
246
  wire = {key: zone.get(key) for key in ("id", "name", "color", "geometryGeoJson", "visible",
247
+ "geographicField", "zipCodes", "memberships",
248
+ "createdBy", "createdAt")}
249
  # Storage keeps ids as strings because table records may originate in several backends; Map
250
  # selection is numeric `pid`s. The wire performs that one boundary conversion explicitly.
251
  members = []
 
257
  if pid > 0:
258
  members.append(pid)
259
  wire["memberships"] = members
260
+ wire["zipCodes"] = list(zone.get("zipCodes") or ())
261
  return wire
262
 
263
 
264
+ def _zone_membership_union(zone, rows, allowed_pids, *, refuse_overflow=False):
265
+ """Return a scoped selected/polygon/ZIP union without mutating the stored Zone.
266
+
267
+ C3's durable ``memberships`` snapshot is retained for existing Zones and explicit geography
268
+ groups. Wave 44 adds current polygon/ZIP matches from the already permission-walled rows.
269
+ GET calls this pure projection too, so an address change can update the visible chooser while
270
+ tenant data remains untouched.
271
+ """
272
+ from core import route_system
273
+
274
+ allowed = {str(pid) for pid in allowed_pids or ()}
275
+ prepared = []
276
+ geographic = str(zone.get("geographicField") or "")
277
+ geographic_is_zip = bool(re.search(r"zip|postal", geographic, re.IGNORECASE))
278
+ for raw in rows or ():
279
+ if not isinstance(raw, dict):
280
+ continue
281
+ item = raw
282
+ if geographic_is_zip and geographic in raw and not any(
283
+ raw.get(key) not in (None, "")
284
+ for key in ("zip", "zip_code", "postal_code", "postalCode")):
285
+ item = {**raw, "zip": raw.get(geographic)}
286
+ prepared.append(item)
287
+ derived = route_system.zone_members(zone, prepared)
288
+ members, seen = [], set()
289
+ for value in list(zone.get("memberships") or ()) + list(derived):
290
+ try:
291
+ pid = int(value)
292
+ except (TypeError, ValueError):
293
+ continue
294
+ marker = str(pid)
295
+ if pid <= 0 or marker in seen or marker not in allowed:
296
+ continue
297
+ seen.add(marker)
298
+ members.append(pid)
299
+ if refuse_overflow and len(members) > MAX_ZONE_MEMBERSHIPS:
300
+ raise ValueError(f"a Zone can contain at most {MAX_ZONE_MEMBERSHIPS:,} record IDs")
301
+ return {**zone, "memberships": members}
302
+
303
+
304
  def _zone_context(session, raw_table_key):
305
  """One table-scoped Zone context, using the existing grid assemblies as permission walls."""
306
  table_key = str(raw_table_key or "").strip()
 
319
  raise err(400, "invalid_zone_table", "choose a database before working with Zones")
320
  fields = {str(field.get("key") or "") for field in (grid.get("fields") or [])
321
  if isinstance(field, dict) and field.get("key")}
322
+ return table_key, fields, set(grid.get("pids") or ()), list(grid.get("rows_src") or ())
323
 
324
 
325
  def _zone_subject(session, table_key, zone_id):
 
506
  def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(require_session)):
507
  """The canonical table-scoped Zone DTOs a Map may draw or filter by."""
508
  from core import user_tables
509
+ table_key, _fields, pids, rows = _zone_context(session, tableKey)
510
  zones = user_tables.zones(table_key, st=session.runtime)
511
  # A hidden Zone remains recoverable to its creator/admin, but cannot become visible through a
512
  # second table simply because row ids happen to collide there.
513
  visible = [zone for zone in zones if zone.get("visible", True)
514
  or session.admin or str(zone.get("createdBy") or "") == session.uname]
515
+ projected = [_zone_membership_union(zone, rows, pids) for zone in visible]
516
+ return {"zones": [_zone_wire(zone) for zone in sorted(projected,
517
  key=lambda zone: (str(zone.get("name") or "").casefold(), str(zone.get("id") or "")))]}
518
 
519
 
 
522
  """Persist one Zone in the existing table-scoped Zone store and field/filter contract."""
523
  from core import user_tables
524
  body = body if isinstance(body, dict) else {}
525
+ table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey"))
526
  try:
527
  zone = _clean_zone(body)
528
+ zone = _zone_membership_union(zone, rows, pids, refuse_overflow=True)
529
  except ValueError as exc:
530
  raise err(400, "invalid_zone", str(exc))
531
  if not zone["id"]:
 
547
  """Edit a table-scoped Zone while retaining creator, geometry and membership invariants."""
548
  from core import user_tables
549
  body = body if isinstance(body, dict) else {}
550
+ table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey"))
551
  previous = _zone_subject(session, table_key, zone_id)
552
  try:
553
  zone = _clean_zone(body, previous, zone_id=str(zone_id))
554
+ zone = _zone_membership_union(zone, rows, pids, refuse_overflow=True)
555
  except ValueError as exc:
556
  raise err(400, "invalid_zone", str(exc))
557
  saved = user_tables.upsert_zone(table_key, zone, field_keys=field_keys,
 
567
  session: Session = Depends(require_session)):
568
  """Delete exactly one table-scoped Zone; record values are never mutated here."""
569
  body = body if isinstance(body, dict) else {}
570
+ table_key, _fields, _pids, _rows = _zone_context(session, body.get("tableKey"))
571
  _zone_subject(session, table_key, zone_id)
572
  from core import user_tables
573
  if not user_tables.delete_zone(table_key, zone_id, st=session.runtime):
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
28
 
29
  from deps import Session, err, module_gate, perms, require_session
30
 
@@ -167,7 +167,8 @@ def workspace(scope: str = "customer",
167
  # The field contract rides the cheap re-read on EVERY topic — see the customer branch
168
  # below for why (a user table's first cohort changes its contract too: `_cohorts(ctx)`
169
  # is scope-parameterized, so `ut_` surfaces have their own sets).
170
- workspace["fields"] = g["fields"]
 
171
  workspace["measures"] = g["measures"]
172
  workspace["measureSets"] = g["measure_sets"]
173
  # ⚠ `g["derived"]`, NOT `{}` (2026-08-04). R9 gave every topic its own cohort sets, and
@@ -267,6 +268,10 @@ def workspace(scope: str = "customer",
267
  except grid_events.StoreUnavailable:
268
  raise err(503, "store_unavailable", "the tenant store is unavailable")
269
  workspace = g["workspace"]
 
 
 
 
270
  # ADDITIVE to the wire: the caller's own overlay cells. The grid reads overlays from the
271
  # /customers rows, but this route is the cheap read-back a write can be verified against
272
  # (verify_api's overlay probe) without paying the pool call. Per-user by construction —
@@ -286,7 +291,7 @@ def workspace(scope: str = "customer",
286
  # same permission wall (`hidden_keys` already applied) — so the two wires cannot disagree
287
  # about what a column is. Taking it from anywhere else would fork the contract that
288
  # verify_fields_contract.py exists to keep single-sourced.
289
- workspace["fields"] = g["fields"]
290
  # ── the STANDALONE measure channel (owner item 1, 2026-07-31) ────────────────────────────
291
  # The embed receives these as top-level render args; standalone lifts them off THIS route
292
  # (useCustomerData merges them into the payload slots the grid already reads). They ride
@@ -1066,6 +1071,9 @@ def grid_events_route(body: dict = Body(default=None),
1066
  #: [[date-window-vocabulary]]. This is a RENAME and nothing else. `all` resolves to `(None, None)`.
1067
  PIVOT_WINDOWS = {"all": "all_time", "last12m": "ltm", "ytd": "ytd"}
1068
 
 
 
 
1069
  #: The DECLARED pivot routes: `(source, target) -> the edge that answers it`. A pair with no entry
1070
  #: is a 400, never an empty grid — "there is no way to get there" and "nothing is related" are two
1071
  #: different answers and only one of them is true.
@@ -1089,13 +1097,75 @@ _PIVOT_ROUTES = {
1089
  "measure": "revenue",
1090
  "scope_key": "customer", # the cohort bucket the SOURCE tree's cohort leaves name
1091
  "source_dim": "order_partner",
1092
- "source_key": "pid",
1093
  "target_dim": "product_code",
1094
  "target_key": "code",
1095
  },
1096
  }
1097
 
1098
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1099
  def _pivot_today():
1100
  """The tenant's today, ISO. One clock, so the window and any date leaf agree."""
1101
  import core.periods as periods
@@ -1228,12 +1298,12 @@ def grid_pivot(body: dict = Body(default=None),
1228
  f"window must be one of {', '.join(sorted(PIVOT_WINDOWS))}. Refusing to guess "
1229
  f"which period was meant, because guessing 'all time' would widen the answer "
1230
  f"under a count nobody would doubt")
1231
- route = _PIVOT_ROUTES.get((source, target))
1232
- if route is None:
1233
- raise err(400, "no_pivot_route",
1234
- f"there is no declared way to get from '{source}' to '{target}'. "
1235
- f"Declared: " +
1236
- "; ".join(f"{a} to {b}" for a, b in sorted(_PIVOT_ROUTES)))
1237
 
1238
  # ── THE WALL, ON BOTH SIDES OF THE JOIN (R12) ────────────────────────────────────────────
1239
  src, refusal = _pivot_side(session, source)
@@ -1246,6 +1316,9 @@ def grid_pivot(body: dict = Body(default=None),
1246
  src_fields, src_rows = src
1247
  tgt_fields, tgt_rows = tgt
1248
 
 
 
 
1249
  today = _pivot_today()
1250
  columns = filter_eval._columns_map(src_fields)
1251
  unanswerable = _pivot_unanswerable(filters, columns)
@@ -1270,10 +1343,6 @@ def grid_pivot(body: dict = Body(default=None),
1270
  for cid, c in cohort_mod.scoped(route["scope_key"]).visible(
1271
  session.uname, pool_pids).items()}
1272
 
1273
- if route["source_key"] != "pid":
1274
- raise err(500, "pivot_source_key",
1275
- f"this pivot names '{route['source_key']}' as the source identity and the row "
1276
- f"engine reads 'pid'. Refusing rather than pivoting on the wrong column")
1277
  member = sorted({p for p in filter_eval.visible_pids(
1278
  {"conj": filter_conj, "nodes": filters}, src_rows, src_fields,
1279
  ctx=filter_eval.EvalCtx(cohort_sets=cohort_sets, today=today))
@@ -1295,8 +1364,20 @@ def grid_pivot(body: dict = Body(default=None),
1295
  filters={route["source_dim"]: member},
1296
  date_from=date_from, date_to=date_to, team_id=team_id, today=today,
1297
  limit=semantic.MAX_GROUPS)
 
 
 
 
 
 
 
1298
  except semantic.ModelError as exc:
1299
- raise err(503, "pivot_unavailable", str(exc))
 
 
 
 
 
1300
 
1301
  # ⛔ `truncated` IS READ, NOT ASSUMED FALSE. `store_query` returns groups plus a flag, and a
1302
  # grouped query's groups ARE the answer, so a dropped one is missing data with nothing to
@@ -1396,3 +1477,84 @@ def _register_topic_rows():
1396
  _PRODUCT_MODULE = "product_data"
1397
 
1398
  _C1_ROW_SOURCES = _register_topic_rows()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
 
 
167
  # The field contract rides the cheap re-read on EVERY topic — see the customer branch
168
  # below for why (a user table's first cohort changes its contract too: `_cohorts(ctx)`
169
  # is scope-parameterized, so `ut_` surfaces have their own sets).
170
+ from core import route_system
171
+ workspace["fields"] = [route_system.field_axes(field) for field in g["fields"]]
172
  workspace["measures"] = g["measures"]
173
  workspace["measureSets"] = g["measure_sets"]
174
  # ⚠ `g["derived"]`, NOT `{}` (2026-08-04). R9 gave every topic its own cohort sets, and
 
268
  except grid_events.StoreUnavailable:
269
  raise err(503, "store_unavailable", "the tenant store is unavailable")
270
  workspace = g["workspace"]
271
+ # C1: this is a server projection, not an editable workspace preference. A customer user
272
+ # can reorder private folders but cannot remove or relocate Loopable's protected system one.
273
+ from core import route_system
274
+ workspace = route_system.inject_loopable_folder(workspace)
275
  # ADDITIVE to the wire: the caller's own overlay cells. The grid reads overlays from the
276
  # /customers rows, but this route is the cheap read-back a write can be verified against
277
  # (verify_api's overlay probe) without paying the pool call. Per-user by construction —
 
291
  # same permission wall (`hidden_keys` already applied) — so the two wires cannot disagree
292
  # about what a column is. Taking it from anywhere else would fork the contract that
293
  # verify_fields_contract.py exists to keep single-sourced.
294
+ workspace["fields"] = [route_system.field_axes(field) for field in g["fields"]]
295
  # ── the STANDALONE measure channel (owner item 1, 2026-07-31) ────────────────────────────
296
  # The embed receives these as top-level render args; standalone lifts them off THIS route
297
  # (useCustomerData merges them into the payload slots the grid already reads). They ride
 
1071
  #: [[date-window-vocabulary]]. This is a RENAME and nothing else. `all` resolves to `(None, None)`.
1072
  PIVOT_WINDOWS = {"all": "all_time", "last12m": "ltm", "ytd": "ytd"}
1073
 
1074
+ # The required subset of a stored semantic `via` bag consumed by the pivot door.
1075
+ _PIVOT_VIA_REQUIRED = ("topic", "measure", "scope_key", "source_dim", "target_dim", "target_key")
1076
+
1077
  #: The DECLARED pivot routes: `(source, target) -> the edge that answers it`. A pair with no entry
1078
  #: is a 400, never an empty grid — "there is no way to get there" and "nothing is related" are two
1079
  #: different answers and only one of them is true.
 
1097
  "measure": "revenue",
1098
  "scope_key": "customer", # the cohort bucket the SOURCE tree's cohort leaves name
1099
  "source_dim": "order_partner",
 
1100
  "target_dim": "product_code",
1101
  "target_key": "code",
1102
  },
1103
  }
1104
 
1105
 
1106
+ def _pivot_route(fields, source, target, via_field):
1107
+ """Resolve a visible link field first; allow only the single dated A23 fallback."""
1108
+ try:
1109
+ return _pivot_route_via(fields, source, target, via_field)
1110
+ except HTTPException as exc:
1111
+ detail = exc.detail if isinstance(exc.detail, dict) else {}
1112
+ if (detail.get("error") or {}).get("code") != "no_pivot_route":
1113
+ raise
1114
+ tombstone = _PIVOT_ROUTES.get((source, target))
1115
+ if tombstone is None:
1116
+ raise
1117
+ return dict(tombstone)
1118
+
1119
+
1120
+ def _pivot_route_via(fields, source, target, via_field):
1121
+ """Return the `via` bag from the link field named by the request, or refuse by name."""
1122
+ via_field = str(via_field or "").strip()
1123
+ if not via_field:
1124
+ raise err(400, "no_pivot_route",
1125
+ f"this pivot did not name a link field, so there is no edge to answer it with. "
1126
+ f"Send 'viaField' naming a link field on '{source}' that points at '{target}'")
1127
+
1128
+ match = None
1129
+ for field in fields or ():
1130
+ if not isinstance(field, dict):
1131
+ continue
1132
+ if str(field.get("key") or "") == via_field and field.get("type") == "link":
1133
+ match = field
1134
+ break
1135
+ if match is None:
1136
+ raise err(400, "no_pivot_route",
1137
+ f"this account cannot resolve a link field named '{via_field}' on '{source}', "
1138
+ f"so there is no declared edge to '{target}'. Pivot from a link field this "
1139
+ f"account can see on that grid")
1140
+
1141
+ link = match.get("link") if isinstance(match.get("link"), dict) else {}
1142
+ points_at = str(link.get("table") or "")
1143
+ if points_at != target:
1144
+ raise err(400, "no_pivot_route",
1145
+ f"the link field '{via_field}' points at "
1146
+ f"'{points_at or 'nothing this door can name'}', not at '{target}'. Refusing "
1147
+ f"rather than pivoting through an edge nobody asked for")
1148
+
1149
+ via = link.get("via") if isinstance(link.get("via"), dict) else None
1150
+ if not via:
1151
+ raise err(400, "no_pivot_route",
1152
+ f"the link field '{via_field}' joins '{source}' to '{target}' directly and "
1153
+ f"carries no 'via' declaration, so this door has no fact table to ask")
1154
+ missing = [key for key in _PIVOT_VIA_REQUIRED if not via.get(key)]
1155
+ if missing:
1156
+ raise err(400, "no_pivot_route",
1157
+ f"the 'via' declaration on link field '{via_field}' is missing "
1158
+ f"{', '.join(missing)}, so the edge is not fully described")
1159
+ return via
1160
+
1161
+
1162
+ _PIVOT_AUTHORING = (
1163
+ "unknown metric", "unknown topic", "belong to another topic", "is company-level",
1164
+ "at least one measure required", "filter tree", "filter rule", "must reference",
1165
+ "grain must be", "is store-only", "unknown dim", "has no name column",
1166
+ )
1167
+
1168
+
1169
  def _pivot_today():
1170
  """The tenant's today, ISO. One clock, so the window and any date leaf agree."""
1171
  import core.periods as periods
 
1298
  f"window must be one of {', '.join(sorted(PIVOT_WINDOWS))}. Refusing to guess "
1299
  f"which period was meant, because guessing 'all time' would widen the answer "
1300
  f"under a count nobody would doubt")
1301
+ # Permission and path validity are decided before either database is fetched.
1302
+ scope = perm_scope.pivot_scope(session.user, source, target, st=session.runtime)
1303
+ if not scope.permitted:
1304
+ return _pivot_reply(source, target, [], [], 0, 0,
1305
+ refusal=scope.refusal(),
1306
+ limits=scope.limits(st=session.runtime))
1307
 
1308
  # ── THE WALL, ON BOTH SIDES OF THE JOIN (R12) ────────────────────────────────────────────
1309
  src, refusal = _pivot_side(session, source)
 
1316
  src_fields, src_rows = src
1317
  tgt_fields, tgt_rows = tgt
1318
 
1319
+ # Resolve the relationship from the visible link field the request actually named.
1320
+ route = _pivot_route(src_fields, source, target, body.get("viaField"))
1321
+
1322
  today = _pivot_today()
1323
  columns = filter_eval._columns_map(src_fields)
1324
  unanswerable = _pivot_unanswerable(filters, columns)
 
1343
  for cid, c in cohort_mod.scoped(route["scope_key"]).visible(
1344
  session.uname, pool_pids).items()}
1345
 
 
 
 
 
1346
  member = sorted({p for p in filter_eval.visible_pids(
1347
  {"conj": filter_conj, "nodes": filters}, src_rows, src_fields,
1348
  ctx=filter_eval.EvalCtx(cohort_sets=cohort_sets, today=today))
 
1364
  filters={route["source_dim"]: member},
1365
  date_from=date_from, date_to=date_to, team_id=team_id, today=today,
1366
  limit=semantic.MAX_GROUPS)
1367
+ except semantic.UnknownColumnError as exc:
1368
+ others = [column for column in (exc.columns or ()) if column != exc.column]
1369
+ also = f" It also names {', '.join(others)}." if others else ""
1370
+ raise err(400, "pivot_unknown_column",
1371
+ f"{str(exc).rstrip('. ')}. The column this pivot could not resolve is "
1372
+ f"'{exc.column}'.{also} Fix the link field's 'via' declaration, or pivot "
1373
+ f"through a link field whose dims this topic actually carries")
1374
  except semantic.ModelError as exc:
1375
+ sentence = str(exc)
1376
+ if any(needle in sentence.lower() for needle in _PIVOT_AUTHORING):
1377
+ raise err(400, "pivot_bad_edge",
1378
+ f"{sentence.rstrip('. ')}. This pivot's edge comes from the link "
1379
+ f"field's 'via' declaration, so that declaration is what needs correcting")
1380
+ raise err(503, "pivot_unavailable", sentence)
1381
 
1382
  # ⛔ `truncated` IS READ, NOT ASSUMED FALSE. `store_query` returns groups plus a flag, and a
1383
  # grouped query's groups ARE the answer, so a dropped one is missing data with nothing to
 
1477
  _PRODUCT_MODULE = "product_data"
1478
 
1479
  _C1_ROW_SOURCES = _register_topic_rows()
1480
+
1481
+
1482
+ # W42-T07 / C2: model-derived operands for the one-hop link editor. This deliberately reads
1483
+ # model files, not a tenant store, so a cold/locked store cannot silently empty the picker.
1484
+ _HOP_CACHE = {}
1485
+ _HOP_FIELD_SOURCE = "topic"
1486
+ _HOP_FIELD_TYPES = ("text", "int", "date", "currency", "pct")
1487
+
1488
+
1489
+ def _hop_dim_type(columns, dim_key):
1490
+ field_type = ((columns or {}).get(dim_key) or {}).get("type")
1491
+ return field_type if field_type in _HOP_FIELD_TYPES else "text"
1492
+
1493
+
1494
+ def _hop_topic_offer():
1495
+ """Return answerable topics plus the exact windows accepted by `_clean_via`."""
1496
+ if _HOP_CACHE.get("offer"):
1497
+ return _HOP_CACHE["offer"]
1498
+ from harness import semantic as sem
1499
+ from harness import windows as window_model
1500
+ import core.user_tables as user_tables
1501
+
1502
+ topics, metrics = sem.topics(), sem.metrics()
1503
+ by_topic = {}
1504
+ for key, metric in metrics.items():
1505
+ if metric.get("agg") in ("ratio", "derived"):
1506
+ continue
1507
+ by_topic.setdefault(metric.get("topic"), []).append({
1508
+ "key": key,
1509
+ "label": metric.get("label") or key,
1510
+ "format": metric.get("format") or "usd",
1511
+ "description": metric.get("description") or "",
1512
+ })
1513
+
1514
+ offered, omissions = [], []
1515
+ for topic_key, topic in sorted(topics.items()):
1516
+ dims = ((topic.get("store") or {}).get("dims")) or {}
1517
+ measures = by_topic.get(topic_key) or []
1518
+ label = topic.get("label") or topic_key
1519
+ if not dims or not measures:
1520
+ reasons = []
1521
+ if not dims:
1522
+ reasons.append("no_dims")
1523
+ if not measures:
1524
+ reasons.append("no_measures")
1525
+ omissions.append({"topic": topic_key, "label": label, "reasons": reasons})
1526
+ continue
1527
+ try:
1528
+ columns = sem.store_columns(topic_key, include_measures=False)
1529
+ except Exception:
1530
+ omissions.append({"topic": topic_key, "label": label,
1531
+ "reasons": ["no_store_columns"]})
1532
+ continue
1533
+ offered.append({
1534
+ "key": topic_key,
1535
+ "label": label,
1536
+ "grain": topic.get("grain") or "",
1537
+ "dims": [{
1538
+ "key": dim_key,
1539
+ "label": dim.get("label") or dim_key,
1540
+ "type": _hop_dim_type(columns, dim_key),
1541
+ "source": _HOP_FIELD_SOURCE,
1542
+ "keyedBy": "id" if dim.get("name_col") else "value",
1543
+ } for dim_key, dim in dims.items()],
1544
+ "measures": sorted(measures, key=lambda measure: measure["label"].lower()),
1545
+ })
1546
+
1547
+ windows = [{"key": key, "label": window_model.WINDOW_LABELS.get(key, key).format(n="N")}
1548
+ for key in user_tables.LINK_VIA_WINDOWS]
1549
+ offer = {"topics": offered, "windows": windows, "omissions": omissions}
1550
+ _HOP_CACHE["offer"] = offer
1551
+ return offer
1552
+
1553
+
1554
+ @router.get("/grid/hop-topics")
1555
+ def grid_hop_topics(session: Session = Depends(require_session)):
1556
+ """Serve the one-hop authoring offer with an unconditional response shape."""
1557
+ import odoo_relational
1558
+ if not odoo_relational.is_royal(session.tenant):
1559
+ return {"topics": [], "windows": [], "omissions": []}
1560
+ return _hop_topic_offer()
api/routes_nav.py CHANGED
@@ -914,7 +914,10 @@ def nav_schema(key: str, session: Session = Depends(require_session)):
914
  # shared stratum and this ticket is not where it starts; widening the list handed to the
915
  # closure can only ever ADD to the hidden set, never remove from it.
916
  import routes_tables as _rt
917
- base = list(defn.get("fields") or [])
 
 
 
918
  hidden = _rt._ut_hidden(session, key,
919
  _rt._ut_shared_fields(session, key, base),
920
  st=session.runtime)
 
914
  # shared stratum and this ticket is not where it starts; widening the list handed to the
915
  # closure can only ever ADD to the hidden set, never remove from it.
916
  import routes_tables as _rt
917
+ # Zone is a canonical derived field on the same pre-wall contract the grid uses. Shared
918
+ # tenant-wide fields remain schema-private here; this only prevents the two real doors
919
+ # from evaluating the Zone field on opposite sides of their common wall.
920
+ base = _rt._ut_contract_fields(key, defn.get("fields") or [], st=session.runtime)
921
  hidden = _rt._ut_hidden(session, key,
922
  _rt._ut_shared_fields(session, key, base),
923
  st=session.runtime)
api/routes_shares.py CHANGED
@@ -415,6 +415,415 @@ def _unremovable(held_rows, entries, uname):
415
  stuck.add(user)
416
  return stuck
417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
 
419
  @router.get("/share/mine")
420
  def my_shares(session: Session = Depends(require_session)):
@@ -662,21 +1071,15 @@ def put_share(kind: str, oid: str, body: dict = Body(default=None),
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,6 +1109,20 @@ def put_share(kind: str, oid: str, body: dict = Body(default=None),
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
 
 
415
  stuck.add(user)
416
  return stuck
417
 
418
+ # ── ⭐⭐ WAVE 42 · T25 — SHARING A VIEW SHARES THE FIELDS IT NAMES ──────────────────────────────
419
+ #
420
+ # A saved view is a SELECTION expressed in columns: an order, a visible set, a group, a colour,
421
+ # a sort and a filter tree, every one of which names a field key. Granting the view alone hands
422
+ # the receiver a rail row whose columns resolve to nothing they may read, so the feature that
423
+ # looked shipped puts an empty grid on their screen. This block closes that, and it refuses
424
+ # LOUDLY in the three places where a grant would otherwise be a lie.
425
+ #
426
+ # ⛔⛔ TRAP 1 — A FIELD GRANT IS TOPIC-WIDE, NOT VIEW-SCOPED. It is keyed
427
+ # `shares.field_oid(topic, key)`, so it hands the receiver that column on EVERY view of that
428
+ # database, for as long as the grant stands. That is the existing grant primitive and this
429
+ # ticket does not narrow it; what it does is refuse to let the response PRETEND otherwise, which
430
+ # is why `sharedFieldScope` rides back beside the list.
431
+ #
432
+ # ⛔⛔ TRAP 2 — THE SHARER CANNOT GRANT A COLUMN THEY DO NOT OWN. `field` is absent from
433
+ # `shares.RESHARE_KINDS` and `_owns_object`'s field branch demands `createdBy == session.uname`,
434
+ # so a view built over a colleague's column simply cannot carry that column with it. Silently
435
+ # skipping it ships an empty column; silently granting it is a permission hole. It is REFUSED
436
+ # BY NAME, inside the 200 response, with the sentence that says who to ask.
437
+ #
438
+ # ⛔⛔ TRAP 3 — A GRANT CANNOT UN-HIDE AN ADMIN-WALLED COLUMN. `perm_scope.hidden_keys` UNIONS
439
+ # the administrator's `hiddenFields` with the field-grant source, so granting a walled column
440
+ # answers 200, writes the record, and the receiver still sees nothing: granted with no effect,
441
+ # which is the failure this ticket exists to end. Detected BEFORE the grant, refused by name,
442
+ # and the receiver it is walled from is named too.
443
+ #
444
+ # ⚠ THE WALL IS READ FROM THE ADMIN SOURCE DIRECTLY AND NEVER THROUGH `hidden_keys`, AND THAT IS
445
+ # NOT AN OPTIMISATION. `hidden_keys` unions `field_grant_hidden` — "hidden because you were not
446
+ # granted it" — which is true of every column this route is ABOUT to grant. Asking it here would
447
+ # refuse the whole set on the grounds that the grant has not happened yet.
448
+
449
+
450
+ def _view_configs(view):
451
+ """The dicts a saved view keeps its column state in.
452
+
453
+ `SavedView.config` is the contract (`types.ts::ViewConfig`) and is where every key below
454
+ actually lives. The record ITSELF is read as well because a legacy row that stored the same
455
+ members flat costs one dict lookup to cover and would otherwise hand back an empty key set,
456
+ which is the shape that grants nothing and reports nothing wrong.
457
+ """
458
+ out = []
459
+ if not isinstance(view, dict):
460
+ return out
461
+ cfg = view.get("config")
462
+ if isinstance(cfg, dict):
463
+ out.append(cfg)
464
+ out.append(view)
465
+ return out
466
+
467
+
468
+ def _view_field_keys(view):
469
+ """Every field key this view NAMES, in the order a reader would meet them.
470
+
471
+ ⚠ `filters[].rhs` IS ONE OF THEM AND IS THE ONE THAT GETS DROPPED. A field-vs-field leaf
472
+ (`{colId: price, op: lt, rhs: {kind: field, colId: cost}}`) names TWO columns, and a share
473
+ carrying only the left one leaves the receiver a filter that cannot evaluate. `kind` `stat`
474
+ is not a column reference and is skipped, matching `perm_scope`'s own reader of the tree.
475
+
476
+ ⚠ AND `filters` IS A TREE, NOT A LIST. Condition groups nest under `children`, so the walk
477
+ recurses rather than iterating once: a column named only inside a group is still named.
478
+ """
479
+ keys, seen = [], set()
480
+
481
+ def add(raw):
482
+ key = str(raw or "").strip()
483
+ if key and key not in seen:
484
+ seen.add(key)
485
+ keys.append(key)
486
+
487
+ def walk(node):
488
+ if isinstance(node, list):
489
+ for child in node:
490
+ walk(child)
491
+ return
492
+ if not isinstance(node, dict):
493
+ return
494
+ kids = node.get("children")
495
+ if isinstance(kids, list):
496
+ walk(kids)
497
+ add(node.get("colId"))
498
+ rhs = node.get("rhs")
499
+ if isinstance(rhs, dict) and rhs.get("kind") != "stat":
500
+ add(rhs.get("colId"))
501
+
502
+ for cfg in _view_configs(view):
503
+ for key in (cfg.get("order") or ()):
504
+ add(key)
505
+ for key in (cfg.get("visible") or ()):
506
+ add(key)
507
+ walk(cfg.get("filters"))
508
+ add(cfg.get("groupBy"))
509
+ colour = cfg.get("colorBy")
510
+ add(colour.get("colId") if isinstance(colour, dict) else colour)
511
+ sorts = cfg.get("sorts")
512
+ if isinstance(sorts, dict):
513
+ sorts = [sorts]
514
+ for spec in (sorts or ()):
515
+ if isinstance(spec, dict):
516
+ add(spec.get("colId"))
517
+ return keys
518
+
519
+
520
+ def _find_view_topic(session, oid):
521
+ """`(topic, view)` for a saved view living in any personal stratum of any topic, else
522
+ `(None, None)`.
523
+
524
+ ⚠ THE TOPIC IS HALF THE ANSWER. A field grant is keyed by TOPIC, so resolving the view
525
+ without remembering which workspace answered would leave the caller guessing at the oid,
526
+ which is exactly how two arms of one route come to write two different keys for one column.
527
+ Same loop and same finder as `_owns_object`, which answers a different question about the
528
+ same lookup and is deliberately left alone.
529
+ """
530
+ try:
531
+ import core.table_store as table_store
532
+ except Exception: # noqa: BLE001
533
+ return None, None
534
+ for topic in _topics(session):
535
+ try:
536
+ hit = table_store.make(f"{topic}_table_workspace", st=session.runtime).find_view(oid)
537
+ except Exception: # noqa: BLE001
538
+ continue
539
+ if hit:
540
+ return str(topic), (hit[1] if len(hit) > 1 else {})
541
+ return None, None
542
+
543
+
544
+ def _promote_field_for_grant(session, table_key, field_key):
545
+ """Promote a private column exactly once, stamp it shared, and answer its GRANT OID.
546
+
547
+ ⛔⛔ ONE SEQUENCE, TWO ARMS, AND THAT IS THE WHOLE REASON THIS IS A FUNCTION. `put_share`'s
548
+ `field` arm and its `view` arm (T25) both hand a column to somebody. Two spellings of
549
+ "promote, stamp, key the oid" is how two surfaces start disagreeing about what a grant
550
+ means, and the oid is the exact member that would drift: it is normalised through
551
+ `_field_storage_keys(...)[2]`, never built from whatever key the caller happened to hold.
552
+
553
+ Answers `None` for a key with no definition on that database, so the caller decides whether
554
+ that is a 404 (the `field` arm, where the column IS the request) or a named refusal (the
555
+ `view` arm, where it is one entry in a list).
556
+ """
557
+ from core import field_permissions, shared_overlay
558
+ defn, already_shared, workspace_key, shared_key, grant_topic = _field_definition(
559
+ session, table_key, field_key)
560
+ if not isinstance(defn, dict):
561
+ return None
562
+ if not already_shared:
563
+ defn = field_permissions.promote_field(
564
+ workspace_key, shared_key, grant_topic,
565
+ session.uname, defn, st=session.runtime)
566
+ stamped = dict(defn)
567
+ stamped["shared"] = True
568
+ stamped["granted"] = True
569
+ shared_overlay.put_field(shared_key, field_key, stamped, st=session.runtime)
570
+ return shares.field_oid(grant_topic, field_key)
571
+
572
+
573
+ def _grant_receivers(session, entries):
574
+ """`{username: display name}` for everybody a grant list actually reaches.
575
+
576
+ `shares.EVERYONE` is a real audience, not a placeholder, so it expands to the tenant roster
577
+ `_people` already computes for the picker. Reading it from a second place would be a second
578
+ answer to "who is in this workspace".
579
+ """
580
+ people = None
581
+ out = {}
582
+ for entry in shares._clean_entries(entries):
583
+ who = str(entry.get("user") or "").strip().lower()
584
+ if not who:
585
+ continue
586
+ if who == shares.EVERYONE:
587
+ if people is None:
588
+ people = _people(session.tenant)
589
+ for person in people:
590
+ out.setdefault(str(person["username"]).strip().lower(), person["name"])
591
+ continue
592
+ out.setdefault(who, who)
593
+ if out:
594
+ try:
595
+ reg = users.registry() or {}
596
+ except Exception: # noqa: BLE001
597
+ reg = {}
598
+ for uname in list(out):
599
+ rec = reg.get(uname)
600
+ if isinstance(rec, dict) and rec.get("name"):
601
+ out[uname] = str(rec["name"])
602
+ return out
603
+
604
+
605
+ def _admin_walled(session, grant_topic, defs, receivers):
606
+ """`{field key: [display names]}` for receivers an ADMINISTRATOR has already walled off.
607
+
608
+ ⛔ THE ADMIN SOURCE ONLY. `perm_scope.entry(rec, module)['hiddenFields']` is the half of
609
+ `hidden_keys` a field grant cannot overrule; the other half IS the field grant, so consulting
610
+ the closure here would report every column this route is about to grant as hidden and refuse
611
+ the lot (see the block note above).
612
+
613
+ ⭐ THE MEASURE BINDING IS BORROWED, NEVER RESPELLED. An administrator ticking
614
+ "Metric - Gross margin" stores `measure_margin`, while the COLUMNS carrying that number are
615
+ keyed `measure_margin_<rand>`; `perm_scope._measure_bound_keys` is the one evaluator that
616
+ joins the two, and a second copy here would be the first to drift.
617
+
618
+ ⚠ AN ADMINISTRATOR RECEIVER IS NEVER WALLED — `hidden_keys` answers an empty set for one
619
+ before it reads anything — so the same short circuit runs here, or this function would refuse
620
+ a grant to somebody who can already see the column.
621
+
622
+ ⚠ A RECEIVER WITH NO REGISTRY RECORD IS SKIPPED RATHER THAN TREATED AS WALLED: `perm_scope`
623
+ reads a permission block off the RECORD (`_rec` answers `{}` for a bare username), so a name
624
+ this tenant cannot resolve carries no admin wall to find. `_entries_or_400` has already
625
+ refused a grant list naming an account that does not exist.
626
+ """
627
+ import core.perm_scope as perm_scope
628
+ import core.perms as perms
629
+ try:
630
+ reg = users.registry() or {}
631
+ except Exception: # noqa: BLE001
632
+ reg = {}
633
+ field_list = [dict(defn or {}, key=key) for key, defn in defs.items()
634
+ if isinstance(defn, dict)]
635
+ walled = {}
636
+ for uname, display in sorted(receivers.items()):
637
+ rec = reg.get(uname)
638
+ if not isinstance(rec, dict) or perms.is_admin(rec):
639
+ continue
640
+ try:
641
+ entry = perm_scope.entry(rec, grant_topic) or {}
642
+ except Exception: # noqa: BLE001
643
+ continue
644
+ hidden = {str(k) for k in (entry.get("hiddenFields") or ()) if k}
645
+ if not hidden:
646
+ continue
647
+ try:
648
+ hidden |= set(perm_scope._measure_bound_keys(hidden, field_list))
649
+ except Exception: # noqa: BLE001
650
+ pass
651
+ for key in defs:
652
+ if key in hidden:
653
+ walled.setdefault(key, []).append(display)
654
+ return walled
655
+
656
+
657
+ #: ⭐ THE THREE REASONS A VIEW'S COLUMN IS NOT GRANTED, EACH ITS OWN CODE. One fused
658
+ #: "could not share" would make the three walls unprovable apart, which is the
659
+ #: [[a-declared-gate-is-an-unchecked-claim]] failure `verify_field_doors` section 8 exists to
660
+ #: prevent: every cause fails by its own name, or it is not gated at all.
661
+ #: ⛔ STANDING RULE 2 — no em dash and no en dash in any sentence below; these reach a screen.
662
+ FIELD_REFUSAL_CODES = ("not_a_shared_column", "not_owned", "admin_hidden")
663
+
664
+ #: ⭐ TRAP 1, SAID OUT LOUD. A column grant is keyed by DATABASE, so it is not scoped to the view
665
+ #: that occasioned it. The response carries this sentence rather than letting a caller infer a
666
+ #: narrower promise than the store actually makes.
667
+ FIELD_GRANT_SCOPE = ("A column shared this way is shared on the whole database, so the people "
668
+ "you named can see it on every view of it, not only on this one.")
669
+
670
+
671
+ def _refusal(key, code, names=()):
672
+ """One refused column, with the sentence a person reads."""
673
+ if code == "not_a_shared_column":
674
+ why = ('"{k}" belongs to the database itself rather than to a person, so there was '
675
+ 'nothing to grant. Anybody who can open the database already sees it.')
676
+ elif code == "not_owned":
677
+ why = ('"{k}" is somebody else\'s column, and only its owner (or an administrator) can '
678
+ 'share it. Ask them to share it, then share this view again.')
679
+ else:
680
+ why = ('"{k}" is hidden from {who} by an administrator, so sharing it would change '
681
+ 'nothing. Ask an administrator to unhide it first.')
682
+ return {"field": key, "reason": code,
683
+ "message": why.format(k=key, who=_named(names) if names else "them")}
684
+
685
+
686
+ def _classify_view_fields(keys, owned, defined, walled):
687
+ """`(sharedFieldKeys, refusedFieldKeys)` for the columns a view names. PURE.
688
+
689
+ ⛔ EVERY KEY IS DECIDED BEFORE ANY OF THEM IS WRITTEN, which is the same property the ceiling
690
+ block above claims for the three role walls: a refusal must not be able to leave part of the
691
+ set promoted and part of it untouched.
692
+
693
+ ⚠ THE ORDER OF THE CAUSES IS FIXED AND IT DECIDES WHICH SENTENCE A PERSON READS. A built-in
694
+ column is owned by nobody, so "there was nothing to grant" has to be asked before "you do not
695
+ own it", or every database column in `visible` would be reported as somebody else's.
696
+ """
697
+ granted, refused = [], []
698
+ for key in keys:
699
+ if key not in defined:
700
+ refused.append(_refusal(key, "not_a_shared_column"))
701
+ elif key not in owned:
702
+ refused.append(_refusal(key, "not_owned"))
703
+ elif walled.get(key):
704
+ refused.append(_refusal(key, "admin_hidden", walled.get(key)))
705
+ else:
706
+ granted.append(key)
707
+ return granted, refused
708
+
709
+
710
+ def _merge_field_entries(existing, incoming):
711
+ """A column's grant list with `incoming` ADDED to it. Nobody is removed, nobody is lowered.
712
+
713
+ ⛔⛔ THE SHARE PUT REPLACES, AND A COLUMN'S AUDIENCE IS NOT THE VIEW'S AUDIENCE. This route's
714
+ contract is a REPLACING set (`PUT ... entries` at the top of the file), which is right for the
715
+ object the caller is looking at and catastrophic for the columns underneath it: a column grant
716
+ is TOPIC-WIDE, so handing the view's list straight to `set_grants` would rewrite the column's
717
+ audience to whoever this view happens to be shared with. A colleague granted that column
718
+ through the `field` door would lose it, on every view of the database, silently, inside a 200.
719
+ That is exactly the harm D-474 closed at the view door, arriving one door over.
720
+
721
+ ⚠ AND A LENGTH CHECK DOES NOT SEE IT. Replacing a one-person list with a different one-person
722
+ list keeps the count identical, so the gate asserts the HELD USER IS STILL THERE AT THEIR OWN
723
+ ROLE rather than counting rows.
724
+
725
+ ⭐ RAISED, NEVER LOWERED. A receiver already held at `view` who arrives on an `edit` share is
726
+ raised, because only the column's owner (or an administrator) reaches this path at all and
727
+ that is the access they just asked to hand over. An `edit` holder meeting a `view` share keeps
728
+ `edit`: a share is an addition, and nothing here is a revocation.
729
+
730
+ ⚠ `by` RIDES ON EXISTING ROWS AND IS NEVER TAKEN FROM AN INCOMING ONE. Provenance decides who
731
+ may revoke a grant (`_unremovable`), so an incoming payload must not be able to claim it;
732
+ `set_grants` stamps a genuinely new row from `granter`.
733
+ """
734
+ rank = {"view": 0, "edit": 1}
735
+ order, merged = [], {}
736
+ for row in (existing or ()):
737
+ if not isinstance(row, dict):
738
+ continue
739
+ who = str(row.get("user") or "").strip().lower()
740
+ role = str(row.get("role") or "").strip().lower()
741
+ if not who or role not in rank or who in merged:
742
+ continue
743
+ kept = {"user": who, "role": role}
744
+ stamp = str(row.get("by") or "").strip().lower()
745
+ if stamp:
746
+ kept["by"] = stamp
747
+ merged[who] = kept
748
+ order.append(who)
749
+ for row in (incoming or ()):
750
+ if not isinstance(row, dict):
751
+ continue
752
+ who = str(row.get("user") or "").strip().lower()
753
+ role = str(row.get("role") or "").strip().lower()
754
+ if not who or role not in rank:
755
+ continue
756
+ if who not in merged:
757
+ merged[who] = {"user": who, "role": role}
758
+ order.append(who)
759
+ elif rank[role] > rank[merged[who]["role"]]:
760
+ merged[who]["role"] = role
761
+ return [merged[who] for who in order]
762
+
763
+
764
+ def _share_view_fields(session, oid, entries):
765
+ """The `view` arm's field half: classify every column the view names, then grant the ones
766
+ that survive. `(sharedFieldKeys, refusedFieldKeys)`.
767
+
768
+ ⛔ CLASSIFY EVERYTHING, THEN WRITE. `_classify_view_fields` sees the whole key set before
769
+ `_promote_field_for_grant` touches a single definition, so a refusal cannot leave half the
770
+ view's columns promoted.
771
+
772
+ ⚠ THE VIEW'S OWN GRANT HAS ALREADY BEEN WRITTEN when this runs, and that order is the safe
773
+ one: a `409 grants_changed` on the view must not be preceded by a set of column promotions
774
+ for a share that then did not happen.
775
+ """
776
+ topic, view = _find_view_topic(session, oid)
777
+ if not topic or not isinstance(view, dict):
778
+ return [], []
779
+ keys = _view_field_keys(view)
780
+ if not keys:
781
+ return [], []
782
+ table_key = f"{topic}_table_workspace"
783
+ grant_topic = _field_storage_keys(table_key)[2]
784
+ defs, defined, owned, owners = {}, set(), set(), {}
785
+ for key in keys:
786
+ defn, already_shared = _field_definition(session, table_key, key)[:2]
787
+ if not isinstance(defn, dict):
788
+ continue
789
+ defs[key] = defn
790
+ defined.add(key)
791
+ # ⚠ THE COLUMN'S OWNER, NOT THIS SESSION. `set_grants`' owner is sticky, so stamping the
792
+ # SHARER here would hand an administrator sharing somebody else's column the ownership
793
+ # of it as a side effect of sharing a view. Same resolver the claim wall uses.
794
+ owners[key] = _field_owner(session, defn, already_shared)
795
+ # ⛔ ONE OWNERSHIP PREDICATE. `_owns_object` is the wall the `field` arm claims through
796
+ # and the DELETE door reads; a second "does this person own this column" here is how the
797
+ # two answers come apart. It short circuits True for an administrator, which is right:
798
+ # an administrator may already share any column through the `field` door.
799
+ if _owns_object(session, "field", shares.field_oid(grant_topic, key)):
800
+ owned.add(key)
801
+ walled = _admin_walled(session, grant_topic, defs, _grant_receivers(session, entries))
802
+ granted, refused = _classify_view_fields(keys, owned, defined, walled)
803
+ written = []
804
+ for key in granted:
805
+ field_oid = _promote_field_for_grant(session, table_key, key)
806
+ if not field_oid:
807
+ refused.append(_refusal(key, "not_a_shared_column"))
808
+ continue
809
+ # ⛔⛔ ADDED TO, NEVER REPLACED. `set_grants` writes the list it is given, and this route
810
+ # PUTs a REPLACING set, so handing it the view's `entries` would make the view's audience
811
+ # the COLUMN's audience: a colleague granted this column through the `field` door would
812
+ # lose it, on every view of the database, inside a 200. `_merge_field_entries` says what
813
+ # that sentence means once, and it is the only writer of a column list on this path.
814
+ held = shares.grants("field", field_oid, st=session.runtime)
815
+ # ⚠ NO `expect` HERE, AND THAT IS NOT AN OVERSIGHT. The compare-and-set on the view's own
816
+ # grant guards a record TWO PEOPLE ARE EDITING through the same dialog. A column's record
817
+ # was just read (and possibly created) inside this call, nobody is looking at it in a
818
+ # dialog, and a `409` raised at this point would fail a PUT whose view grant has ALREADY
819
+ # been written, which is the half-applied state the refusals above exist to avoid.
820
+ shares.set_grants("field", field_oid,
821
+ _merge_field_entries(held.get("entries"), entries),
822
+ owner=held.get("owner") or owners.get(key) or session.uname,
823
+ granter=session.uname, st=session.runtime)
824
+ written.append(key)
825
+ return written, refused
826
+
827
 
828
  @router.get("/share/mine")
829
  def my_shares(session: Session = Depends(require_session)):
 
1071
  # A field grant is a visibility and edit wall. Promote a private custom
1072
  # field exactly once, then keep the requested Share field role as the
1073
  # authoritative override for the legacy permissions bag.
1074
+ # ⭐⭐ W42-T25 — THE SEQUENCE MOVED INTO `_promote_field_for_grant` AND DID NOT CHANGE.
1075
+ # The `view` arm below now hands columns to people as well, and one function answering
1076
+ # "promote, stamp, key the oid" is what keeps the two arms writing the SAME oid for the
1077
+ # same column. `None` here still means the column does not exist on that database.
1078
  table_key, field_key = shares.split_field_oid(oid)
1079
+ promoted = _promote_field_for_grant(session, table_key, field_key)
1080
+ if promoted is None:
 
1081
  raise err(404, "no_object", "no such field, or it is not shared with this account")
1082
+ oid = promoted
 
 
 
 
 
 
 
 
1083
  # ⭐⭐ R4 / W40-T02 (D3) — OWNERSHIP NEVER MOVES ON A RE-SHARE, AND IT IS SAID HERE RATHER
1084
  # THAN LEFT TO FALL OUT. `set_grants`' owner is sticky, so the old `rec["owner"] or
1085
  # session.uname` already happened not to transfer ownership — incidentally, as a property of
 
1109
  except shares.GrantsChanged as exc:
1110
  raise err(409, "grants_changed", str(exc))
1111
  _notify_new_grantees(session, kind, oid, before=rec["entries"], after=out.get("entries") or [])
1112
+ # ⭐⭐ W42-T25 — SHARING A VIEW SHARES THE FIELDS IT NAMES. A view is a selection expressed
1113
+ # in columns, so a grant that carries the view and none of its columns puts a rail row on
1114
+ # the receiver's screen over an empty grid. The three refusals are named rather than thrown:
1115
+ # this PUT succeeded, the view IS shared, and what could not follow it is reported by name
1116
+ # with the reason. Throwing instead would make the ordinary case (a view over one built-in
1117
+ # column) unshareable.
1118
+ # ⛔ THE EXISTING KEYS ARE UNTOUCHED. `{owner, entries}` is what every current client reads
1119
+ # off this route; the field report is additive, and a caller that ignores it is unaffected.
1120
+ if kind == "view":
1121
+ shared_fields, refused_fields = _share_view_fields(session, oid, entries)
1122
+ return {**out,
1123
+ "sharedFieldKeys": shared_fields,
1124
+ "refusedFieldKeys": refused_fields,
1125
+ "sharedFieldScope": FIELD_GRANT_SCOPE}
1126
  return out
1127
 
1128
 
api/routes_tables.py CHANGED
@@ -52,6 +52,38 @@ def _ut():
52
  return user_tables
53
 
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  def _ops(session, table_key, st=None):
56
  """This database's per-user workspace store, bound to the tenant.
57
 
@@ -800,7 +832,19 @@ def _ut_hidden(session, table_key, fields, st=None):
800
  return perm_scope.hidden_keys(session.user, table_key, fields, st=st)
801
 
802
 
803
- def _ut_shared_fields(session, table_key, fields):
 
 
 
 
 
 
 
 
 
 
 
 
804
  """`fields` PLUS this database's TENANT-WIDE columns — the read-side merge, W38-T16.
805
 
806
  ⛔⛔ WHY THIS DID NOT EXIST AND WHY THAT WAS A HOLE. `patch_shared_cell` has written into
@@ -817,12 +861,15 @@ def _ut_shared_fields(session, table_key, fields):
817
  contract, never a redefinition of a column that database already has.
818
  """
819
  from core import field_permissions, shared_overlay
 
 
820
  field_permissions.migrate_legacy_fields(
821
  f"{table_key}_table_workspace", st=session.runtime,
822
- grant_topic=table_key, shared_key=table_key)
823
- defs = shared_overlay.fields(table_key, st=session.runtime) or {}
 
824
  if not defs:
825
- return fields
826
  have = {f.get("key") for f in (fields or ()) if isinstance(f, dict)}
827
  from core import shares
828
  projected = []
@@ -836,7 +883,8 @@ def _ut_shared_fields(session, table_key, fields):
836
  if role:
837
  item["sharedRole"] = role
838
  projected.append(item)
839
- return list(fields or ()) + projected
 
840
 
841
 
842
  def _ut_shared_cells(session, table_key, pids):
@@ -1050,7 +1098,7 @@ def _usage_column_refs(field):
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
 
@@ -1099,18 +1147,16 @@ def _field_usage(session, table_key, fields, defn, ops, st=None):
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:
@@ -1254,7 +1300,8 @@ def ut_assembly(session: Session, table_key: str, storage_key: str = "",
1254
  st=session.runtime,
1255
  scope_key=table_key, table=ops)
1256
  ws = grid_events.table_workspace(ctx, allowed_pids=pids,
1257
- consume_corrections=consume_corrections)
 
1258
  workspace, fields, views, lists = aios_grid.workspace_wire(
1259
  ws, session.uname, set(pids), defs={}, scope_key=table_key,
1260
  storage_key=storage_key, fields_base=fields_base, st=session.runtime)
@@ -1262,7 +1309,9 @@ def ut_assembly(session: Session, table_key: str, storage_key: str = "",
1262
  # `workspace_wire` and the wall, which is `routes_odoo_tables`' own position for the same two
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")
@@ -1306,13 +1355,30 @@ def ut_assembly(session: Session, table_key: str, storage_key: str = "",
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
@@ -1339,10 +1405,8 @@ def ut_assembly(session: Session, table_key: str, storage_key: str = "",
1339
  shared_cells = _ut_shared_cells(session, table_key, pids) if with_rows else {}
1340
  # ⭐⭐ W36-T21 / R6 — the READ half, in `grid_assembly`'s own position: after `workspace_wire`,
1341
  # so the closure covers this user's `custom_` and `measure_` columns too.
 
1342
  fields, rows_src, hidden = _ut_field_wall(session, table_key, fields, rows_src, st=st)
1343
- # The canonical Zone field is derived from the same table-scoped store as the map DTO, so
1344
- # FilterBuilder and saved Views use their ordinary multiselect path rather than a map-only one.
1345
- fields = _ut().with_zone_field(table_key, fields, st=st)
1346
  if hidden and shared_cells:
1347
  # ⛔ BOTH WIRES, AND THE SHARED STRATUM IS A THIRD ONE. `strip_row` above cleaned the
1348
  # DEFINITION rows; these cells arrived by a different door and one narrowing cannot speak
@@ -1688,6 +1752,18 @@ def list_tables(brief: bool = Query(False),
1688
  # picker renders this order verbatim.
1689
  out.extend(_module_link_targets(session, meta, st=lent))
1690
  out.sort(key=lambda r: (r.get("label") or "").lower())
 
 
 
 
 
 
 
 
 
 
 
 
1691
  return {"tables": out}
1692
 
1693
 
@@ -1837,6 +1913,15 @@ def create_table(body: dict = Body(default=None),
1837
  if not session.runtime.available():
1838
  raise err(503, "store_unavailable",
1839
  "the tenant store is unavailable. Nothing was created")
 
 
 
 
 
 
 
 
 
1840
  source = body.get("source")
1841
  try:
1842
  key = ut.create(label, session.uname, fields=body.get("fields"),
@@ -1862,6 +1947,7 @@ def patch_table(table_key: str, body: dict = Body(default=None),
1862
  picker that is confidently wrong rather than obviously stale. Posted to the wave doc as an
1863
  amendment for whoever owns that door.
1864
  """
 
1865
  defn = _defn_or_refuse(session, table_key)
1866
  ut = _ut()
1867
  if not (session.admin or defn.get("createdBy") == session.uname):
@@ -1935,6 +2021,7 @@ def delete_table(table_key: str, session: Session = Depends(require_session)):
1935
  DISABLES bound automations with a status note — never deletes them. The client's confirm
1936
  dialog disclosed `/footprint` first; the server cannot tell a click from a plan, so the
1937
  dialog is a product requirement, not a formality."""
 
1938
  defn = _defn_or_refuse(session, table_key)
1939
  if not (session.admin or defn.get("createdBy") == session.uname):
1940
  raise err(403, "forbidden", "only the database's creator or an admin can delete it")
@@ -2137,7 +2224,7 @@ def table_rows(table_key: str, session: Session = Depends(require_session)):
2137
  _zones = [dict(zone, memberships=[pid for pid in zone.get("memberships", [])
2138
  if str(pid) in _zone_pids])
2139
  for zone in _ut().zones(table_key, st=_lent)]
2140
- return {"fields": g["fields"], "rows": rows, "today": g["today"],
2141
  "zones": _zones,
2142
  "docs": _ge.docs_for(g["pids"], scope_key=table_key, uname=session.uname,
2143
  admin=session.admin, st=session.runtime),
@@ -2227,6 +2314,7 @@ def add_row(table_key: str, body: dict = Body(default=None),
2227
  that requested `rid: 7` and got 12 because 7 had been re-used must find that out from the
2228
  response rather than assume; the client re-anchors on what came back.
2229
  """
 
2230
  _records_or_refuse(session, table_key)
2231
  ut = _ut()
2232
  values = (body or {}).get("values") or {}
@@ -2274,6 +2362,7 @@ def import_rows(table_key: str, body: dict = Body(default=None),
2274
  profile cell validates, because a half-imported file is the worst outcome available: the user
2275
  cannot tell which rows landed without reconciling the spreadsheet by hand.
2276
  """
 
2277
  _records_or_refuse(session, table_key)
2278
  ut = _ut()
2279
  rows_in = (body or {}).get("rows")
@@ -2377,6 +2466,7 @@ def _field_or_refuse(session, table_key, fkey=""):
2377
  @router.post("/tables/{table_key}/fields", status_code=201)
2378
  def add_field(table_key: str, body: dict = Body(default=None),
2379
  session: Session = Depends(require_session)):
 
2380
  _field_or_refuse(session, table_key)
2381
  ut = _ut()
2382
  field = ut.add_field(table_key, body or {}, st=session.runtime)
@@ -2444,6 +2534,9 @@ def _refusal_sentence(ut, session, body, table_key="", fkey=""):
2444
  # column would otherwise be explained by the flow law -- "pick a flow, or make this an
2445
  # ordinary column" -- which is the D-46 misdirection exactly, pointing at a control the user
2446
  # never touched.
 
 
 
2447
  if str((body or {}).get("type") or "").strip().lower() == "ai_enrich":
2448
  bag = (body or {}).get("aiEnrich")
2449
  if not isinstance(bag, dict) or not str(bag.get("prompt") or "").strip():
@@ -2495,9 +2588,12 @@ def patch_field(table_key: str, fkey: str, body: dict = Body(default=None),
2495
  Blue to Navy" from "deleted Blue, added Navy" — and guessing wrong empties the column and
2496
  every saved view that filtered on it.
2497
  """
 
2498
  _field_or_refuse(session, table_key, fkey)
2499
  ut = _ut()
2500
  body = body or {}
 
 
2501
  migrated = None
2502
  renames = body.get("renames")
2503
  if renames:
@@ -2620,6 +2716,7 @@ def enrich_field(table_key: str, fkey: str, body: dict = Body(default=None),
2620
 
2621
  @router.delete("/tables/{table_key}/fields/{fkey}")
2622
  def delete_field(table_key: str, fkey: str, session: Session = Depends(require_session)):
 
2623
  _field_or_refuse(session, table_key, fkey)
2624
  if not _ut().delete_field(table_key, fkey, st=session.runtime):
2625
  raise err(400, "refused",
@@ -2628,6 +2725,108 @@ def delete_field(table_key: str, fkey: str, session: Session = Depends(require_s
2628
  return {"deleted": fkey}
2629
 
2630
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2631
  @router.delete("/tables/{table_key}/rows/{rid}")
2632
  def delete_row(table_key: str, rid: str, session: Session = Depends(require_session)):
2633
  # ⭐⭐ W31 QA — ONE SNAPSHOT FOR THE WHOLE DELETE, and the owner reported what it cost.
@@ -2643,6 +2842,7 @@ def delete_row(table_key: str, rid: str, session: Session = Depends(require_sess
2643
  # ⚠ `flush='sync'` IS DELIBERATELY UNTOUCHED (D-118): nobody spams a delete, and an eventually
2644
  # consistent delete is indistinguishable from one that did not work. This makes the guard
2645
  # cheap; it does not make the commit optimistic.
 
2646
  lent = _ut().lend(session.runtime)
2647
  _records_or_refuse(session, table_key, st=lent)
2648
  # ⭐⭐ W36-T21 — THE ROW SCOPE, ON THE DELETE DOOR. `patch_row` has asked this since it was
@@ -2678,6 +2878,7 @@ def patch_row(table_key: str, pid: int, body: dict = Body(default=None),
2678
  updates = dict(body or {})
2679
  if not updates:
2680
  raise err(400, "empty_patch", "no fields to update")
 
2681
  _records_or_refuse(session, table_key)
2682
  g = ut_assembly(session, table_key, consume_corrections=False)
2683
  if pid not in g["pids"]:
 
52
  return user_tables
53
 
54
 
55
+ def _managed_or_refuse(session, table_key, *, mutation=False):
56
+ """C1 generic-door policy. Dedicated Route/Zone handlers use their own capability."""
57
+ from core import route_system
58
+ definition = _ut().get(table_key, st=session.runtime)
59
+ # Route/Zone are virtual system descriptors until their first dedicated write, so looking
60
+ # only in `user_tables` would leave a generic mutation path open during that empty state.
61
+ managed = route_system.descriptor(table_key)
62
+ if managed is not None:
63
+ if mutation:
64
+ raise err(403, "loopable_managed", "Loopable system databases can only be changed from Route or Zone tools")
65
+ return managed
66
+ if definition and (_ut().is_managed_system_table(table_key, st=session.runtime, definition=definition)
67
+ or route_system.is_managed(definition)):
68
+ if mutation:
69
+ raise err(403, "loopable_managed", "Loopable system databases can only be changed from Route or Zone tools")
70
+ return definition
71
+ return definition
72
+
73
+
74
+ def _field_axes(fields):
75
+ """C3 wire projection; the four axes are explicit on every server field payload."""
76
+ from core import route_system
77
+ out = []
78
+ for field in fields or ():
79
+ try:
80
+ out.append(route_system.field_axes(field))
81
+ except ValueError:
82
+ # Stored historical fields may not invent a new vocabulary just by being read.
83
+ raise err(500, "invalid_field_contract", "stored field has an unapproved field axis")
84
+ return out
85
+
86
+
87
  def _ops(session, table_key, st=None):
88
  """This database's per-user workspace store, bound to the tenant.
89
 
 
832
  return perm_scope.hidden_keys(session.user, table_key, fields, st=st)
833
 
834
 
835
+ def _ut_contract_fields(table_key, fields, st=None):
836
+ """The base contract every `ut_*` read door presents before its field wall.
837
+
838
+ Zone is a real derived field, not a map-only decoration: saved filters and views address its
839
+ canonical key. It therefore joins the contract before the one field-wall evaluator runs.
840
+ Keeping this boundary named prevents `/nav/schema` and the grid from attaching it on
841
+ opposite sides of that wall.
842
+ """
843
+ return _ut().with_zone_field(table_key, fields, st=st)
844
+
845
+
846
+ def _ut_shared_fields(session, table_key, fields, workspace_document=None,
847
+ shared_document=None, return_document=False):
848
  """`fields` PLUS this database's TENANT-WIDE columns — the read-side merge, W38-T16.
849
 
850
  ⛔⛔ WHY THIS DID NOT EXIST AND WHY THAT WAS A HOLE. `patch_shared_cell` has written into
 
861
  contract, never a redefinition of a column that database already has.
862
  """
863
  from core import field_permissions, shared_overlay
864
+ document = (shared_document if isinstance(shared_document, dict)
865
+ else shared_overlay.document(table_key, st=session.runtime))
866
  field_permissions.migrate_legacy_fields(
867
  f"{table_key}_table_workspace", st=session.runtime,
868
+ grant_topic=table_key, shared_key=table_key,
869
+ workspace_document=workspace_document, shared_document=document)
870
+ defs = shared_overlay.fields(table_key, st=session.runtime, document=document) or {}
871
  if not defs:
872
+ return (fields, document) if return_document else fields
873
  have = {f.get("key") for f in (fields or ()) if isinstance(f, dict)}
874
  from core import shares
875
  projected = []
 
883
  if role:
884
  item["sharedRole"] = role
885
  projected.append(item)
886
+ merged = list(fields or ()) + projected
887
+ return (merged, document) if return_document else merged
888
 
889
 
890
  def _ut_shared_cells(session, table_key, pids):
 
1098
  return rollup, automation
1099
 
1100
 
1101
+ def _field_usage(session, table_key, fields, defn, ws_st, ws_key, st=None):
1102
  """`{field_key: {views, filters, rollups, automations, permRules}}` — C8's `usage`, computed
1103
  over the WHOLE workspace, or `{}` when it cannot be established.
1104
 
 
1147
  return {}
1148
  lent = st if st is not None else session.runtime
1149
  memo_key = (str(getattr(session, "tenant", "") or ""), str(table_key))
1150
+ token = _usage_token(lent, ws_key)
1151
  if token is not None:
1152
  hit = _USAGE_MEMO.get(memo_key)
1153
  if hit and hit[0] == token:
1154
  return hit[1]
1155
  try:
1156
+ # The caller lends either its already-captured whole workspace document or the exact store
1157
+ # handle plus key that produced it. Customer's document is `customer_table_workspace`,
1158
+ # which cannot be reconstructed from its topic name `customer_data`.
1159
+ ws_doc = (ws_st if isinstance(ws_st, dict) else (ws_st.get(ws_key) or {}))
 
 
1160
  except Exception: # noqa: BLE001
1161
  return {}
1162
  try:
 
1300
  st=session.runtime,
1301
  scope_key=table_key, table=ops)
1302
  ws = grid_events.table_workspace(ctx, allowed_pids=pids,
1303
+ consume_corrections=consume_corrections,
1304
+ capture_document=True)
1305
  workspace, fields, views, lists = aios_grid.workspace_wire(
1306
  ws, session.uname, set(pids), defs={}, scope_key=table_key,
1307
  storage_key=storage_key, fields_base=fields_base, st=session.runtime)
 
1309
  # `workspace_wire` and the wall, which is `routes_odoo_tables`' own position for the same two
1310
  # lines and for the same reason: the closure must be recomputed on the MERGED contract or a
1311
  # formula in a shared column reaches past it.
1312
+ fields, _shared_document = _ut_shared_fields(
1313
+ session, table_key, fields,
1314
+ workspace_document=getattr(ctx, "workspace_document", None), return_document=True)
1315
  # W43C C2: store compact recurrence configuration, then derive next/preview under the
1316
  # request's server day only after every field stratum is merged.
1317
  _recurrence_today = time.strftime("%Y-%m-%d")
 
1355
  # ⚠ A COPY OF THE BAG, because `_field_usage` MEMOISES its answer: handing the memo's own dict
1356
  # out would let anything downstream write into the number the next request reads.
1357
  try:
1358
+ _usage_source = getattr(ctx, "workspace_document", None)
1359
+ if not isinstance(_usage_source, dict):
1360
+ _usage_source = ops.st
1361
+ _usage = _field_usage(session, table_key, fields, defn,
1362
+ _usage_source, ops.table_key, st=st)
1363
  except Exception: # noqa: BLE001
1364
  _usage = {}
1365
  if _usage:
1366
  fields = [dict(f, usage=dict(_usage[f["key"]]))
1367
  if isinstance(f, dict) and _usage.get(f.get("key")) else f
1368
  for f in fields]
1369
+ # C4 parity: user databases carry the same field-class badges as topic grids. The batch
1370
+ # producer reads the grant registry once and the shared-value stratum once for the full list.
1371
+ try:
1372
+ from core import field_permissions as _fp
1373
+ _classes = _fp.field_classes(
1374
+ fields, session.uname, table_key=table_key, grant_topic=table_key,
1375
+ values_shared=((_shared_document.get("fields") or {}).keys()
1376
+ if isinstance(_shared_document, dict) else ()), st=st)
1377
+ fields = [dict(f, **{"class": _classes[f["key"]]})
1378
+ if isinstance(f, dict) and _classes.get(f.get("key")) else f
1379
+ for f in fields]
1380
+ except Exception: # noqa: BLE001
1381
+ pass
1382
  # ⭐⭐ C8's `descriptionEdited`, AND IT CLOSES A CONSUMER THAT WAS ALREADY WRITTEN.
1383
  # W41-T11 built the producer (`user_tables.description_edited`, R19's custody mark scoped to the
1384
  # description) and correctly stopped at its own fence, which is one core file. Measured across
 
1405
  shared_cells = _ut_shared_cells(session, table_key, pids) if with_rows else {}
1406
  # ⭐⭐ W36-T21 / R6 — the READ half, in `grid_assembly`'s own position: after `workspace_wire`,
1407
  # so the closure covers this user's `custom_` and `measure_` columns too.
1408
+ fields = _ut_contract_fields(table_key, fields, st=st)
1409
  fields, rows_src, hidden = _ut_field_wall(session, table_key, fields, rows_src, st=st)
 
 
 
1410
  if hidden and shared_cells:
1411
  # ⛔ BOTH WIRES, AND THE SHARED STRATUM IS A THIRD ONE. `strip_row` above cleaned the
1412
  # DEFINITION rows; these cells arrived by a different door and one narrowing cannot speak
 
1752
  # picker renders this order verbatim.
1753
  out.extend(_module_link_targets(session, meta, st=lent))
1754
  out.sort(key=lambda r: (r.get("label") or "").lower())
1755
+ else:
1756
+ # C1's Loopable folder has virtual descriptor rows even before the first Route/Zone
1757
+ # exists. They deliberately do NOT enter `brief=1`: stops are a protected relation,
1758
+ # never a generic Link target.
1759
+ try:
1760
+ session.require("customer_data")
1761
+ except Exception:
1762
+ pass
1763
+ else:
1764
+ from core import route_system
1765
+ out.extend(route_system.system_table_descriptors())
1766
+ out.sort(key=lambda r: (r.get("label") or "").lower())
1767
  return {"tables": out}
1768
 
1769
 
 
1913
  if not session.runtime.available():
1914
  raise err(503, "store_unavailable",
1915
  "the tenant store is unavailable. Nothing was created")
1916
+ # C8b: table creation is the bulk field-definition door. `clean_fields` deliberately drops
1917
+ # one invalid field while preserving valid siblings, so the route must narrate an over-cap
1918
+ # option list before that validator runs; otherwise the whole column disappears under 201.
1919
+ for raw_field in (body.get("fields") or []):
1920
+ if not isinstance(raw_field, dict):
1921
+ continue
1922
+ option_refusal = ut.option_cap_refusal(raw_field.get("options"))
1923
+ if option_refusal:
1924
+ raise err(400, "refused", option_refusal)
1925
  source = body.get("source")
1926
  try:
1927
  key = ut.create(label, session.uname, fields=body.get("fields"),
 
1947
  picker that is confidently wrong rather than obviously stale. Posted to the wave doc as an
1948
  amendment for whoever owns that door.
1949
  """
1950
+ _managed_or_refuse(session, table_key, mutation=True)
1951
  defn = _defn_or_refuse(session, table_key)
1952
  ut = _ut()
1953
  if not (session.admin or defn.get("createdBy") == session.uname):
 
2021
  DISABLES bound automations with a status note — never deletes them. The client's confirm
2022
  dialog disclosed `/footprint` first; the server cannot tell a click from a plan, so the
2023
  dialog is a product requirement, not a formality."""
2024
+ _managed_or_refuse(session, table_key, mutation=True)
2025
  defn = _defn_or_refuse(session, table_key)
2026
  if not (session.admin or defn.get("createdBy") == session.uname):
2027
  raise err(403, "forbidden", "only the database's creator or an admin can delete it")
 
2224
  _zones = [dict(zone, memberships=[pid for pid in zone.get("memberships", [])
2225
  if str(pid) in _zone_pids])
2226
  for zone in _ut().zones(table_key, st=_lent)]
2227
+ return {"fields": _field_axes(g["fields"]), "rows": rows, "today": g["today"],
2228
  "zones": _zones,
2229
  "docs": _ge.docs_for(g["pids"], scope_key=table_key, uname=session.uname,
2230
  admin=session.admin, st=session.runtime),
 
2314
  that requested `rid: 7` and got 12 because 7 had been re-used must find that out from the
2315
  response rather than assume; the client re-anchors on what came back.
2316
  """
2317
+ _managed_or_refuse(session, table_key, mutation=True)
2318
  _records_or_refuse(session, table_key)
2319
  ut = _ut()
2320
  values = (body or {}).get("values") or {}
 
2362
  profile cell validates, because a half-imported file is the worst outcome available: the user
2363
  cannot tell which rows landed without reconciling the spreadsheet by hand.
2364
  """
2365
+ _managed_or_refuse(session, table_key, mutation=True)
2366
  _records_or_refuse(session, table_key)
2367
  ut = _ut()
2368
  rows_in = (body or {}).get("rows")
 
2466
  @router.post("/tables/{table_key}/fields", status_code=201)
2467
  def add_field(table_key: str, body: dict = Body(default=None),
2468
  session: Session = Depends(require_session)):
2469
+ _managed_or_refuse(session, table_key, mutation=True)
2470
  _field_or_refuse(session, table_key)
2471
  ut = _ut()
2472
  field = ut.add_field(table_key, body or {}, st=session.runtime)
 
2534
  # column would otherwise be explained by the flow law -- "pick a flow, or make this an
2535
  # ordinary column" -- which is the D-46 misdirection exactly, pointing at a control the user
2536
  # never touched.
2537
+ option_refusal = ut.option_cap_refusal((body or {}).get("options"))
2538
+ if option_refusal:
2539
+ return option_refusal
2540
  if str((body or {}).get("type") or "").strip().lower() == "ai_enrich":
2541
  bag = (body or {}).get("aiEnrich")
2542
  if not isinstance(bag, dict) or not str(bag.get("prompt") or "").strip():
 
2588
  Blue to Navy" from "deleted Blue, added Navy" — and guessing wrong empties the column and
2589
  every saved view that filtered on it.
2590
  """
2591
+ _managed_or_refuse(session, table_key, mutation=True)
2592
  _field_or_refuse(session, table_key, fkey)
2593
  ut = _ut()
2594
  body = body or {}
2595
+ if 'deletionLocked' in body and not session.admin:
2596
+ raise err(403, "owner_required", "only an Owner can change a field deletion lock")
2597
  migrated = None
2598
  renames = body.get("renames")
2599
  if renames:
 
2716
 
2717
  @router.delete("/tables/{table_key}/fields/{fkey}")
2718
  def delete_field(table_key: str, fkey: str, session: Session = Depends(require_session)):
2719
+ _managed_or_refuse(session, table_key, mutation=True)
2720
  _field_or_refuse(session, table_key, fkey)
2721
  if not _ut().delete_field(table_key, fkey, st=session.runtime):
2722
  raise err(400, "refused",
 
2725
  return {"deleted": fkey}
2726
 
2727
 
2728
+ _BULK_DELETE_SENTENCES = {
2729
+ "unknown_field": ("that column is not on this database. It may already have been removed, "
2730
+ "so reload and check before trying again"),
2731
+ "field_hidden": "this database has no column by that name that you may remove",
2732
+ "last_field": ("a database must keep at least one column, so this one cannot be removed. "
2733
+ "Add another column first, then remove this one"),
2734
+ "delete_failed": "that column could not be removed. Reload the database and try again",
2735
+ }
2736
+
2737
+
2738
+ def _bulk_delete_refusal(key, code):
2739
+ return {"key": key, "status": "refused", "code": code,
2740
+ "reason": _BULK_DELETE_SENTENCES.get(code, _BULK_DELETE_SENTENCES["delete_failed"])}
2741
+
2742
+
2743
+ def _contract_holds_field(ut, table_key, fkey, st):
2744
+ fields = (ut.get(table_key, st=st) or {}).get("fields") or []
2745
+ return any(isinstance(field, dict) and str(field.get("key")) == str(fkey)
2746
+ for field in fields)
2747
+
2748
+
2749
+ @router.post("/tables/{table_key}/fields/delete")
2750
+ @router.delete("/tables/{table_key}/fields")
2751
+ def delete_fields(table_key: str, body: dict = Body(default=None),
2752
+ session: Session = Depends(require_session)):
2753
+ """Delete N schema fields once and return one explicit verdict for every requested key."""
2754
+ # Preserve W44's managed-database lifecycle wall on the plural door too.
2755
+ _managed_or_refuse(session, table_key, mutation=True)
2756
+ defn = _defn_or_refuse(session, table_key, scope_applied=True)
2757
+ ut = _ut()
2758
+ if not ut.is_user_table(table_key, st=session.runtime):
2759
+ raise err(400, "not_a_user_table",
2760
+ "only a user-created database has an editable schema. A connected source "
2761
+ "owns its own columns")
2762
+ raw = (body or {}).get("keys")
2763
+ if not isinstance(raw, list):
2764
+ raise err(400, "bad_keys", "send `keys`, the list of columns to remove")
2765
+ ordered = []
2766
+ for candidate in raw:
2767
+ key = str(candidate or "").strip()
2768
+ if key and key not in ordered:
2769
+ ordered.append(key)
2770
+ if not ordered:
2771
+ raise err(400, "bad_keys", "name at least one column to remove")
2772
+
2773
+ from core import field_permissions, shared_overlay
2774
+ declared = [field for field in (defn.get("fields") or []) if isinstance(field, dict)]
2775
+ contract_keys = {str(field.get("key")) for field in declared}
2776
+ hidden = _ut_hidden(session, table_key, declared)
2777
+ bucket_read = True
2778
+ try:
2779
+ shared_defs = shared_overlay.fields(table_key, st=session.runtime) or {}
2780
+ except Exception: # noqa: BLE001
2781
+ shared_defs, bucket_read = {}, False
2782
+
2783
+ results = []
2784
+ landed = []
2785
+ for key in ordered:
2786
+ field = next((item for item in declared if str(item.get("key")) == key), None)
2787
+ if field is None and isinstance(shared_defs.get(key), dict):
2788
+ field = shared_defs[key]
2789
+ if field is None:
2790
+ results.append(_bulk_delete_refusal(
2791
+ key, "unknown_field" if bucket_read else "delete_failed"))
2792
+ continue
2793
+ if key in hidden:
2794
+ results.append(_bulk_delete_refusal(key, "field_hidden"))
2795
+ continue
2796
+ refusal = ut.delete_field_refusal(
2797
+ table_key, key, session.uname, session.admin, session.runtime,
2798
+ field=field, grant_topic=table_key)
2799
+ if refusal is not None:
2800
+ results.append({"key": key, "status": "refused", "code": refusal,
2801
+ "reason": _delete_field_sentence(
2802
+ refusal, str(field.get("createdBy") or ""))})
2803
+ continue
2804
+ try:
2805
+ dropped = False
2806
+ if key in contract_keys:
2807
+ dropped = bool(ut.delete_field(table_key, key, st=session.runtime))
2808
+ if not dropped and _contract_holds_field(ut, table_key, key, session.runtime):
2809
+ results.append(_bulk_delete_refusal(key, "last_field"))
2810
+ continue
2811
+ removed = field_permissions.delete_field_everywhere(
2812
+ f"{table_key}_table_workspace", table_key, table_key, key,
2813
+ st=session.runtime)
2814
+ except Exception: # noqa: BLE001
2815
+ results.append(_bulk_delete_refusal(key, "delete_failed"))
2816
+ continue
2817
+ if not (dropped or removed.get("shared") or removed.get("personal")):
2818
+ results.append(_bulk_delete_refusal(key, "delete_failed"))
2819
+ continue
2820
+ landed.append(key)
2821
+ results.append({"key": key, "status": "deleted", "contract": dropped,
2822
+ "removed": removed})
2823
+
2824
+ if landed:
2825
+ _refresh_relations(session)
2826
+ return {"ok": True, "rerender": True, "results": results, "deleted": landed,
2827
+ "refused": [item["key"] for item in results if item["status"] == "refused"]}
2828
+
2829
+
2830
  @router.delete("/tables/{table_key}/rows/{rid}")
2831
  def delete_row(table_key: str, rid: str, session: Session = Depends(require_session)):
2832
  # ⭐⭐ W31 QA — ONE SNAPSHOT FOR THE WHOLE DELETE, and the owner reported what it cost.
 
2842
  # ⚠ `flush='sync'` IS DELIBERATELY UNTOUCHED (D-118): nobody spams a delete, and an eventually
2843
  # consistent delete is indistinguishable from one that did not work. This makes the guard
2844
  # cheap; it does not make the commit optimistic.
2845
+ _managed_or_refuse(session, table_key, mutation=True)
2846
  lent = _ut().lend(session.runtime)
2847
  _records_or_refuse(session, table_key, st=lent)
2848
  # ⭐⭐ W36-T21 — THE ROW SCOPE, ON THE DELETE DOOR. `patch_row` has asked this since it was
 
2878
  updates = dict(body or {})
2879
  if not updates:
2880
  raise err(400, "empty_patch", "no fields to update")
2881
+ _managed_or_refuse(session, table_key, mutation=True)
2882
  _records_or_refuse(session, table_key)
2883
  g = ut_assembly(session, table_key, consume_corrections=False)
2884
  if pid not in g["pids"]:
api/voice_control_plane.py ADDED
@@ -0,0 +1,745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Provider-neutral Voice records, redacted browser DTOs, and a no-dial harness.
2
+
3
+ Voice configuration is inert by construction. Browser drafts cannot carry credentials, raw
4
+ numbers, SIP/routing material, webhook controls, or raw provider payloads. Provider inventory is
5
+ reconciled only through :mod:`voice_provider_adapters`' injected GET-only seam. Ordinary
6
+ automation/webhook/schedule execution has no dispatch door here; a dry-run resolves a saved View,
7
+ records a normalized local event, and always reports ``noExternalDispatch: true``.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import copy
12
+ import hashlib
13
+ import re
14
+ import secrets
15
+ import time
16
+ from typing import Any, Callable
17
+
18
+ import voice_provider_adapters as adapters
19
+
20
+
21
+ STORE_KEY = "voice_control_plane"
22
+ SCHEMA_VERSION = 1
23
+ RECORD_TYPES = (
24
+ "voice_provider_connection",
25
+ "voice_agent",
26
+ "voice_number",
27
+ "voice_number_route",
28
+ "voice_knowledge_profile",
29
+ "voice_provider_sync",
30
+ "voice_outbound_lease",
31
+ "voice_provider_event",
32
+ )
33
+ SAFE_LIFECYCLES = frozenset({"draft", "needs_attention", "inactive"})
34
+ EMPTY_POLICIES = frozenset({"skip", "refuse"})
35
+ MAX_RECIPIENTS = 1000
36
+ MAX_LEASE_SECONDS = 300
37
+
38
+ _SENSITIVE_KEYS = frozenset({
39
+ "credential", "credentials", "secret", "secrets", "apikey", "api_key", "token",
40
+ "authorization", "sip", "sipcredential", "sipcredentials", "webhook", "webhookurl",
41
+ "rawnumber", "phonenumber", "phone_number", "e164", "inboundroute", "routing",
42
+ })
43
+ _PHONE = re.compile(r"\+?\d[\d .()\-]{5,}\d")
44
+ _ID = re.compile(r"^[a-z][a-z0-9_\-]{0,119}$")
45
+
46
+
47
+ class VoiceRefusal(ValueError):
48
+ """A request was structurally unsafe; its message is fit for the API client."""
49
+
50
+
51
+ def _text(value: Any, limit: int = 160) -> str:
52
+ return " ".join(str(value or "").split())[:limit]
53
+
54
+
55
+ def _now(value: Any = None) -> int:
56
+ try:
57
+ return int(value if value is not None else time.time())
58
+ except (TypeError, ValueError):
59
+ return int(time.time())
60
+
61
+
62
+ def _mint(prefix: str) -> str:
63
+ return f"{prefix}_{secrets.token_urlsafe(9)}"
64
+
65
+
66
+ def _empty_document() -> dict[str, Any]:
67
+ return {"schemaVersion": SCHEMA_VERSION, **{name: {} for name in RECORD_TYPES}}
68
+
69
+
70
+ def _normalise_document(raw: Any) -> dict[str, Any]:
71
+ """Read the v1 document and project the pre-v1 flat draft bucket without data loss."""
72
+ if isinstance(raw, dict) and raw.get("schemaVersion") == SCHEMA_VERSION:
73
+ doc = copy.deepcopy(raw)
74
+ for name in RECORD_TYPES:
75
+ if not isinstance(doc.get(name), dict):
76
+ doc[name] = {}
77
+ return doc
78
+ doc = _empty_document()
79
+ if not isinstance(raw, dict):
80
+ return doc
81
+ for key, legacy in raw.items():
82
+ if str(key).startswith("_") or not isinstance(legacy, dict):
83
+ continue
84
+ agent_id = str(legacy.get("id") or key)
85
+ if not agent_id:
86
+ continue
87
+ doc["voice_agent"][agent_id] = {
88
+ "id": agent_id,
89
+ "tenant_id": "",
90
+ "display_name": _text(legacy.get("displayName"), 120),
91
+ "lifecycle": str(legacy.get("activationState") or "draft"),
92
+ "provider_connection_id": "",
93
+ "external_agent_ref": "",
94
+ "direction_policy": ["inbound"] if legacy.get("callbackOnly", True)
95
+ else ["inbound", "outbound"],
96
+ "core_config": {
97
+ "purpose": _text(legacy.get("purpose"), 240),
98
+ "callbackPolicy": "callbacks_only" if legacy.get("callbackOnly", True) else "",
99
+ },
100
+ "provider_extension": {"provider": "retell", "version": 1,
101
+ "config": dict(legacy.get("supportedConfiguration") or {})},
102
+ "knowledge_profile_id": "",
103
+ "audience": _clean_audience({}),
104
+ "created_at": _now(legacy.get("createdAt")),
105
+ "updated_at": _now(legacy.get("updatedAt")),
106
+ }
107
+ return doc
108
+
109
+
110
+ def _store(rt: Any) -> dict[str, Any]:
111
+ try:
112
+ return _normalise_document(rt.get(STORE_KEY))
113
+ except Exception:
114
+ return _empty_document()
115
+
116
+
117
+ def _update(rt: Any, fn: Callable[[dict[str, Any]], dict[str, Any]]) -> Any:
118
+ def wrapped(raw: Any) -> dict[str, Any]:
119
+ return fn(_normalise_document(raw))
120
+ return rt.update(STORE_KEY, wrapped, flush="async")
121
+
122
+
123
+ def _reject_sensitive(value: Any) -> None:
124
+ if isinstance(value, dict):
125
+ for key, item in value.items():
126
+ norm = str(key).replace("-", "").lower()
127
+ if norm in _SENSITIVE_KEYS:
128
+ raise VoiceRefusal(
129
+ "Voice credentials, SIP, webhooks, routing, and raw phone controls are server-only")
130
+ _reject_sensitive(item)
131
+ elif isinstance(value, list):
132
+ for item in value:
133
+ _reject_sensitive(item)
134
+ elif isinstance(value, str) and _PHONE.search(value):
135
+ raise VoiceRefusal("raw phone numbers are not accepted by the browser Voice API")
136
+
137
+
138
+ def _safe_id(value: Any, label: str, allow_empty: bool = True) -> str:
139
+ result = str(value or "").strip()[:120]
140
+ if not result and allow_empty:
141
+ return ""
142
+ if not result or not _ID.fullmatch(result):
143
+ raise VoiceRefusal(f"{label} is not a valid Loopable reference")
144
+ return result
145
+
146
+
147
+ def _clean_directions(value: Any) -> list[str]:
148
+ if value in (None, ""):
149
+ return ["inbound"]
150
+ if not isinstance(value, list):
151
+ raise VoiceRefusal("direction policy must be a list")
152
+ result: list[str] = []
153
+ for item in value:
154
+ key = str(item or "").strip().lower()
155
+ if key not in {"inbound", "outbound"}:
156
+ raise VoiceRefusal("direction policy accepts inbound and outbound only")
157
+ if key not in result:
158
+ result.append(key)
159
+ if not result:
160
+ raise VoiceRefusal("select at least one permitted Voice direction")
161
+ return result
162
+
163
+
164
+ def _clean_string_list(value: Any, label: str, limit: int = 12) -> list[str]:
165
+ if value in (None, ""):
166
+ return []
167
+ if not isinstance(value, list) or len(value) > limit:
168
+ raise VoiceRefusal(f"{label} must be a list of at most {limit} items")
169
+ return [item for item in (_text(v, 160) for v in value) if item]
170
+
171
+
172
+ def _clean_core(raw: Any, previous: Any = None) -> dict[str, Any]:
173
+ previous = previous if isinstance(previous, dict) else {}
174
+ if raw in (None, ""):
175
+ return copy.deepcopy(previous)
176
+ if not isinstance(raw, dict):
177
+ raise VoiceRefusal("portable Voice configuration must be an object")
178
+ allowed = {
179
+ "role", "purpose", "businessIdentity", "languagePolicy", "transferPolicy",
180
+ "callbackPolicy", "safetyBoundaries", "consentMode", "outcomeSchema",
181
+ }
182
+ unknown = sorted(set(raw) - allowed)
183
+ if unknown:
184
+ raise VoiceRefusal("unsupported portable Voice setting: " + ", ".join(unknown))
185
+ merged = {**previous, **raw}
186
+ out: dict[str, Any] = {}
187
+ for key in ("role", "purpose", "businessIdentity", "languagePolicy", "transferPolicy",
188
+ "callbackPolicy", "consentMode"):
189
+ out[key] = _text(merged.get(key), 500 if key == "purpose" else 240)
190
+ out["safetyBoundaries"] = _clean_string_list(
191
+ merged.get("safetyBoundaries"), "safety boundaries")
192
+ schema = merged.get("outcomeSchema")
193
+ if schema in (None, ""):
194
+ out["outcomeSchema"] = []
195
+ elif isinstance(schema, list) and len(schema) <= 20:
196
+ out["outcomeSchema"] = [
197
+ {"key": _safe_id((row or {}).get("key"), "outcome field", allow_empty=False),
198
+ "label": _text((row or {}).get("label"), 80),
199
+ "type": str((row or {}).get("type") or "text")
200
+ if str((row or {}).get("type") or "text") in {"text", "number", "boolean"}
201
+ else "text"}
202
+ for row in schema if isinstance(row, dict)
203
+ ]
204
+ else:
205
+ raise VoiceRefusal("outcome schema must be a list of at most 20 fields")
206
+ return out
207
+
208
+
209
+ def _clean_audience(raw: Any, previous: Any = None) -> dict[str, Any]:
210
+ previous = previous if isinstance(previous, dict) else {}
211
+ if raw in (None, ""):
212
+ raw = {}
213
+ if not isinstance(raw, dict):
214
+ raise VoiceRefusal("Voice audience must be an object")
215
+ allowed = {"tableKey", "viewId", "viewRevision", "phoneFieldKey",
216
+ "emptyPolicy", "maxRecipients"}
217
+ unknown = sorted(set(raw) - allowed)
218
+ if unknown:
219
+ raise VoiceRefusal("unsupported Voice audience setting: " + ", ".join(unknown))
220
+ merged = {**previous, **raw}
221
+ empty_policy = str(merged.get("emptyPolicy") or "skip").strip().lower()
222
+ if empty_policy not in EMPTY_POLICIES:
223
+ raise VoiceRefusal("empty phone values must be skipped or refused")
224
+ try:
225
+ maximum = int(merged.get("maxRecipients") or 100)
226
+ except (TypeError, ValueError):
227
+ raise VoiceRefusal("maximum recipients must be a whole number") from None
228
+ if maximum < 1 or maximum > MAX_RECIPIENTS:
229
+ raise VoiceRefusal(f"maximum recipients must be between 1 and {MAX_RECIPIENTS}")
230
+ revision = merged.get("viewRevision")
231
+ if revision not in (None, "") and not isinstance(revision, (str, int)):
232
+ raise VoiceRefusal("View revision must be text or a number")
233
+ return {
234
+ "tableKey": _safe_id(merged.get("tableKey"), "database", allow_empty=True),
235
+ "viewId": _safe_id(merged.get("viewId"), "View", allow_empty=True),
236
+ "viewRevision": str(revision or "")[:120],
237
+ "phoneFieldKey": _safe_id(merged.get("phoneFieldKey"), "phone field", allow_empty=True),
238
+ "emptyPolicy": empty_policy,
239
+ "maxRecipients": maximum,
240
+ }
241
+
242
+
243
+ def _provider_for(doc: dict[str, Any], connection_id: str, extension: Any) -> str:
244
+ connection = doc["voice_provider_connection"].get(connection_id) if connection_id else None
245
+ if connection_id and not isinstance(connection, dict):
246
+ raise VoiceRefusal("select a Voice provider connection available to this workspace")
247
+ provider = str((connection or {}).get("provider") or "").lower()
248
+ if isinstance(extension, dict):
249
+ requested = str(extension.get("provider") or "").strip().lower()
250
+ if requested and provider and requested != provider:
251
+ raise VoiceRefusal("provider extension does not match the selected connection")
252
+ provider = provider or requested
253
+ return provider
254
+
255
+
256
+ def _agent_record(doc: dict[str, Any], raw: Any, previous: Any = None,
257
+ actor: str = "") -> dict[str, Any]:
258
+ raw = raw if isinstance(raw, dict) else {}
259
+ previous = previous if isinstance(previous, dict) else {}
260
+ _reject_sensitive(raw)
261
+ forbidden = {"phoneBindings", "numberBinding", "externalAgentRef", "provider", "route"}
262
+ if forbidden & set(raw):
263
+ raise VoiceRefusal("provider identity and number routing are server-managed")
264
+ name = _text(raw.get("displayName", previous.get("display_name")), 120)
265
+ if not name:
266
+ raise VoiceRefusal("name the Voice agent")
267
+ lifecycle = str(raw.get("lifecycle", raw.get("activationState",
268
+ previous.get("lifecycle", "draft")))).strip().lower()
269
+ if lifecycle not in SAFE_LIFECYCLES:
270
+ raise VoiceRefusal("Voice activation is unavailable until an explicit verified activation gate")
271
+ connection_id = _safe_id(raw.get("providerConnectionId",
272
+ previous.get("provider_connection_id")),
273
+ "provider connection", allow_empty=True)
274
+ extension_raw = raw.get("providerExtension", previous.get("provider_extension") or {})
275
+ provider = _provider_for(doc, connection_id, extension_raw)
276
+ if provider:
277
+ try:
278
+ extension = adapters.clean_extension(provider, extension_raw)
279
+ except adapters.ProviderAdapterRefusal as exc:
280
+ raise VoiceRefusal(str(exc)) from exc
281
+ else:
282
+ extension = {"provider": "", "version": 1, "config": {}}
283
+ core_raw = raw.get("portableConfig")
284
+ if core_raw is None and any(key in raw for key in ("purpose", "callbackOnly")):
285
+ core_raw = dict(previous.get("core_config") or {})
286
+ if "purpose" in raw:
287
+ core_raw["purpose"] = raw.get("purpose")
288
+ if "callbackOnly" in raw:
289
+ core_raw["callbackPolicy"] = "callbacks_only" if raw.get("callbackOnly") else ""
290
+ core = _clean_core(core_raw, previous.get("core_config"))
291
+ directions_raw = raw.get("directionPolicy")
292
+ if directions_raw is None and "callbackOnly" in raw:
293
+ directions_raw = ["inbound"] if raw.get("callbackOnly") else ["inbound", "outbound"]
294
+ directions = _clean_directions(directions_raw if directions_raw is not None
295
+ else previous.get("direction_policy"))
296
+ audience = _clean_audience(raw.get("audience"), previous.get("audience"))
297
+ knowledge_id = _safe_id(raw.get("knowledgeProfileId",
298
+ previous.get("knowledge_profile_id")),
299
+ "knowledge profile", allow_empty=True)
300
+ if knowledge_id and knowledge_id not in doc["voice_knowledge_profile"]:
301
+ raise VoiceRefusal("select a Voice knowledge profile available to this workspace")
302
+ stamp = _now()
303
+ return {
304
+ "id": str(previous.get("id") or _mint("va")),
305
+ "tenant_id": str(previous.get("tenant_id") or ""),
306
+ "display_name": name,
307
+ "lifecycle": lifecycle,
308
+ "provider_connection_id": connection_id,
309
+ "external_agent_ref": str(previous.get("external_agent_ref") or ""),
310
+ "direction_policy": directions,
311
+ "core_config": core,
312
+ "provider_extension": extension,
313
+ "knowledge_profile_id": knowledge_id,
314
+ "audience": audience,
315
+ "created_by": str(previous.get("created_by") or actor or "")[:120],
316
+ "updated_by": str(actor or previous.get("updated_by") or "")[:120],
317
+ "created_at": _now(previous.get("created_at")) if previous else stamp,
318
+ "updated_at": stamp,
319
+ }
320
+
321
+
322
+ def save_draft(rt: Any, raw: Any, actor: str = "") -> dict[str, Any]:
323
+ result: dict[str, Any] = {}
324
+ def up(doc: dict[str, Any]) -> dict[str, Any]:
325
+ rec = _agent_record(doc, raw, actor=actor)
326
+ doc["voice_agent"][rec["id"]] = rec
327
+ result.update(rec)
328
+ return doc
329
+ _update(rt, up)
330
+ return result
331
+
332
+
333
+ def patch_draft(rt: Any, voice_id: str, raw: Any, actor: str = "") -> dict[str, Any]:
334
+ result: dict[str, Any] = {}
335
+ def up(doc: dict[str, Any]) -> dict[str, Any]:
336
+ previous = doc["voice_agent"].get(str(voice_id))
337
+ if not isinstance(previous, dict):
338
+ raise VoiceRefusal("unknown Voice agent")
339
+ rec = _agent_record(doc, raw, previous, actor=actor)
340
+ doc["voice_agent"][rec["id"]] = rec
341
+ result.update(rec)
342
+ return doc
343
+ _update(rt, up)
344
+ return result
345
+
346
+
347
+ def server_register_provider_connection(rt: Any, provider: str, secret_ref: str,
348
+ tenant_id: str = "", connection_id: str = "") -> dict[str, Any]:
349
+ """Internal server seam. ``secret_ref`` names a secret; it is never a browser value."""
350
+ key = str(provider or "").strip().lower()
351
+ if not adapters.provider_label(key):
352
+ raise VoiceRefusal("select Retell or ElevenLabs")
353
+ ref = str(secret_ref or "").strip()
354
+ if not re.fullmatch(r"(?:env|keychain|secret):[A-Z0-9_./\-]{3,160}", ref):
355
+ raise VoiceRefusal("provider credential must be a server-side secret reference")
356
+ rec = {
357
+ "id": _safe_id(connection_id, "provider connection") or _mint("vpc"),
358
+ "tenant_id": str(tenant_id or "")[:120],
359
+ "provider": key, "secret_ref": ref, "status": "unconfigured",
360
+ "last_probe_at": 0, "created_at": _now(), "updated_at": _now(),
361
+ }
362
+ def up(doc: dict[str, Any]) -> dict[str, Any]:
363
+ doc["voice_provider_connection"][rec["id"]] = rec
364
+ return doc
365
+ _update(rt, up)
366
+ return copy.deepcopy(rec)
367
+
368
+
369
+ def server_reconcile_provider(rt: Any, connection_id: str,
370
+ transport: adapters.Transport) -> dict[str, Any]:
371
+ """Perform GET-only inventory and persist redacted sync outcomes, never provider payloads."""
372
+ doc = _store(rt)
373
+ connection = doc["voice_provider_connection"].get(str(connection_id))
374
+ if not isinstance(connection, dict):
375
+ raise VoiceRefusal("unknown Voice provider connection")
376
+ try:
377
+ observed = adapters.reconcile(connection.get("provider"), transport)
378
+ except adapters.ProviderAdapterRefusal as exc:
379
+ raise VoiceRefusal(str(exc)) from exc
380
+ at = _now()
381
+ def up(current: dict[str, Any]) -> dict[str, Any]:
382
+ rec = current["voice_provider_connection"].get(str(connection_id))
383
+ if not isinstance(rec, dict):
384
+ raise VoiceRefusal("unknown Voice provider connection")
385
+ rec = {**rec, "status": observed["status"], "last_probe_at": at, "updated_at": at}
386
+ current["voice_provider_connection"][str(connection_id)] = rec
387
+ for row in observed["checks"]:
388
+ sync_id = _mint("vps")
389
+ current["voice_provider_sync"][sync_id] = {
390
+ "id": sync_id, "tenant_id": rec.get("tenant_id") or "",
391
+ "provider": rec.get("provider") or "", "resource_type": row["resource"],
392
+ "external_ref": "", "profile_version": "", "status": row["status"],
393
+ "count": row["count"], "error_class": row.get("errorClass") or "",
394
+ "observed_at": at, "raw_payload_stored": False,
395
+ }
396
+ return current
397
+ _update(rt, up)
398
+ return copy.deepcopy(observed)
399
+
400
+
401
+ def server_register_knowledge_profile(rt: Any, version: str, content_hash: str,
402
+ classification: str, approval_state: str,
403
+ tenant_id: str = "", profile_id: str = "") -> dict[str, Any]:
404
+ if approval_state not in {"draft", "approved", "revoked"}:
405
+ raise VoiceRefusal("knowledge approval state is invalid")
406
+ digest = str(content_hash or "").lower()
407
+ if not re.fullmatch(r"[0-9a-f]{32,64}", digest):
408
+ raise VoiceRefusal("knowledge profile needs a content hash, never raw content")
409
+ rec = {"id": _safe_id(profile_id, "knowledge profile") or _mint("vkp"),
410
+ "tenant_id": str(tenant_id or "")[:120], "version": _text(version, 80),
411
+ "content_hash": digest, "classification": _text(classification, 80),
412
+ "approval_state": approval_state, "created_at": _now(), "updated_at": _now()}
413
+ def up(doc: dict[str, Any]) -> dict[str, Any]:
414
+ doc["voice_knowledge_profile"][rec["id"]] = rec
415
+ return doc
416
+ _update(rt, up)
417
+ return copy.deepcopy(rec)
418
+
419
+
420
+ def server_bind_agent_ref(rt: Any, voice_id: str, external_ref: str) -> dict[str, Any]:
421
+ """Internal opaque provider binding. The external reference never serializes to the browser."""
422
+ ref = str(external_ref or "").strip()[:240]
423
+ if not ref or _PHONE.search(ref):
424
+ raise VoiceRefusal("provider agent binding must be an opaque server reference")
425
+ result: dict[str, Any] = {}
426
+ def up(doc: dict[str, Any]) -> dict[str, Any]:
427
+ rec = doc["voice_agent"].get(str(voice_id))
428
+ if not isinstance(rec, dict):
429
+ raise VoiceRefusal("unknown Voice agent")
430
+ rec = {**rec, "external_agent_ref": ref, "updated_at": _now()}
431
+ doc["voice_agent"][str(voice_id)] = rec
432
+ result.update(rec)
433
+ return doc
434
+ _update(rt, up)
435
+ return result
436
+
437
+
438
+ def _masked_display(value: Any) -> str:
439
+ display = _text(value, 80)
440
+ if not display or _PHONE.search(display) or not any(ch in display for ch in "*•xX"):
441
+ raise VoiceRefusal("phone display must already be masked")
442
+ return display
443
+
444
+
445
+ def server_bind_number(rt: Any, voice_id: str, opaque_id: str, masked_number: str,
446
+ active: bool = False, carrier_provider: str = "server") -> dict[str, Any]:
447
+ """Internal-only number/route seam enforcing exactly one active inbound owner per DID."""
448
+ external = str(opaque_id or "").strip()[:240]
449
+ if not external or _PHONE.search(external):
450
+ raise VoiceRefusal("a phone binding needs an opaque server reference")
451
+ masked = _masked_display(masked_number)
452
+ result: dict[str, Any] = {}
453
+ def up(doc: dict[str, Any]) -> dict[str, Any]:
454
+ agent = doc["voice_agent"].get(str(voice_id))
455
+ if not isinstance(agent, dict):
456
+ raise VoiceRefusal("unknown Voice agent")
457
+ number = next((row for row in doc["voice_number"].values()
458
+ if isinstance(row, dict) and row.get("external_number_ref") == external), None)
459
+ if not number:
460
+ nid = _mint("vn")
461
+ number = {"id": nid, "tenant_id": agent.get("tenant_id") or "",
462
+ "carrier_provider": _text(carrier_provider, 40),
463
+ "external_number_ref": external, "masked_display": masked,
464
+ "status": "verified", "created_at": _now(), "updated_at": _now()}
465
+ doc["voice_number"][nid] = number
466
+ existing = [row for row in doc["voice_number_route"].values()
467
+ if isinstance(row, dict) and row.get("voice_number_id") == number["id"]
468
+ and row.get("direction") == "inbound" and row.get("status") == "active"
469
+ and row.get("voice_agent_id") != str(voice_id)]
470
+ if active and existing:
471
+ raise VoiceRefusal("that phone already has an active inbound owner")
472
+ route = next((row for row in doc["voice_number_route"].values()
473
+ if isinstance(row, dict) and row.get("voice_number_id") == number["id"]
474
+ and row.get("direction") == "inbound"
475
+ and row.get("voice_agent_id") == str(voice_id)), None)
476
+ rid = str((route or {}).get("id") or _mint("vnr"))
477
+ provider = str((agent.get("provider_extension") or {}).get("provider") or "")
478
+ route = {"id": rid, "tenant_id": agent.get("tenant_id") or "",
479
+ "voice_number_id": number["id"], "direction": "inbound",
480
+ "selected_provider": provider, "voice_agent_id": str(voice_id),
481
+ "status": "active" if active else "inactive", "callback_window": "",
482
+ "created_at": _now((route or {}).get("created_at")), "updated_at": _now()}
483
+ doc["voice_number_route"][rid] = route
484
+ result.update({"voiceAgentId": str(voice_id), "numberId": number["id"],
485
+ "maskedDisplay": masked, "active": bool(active), "routeId": rid})
486
+ return doc
487
+ _update(rt, up)
488
+ return result
489
+
490
+
491
+ def acquire_outbound_lease(rt: Any, voice_id: str, number_id: str, run_ref: str,
492
+ capacity: int = 1, ttl_seconds: int = 60, now: Any = None) -> dict[str, Any]:
493
+ """Atomically acquire one per-DID permit. No dispatcher exists in this module."""
494
+ stamp = _now(now)
495
+ try:
496
+ cap, ttl = int(capacity), int(ttl_seconds)
497
+ except (TypeError, ValueError):
498
+ raise VoiceRefusal("Voice lease capacity and duration must be whole numbers") from None
499
+ if cap < 1 or cap > 100 or ttl < 1 or ttl > MAX_LEASE_SECONDS:
500
+ raise VoiceRefusal("Voice lease capacity or duration is outside the safe bound")
501
+ run = _safe_id(run_ref, "run", allow_empty=False)
502
+ result: dict[str, Any] = {}
503
+ def up(doc: dict[str, Any]) -> dict[str, Any]:
504
+ agent = doc["voice_agent"].get(str(voice_id))
505
+ number = doc["voice_number"].get(str(number_id))
506
+ if not isinstance(agent, dict) or not isinstance(number, dict):
507
+ raise VoiceRefusal("unknown Voice agent or number")
508
+ if "outbound" not in (agent.get("direction_policy") or []):
509
+ raise VoiceRefusal("this Voice agent is not permitted for outbound work")
510
+ for lid, lease in list(doc["voice_outbound_lease"].items()):
511
+ if isinstance(lease, dict) and lease.get("state") == "active" \
512
+ and _now(lease.get("expires_at")) <= stamp:
513
+ doc["voice_outbound_lease"][lid] = {**lease, "state": "expired"}
514
+ active = [lease for lease in doc["voice_outbound_lease"].values()
515
+ if isinstance(lease, dict) and lease.get("voice_number_id") == str(number_id)
516
+ and lease.get("state") == "active" and _now(lease.get("expires_at")) > stamp]
517
+ if len(active) >= cap:
518
+ raise VoiceRefusal("outbound capacity for that phone is already leased")
519
+ lid = _mint("vol")
520
+ lease = {"id": lid, "tenant_id": agent.get("tenant_id") or "",
521
+ "voice_number_id": str(number_id),
522
+ "provider": str((agent.get("provider_extension") or {}).get("provider") or ""),
523
+ "voice_agent_id": str(voice_id), "run_ref": run,
524
+ "permit": secrets.token_urlsafe(18), "expires_at": stamp + ttl,
525
+ "state": "active", "created_at": stamp, "updated_at": stamp}
526
+ doc["voice_outbound_lease"][lid] = lease
527
+ result.update(lease)
528
+ return doc
529
+ _update(rt, up)
530
+ return result
531
+
532
+
533
+ def release_outbound_lease(rt: Any, lease_id: str, permit: str, now: Any = None) -> dict[str, Any]:
534
+ result: dict[str, Any] = {}
535
+ def up(doc: dict[str, Any]) -> dict[str, Any]:
536
+ lease = doc["voice_outbound_lease"].get(str(lease_id))
537
+ if not isinstance(lease, dict) or not secrets.compare_digest(
538
+ str(lease.get("permit") or ""), str(permit or "")):
539
+ raise VoiceRefusal("unknown outbound lease permit")
540
+ lease = {**lease, "state": "released", "updated_at": _now(now)}
541
+ doc["voice_outbound_lease"][str(lease_id)] = lease
542
+ result.update(lease)
543
+ return doc
544
+ _update(rt, up)
545
+ return result
546
+
547
+
548
+ def _connection_dto(connection: Any) -> dict[str, Any] | None:
549
+ if not isinstance(connection, dict):
550
+ return None
551
+ key = str(connection.get("provider") or "")
552
+ return {"id": str(connection.get("id") or ""), "provider": key,
553
+ "label": adapters.provider_label(key),
554
+ "status": str(connection.get("status") or "unconfigured"),
555
+ "lastProbeAt": _now(connection.get("last_probe_at"))}
556
+
557
+
558
+ def _knowledge_dto(profile: Any) -> dict[str, Any] | None:
559
+ if not isinstance(profile, dict):
560
+ return None
561
+ return {"id": str(profile.get("id") or ""), "version": _text(profile.get("version"), 80),
562
+ "classification": _text(profile.get("classification"), 80),
563
+ "approvalState": str(profile.get("approval_state") or "draft")}
564
+
565
+
566
+ def _binding_dto(doc: dict[str, Any], voice_id: str) -> dict[str, Any] | None:
567
+ routes = [row for row in doc["voice_number_route"].values()
568
+ if isinstance(row, dict) and row.get("voice_agent_id") == str(voice_id)
569
+ and row.get("direction") == "inbound"]
570
+ if not routes:
571
+ return None
572
+ route = sorted(routes, key=lambda row: (row.get("status") != "active",
573
+ -_now(row.get("updated_at"))))[0]
574
+ number = doc["voice_number"].get(str(route.get("voice_number_id") or "")) or {}
575
+ return {"numberId": str(number.get("id") or ""),
576
+ "maskedDisplay": _text(number.get("masked_display"), 80),
577
+ "numberStatus": str(number.get("status") or "unconfigured"),
578
+ "routeStatus": str(route.get("status") or "inactive")}
579
+
580
+
581
+ def browser_dto(record: Any, document: Any = None) -> dict[str, Any]:
582
+ """The complete allow-list for data that may cross into the browser."""
583
+ rec = record if isinstance(record, dict) else {}
584
+ doc = _normalise_document(document)
585
+ connection = doc["voice_provider_connection"].get(str(rec.get("provider_connection_id") or ""))
586
+ knowledge = doc["voice_knowledge_profile"].get(str(rec.get("knowledge_profile_id") or ""))
587
+ binding = _binding_dto(doc, str(rec.get("id") or ""))
588
+ audience = _clean_audience(rec.get("audience") or {})
589
+ reasons: list[str] = []
590
+ if not connection or connection.get("status") != "connected":
591
+ reasons.append("provider_connection")
592
+ if not all(audience.get(key) for key in ("tableKey", "viewId", "phoneFieldKey")):
593
+ reasons.append("audience")
594
+ if not knowledge or knowledge.get("approval_state") != "approved":
595
+ reasons.append("knowledge_profile")
596
+ if not binding or binding.get("routeStatus") != "active":
597
+ reasons.append("inbound_binding")
598
+ if rec.get("lifecycle") != "inactive":
599
+ reasons.append("activation_gate")
600
+ core = copy.deepcopy(rec.get("core_config") or {})
601
+ extension = copy.deepcopy(rec.get("provider_extension") or
602
+ {"provider": "", "version": 1, "config": {}})
603
+ callback_only = (rec.get("direction_policy") or ["inbound"]) == ["inbound"]
604
+ return {
605
+ "schemaVersion": SCHEMA_VERSION,
606
+ "automationId": str(rec.get("id") or ""), "voiceAgentId": str(rec.get("id") or ""),
607
+ "displayName": _text(rec.get("display_name", rec.get("displayName")), 120),
608
+ "agentType": "voice", "lifecycle": str(rec.get("lifecycle") or "draft"),
609
+ "readiness": {"state": "configured" if not reasons else "needs_attention",
610
+ "reasons": reasons, "productionDispatch": False},
611
+ "providerConnectionId": str(rec.get("provider_connection_id") or ""),
612
+ "providerConnection": _connection_dto(connection), "portableConfig": core,
613
+ "providerExtension": extension,
614
+ "opaqueProviderRefs": {"agentBound": bool(rec.get("external_agent_ref"))},
615
+ "directionPolicy": list(rec.get("direction_policy") or ["inbound"]),
616
+ "knowledgeProfileId": str(rec.get("knowledge_profile_id") or ""),
617
+ "knowledgeProfile": _knowledge_dto(knowledge), "phoneBinding": binding,
618
+ "audience": audience,
619
+ "capabilities": {"dryRun": True, "numberProvisioning": "contact_loopable",
620
+ "activation": False, "externalDispatch": False},
621
+ "connectionStatus": str((connection or {}).get("status") or "unconfigured"),
622
+ "supportedConfiguration": copy.deepcopy(extension.get("config") or {}),
623
+ "purpose": _text(core.get("purpose"), 240), "callbackOnly": callback_only,
624
+ "activationState": str(rec.get("lifecycle") or "draft"),
625
+ "phoneBindings": ([{"opaqueId": binding["numberId"],
626
+ "maskedNumber": binding["maskedDisplay"],
627
+ "active": binding["routeStatus"] == "active"}]
628
+ if binding else []),
629
+ }
630
+
631
+
632
+ def list_browser_dtos(rt: Any) -> list[dict[str, Any]]:
633
+ doc = _store(rt)
634
+ return [browser_dto(rec, doc) for _, rec in sorted(doc["voice_agent"].items())
635
+ if isinstance(rec, dict)]
636
+
637
+
638
+ def get_browser_dto(rt: Any, voice_id: str) -> dict[str, Any]:
639
+ doc = _store(rt)
640
+ rec = doc["voice_agent"].get(str(voice_id))
641
+ if not isinstance(rec, dict):
642
+ raise VoiceRefusal("unknown Voice agent")
643
+ return browser_dto(rec, doc)
644
+
645
+
646
+ def browser_options(rt: Any) -> dict[str, Any]:
647
+ """Server-stored choices only; callers add permissioned database/View/field choices."""
648
+ doc = _store(rt)
649
+ connections = [_connection_dto(row) for _, row in sorted(
650
+ doc["voice_provider_connection"].items()) if isinstance(row, dict)]
651
+ knowledge = [_knowledge_dto(row) for _, row in sorted(
652
+ doc["voice_knowledge_profile"].items()) if isinstance(row, dict)]
653
+ return {"schemaVersion": SCHEMA_VERSION, "providers": adapters.providers(),
654
+ "providerConnections": [row for row in connections if row],
655
+ "knowledgeProfiles": [row for row in knowledge if row],
656
+ "emptyPolicies": [{"key": "skip", "label": "Skip empty phone values"},
657
+ {"key": "refuse", "label": "Refuse if any phone is empty"}],
658
+ "maxRecipientsCeiling": MAX_RECIPIENTS}
659
+
660
+
661
+ def _event_key(provider: str, event_ref: str) -> str:
662
+ return hashlib.sha256(f"{provider}:{event_ref}".encode("utf-8")).hexdigest()[:32]
663
+
664
+
665
+ def record_provider_event(rt: Any, provider: str, event_ref: str, voice_id: str,
666
+ verification_state: str, normalized_outcome: Any,
667
+ tenant_id: str = "", received_at: Any = None) -> dict[str, Any]:
668
+ """Idempotent normalized event storage. Raw transcripts/payloads have no parameter."""
669
+ key = str(provider or "local").lower()
670
+ ref = str(event_ref or "").strip()[:240]
671
+ if not ref:
672
+ raise VoiceRefusal("provider event needs an opaque reference")
673
+ if verification_state not in {"verified", "local", "refused"}:
674
+ raise VoiceRefusal("provider event verification state is invalid")
675
+ if not isinstance(normalized_outcome, dict):
676
+ raise VoiceRefusal("provider outcome must be a normalized object")
677
+ _reject_sensitive(normalized_outcome)
678
+ eid = "vpe_" + _event_key(key, ref)
679
+ rec = {"id": eid, "provider": key, "event_ref_hash": _event_key(key, ref),
680
+ "tenant_id": str(tenant_id or "")[:120], "voice_agent_id": str(voice_id or ""),
681
+ "received_at": _now(received_at), "verification_state": verification_state,
682
+ "normalized_outcome": copy.deepcopy(normalized_outcome), "raw_payload_stored": False}
683
+ def up(doc: dict[str, Any]) -> dict[str, Any]:
684
+ doc["voice_provider_event"].setdefault(eid, rec)
685
+ return doc
686
+ _update(rt, up)
687
+ return rec
688
+
689
+
690
+ def dry_run(rt: Any, voice_id: str, audience: Any,
691
+ resolve_view: Callable[[dict[str, Any]], dict[str, Any]]) -> dict[str, Any]:
692
+ """Resolve one allowed saved View and record a redacted local event; never dispatch."""
693
+ doc = _store(rt)
694
+ rec = doc["voice_agent"].get(str(voice_id))
695
+ if not isinstance(rec, dict):
696
+ raise VoiceRefusal("unknown Voice agent")
697
+ if rec.get("lifecycle") not in SAFE_LIFECYCLES:
698
+ raise VoiceRefusal("Voice activation is unavailable until an explicit verified activation gate")
699
+ chosen = _clean_audience(audience, rec.get("audience"))
700
+ if not all(chosen.get(key) for key in ("tableKey", "viewId", "phoneFieldKey")):
701
+ raise VoiceRefusal("select a database, saved View, and phone field before dry-run")
702
+ if not callable(resolve_view):
703
+ raise VoiceRefusal("Voice dry-run needs the server View resolver")
704
+ resolved = resolve_view(copy.deepcopy(chosen))
705
+ if not isinstance(resolved, dict):
706
+ raise VoiceRefusal("Voice View resolver returned no result")
707
+ try:
708
+ recipients = int(resolved.get("recipientCount"))
709
+ selected = int(resolved.get("selectedCount", recipients))
710
+ except (TypeError, ValueError):
711
+ raise VoiceRefusal("Voice View resolver returned an invalid recipient count") from None
712
+ if recipients < 0 or selected < recipients:
713
+ raise VoiceRefusal("Voice View resolver returned an invalid audience")
714
+ if recipients > chosen["maxRecipients"]:
715
+ raise VoiceRefusal(
716
+ f"that View resolves to {recipients} eligible recipients; the saved maximum is "
717
+ f"{chosen['maxRecipients']}")
718
+ if chosen["emptyPolicy"] == "refuse" and selected != recipients:
719
+ raise VoiceRefusal("that View contains empty phone values and this audience refuses them")
720
+ at = _now()
721
+ event_ref = f"dry:{voice_id}:{at}:{secrets.token_urlsafe(5)}"
722
+ outcome = {"kind": "dry_run", "state": "complete", "recipientCount": recipients,
723
+ "selectedCount": selected, "externalDispatches": 0,
724
+ "noExternalDispatch": True}
725
+ event = record_provider_event(
726
+ rt, "local", event_ref, str(voice_id), "local", outcome,
727
+ tenant_id=str(rec.get("tenant_id") or ""), received_at=at)
728
+ return {
729
+ "schemaVersion": SCHEMA_VERSION, "noExternalDispatch": True,
730
+ "externalDispatches": 0, "state": "dry_run_complete",
731
+ "audience": {**chosen, "viewRevision": str(resolved.get("viewRevision")
732
+ or chosen.get("viewRevision") or "")},
733
+ "recipientCount": recipients, "selectedCount": selected,
734
+ "maskedPreview": {"displayName": _text(rec.get("display_name"), 120),
735
+ "recipientCount": recipients},
736
+ "preview": {"displayName": _text(rec.get("display_name"), 120),
737
+ "maskedBindingCount": 1 if _binding_dto(doc, str(voice_id)) else 0},
738
+ "eventId": event["id"],
739
+ }
740
+
741
+
742
+ def refuse_external_dispatch(source: str = "automation") -> None:
743
+ """The explicit ordinary-run/webhook/schedule wall until production activation is built."""
744
+ raise VoiceRefusal(
745
+ f"Voice {str(source or 'automation')} dispatch is not activated; use the no-dial harness")
api/voice_provider_adapters.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read-only, dependency-injected provider reconciliation for Loopable Voice.
2
+
3
+ The adapter boundary deliberately has no HTTP implementation. A caller must inject a transport
4
+ that is already scoped to one server-side secret reference. Only documented inventory GETs are
5
+ accepted; no create, update, publish, assignment, dial, test, or delete verb can cross this module.
6
+ Results contain counts and readiness classes only, never provider identifiers or raw payloads.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from typing import Any, Callable
12
+
13
+
14
+ class ProviderAdapterRefusal(ValueError):
15
+ """A provider or transport tried to leave the read-only reconciliation contract."""
16
+
17
+
18
+ Transport = Callable[[str, str], Any]
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class InventoryCheck:
23
+ name: str
24
+ path: str
25
+ list_key: str | None = None
26
+
27
+
28
+ _CHECKS: dict[str, tuple[InventoryCheck, ...]] = {
29
+ "retell": (
30
+ InventoryCheck("agents", "/list-agents?limit=5&is_latest=true"),
31
+ InventoryCheck("response_engines", "/v2/list-retell-llms?limit=5", "items"),
32
+ InventoryCheck("phone_numbers", "/v2/list-phone-numbers?limit=5", "items"),
33
+ InventoryCheck("knowledge_bases", "/list-knowledge-bases"),
34
+ ),
35
+ "elevenlabs": (
36
+ InventoryCheck("agents", "/v1/convai/agents?page_size=5", "agents"),
37
+ InventoryCheck("phone_numbers", "/v1/convai/phone-numbers"),
38
+ InventoryCheck("knowledge_base_documents",
39
+ "/v1/convai/knowledge-base?page_size=5", "documents"),
40
+ ),
41
+ }
42
+
43
+ _EXTENSIONS: dict[str, dict[str, tuple[type, ...]]] = {
44
+ "retell": {
45
+ "responseEngineRef": (str,),
46
+ "voiceRef": (str,),
47
+ "conversationFlowRef": (str,),
48
+ "responsiveness": (int, float),
49
+ "interruptionSensitivity": (int, float),
50
+ },
51
+ "elevenlabs": {
52
+ "voiceRef": (str,),
53
+ "language": (str,),
54
+ "firstMessageMode": (str,),
55
+ "stability": (int, float),
56
+ "similarityBoost": (int, float),
57
+ },
58
+ }
59
+
60
+ _LABELS = {"retell": "Retell", "elevenlabs": "ElevenLabs"}
61
+
62
+
63
+ def providers() -> list[dict[str, Any]]:
64
+ """Browser-safe provider choices and deliberately supported extension fields."""
65
+ return [
66
+ {
67
+ "key": key,
68
+ "label": _LABELS[key],
69
+ "extensionVersion": 1,
70
+ "extensionFields": [
71
+ {"key": name, "type": "number" if float in types else "text"}
72
+ for name, types in fields.items()
73
+ ],
74
+ }
75
+ for key, fields in _EXTENSIONS.items()
76
+ ]
77
+
78
+
79
+ def provider_label(provider: str) -> str:
80
+ return _LABELS.get(str(provider or "").lower(), "")
81
+
82
+
83
+ def clean_extension(provider: str, raw: Any) -> dict[str, Any]:
84
+ """Validate one typed provider bag and discard no unknown setting silently."""
85
+ key = str(provider or "").strip().lower()
86
+ allowed = _EXTENSIONS.get(key)
87
+ if allowed is None:
88
+ raise ProviderAdapterRefusal("select Retell or ElevenLabs")
89
+ if raw in (None, ""):
90
+ return {"provider": key, "version": 1, "config": {}}
91
+ if not isinstance(raw, dict):
92
+ raise ProviderAdapterRefusal("provider extension must be an object")
93
+ version = raw.get("version", 1)
94
+ if version != 1:
95
+ raise ProviderAdapterRefusal("provider extension version must be 1")
96
+ config = raw.get("config", raw)
97
+ if not isinstance(config, dict):
98
+ raise ProviderAdapterRefusal("provider extension config must be an object")
99
+ config = {k: v for k, v in config.items() if k not in {"provider", "version"}}
100
+ unknown = sorted(set(config) - set(allowed))
101
+ if unknown:
102
+ raise ProviderAdapterRefusal(
103
+ "unsupported provider setting: " + ", ".join(unknown))
104
+ out: dict[str, Any] = {}
105
+ for name, value in config.items():
106
+ if isinstance(value, bool) or not isinstance(value, allowed[name]):
107
+ expected = "a number" if float in allowed[name] else "text"
108
+ raise ProviderAdapterRefusal(f"{name} must be {expected}")
109
+ if isinstance(value, str):
110
+ value = " ".join(value.split())[:160]
111
+ elif isinstance(value, (int, float)):
112
+ value = max(0.0, min(float(value), 1.0))
113
+ out[name] = value
114
+ return {"provider": key, "version": 1, "config": out}
115
+
116
+
117
+ def _status_payload(result: Any) -> tuple[int, Any]:
118
+ if isinstance(result, tuple) and len(result) == 2:
119
+ try:
120
+ return int(result[0]), result[1]
121
+ except (TypeError, ValueError):
122
+ return 0, None
123
+ if isinstance(result, dict) and "status" in result:
124
+ try:
125
+ return int(result.get("status") or 0), result.get("payload")
126
+ except (TypeError, ValueError):
127
+ return 0, None
128
+ raise ProviderAdapterRefusal("provider transport must return (status, payload)")
129
+
130
+
131
+ def _count(payload: Any, list_key: str | None) -> int:
132
+ if isinstance(payload, list):
133
+ return len(payload)
134
+ if isinstance(payload, dict):
135
+ candidates = payload.get(list_key) if list_key else payload.get("items")
136
+ if isinstance(candidates, list):
137
+ return len(candidates)
138
+ # Several provider list endpoints answer an object keyed by resource ids. We expose only
139
+ # its cardinality, never a key or value.
140
+ if list_key is None and payload and all(isinstance(k, str) for k in payload):
141
+ return len(payload)
142
+ return 0
143
+
144
+
145
+ def reconcile(provider: str, transport: Transport) -> dict[str, Any]:
146
+ """Run the exact safe inventory reads for one provider through an injected transport."""
147
+ key = str(provider or "").strip().lower()
148
+ checks = _CHECKS.get(key)
149
+ if checks is None:
150
+ raise ProviderAdapterRefusal("select Retell or ElevenLabs")
151
+ if not callable(transport):
152
+ raise ProviderAdapterRefusal("a server-side read transport is required")
153
+ rows: list[dict[str, Any]] = []
154
+ for check in checks:
155
+ method = "GET"
156
+ if method != "GET": # structural tripwire: this module has no mutation verb.
157
+ raise ProviderAdapterRefusal("provider reconciliation is read-only")
158
+ try:
159
+ status, payload = _status_payload(transport(method, check.path))
160
+ except ProviderAdapterRefusal:
161
+ raise
162
+ except Exception as exc: # noqa: BLE001 - classify, never serialize provider errors.
163
+ rows.append({"resource": check.name, "status": 0,
164
+ "count": 0, "errorClass": type(exc).__name__})
165
+ continue
166
+ row = {"resource": check.name, "status": status,
167
+ "count": _count(payload, check.list_key)}
168
+ if status != 200:
169
+ row["errorClass"] = "http"
170
+ rows.append(row)
171
+ required = {"agents", "phone_numbers"}
172
+ healthy = all(row["status"] == 200 for row in rows)
173
+ foundation = all(any(row["resource"] == name and row["status"] == 200
174
+ and row["count"] > 0 for row in rows) for name in required)
175
+ return {
176
+ "provider": key,
177
+ "providerLabel": _LABELS[key],
178
+ "readOnly": True,
179
+ "requests": len(rows),
180
+ "status": "connected" if healthy and foundation else "needs_attention",
181
+ "checks": rows,
182
+ "rawPayloadStored": False,
183
+ }
184
+
185
+
186
+ def assert_read_only_request(method: str) -> None:
187
+ """Public negative control for transports that want an explicit verb guard."""
188
+ if str(method or "").upper() != "GET":
189
+ raise ProviderAdapterRefusal("provider reconciliation accepts GET inventory only")
platform/aios_grid.py CHANGED
@@ -211,7 +211,9 @@ def _clean_code(raw):
211
  #: Emitted with the cohort column's read-only mechanism — `source: 'odoo'` + `derived` — so
212
  #: the client never offers an editor and the host never accepts a cell write for them.
213
  READONLY_CUSTOM_TYPES = {"created_time", "formula"}
214
- MAX_FIELD_OPTIONS = 50
 
 
215
  MAX_FORMULA_LEN = 500
216
  #: `rating` bounds. Airtable caps at 10; below 2 a rating is a checkbox.
217
  RATING_MAX_DEFAULT, RATING_MAX_MIN, RATING_MAX_MAX = 5, 2, 10
@@ -226,12 +228,25 @@ MEASURE_FIELD_PREFIX = "measure_"
226
  MEASURE_FIELD_TYPES = {"currency", "int", "pct"}
227
 
228
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  def _clean_options(raw):
230
  """Choices for a `select`: strings, trimmed, de-duplicated case-insensitively, capped.
231
  Mirrors types.ts parseOptions — a choice list that means one thing in the picker and
232
  another in the filter dropdown is a column with two vocabularies."""
233
  out, seen = [], set()
234
- for v in list(raw or [])[:MAX_FIELD_OPTIONS * 2]:
235
  if not isinstance(v, (str, int, float)) or isinstance(v, bool):
236
  continue
237
  s = str(v).strip()[:120]
@@ -239,7 +254,9 @@ def _clean_options(raw):
239
  continue
240
  seen.add(s.lower())
241
  out.append(s)
242
- return out[:MAX_FIELD_OPTIONS]
 
 
243
 
244
 
245
  def merge_choice_options(*sources):
@@ -440,19 +457,71 @@ def _clean_permissions(raw):
440
  #: drift risk this file's docstring names. The charset says which characters may appear; the
441
  #: engine says what they mean. `_quotes_balanced` below is the one structural rule the quote
442
  #: character brings with it.
443
- _FORMULA_CHARS = re.compile(r"^[\w\s{}()+\-*/.,<>=!^&\"]*$")
 
 
 
 
 
 
 
 
 
 
 
 
 
444
  _FORMULA_REF = re.compile(r"\{([^{}]*)\}")
445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
446
 
447
  def _quotes_balanced(s):
448
- """An even number of `"` — the structural half of string support.
449
 
450
- Sound because the engine's own escape is Excel's: `""` inside a string is one quote, and it
451
- contributes TWO characters. So a well-formed expression always has an even count and an
452
- unterminated string always has an odd one. What a balanced pair MEANS is the engine's
453
- business, exactly as with parentheses.
454
  """
455
- return s.count('"') % 2 == 0
456
 
457
 
458
  #: Wave-18 C5-AUTOFIELD. `kind` is a whitelist because an unknown kind would be a column that
@@ -537,6 +606,19 @@ def _clean_formula(raw, valid_keys=None):
537
  return None
538
  if not _quotes_balanced(s):
539
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
540
  refs = _FORMULA_REF.findall(s)
541
  leftover = _FORMULA_REF.sub("", s)
542
  if "{" in leftover or "}" in leftover: # unbalanced / nested braces
@@ -1247,6 +1329,7 @@ def rows_from_pool(pool_rows, fields=None, overlays=None, derived=None):
1247
  out = []
1248
  for r in pool_rows:
1249
  pid = r.get("pid")
 
1250
  # `_created` (wave-5 item 11) rides every row like `pid` does — the datum the
1251
  # `created_time` field type renders, regardless of that field's own key. Not a Field:
1252
  # it has no column of its own until a user creates one. `lat`/`lon` (wave-7 W11) ride
@@ -1258,11 +1341,12 @@ def rows_from_pool(pool_rows, fields=None, overlays=None, derived=None):
1258
  if field.get("derived"):
1259
  continue # not on the pool row — filled from `derived` below
1260
  v = r.get(k)
 
 
1261
  # D-153 — three roundings, not two: text/status/date pass through verbatim, currency
1262
  # and pct keep two decimals (`_round2`), everything else stays a whole number.
1263
  row[k] = v if field["type"] in {"text", "status", "date"} else (
1264
  _round2(v) if field["type"] in {"currency", "pct"} else _round(v))
1265
- saved = overlays.get(str(pid), {}) or {}
1266
  for field in overlay_fields:
1267
  row[field["key"]] = saved.get(field["key"], "")
1268
  got = derived.get(pid) or {}
@@ -2618,8 +2702,11 @@ def clean_filter_tree(raw, valid_keys, depth=1, budget=None, cohort_ids=None,
2618
  # is the same all-or-nothing the single-cohort leaf already had, extended to a set.
2619
  if op in COHORT_OPS and named and all(c in (cohort_ids or ()) for c in named):
2620
  budget[0] -= 1
2621
- out.append({'colId': COHORT_FIELD, 'op': op,
2622
- 'value': ','.join(named), 'value2': ''})
 
 
 
2623
  continue
2624
  if node.get('colId') == VIEW_FIELD: # C4: a view-membership leaf
2625
  # ⛔ THE SAME ALL-OR-NOTHING THE COHORT ARM ABOVE APPLIES, AND FOR THE SAME REASON.
@@ -2634,7 +2721,10 @@ def clean_filter_tree(raw, valid_keys, depth=1, budget=None, cohort_ids=None,
2634
  v_id = str(node.get('value') or '').strip()[:MAX_VIEW_ID]
2635
  if v_op in VIEW_OPS and v_id and v_id in (visible_view_ids or ()):
2636
  budget[0] -= 1
2637
- out.append({'colId': VIEW_FIELD, 'op': v_op, 'value': v_id, 'value2': ''})
 
 
 
2638
  continue
2639
  if node.get('colId') in valid_keys and node.get('op') in FILTER_OPS:
2640
  budget[0] -= 1
@@ -2690,10 +2780,49 @@ def clean_filter_tree(raw, valid_keys, depth=1, budget=None, cohort_ids=None,
2690
  rhs = _clean_rhs(node.get('rhs'), valid_keys)
2691
  if rhs is not None:
2692
  leaf['rhs'] = rhs
 
 
 
 
 
2693
  out.append(leaf)
2694
  return out
2695
 
2696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2697
  def _clean_rank_scope(raw, valid_keys):
2698
  """The persisted rank scope, or ``None`` when absent/malformed.
2699
 
 
211
  #: Emitted with the cohort column's read-only mechanism — `source: 'odoo'` + `derived` — so
212
  #: the client never offers an editor and the host never accepts a cell write for them.
213
  READONLY_CUSTOM_TYPES = {"created_time", "formula"}
214
+ # Mirrored server persistence ceiling. ``core.route_system.MAX_OPTIONS`` owns what is published
215
+ # to clients; the focused contract gate keeps this import-free helper equal to that value.
216
+ MAX_FIELD_OPTIONS = 200
217
  MAX_FORMULA_LEN = 500
218
  #: `rating` bounds. Airtable caps at 10; below 2 a rating is a checkbox.
219
  RATING_MAX_DEFAULT, RATING_MAX_MIN, RATING_MAX_MAX = 5, 2, 10
 
228
  MEASURE_FIELD_TYPES = {"currency", "int", "pct"}
229
 
230
 
231
+ class OptionLimitExceeded(ValueError):
232
+ """A choice vocabulary cannot be represented without discarding entered values."""
233
+
234
+ def __init__(self, entered):
235
+ self.entered = int(entered)
236
+ self.limit = MAX_FIELD_OPTIONS
237
+ self.rejected = max(0, self.entered - self.limit)
238
+ super().__init__(
239
+ f"This list has {self.entered} choices; the server limit is {self.limit}, so "
240
+ f"{self.rejected} would be rejected. Remove {self.rejected} choices, then save."
241
+ )
242
+
243
+
244
  def _clean_options(raw):
245
  """Choices for a `select`: strings, trimmed, de-duplicated case-insensitively, capped.
246
  Mirrors types.ts parseOptions — a choice list that means one thing in the picker and
247
  another in the filter dropdown is a column with two vocabularies."""
248
  out, seen = [], set()
249
+ for v in list(raw or []):
250
  if not isinstance(v, (str, int, float)) or isinstance(v, bool):
251
  continue
252
  s = str(v).strip()[:120]
 
254
  continue
255
  seen.add(s.lower())
256
  out.append(s)
257
+ if len(out) > MAX_FIELD_OPTIONS:
258
+ raise OptionLimitExceeded(len(out))
259
+ return out
260
 
261
 
262
  def merge_choice_options(*sources):
 
457
  #: drift risk this file's docstring names. The charset says which characters may appear; the
458
  #: engine says what they mean. `_quotes_balanced` below is the one structural rule the quote
459
  #: character brings with it.
460
+ #: WAVE 42 G7 (2026-08-25) -- THE SAME SCAR, WIDENED IN THE SAME CHANGE THIS TIME.
461
+ #:
462
+ #: The client engine gained REGEX_EXTRACT, REGEX_REPLACE, SUBSTITUTE, FIND, SWITCH, DATEADD,
463
+ #: DATETIME_DIFF and DATETIME_FORMAT. Each added character below is admitted because a token
464
+ #: the client's tokenizer parses would otherwise die here:
465
+ #:
466
+ #: ' a SINGLE-QUOTED literal. Airtable documents units and date formats that way.
467
+ #: [ ] a regex character class, the commonest construct there is: "[0-9]+".
468
+ #: | ? \\ : regex alternation, optional/non-capturing groups, and escapes.
469
+ #: @ SUBSTITUTE/FIND over an email or URL.
470
+ #: # $ % TEXT number formats already accepted by the client; `$` is also a regex anchor.
471
+ #:
472
+ #: `;` stays refused: no legal formula token needs a statement separator.
473
+ _FORMULA_CHARS = re.compile(r"^[\w\s{}()+\-*/.,<>=!^&\"'\[\]|?:\\#$%@]*$")
474
  _FORMULA_REF = re.compile(r"\{([^{}]*)\}")
475
 
476
+ #: Longest single regex-pattern literal. The client independently caps both pattern and subject.
477
+ MAX_FORMULA_LITERAL_LEN = 200
478
+
479
+ #: Catastrophic-backtracking shape, applied to STRING LITERALS only. Applying this to the whole
480
+ #: source would also match ordinary arithmetic such as `({a} + {b}) * 2`.
481
+ _NESTED_QUANT = re.compile(r"\((?:[^()\\]|\\.)*[*+](?:[^()\\]|\\.)*\)\??\s*[*+]")
482
+
483
+
484
+ def _string_literals(s):
485
+ """Return literal bodies, or None for an unterminated quote.
486
+
487
+ This mirrors the client tokenizer's structural rule: single and double quoted strings are
488
+ equivalent, a doubled opening quote escapes itself, and the other quote kind is ordinary
489
+ text. It assigns no formula meaning; it only locates literal boundaries.
490
+ """
491
+ out = []
492
+ i = 0
493
+ n = len(s)
494
+ while i < n:
495
+ quote = s[i]
496
+ if quote not in ('"', "'"):
497
+ i += 1
498
+ continue
499
+ j = i + 1
500
+ body = []
501
+ while True:
502
+ if j >= n:
503
+ return None
504
+ if s[j] == quote:
505
+ if j + 1 < n and s[j + 1] == quote:
506
+ body.append(quote)
507
+ j += 2
508
+ continue
509
+ break
510
+ body.append(s[j])
511
+ j += 1
512
+ out.append("".join(body))
513
+ i = j + 1
514
+ return out
515
+
516
 
517
  def _quotes_balanced(s):
518
+ """Whether every single- or double-quoted literal is structurally closed.
519
 
520
+ A parity count is not sound now that both spellings are legal: the double quote inside
521
+ ``'5" pipe'`` is ordinary text, not an opener. The shared scanner answers exactly the same
522
+ boundary question as the client tokenizer without assigning meaning to the literal.
 
523
  """
524
+ return _string_literals(s) is not None
525
 
526
 
527
  #: Wave-18 C5-AUTOFIELD. `kind` is a whitelist because an unknown kind would be a column that
 
606
  return None
607
  if not _quotes_balanced(s):
608
  return None
609
+ # Regex patterns are user input reaching JavaScript's regex engine. The client owns the
610
+ # load-bearing runtime bounds (pattern AND subject); this structural wall rejects an obvious
611
+ # unsafe literal before it is stored. Run it on read too: literal shape is intrinsic and
612
+ # cannot become invalid merely because the table's field set later changes.
613
+ literals = _string_literals(s)
614
+ if literals is None:
615
+ return None
616
+ regexy = 'REGEX_' in s.upper()
617
+ for literal in literals:
618
+ if regexy and len(literal) > MAX_FORMULA_LITERAL_LEN:
619
+ return None
620
+ if _NESTED_QUANT.search(literal):
621
+ return None
622
  refs = _FORMULA_REF.findall(s)
623
  leftover = _FORMULA_REF.sub("", s)
624
  if "{" in leftover or "}" in leftover: # unbalanced / nested braces
 
1329
  out = []
1330
  for r in pool_rows:
1331
  pid = r.get("pid")
1332
+ saved = overlays.get(str(pid), {}) or {}
1333
  # `_created` (wave-5 item 11) rides every row like `pid` does — the datum the
1334
  # `created_time` field type renders, regardless of that field's own key. Not a Field:
1335
  # it has no column of its own until a user creates one. `lat`/`lon` (wave-7 W11) ride
 
1341
  if field.get("derived"):
1342
  continue # not on the pool row — filled from `derived` below
1343
  v = r.get(k)
1344
+ if k == "maps_url" and saved.get(k):
1345
+ v = saved[k]
1346
  # D-153 — three roundings, not two: text/status/date pass through verbatim, currency
1347
  # and pct keep two decimals (`_round2`), everything else stays a whole number.
1348
  row[k] = v if field["type"] in {"text", "status", "date"} else (
1349
  _round2(v) if field["type"] in {"currency", "pct"} else _round(v))
 
1350
  for field in overlay_fields:
1351
  row[field["key"]] = saved.get(field["key"], "")
1352
  got = derived.get(pid) or {}
 
2702
  # is the same all-or-nothing the single-cohort leaf already had, extended to a set.
2703
  if op in COHORT_OPS and named and all(c in (cohort_ids or ()) for c in named):
2704
  budget[0] -= 1
2705
+ leaf = {'colId': COHORT_FIELD, 'op': op,
2706
+ 'value': ','.join(named), 'value2': ''}
2707
+ if node.get('locked') is True:
2708
+ leaf['locked'] = True
2709
+ out.append(leaf)
2710
  continue
2711
  if node.get('colId') == VIEW_FIELD: # C4: a view-membership leaf
2712
  # ⛔ THE SAME ALL-OR-NOTHING THE COHORT ARM ABOVE APPLIES, AND FOR THE SAME REASON.
 
2721
  v_id = str(node.get('value') or '').strip()[:MAX_VIEW_ID]
2722
  if v_op in VIEW_OPS and v_id and v_id in (visible_view_ids or ()):
2723
  budget[0] -= 1
2724
+ leaf = {'colId': VIEW_FIELD, 'op': v_op, 'value': v_id, 'value2': ''}
2725
+ if node.get('locked') is True:
2726
+ leaf['locked'] = True
2727
+ out.append(leaf)
2728
  continue
2729
  if node.get('colId') in valid_keys and node.get('op') in FILTER_OPS:
2730
  budget[0] -= 1
 
2780
  rhs = _clean_rhs(node.get('rhs'), valid_keys)
2781
  if rhs is not None:
2782
  leaf['rhs'] = rhs
2783
+ # C3: a record lock is explicit on the leaf, not a view-wide presentation flag.
2784
+ # Once stored, grid_events preserves the containing filter config unless it is copied
2785
+ # to a new View; a later caller cannot turn this `True` into an editable-looking false.
2786
+ if node.get('locked') is True:
2787
+ leaf['locked'] = True
2788
  out.append(leaf)
2789
  return out
2790
 
2791
 
2792
+ def preserve_locked_view_records(prior_config, filters, sorts):
2793
+ """Return authoritative filter/sort records when an in-place lock was touched.
2794
+
2795
+ A lock protects its semantic position as well as its leaf text: moving a locked condition
2796
+ between AND/OR groups changes the question even when the leaf itself is byte-identical. We
2797
+ therefore retain the full corresponding list on any attempted change. A new View has no
2798
+ prior config, so copying is the explicit alteration path.
2799
+ """
2800
+ prior = prior_config if isinstance(prior_config, dict) else {}
2801
+ old_filters = prior.get('filters') if isinstance(prior.get('filters'), list) else []
2802
+ old_sorts = prior.get('sorts') if isinstance(prior.get('sorts'), list) else []
2803
+
2804
+ def _has_locked_filter(nodes):
2805
+ for node in nodes or ():
2806
+ if not isinstance(node, dict):
2807
+ continue
2808
+ if node.get('locked') is True:
2809
+ return True
2810
+ if _has_locked_filter(node.get('children') if isinstance(node.get('children'), list) else []):
2811
+ return True
2812
+ return False
2813
+
2814
+ def _same(left, right):
2815
+ return json.dumps(left, sort_keys=True, separators=(',', ':')) == json.dumps(
2816
+ right, sort_keys=True, separators=(',', ':'))
2817
+
2818
+ if _has_locked_filter(old_filters) and not _same(old_filters, filters):
2819
+ filters = json.loads(json.dumps(old_filters))
2820
+ if any(isinstance(rule, dict) and rule.get('locked') is True for rule in old_sorts) \
2821
+ and not _same(old_sorts, sorts):
2822
+ sorts = json.loads(json.dumps(old_sorts))
2823
+ return filters, sorts
2824
+
2825
+
2826
  def _clean_rank_scope(raw, valid_keys):
2827
  """The persisted rank scope, or ``None`` when absent/malformed.
2828
 
platform/aios_grid_fields.json CHANGED
@@ -1,5 +1,6 @@
1
  {
2
  "_comment": "CANONICAL field contract for the AIOS Airtable-style grid — the SINGLE source of truth. Consumed by platform/aios_grid.py (embed/Space host) and aios-web/api/main.py (standalone API), and regenerated into aios-web/web/public/sample_customers.json. Edit HERE only, then run aios-web/verify_fields_contract.py. source=odoo is READ-ONLY; source=overlay is the editable stratum (notes/tags) outside Odoo. type in {text,status,select,multiselect,currency,int,date,pct,url} (select = a fixed-choice READ-ONLY brand attribute; dba is the first, wave 2026-08-02. multiselect = one cell holding a comma-joined SET, so a choice list offers the MEMBERS, not the joined string; customer tags and product supplier are the first, wave 40 W40-T06. url = a link cell, GridCellKind.Uri, drawn by cells.ts and opened by CustomerGrid's scheme-guarded click path; maps_url is the first, wave 40 W40-T08). W40-T08 also adds created_on, the uniform records-created DATE column every database carries (owner I24). It is a plain date field and NOT the created_time TYPE on purpose: created_time renders the row-level _created datum and its value never lives at the field's own key, so it is invisible to the semantic topic, to a stored-cell read and to any host-side export, while a date field is an ordinary cell that all three can see. The _created datum still rides every row for a created_time column a user creates. `description` (wave 5) is the CANONICAL per-field description — every field must carry one, and since wave 7 (owner W8, 2026-07-28) every description is ONE SHORT PLAIN sentence (two only when a fact would otherwise mislead): what the field IS, nothing else — no filter tips, no '(none)' coaching, no rationale; the user's workspace NOTE overrides it in the (i) hover, never in this file. BUILDER FACT (documented here, deliberately NOT in user-facing text): blank connector attributes display as '(none)' (they are no longer all `text`: W40-T06 retyped eight of them to `select` and `tags` to `multiselect`, and the sentinel is a real member of every one of those vocabularies), so `is '(none)'` — not `is empty` — finds the blanks on agent/city/state/country/zip/payment_terms/pricelist/tags. filterable:false = the CONDITION BUILDER does not offer it (still displayed, still sortable); every such field must have a replacement declared in aios-web/verify_fields_contract.py. 2026-07-27 partner attributes: country/zip/payment_terms/pricelist/tags/customer_since all ship default:false. zip is TEXT because a postal code has leading zeros. Odoo's credit_limit (1% populated) and user_id salesperson (2%) are deliberately ABSENT; agent_ids is the salesperson field and AR is where credit exposure comes from. Wave-5 item 8 (2026-07-27): ltm_rev and at_risk are DELETED — LTM's replacement is a creatable Sales measure column (the demo column IS Sales · the last 12 months), at_risk's replacement is a formula field, e.g. MAX(0, {revenue_ly} - {revenue_ytd}). Wave-6 item 8 (2026-07-27, the no-buildable-presets rule): revenue_ytd, revenue_ly, orders_24m, aov and yoy_pct are DELETED — every one is self-buildable, so a frozen pre-set beside the builder was two ways to ask one question. Replacements (recorded in verify_fields_contract.py): creatable measure columns for Sales / Orders / Avg order $ over any period (harness/measure_filter.py ADMITTED carries revenue, orders and the composite aov), and a formula over two measure columns for YoY, e.g. ({sales_ytd} - {sales_ly}) / {sales_ly}. Stale view colIds naming the five self-heal on the next autosave (the established rule).",
 
3
  "fields": [
4
  {
5
  "key": "customer",
@@ -113,6 +114,7 @@
113
  "label": "Google Maps",
114
  "type": "url",
115
  "source": "odoo",
 
116
  "default": true,
117
  "description": "A Google Maps link to this customer's address."
118
  },
 
1
  {
2
  "_comment": "CANONICAL field contract for the AIOS Airtable-style grid — the SINGLE source of truth. Consumed by platform/aios_grid.py (embed/Space host) and aios-web/api/main.py (standalone API), and regenerated into aios-web/web/public/sample_customers.json. Edit HERE only, then run aios-web/verify_fields_contract.py. source=odoo is READ-ONLY; source=overlay is the editable stratum (notes/tags) outside Odoo. type in {text,status,select,multiselect,currency,int,date,pct,url} (select = a fixed-choice READ-ONLY brand attribute; dba is the first, wave 2026-08-02. multiselect = one cell holding a comma-joined SET, so a choice list offers the MEMBERS, not the joined string; customer tags and product supplier are the first, wave 40 W40-T06. url = a link cell, GridCellKind.Uri, drawn by cells.ts and opened by CustomerGrid's scheme-guarded click path; maps_url is the first, wave 40 W40-T08). W40-T08 also adds created_on, the uniform records-created DATE column every database carries (owner I24). It is a plain date field and NOT the created_time TYPE on purpose: created_time renders the row-level _created datum and its value never lives at the field's own key, so it is invisible to the semantic topic, to a stored-cell read and to any host-side export, while a date field is an ordinary cell that all three can see. The _created datum still rides every row for a created_time column a user creates. `description` (wave 5) is the CANONICAL per-field description — every field must carry one, and since wave 7 (owner W8, 2026-07-28) every description is ONE SHORT PLAIN sentence (two only when a fact would otherwise mislead): what the field IS, nothing else — no filter tips, no '(none)' coaching, no rationale; the user's workspace NOTE overrides it in the (i) hover, never in this file. BUILDER FACT (documented here, deliberately NOT in user-facing text): blank connector attributes display as '(none)' (they are no longer all `text`: W40-T06 retyped eight of them to `select` and `tags` to `multiselect`, and the sentinel is a real member of every one of those vocabularies), so `is '(none)'` — not `is empty` — finds the blanks on agent/city/state/country/zip/payment_terms/pricelist/tags. filterable:false = the CONDITION BUILDER does not offer it (still displayed, still sortable); every such field must have a replacement declared in aios-web/verify_fields_contract.py. 2026-07-27 partner attributes: country/zip/payment_terms/pricelist/tags/customer_since all ship default:false. zip is TEXT because a postal code has leading zeros. Odoo's credit_limit (1% populated) and user_id salesperson (2%) are deliberately ABSENT; agent_ids is the salesperson field and AR is where credit exposure comes from. Wave-5 item 8 (2026-07-27): ltm_rev and at_risk are DELETED — LTM's replacement is a creatable Sales measure column (the demo column IS Sales · the last 12 months), at_risk's replacement is a formula field, e.g. MAX(0, {revenue_ly} - {revenue_ytd}). Wave-6 item 8 (2026-07-27, the no-buildable-presets rule): revenue_ytd, revenue_ly, orders_24m, aov and yoy_pct are DELETED — every one is self-buildable, so a frozen pre-set beside the builder was two ways to ask one question. Replacements (recorded in verify_fields_contract.py): creatable measure columns for Sales / Orders / Avg order $ over any period (harness/measure_filter.py ADMITTED carries revenue, orders and the composite aov), and a formula over two measure columns for YoY, e.g. ({sales_ytd} - {sales_ly}) / {sales_ly}. Stale view colIds naming the five self-heal on the next autosave (the established rule).",
3
+ "_valueOverride": "A source field remains immutable unless its exact contract carries valueOverride=overlay; maps_url is the only admitted source-backed override.",
4
  "fields": [
5
  {
6
  "key": "customer",
 
114
  "label": "Google Maps",
115
  "type": "url",
116
  "source": "odoo",
117
+ "valueOverride": "overlay",
118
  "default": true,
119
  "description": "A Google Maps link to this customer's address."
120
  },
platform/core/field_permissions.py CHANGED
@@ -26,6 +26,26 @@ FIELD_ORIGINS = ("preset", "user")
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,6 +220,82 @@ def field_origin(field):
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,12 +368,24 @@ def grant_records(grant_topic, st=None):
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,6 +434,19 @@ def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
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,8 +463,45 @@ def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
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,10 +512,19 @@ def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
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,13 +539,30 @@ def field_class(field, viewer, grants=None, *, table_key=None, grant_topic=None,
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,6 +573,7 @@ def field_classes(fields, viewer, *, table_key=None, grant_topic=None, values_sh
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,7 +583,7 @@ def field_classes(fields, viewer, *, table_key=None, grant_topic=None, values_sh
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
 
@@ -416,7 +601,7 @@ def _same_classification(left, right):
416
  return set(left.get("users") or ()) == set(right.get("users") or ())
417
 
418
 
419
- def reconcile_shared_permissions(shared_key, grant_topic, st=None):
420
  """Re-derive every SHARED definition's `permissions` bag from the grant registry. Returns the
421
  number of definitions actually rewritten.
422
 
@@ -463,7 +648,8 @@ def reconcile_shared_permissions(shared_key, grant_topic, st=None):
463
  if not bucket or st is None:
464
  return 0
465
  rewritten = 0
466
- for field_key, defn in list(shared_overlay.fields(bucket, st=st).items()):
 
467
  # ⚠ EACH DEFINITION IS GUARDED ON ITS OWN. `shares.field_oid` RAISES on an empty key, and
468
  # the caller wraps this whole function in one swallowing except — so a single malformed
469
  # entry would otherwise skip every REMAINING column, including the one the owner reported,
@@ -494,6 +680,8 @@ def reconcile_shared_permissions(shared_key, grant_topic, st=None):
494
  updated = dict(defn)
495
  updated["permissions"] = derived
496
  shared_overlay.put_field(bucket, key, updated, st=st)
 
 
497
  rewritten += 1
498
  except Exception:
499
  continue
@@ -648,12 +836,14 @@ def _field_is_migratable(field):
648
  and field.get("source") == "overlay")
649
 
650
 
651
- def migrate_legacy_fields(table_key, st=None, known_users=None, grant_topic=None, shared_key=None):
 
652
  """Promote legacy shared-looking custom fields into the shared field stratum.
653
 
654
  The operation is intentionally idempotent and copy-before-remove. A failed request can
655
  therefore leave a private shadow behind, but it cannot lose the creator's values. The next
656
- read retries the promotion and the shared definition wins.
 
657
  """
658
  key = str(table_key or "").strip()
659
  grant_key = str(grant_topic or key).strip()
@@ -679,14 +869,25 @@ def migrate_legacy_fields(table_key, st=None, known_users=None, grant_topic=None
679
  # finds no grant record, the "no record" arm fires for every column, and the reconcile
680
  # silently does nothing at all.
681
  try:
682
- reclassified = reconcile_shared_permissions(shared_key, grant_key, st=st)
 
683
  except Exception:
684
  reclassified = 0
685
- try:
686
- document = st.get(key) or {}
687
- except Exception:
688
- return {"promoted": 0, "normalized": 0, "reclassified": reclassified,
689
- "suppressed": 0, "purged": 0}
 
 
 
 
 
 
 
 
 
 
690
  if not isinstance(document, dict):
691
  return {"promoted": 0, "normalized": 0, "reclassified": reclassified,
692
  "suppressed": 0, "purged": 0}
@@ -730,7 +931,8 @@ def migrate_legacy_fields(table_key, st=None, known_users=None, grant_topic=None
730
  normalized += 1
731
  continue
732
 
733
- existing = shared_overlay.fields(shared_key, st=st).get(field_key)
 
734
  if isinstance(existing, dict):
735
  # A completed promotion is authoritative. Remove a duplicate personal copy
736
  # only when it has the same creator; a collision from another owner fails closed.
@@ -744,6 +946,8 @@ def migrate_legacy_fields(table_key, st=None, known_users=None, grant_topic=None
744
  "createdBy": original.get("createdBy") or owner,
745
  "source": "overlay", "custom": True})
746
  shared_overlay.put_field(shared_key, field_key, shared, st=st)
 
 
747
  promoted += 1
748
 
749
  rows = {}
@@ -790,7 +994,7 @@ def migrate_legacy_fields(table_key, st=None, known_users=None, grant_topic=None
790
  purged = 0
791
  if tombstoned:
792
  try:
793
- live = shared_overlay.fields(shared_key, st=st)
794
  except Exception: # noqa: BLE001
795
  live = {}
796
  for dead in tombstoned:
 
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
  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
 
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
  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
  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
  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
  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
  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
  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
 
 
601
  return set(left.get("users") or ()) == set(right.get("users") or ())
602
 
603
 
604
+ def reconcile_shared_permissions(shared_key, grant_topic, st=None, shared_document=None):
605
  """Re-derive every SHARED definition's `permissions` bag from the grant registry. Returns the
606
  number of definitions actually rewritten.
607
 
 
648
  if not bucket or st is None:
649
  return 0
650
  rewritten = 0
651
+ for field_key, defn in list(shared_overlay.fields(
652
+ bucket, st=st, document=shared_document).items()):
653
  # ⚠ EACH DEFINITION IS GUARDED ON ITS OWN. `shares.field_oid` RAISES on an empty key, and
654
  # the caller wraps this whole function in one swallowing except — so a single malformed
655
  # entry would otherwise skip every REMAINING column, including the one the owner reported,
 
680
  updated = dict(defn)
681
  updated["permissions"] = derived
682
  shared_overlay.put_field(bucket, key, updated, st=st)
683
+ if isinstance(shared_document, dict):
684
+ shared_document.setdefault("fields", {})[key] = updated
685
  rewritten += 1
686
  except Exception:
687
  continue
 
836
  and field.get("source") == "overlay")
837
 
838
 
839
+ def migrate_legacy_fields(table_key, st=None, known_users=None, grant_topic=None, shared_key=None,
840
+ workspace_document=None, shared_document=None):
841
  """Promote legacy shared-looking custom fields into the shared field stratum.
842
 
843
  The operation is intentionally idempotent and copy-before-remove. A failed request can
844
  therefore leave a private shadow behind, but it cannot lose the creator's values. The next
845
+ read retries the promotion and the shared definition wins. A caller that already captured
846
+ the workspace document may lend that read-only snapshot to avoid reopening the same key.
847
  """
848
  key = str(table_key or "").strip()
849
  grant_key = str(grant_topic or key).strip()
 
869
  # finds no grant record, the "no record" arm fires for every column, and the reconcile
870
  # silently does nothing at all.
871
  try:
872
+ reclassified = reconcile_shared_permissions(
873
+ shared_key, grant_key, st=st, shared_document=shared_document)
874
  except Exception:
875
  reclassified = 0
876
+ # W44 predecessor replay: a table assembly has already read this exact document through
877
+ # `TableStore.workspace(..., include_document=True)`. Reopening it here paid a third whole
878
+ # `<key>_table_workspace` copy for the same rows request. Accept that captured snapshot when
879
+ # supplied; every historical/cold caller still takes the original `st.get(key)` path.
880
+ #
881
+ # A non-dict is NOT treated as an empty captured document. It falls back to the store so a
882
+ # malformed optional argument cannot suppress an existing migration by manufacturing `{}`.
883
+ if isinstance(workspace_document, dict):
884
+ document = workspace_document
885
+ else:
886
+ try:
887
+ document = st.get(key) or {}
888
+ except Exception:
889
+ return {"promoted": 0, "normalized": 0, "reclassified": reclassified,
890
+ "suppressed": 0, "purged": 0}
891
  if not isinstance(document, dict):
892
  return {"promoted": 0, "normalized": 0, "reclassified": reclassified,
893
  "suppressed": 0, "purged": 0}
 
931
  normalized += 1
932
  continue
933
 
934
+ existing = shared_overlay.fields(
935
+ shared_key, st=st, document=shared_document).get(field_key)
936
  if isinstance(existing, dict):
937
  # A completed promotion is authoritative. Remove a duplicate personal copy
938
  # only when it has the same creator; a collision from another owner fails closed.
 
946
  "createdBy": original.get("createdBy") or owner,
947
  "source": "overlay", "custom": True})
948
  shared_overlay.put_field(shared_key, field_key, shared, st=st)
949
+ if isinstance(shared_document, dict):
950
+ shared_document.setdefault("fields", {})[field_key] = dict(shared)
951
  promoted += 1
952
 
953
  rows = {}
 
994
  purged = 0
995
  if tombstoned:
996
  try:
997
+ live = shared_overlay.fields(shared_key, st=st, document=shared_document)
998
  except Exception: # noqa: BLE001
999
  live = {}
1000
  for dead in tombstoned:
platform/core/grid_events.py CHANGED
@@ -333,6 +333,18 @@ def _may_edit_field_value(ctx, key, definition):
333
  str(user).lower() for user in (perms.get('users') or [])})
334
 
335
 
 
 
 
 
 
 
 
 
 
 
 
 
336
  def _cohorts(ctx):
337
  """The COHORT store this ctx operates on — `_tops`'s sibling, and here for the same reason.
338
 
@@ -507,7 +519,7 @@ def _grant_marker(ctx, ws):
507
  return _has_grants
508
 
509
 
510
- def table_workspace(ctx, allowed_pids=None, consume_corrections=True):
511
  """Durable Airtable-style view/schema/overlay state, with an honest session fallback.
512
 
513
  Wave-9 I17: the returned `views` are this user's OWN views MERGED with every view SHARED
@@ -534,8 +546,13 @@ def table_workspace(ctx, allowed_pids=None, consume_corrections=True):
534
  """
535
  uname = ctx.uname
536
  if _store_of(ctx).available():
537
- ws = _tops(ctx).workspace(
538
- uname, consume_corrections=bool(consume_corrections))
 
 
 
 
 
539
  try:
540
  shared = _tops(ctx).shared_views(uname, bool(ctx.admin))
541
  except Exception as _se:
@@ -1261,7 +1278,8 @@ def handle_one(event, ctx):
1261
  # vocabulary is absent (ordinary customer and legacy in-memory contexts have none).
1262
  pass
1263
  valid_keys = set(field_by_key)
1264
- overlay_keys = {f['key'] for f in fields if f.get('source') == 'overlay'}
 
1265
  # Event validation is not a render payload. It must not consume a one-shot label
1266
  # correction before the browser has had a chance to receive it.
1267
  ws = table_workspace(
@@ -1371,7 +1389,10 @@ def handle_one(event, ctx):
1371
  for rule in list(cfg.get('sorts') or [])[:20]:
1372
  if (isinstance(rule, dict) and rule.get('colId') in valid_keys
1373
  and rule.get('dir') in ('asc', 'desc')):
1374
- sorts.append({'colId': rule['colId'], 'dir': rule['dir']})
 
 
 
1375
  order = list(dict.fromkeys(
1376
  key for key in list(cfg.get('order') or []) if key in valid_keys))
1377
  order += [field['key'] for field in fields if field['key'] not in order]
@@ -1469,6 +1490,14 @@ def handle_one(event, ctx):
1469
  if _raw_shared is not None and not _tstore._may_edit(_raw_shared, uname, admin):
1470
  return False # visible but not editable by this caller
1471
  is_new = not prior
 
 
 
 
 
 
 
 
1472
  # C4: the creator is HOST-STAMPED and never read from the browser — the same rule as
1473
  # the field-level createdBy. An existing view keeps whoever made it.
1474
  creator = prior.get('createdBy') or uname
@@ -1787,7 +1816,10 @@ def handle_one(event, ctx):
1787
  # its list and visual treatment rather than silently preserving a
1788
  # read-only source projection.
1789
  if field.get('type') in ('select', 'multiselect') and 'options' in raw:
1790
- options = _ag2._clean_options(raw.get('options'))
 
 
 
1791
  if not options:
1792
  return _refuse(
1793
  ctx, 'no_options', 'a select column needs at least one choice', key)
@@ -1895,7 +1927,10 @@ def handle_one(event, ctx):
1895
  # choices are the tenant's accounts, resolved fresh on every render, so persisting
1896
  # a snapshot here would go stale the moment somebody joins or leaves.
1897
  if ftype in ('select', 'multiselect'):
1898
- field['options'] = _ag2._clean_options(raw.get('options'))
 
 
 
1899
  if not field['options']:
1900
  # a select with no choices can never hold a value
1901
  return _refuse(
@@ -3105,7 +3140,7 @@ def handle_one(event, ctx):
3105
  # A choice value is DATA, not a precondition the field editor must have visited.
3106
  # Pasted/imported/API values therefore mint an option through this same write
3107
  # door. It is deliberately still bounded and case-canonical: "ET" then "et"
3108
- # is one option, and the 51st distinct label is refused rather than creating a
3109
  # picker the contract cannot represent.
3110
  import aios_grid as _ag_choices
3111
  options = _ag_choices.merge_choice_options(definition.get('options'))
 
333
  str(user).lower() for user in (perms.get('users') or [])})
334
 
335
 
336
+ def _may_override_source_value(definition):
337
+ """One source-backed value may write through the ordinary overlay door.
338
+
339
+ The canonical field contract must carry the capability and the field identity must still be
340
+ Maps. Requiring both prevents a copied or caller-forged flag from widening every Odoo field.
341
+ """
342
+ return (isinstance(definition, dict)
343
+ and definition.get('key') == 'maps_url'
344
+ and definition.get('source') == 'odoo'
345
+ and definition.get('valueOverride') == 'overlay')
346
+
347
+
348
  def _cohorts(ctx):
349
  """The COHORT store this ctx operates on — `_tops`'s sibling, and here for the same reason.
350
 
 
519
  return _has_grants
520
 
521
 
522
+ def table_workspace(ctx, allowed_pids=None, consume_corrections=True, capture_document=False):
523
  """Durable Airtable-style view/schema/overlay state, with an honest session fallback.
524
 
525
  Wave-9 I17: the returned `views` are this user's OWN views MERGED with every view SHARED
 
546
  """
547
  uname = ctx.uname
548
  if _store_of(ctx).available():
549
+ read = _tops(ctx).workspace(
550
+ uname, consume_corrections=bool(consume_corrections),
551
+ include_document=bool(capture_document))
552
+ if capture_document:
553
+ ws, ctx.workspace_document = read
554
+ else:
555
+ ws = read
556
  try:
557
  shared = _tops(ctx).shared_views(uname, bool(ctx.admin))
558
  except Exception as _se:
 
1278
  # vocabulary is absent (ordinary customer and legacy in-memory contexts have none).
1279
  pass
1280
  valid_keys = set(field_by_key)
1281
+ overlay_keys = {f['key'] for f in fields
1282
+ if f.get('source') == 'overlay' or _may_override_source_value(f)}
1283
  # Event validation is not a render payload. It must not consume a one-shot label
1284
  # correction before the browser has had a chance to receive it.
1285
  ws = table_workspace(
 
1389
  for rule in list(cfg.get('sorts') or [])[:20]:
1390
  if (isinstance(rule, dict) and rule.get('colId') in valid_keys
1391
  and rule.get('dir') in ('asc', 'desc')):
1392
+ clean_sort = {'colId': rule['colId'], 'dir': rule['dir']}
1393
+ if rule.get('locked') is True:
1394
+ clean_sort['locked'] = True
1395
+ sorts.append(clean_sort)
1396
  order = list(dict.fromkeys(
1397
  key for key in list(cfg.get('order') or []) if key in valid_keys))
1398
  order += [field['key'] for field in fields if field['key'] not in order]
 
1490
  if _raw_shared is not None and not _tstore._may_edit(_raw_shared, uname, admin):
1491
  return False # visible but not editable by this caller
1492
  is_new = not prior
1493
+ if not is_new:
1494
+ # W44 C3: filters/sorts locked in an existing View are immutable records. This
1495
+ # runs after the visibility/edit wall has established `prior`, so a guessed foreign
1496
+ # view cannot be used as a source of lock state. A copied View has no prior and is
1497
+ # consequently the only alteration path.
1498
+ filters, sorts = _ag.preserve_locked_view_records(
1499
+ prior.get('config') or {}, filters, sorts)
1500
+ config['filters'], config['sorts'] = filters, sorts
1501
  # C4: the creator is HOST-STAMPED and never read from the browser — the same rule as
1502
  # the field-level createdBy. An existing view keeps whoever made it.
1503
  creator = prior.get('createdBy') or uname
 
1816
  # its list and visual treatment rather than silently preserving a
1817
  # read-only source projection.
1818
  if field.get('type') in ('select', 'multiselect') and 'options' in raw:
1819
+ try:
1820
+ options = _ag2._clean_options(raw.get('options'))
1821
+ except _ag2.OptionLimitExceeded as exc:
1822
+ return _refuse(ctx, 'option_limit', str(exc), key)
1823
  if not options:
1824
  return _refuse(
1825
  ctx, 'no_options', 'a select column needs at least one choice', key)
 
1927
  # choices are the tenant's accounts, resolved fresh on every render, so persisting
1928
  # a snapshot here would go stale the moment somebody joins or leaves.
1929
  if ftype in ('select', 'multiselect'):
1930
+ try:
1931
+ field['options'] = _ag2._clean_options(raw.get('options'))
1932
+ except _ag2.OptionLimitExceeded as exc:
1933
+ return _refuse(ctx, 'option_limit', str(exc), key)
1934
  if not field['options']:
1935
  # a select with no choices can never hold a value
1936
  return _refuse(
 
3140
  # A choice value is DATA, not a precondition the field editor must have visited.
3141
  # Pasted/imported/API values therefore mint an option through this same write
3142
  # door. It is deliberately still bounded and case-canonical: "ET" then "et"
3143
+ # is one option, and the 201st distinct label is refused rather than creating a
3144
  # picker the contract cannot represent.
3145
  import aios_grid as _ag_choices
3146
  options = _ag_choices.merge_choice_options(definition.get('options'))
platform/core/route_system.py ADDED
@@ -0,0 +1,886 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Loopable-owned Route/Zone system data (Wave 44 C1/C2).
2
+
3
+ The browser never writes the two system databases through the generic table surface. This module
4
+ owns their normalized document and exposes narrow Route/Zone writers. ``InternalWriterCapability``
5
+ remains for the generic-policy seam; it is not a browser credential.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ import datetime as _dt
11
+ import hashlib
12
+ import math
13
+ import re
14
+ import uuid
15
+
16
+ MANAGED_BY = "loopable"
17
+ LOOPABLE_FOLDER_ID = "loopable"
18
+ LOOPABLE_FOLDER = {"id": LOOPABLE_FOLDER_ID, "name": "Loopable", "managedBy": MANAGED_BY}
19
+ ROUTES_KEY, ZONES_KEY = "ut_odoo_customers_routes", "ut_odoo_customers_zones"
20
+ SYSTEM_TABLES = {ROUTES_KEY: "Odoo Customers - Routes", ZONES_KEY: "Odoo Customers - Zones"}
21
+
22
+ # TenantRuntime namespaces this bucket. User-table rows are scalar user data; route stops are a
23
+ # protected relation (route id + customer id + order), so they cannot be a generic Link field.
24
+ STORE_KEY = "loopable_route_system"
25
+ # C3 owns this ceiling on the server. Every field payload publishes it, and clients that do not
26
+ # receive it must refuse choice edits rather than guessing a local value.
27
+ MAX_OPTIONS = 200
28
+ _ROUTE_COLORS = ("#6E4AC7", "#1F4E78", "#C85A54", "#2F8F83", "#B57716", "#A14B8B")
29
+ _COLOR_RE = re.compile(r"^#[0-9A-Fa-f]{6}$")
30
+ _ZIP_RE = re.compile(r"^[A-Za-z0-9 -]{1,20}$")
31
+ _GOOGLE_MAPS_URL_RE = re.compile(
32
+ r"^https://(?:(?:www\.)?google\.(?:com|co\.[a-z]{2}|[a-z]{2,3})|maps\.app\.goo\.gl|goo\.gl)/", re.I)
33
+
34
+
35
+ class InternalWriterCapability:
36
+ """Opaque capability intentionally constructible only by this module."""
37
+ __slots__ = ("_token",)
38
+
39
+ def __init__(self, token):
40
+ self._token = token
41
+
42
+
43
+ _TOKEN = object()
44
+
45
+
46
+ def internal_writer_capability():
47
+ return InternalWriterCapability(_TOKEN)
48
+
49
+
50
+ def is_internal_writer(capability):
51
+ return isinstance(capability, InternalWriterCapability) and capability._token is _TOKEN
52
+
53
+
54
+ def descriptor(key):
55
+ label = SYSTEM_TABLES.get(str(key))
56
+ if not label:
57
+ return None
58
+ return {"key": str(key), "label": label, "managedBy": MANAGED_BY,
59
+ "folderId": LOOPABLE_FOLDER_ID, "protected": True, "source": "Loopable",
60
+ "recordsMutable": False, "canDelete": False, "canMove": False}
61
+
62
+
63
+ def system_table_descriptors():
64
+ """Virtual Data-nav rows that exist before the first Route is created."""
65
+ return [dict(descriptor(key)) for key in (ROUTES_KEY, ZONES_KEY)]
66
+
67
+
68
+ def is_managed(definition_or_key):
69
+ if isinstance(definition_or_key, dict):
70
+ return definition_or_key.get("managedBy") == MANAGED_BY
71
+ return str(definition_or_key) in SYSTEM_TABLES
72
+
73
+
74
+ def may_generic_mutate(definition_or_key, capability=None):
75
+ return not is_managed(definition_or_key) or is_internal_writer(capability)
76
+
77
+
78
+ def field_axes(field):
79
+ """Return the closed C3 axes without accepting caller-invented vocabulary."""
80
+ field = dict(field or {})
81
+ ftype = str(field.get("type") or "text")
82
+ source = str(field.get("source") or "odoo")
83
+ origin = field.get("origin") or ({"odoo": "odoo", "overlay": "user"}.get(source, "system"))
84
+ if origin not in {"odoo", "loopable", "system", "user", "automation"}:
85
+ raise ValueError("unapproved field origin")
86
+ kind = field.get("kind") or ftype
87
+ authority = field.get("valueAuthority") or (
88
+ "derived" if source == "odoo" or field.get("derived") else "user-entered")
89
+ scope = field.get("scope") or ("source" if source == "odoo" else "tenant")
90
+ if authority not in {"source", "derived", "user-entered", "computed"} or scope not in {"source", "tenant", "view", "record"}:
91
+ raise ValueError("unapproved field axis")
92
+ field.update({"kind": kind, "origin": origin, "valueAuthority": authority, "scope": scope})
93
+ # Publish the server-owned limit on EVERY field. The Add-field pane needs the contract before
94
+ # the choice field it is creating exists; restricting it to existing choice fields forces a
95
+ # client literal (or an unsafe guess) on an empty table. Overwrite caller-supplied values:
96
+ # stored metadata is not allowed to mint a different product limit.
97
+ limits = dict(field.get("limits") or {})
98
+ limits["maxOptions"] = MAX_OPTIONS
99
+ field["limits"] = limits
100
+ if ftype == "json":
101
+ field["label"] = "Table"
102
+ return field
103
+
104
+
105
+ def inject_loopable_folder(workspace):
106
+ """Server projection: personal preferences cannot remove or relocate this folder."""
107
+ out = copy.deepcopy(workspace or {})
108
+ folders = out.setdefault("folders", [])
109
+ existing = next((row for row in folders if isinstance(row, dict)
110
+ and row.get("id") == LOOPABLE_FOLDER_ID), None)
111
+ if existing is None:
112
+ folders.append(dict(LOOPABLE_FOLDER))
113
+ else:
114
+ existing.update(LOOPABLE_FOLDER)
115
+ return out
116
+
117
+
118
+ def _now():
119
+ return _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0).isoformat()
120
+
121
+
122
+ def _store(st):
123
+ try:
124
+ return dict(st.get(STORE_KEY) or {})
125
+ except Exception:
126
+ return {}
127
+
128
+
129
+ def _pid(raw):
130
+ if isinstance(raw, bool):
131
+ return None
132
+ try:
133
+ value = int(raw)
134
+ except (TypeError, ValueError):
135
+ return None
136
+ return value if value >= 0 else None
137
+
138
+
139
+ def _color(raw, ordinal=0):
140
+ value = str(raw or "").upper()
141
+ return value if _COLOR_RE.fullmatch(value) else _ROUTE_COLORS[ordinal % len(_ROUTE_COLORS)]
142
+
143
+
144
+ def _name(raw):
145
+ return " ".join(str(raw or "").split())[:120]
146
+
147
+
148
+ def _stops(raw):
149
+ """Canonical dense stop relation. One customer can occur once in a Route."""
150
+ offered, seen = [], set()
151
+ for item in raw or ():
152
+ candidate = item.get("customerPid") if isinstance(item, dict) else item
153
+ pid = _pid(candidate)
154
+ if pid is not None and pid not in seen:
155
+ seen.add(pid)
156
+ offered.append(pid)
157
+ return [{"customerPid": pid, "position": index + 1}
158
+ for index, pid in enumerate(offered)]
159
+
160
+
161
+ def ordered_stops(route):
162
+ return [dict(stop) for stop in sorted(route.get("stops") or [],
163
+ key=lambda stop: int(stop.get("position") or 0))]
164
+
165
+
166
+ def _route(raw, *, ordinal=0, created_by="", tenant_id="", prior=None):
167
+ raw = raw if isinstance(raw, dict) else {}
168
+ prior = prior if isinstance(prior, dict) else {}
169
+ name = _name(raw.get("name", prior.get("name")))
170
+ if not name:
171
+ return None
172
+ rid = str(raw.get("id") or prior.get("id") or "route_" + uuid.uuid4().hex)[:96]
173
+ source_view = raw.get("sourceViewId", raw.get("source_view_id", prior.get("sourceViewId")))
174
+ source_view = str(source_view or "").strip()[:120] or None
175
+ revision = raw.get("sourceViewRevision", prior.get("sourceViewRevision"))
176
+ revision = str(revision or "").strip()[:128] or None
177
+ stops_raw = raw.get("stops") if "stops" in raw else prior.get("stops")
178
+ maps_url = str(raw.get("mapsUrl", prior.get("mapsUrl")) or "").strip()[:2048]
179
+ if maps_url and not _GOOGLE_MAPS_URL_RE.match(maps_url):
180
+ return None
181
+ stamp = _now()
182
+ share_key = str(raw.get("shareKey") or prior.get("shareKey") or route_share_key(rid))[:80]
183
+ out = {"id": rid, "tenantId": str(tenant_id or prior.get("tenantId") or ""), "name": name,
184
+ "color": _color(raw.get("color", prior.get("color")), ordinal),
185
+ "number": int(prior.get("number") or ordinal + 1), "sourceViewId": source_view,
186
+ "sourceViewRevision": revision, "stops": _stops(stops_raw), "managedBy": MANAGED_BY,
187
+ "createdBy": str(prior.get("createdBy") or created_by or "")[:120],
188
+ "shareKey": share_key,
189
+ "createdAt": prior.get("createdAt") or stamp, "updatedAt": stamp}
190
+ if maps_url:
191
+ out["mapsUrl"] = maps_url
192
+ migration = raw.get("migration", prior.get("migration"))
193
+ if isinstance(migration, dict):
194
+ out["migration"] = {"legacyField": str(migration.get("legacyField") or "")[:80],
195
+ "verified": migration.get("verified") is True}
196
+ return out
197
+
198
+
199
+ def _point_in_ring(lon, lat, ring):
200
+ inside = False
201
+ if len(ring) < 4:
202
+ return False
203
+ for index, point in enumerate(ring):
204
+ previous = ring[index - 1]
205
+ try:
206
+ x1, y1, x2, y2 = float(previous[0]), float(previous[1]), float(point[0]), float(point[1])
207
+ except (TypeError, ValueError, IndexError):
208
+ return False
209
+ intersects = (y1 > lat) != (y2 > lat)
210
+ if intersects and lon < (x2 - x1) * (lat - y1) / ((y2 - y1) or 1e-15) + x1:
211
+ inside = not inside
212
+ return inside
213
+
214
+
215
+ def _polygon_contains(geometry, lon, lat):
216
+ if not isinstance(geometry, dict):
217
+ return False
218
+ kind, coords = geometry.get("type"), geometry.get("coordinates")
219
+ polygons = [coords] if kind == "Polygon" else coords if kind == "MultiPolygon" else []
220
+ for polygon in polygons or ():
221
+ if not isinstance(polygon, list) or not polygon:
222
+ continue
223
+ if _point_in_ring(lon, lat, polygon[0]) and not any(
224
+ _point_in_ring(lon, lat, ring) for ring in polygon[1:]):
225
+ return True
226
+ return False
227
+
228
+
229
+ def _zone(raw, *, ordinal=0, created_by="", tenant_id="", prior=None):
230
+ raw = raw if isinstance(raw, dict) else {}
231
+ prior = prior if isinstance(prior, dict) else {}
232
+ name = _name(raw.get("name", prior.get("name")))
233
+ geometry = raw.get("geometryGeoJson", prior.get("geometryGeoJson"))
234
+ zips_raw = raw.get("zipCodes", prior.get("zipCodes", ()))
235
+ zips, seen = [], set()
236
+ for value in zips_raw or ():
237
+ text = " ".join(str(value or "").upper().split())[:20]
238
+ if text and text not in seen and _ZIP_RE.fullmatch(text):
239
+ seen.add(text)
240
+ zips.append(text)
241
+ if not name or (geometry is not None and not isinstance(geometry, dict)) or (geometry is None and not zips):
242
+ return None
243
+ zid = str(raw.get("id") or prior.get("id") or "zone_" + uuid.uuid4().hex)[:96]
244
+ source_view = raw.get("sourceViewId", prior.get("sourceViewId"))
245
+ source_view = str(source_view or "").strip()[:120] or None
246
+ geographic_field = raw.get("geographicField", prior.get("geographicField"))
247
+ geographic_field = str(geographic_field or "").strip()[:120]
248
+ stamp = _now()
249
+ return {"id": zid, "tenantId": str(tenant_id or prior.get("tenantId") or ""), "name": name,
250
+ "color": _color(raw.get("color", prior.get("color")), ordinal),
251
+ "geometryGeoJson": copy.deepcopy(geometry) if isinstance(geometry, dict) else None,
252
+ "zipCodes": zips, "visible": raw.get("visible", prior.get("visible", True)) is not False,
253
+ "sourceViewId": source_view, "geographicField": geographic_field,
254
+ "membershipRevision": int(prior.get("membershipRevision") or 0),
255
+ "memberPids": [int(pid) for pid in prior.get("memberPids") or [] if _pid(pid) is not None],
256
+ "managedBy": MANAGED_BY, "createdBy": str(prior.get("createdBy") or created_by or "")[:120],
257
+ "createdAt": prior.get("createdAt") or stamp, "updatedAt": stamp}
258
+
259
+
260
+ def _customer_zip(row):
261
+ for key in ("zip", "zip_code", "postal_code", "postalCode"):
262
+ value = row.get(key) if isinstance(row, dict) else None
263
+ text = " ".join(str(value or "").upper().split())[:20]
264
+ if text:
265
+ return text
266
+ return ""
267
+
268
+
269
+ def zone_members(zone, rows):
270
+ """Polygon-or-ZIP UNION, recalculated from the current customer address projection."""
271
+ zips = set(zone.get("zipCodes") or ())
272
+ out = []
273
+ for row in rows or ():
274
+ pid = _pid((row or {}).get("pid"))
275
+ if pid is None:
276
+ continue
277
+ zip_match = _customer_zip(row) in zips
278
+ try:
279
+ lon, lat = float(row.get("lon")), float(row.get("lat"))
280
+ polygon_match = math.isfinite(lon) and math.isfinite(lat) and _polygon_contains(
281
+ zone.get("geometryGeoJson"), lon, lat)
282
+ except (TypeError, ValueError):
283
+ polygon_match = False
284
+ if zip_match or polygon_match:
285
+ out.append(pid)
286
+ return out
287
+
288
+
289
+ def refresh_zone_memberships(state, rows):
290
+ """Pure state projection used by dedicated Zone writers and reads."""
291
+ out = copy.deepcopy(state if isinstance(state, dict) else {})
292
+ next_zones = []
293
+ for zone in out.get("zones") or []:
294
+ if not isinstance(zone, dict):
295
+ continue
296
+ members = zone_members(zone, rows)
297
+ previous = [int(pid) for pid in zone.get("memberPids") or [] if _pid(pid) is not None]
298
+ if members != previous:
299
+ zone["memberPids"] = members
300
+ zone["membershipRevision"] = int(zone.get("membershipRevision") or 0) + 1
301
+ zone["updatedAt"] = _now()
302
+ next_zones.append(zone)
303
+ out["zones"] = next_zones
304
+ return out
305
+
306
+
307
+ def _persist(st, mutate):
308
+ result = {}
309
+
310
+ def apply(current):
311
+ state = copy.deepcopy(current) if isinstance(current, dict) else {}
312
+ state.setdefault("routes", [])
313
+ state.setdefault("zones", [])
314
+ state.setdefault("legacyMigrations", {})
315
+ state.setdefault("routeNavigation", {})
316
+ next_state, value = mutate(state)
317
+ result["value"] = copy.deepcopy(value)
318
+ return next_state
319
+
320
+ st.update(STORE_KEY, apply, flush="sync")
321
+ return result.get("value")
322
+
323
+
324
+ def read(st, rows=None):
325
+ state = _store(st)
326
+ state.setdefault("routes", [])
327
+ state.setdefault("zones", [])
328
+ state.setdefault("legacyMigrations", {})
329
+ state.setdefault("routeNavigation", {})
330
+ return refresh_zone_memberships(state, rows or ()) if rows is not None else state
331
+
332
+
333
+ def list_routes(st):
334
+ return [copy.deepcopy(route) for route in read(st).get("routes") or [] if isinstance(route, dict)]
335
+
336
+
337
+ def route_share_key(route_id):
338
+ """Stable generic-field bridge id for the existing share registry.
339
+
340
+ Route records are not generic columns, but the shipped share dialog and grant registry already
341
+ own the access workflow. A bounded digest keeps arbitrary Route ids out of field keys while
342
+ remaining deterministic for old normalized records that predate the stored ``shareKey``.
343
+ """
344
+ digest = hashlib.sha256(str(route_id or "").encode("utf-8")).hexdigest()[:24]
345
+ return "route_object_" + digest
346
+
347
+
348
+ def duplicate_route(st, route_id, *, tenant_id, created_by, name=None):
349
+ """Copy one normalized Route without aliasing its identity, ownership, or share grants."""
350
+ source = next((item for item in list_routes(st) if item.get("id") == str(route_id)), None)
351
+ if source is None:
352
+ return None
353
+ raw = {"name": _name(name) or f"{source.get('name') or 'Route'} copy",
354
+ "color": source.get("color"), "sourceViewId": source.get("sourceViewId"),
355
+ "sourceViewRevision": source.get("sourceViewRevision"),
356
+ "stops": [stop.get("customerPid") for stop in ordered_stops(source)]}
357
+ if source.get("mapsUrl"):
358
+ raw["mapsUrl"] = source["mapsUrl"]
359
+ return put_route(st, raw, tenant_id=tenant_id, created_by=created_by)
360
+
361
+
362
+ def _nav_user(username):
363
+ return str(username or "").strip().lower()[:120]
364
+
365
+
366
+ _NAV_REFUSED = object()
367
+
368
+
369
+ def _folder_name(raw):
370
+ return " ".join(str(raw or "").split())[:80]
371
+
372
+
373
+ def _clean_nav(raw, routes=(), legacy_folders=(), legacy_placements=None):
374
+ """Pure, fail-closed current-reader Route navigation projection.
375
+
376
+ Old Wave 42 folders are accepted only as a read fallback. Invalid parents, cycles, excess
377
+ nesting, dangling placements and stale order ids resolve to root; a GET never writes repairs.
378
+ """
379
+ raw = raw if isinstance(raw, dict) else {}
380
+ offered = raw.get("folders") if isinstance(raw.get("folders"), list) else legacy_folders
381
+ folders, seen = [], set()
382
+ for index, item in enumerate(offered or ()):
383
+ if not isinstance(item, dict):
384
+ continue
385
+ fid = str(item.get("id") or "").strip()[:96]
386
+ name = _folder_name(item.get("name"))
387
+ if not fid or not name or fid in seen:
388
+ continue
389
+ seen.add(fid)
390
+ try:
391
+ order = int(item.get("order", index))
392
+ except (TypeError, ValueError):
393
+ order = index
394
+ parent = str(item.get("parent") or "").strip()[:96] or None
395
+ folders.append({"id": fid, "name": name, "parent": parent, "order": order})
396
+ by_id = {item["id"]: item for item in folders}
397
+ for item in folders:
398
+ parent, trail, depth = item.get("parent"), {item["id"]}, 0
399
+ while parent:
400
+ if parent not in by_id or parent in trail or depth >= 9:
401
+ item["parent"] = None
402
+ break
403
+ trail.add(parent)
404
+ parent = by_id[parent].get("parent")
405
+ depth += 1
406
+ folders.sort(key=lambda item: (int(item.get("order") or 0), item["name"].lower(), item["id"]))
407
+ for index, item in enumerate(folders):
408
+ item["order"] = index
409
+
410
+ placement_raw = raw.get("placements") if isinstance(raw.get("placements"), dict) else legacy_placements or {}
411
+ known_folders = set(by_id)
412
+ route_keys = set()
413
+ for route in routes or ():
414
+ rid = str((route or {}).get("id") or "")
415
+ if rid:
416
+ route_keys.add(rid)
417
+ legacy = ((route or {}).get("migration") or {}).get("legacyField")
418
+ if legacy:
419
+ route_keys.add(str(legacy))
420
+ placements = {}
421
+ for key, folder_id in placement_raw.items():
422
+ key, folder_id = str(key), str(folder_id or "")
423
+ if key in route_keys and folder_id in known_folders:
424
+ placements[key] = folder_id
425
+
426
+ offered_order = raw.get("order") if isinstance(raw.get("order"), list) else []
427
+ canonical_ids = [str((route or {}).get("id") or "") for route in routes or ()]
428
+ order = []
429
+ for route_id in [*offered_order, *canonical_ids]:
430
+ route_id = str(route_id)
431
+ if route_id in canonical_ids and route_id not in order:
432
+ order.append(route_id)
433
+ return {"folders": folders, "placements": placements, "order": order}
434
+
435
+
436
+ def route_navigation(st, username, routes=(), *, legacy_folders=(), legacy_placements=None):
437
+ """This reader's folders, placement and ordering; route object data remains tenant-wide."""
438
+ user = _nav_user(username)
439
+ raw = (read(st).get("routeNavigation") or {}).get(user) if user else None
440
+ nav = _clean_nav(raw, routes, legacy_folders, legacy_placements)
441
+ folders = nav["folders"]
442
+ placement = nav["placements"]
443
+ out_routes = []
444
+ rank = {rid: index for index, rid in enumerate(nav["order"])}
445
+ for route in routes or ():
446
+ item = copy.deepcopy(route)
447
+ legacy_key = ((item.get("migration") or {}).get("legacyField"))
448
+ item["folderId"] = placement.get(item.get("id"), placement.get(str(legacy_key)))
449
+ item["navOrder"] = rank.get(str(item.get("id")), len(rank))
450
+ out_routes.append(item)
451
+ out_routes.sort(key=lambda item: (int(item.get("navOrder") or 0), int(item.get("number") or 0)))
452
+ return {"folders": folders, "routes": out_routes}
453
+
454
+
455
+ def _mutate_nav(st, username, routes, change, *, legacy_folders=(), legacy_placements=None):
456
+ user = _nav_user(username)
457
+ if not user:
458
+ return None
459
+
460
+ def mutate(state):
461
+ navigation = dict(state.get("routeNavigation") or {})
462
+ current = _clean_nav(navigation.get(user), routes, legacy_folders, legacy_placements)
463
+ result = change(current)
464
+ if result is _NAV_REFUSED:
465
+ return state, None
466
+ navigation[user] = _clean_nav(current, routes)
467
+ state["routeNavigation"] = navigation
468
+ return state, result
469
+ return _persist(st, mutate)
470
+
471
+
472
+ def put_route_folder(st, username, raw, routes=(), *, legacy_folders=(), legacy_placements=None):
473
+ folder_id = str((raw or {}).get("id") or "route_folder_" + uuid.uuid4().hex)[:96]
474
+ name, parent = _folder_name((raw or {}).get("name")), str((raw or {}).get("parent") or "")[:96] or None
475
+ if not name:
476
+ return None
477
+ def change(nav):
478
+ folders = nav["folders"]
479
+ prior = next((item for item in folders if item["id"] == folder_id), None)
480
+ if parent == folder_id or (parent and not any(item["id"] == parent for item in folders)):
481
+ return _NAV_REFUSED
482
+ if parent:
483
+ by_id = {item["id"]: item for item in folders}
484
+ cursor, walked, depth = parent, set(), 1
485
+ while cursor:
486
+ if cursor == folder_id or cursor in walked or depth >= 10:
487
+ return _NAV_REFUSED
488
+ walked.add(cursor)
489
+ cursor = (by_id.get(cursor) or {}).get("parent")
490
+ depth += 1
491
+ if prior:
492
+ prior.update({"name": name, "parent": parent})
493
+ else:
494
+ prior = {"id": folder_id, "name": name, "parent": parent, "order": len(folders)}
495
+ folders.append(prior)
496
+ return copy.deepcopy(prior)
497
+ return _mutate_nav(st, username, routes, change,
498
+ legacy_folders=legacy_folders, legacy_placements=legacy_placements)
499
+
500
+
501
+ def delete_route_folder(st, username, folder_id, routes=(), *, legacy_folders=(), legacy_placements=None):
502
+ folder_id = str(folder_id or "")
503
+ def change(nav):
504
+ if not any(item["id"] == folder_id for item in nav["folders"]):
505
+ return _NAV_REFUSED
506
+ nav["folders"] = [item for item in nav["folders"] if item["id"] != folder_id]
507
+ for item in nav["folders"]:
508
+ if item.get("parent") == folder_id:
509
+ item["parent"] = None
510
+ nav["placements"] = {key: value for key, value in nav["placements"].items() if value != folder_id}
511
+ return True
512
+ return bool(_mutate_nav(st, username, routes, change,
513
+ legacy_folders=legacy_folders, legacy_placements=legacy_placements))
514
+
515
+
516
+ def place_route(st, username, route_id, folder_id, routes=(), *, legacy_folders=(), legacy_placements=None):
517
+ route_id, folder_id = str(route_id or ""), str(folder_id or "") or None
518
+ def change(nav):
519
+ if route_id not in {str((item or {}).get("id")) for item in routes or ()}:
520
+ return _NAV_REFUSED
521
+ if folder_id and not any(item["id"] == folder_id for item in nav["folders"]):
522
+ return _NAV_REFUSED
523
+ if folder_id:
524
+ nav["placements"][route_id] = folder_id
525
+ else:
526
+ nav["placements"].pop(route_id, None)
527
+ return folder_id
528
+ result = _mutate_nav(st, username, routes, change,
529
+ legacy_folders=legacy_folders, legacy_placements=legacy_placements)
530
+ return result
531
+
532
+
533
+ def reorder_routes(st, username, order, routes=(), *, legacy_folders=(), legacy_placements=None):
534
+ offered = [str(value) for value in order or ()]
535
+ def change(nav):
536
+ known = {str((item or {}).get("id")) for item in routes or ()}
537
+ if len(offered) != len(set(offered)) or any(value not in known for value in offered):
538
+ return _NAV_REFUSED
539
+ nav["order"] = [*offered, *(value for value in nav["order"] if value not in offered)]
540
+ return list(nav["order"])
541
+ return _mutate_nav(st, username, routes, change,
542
+ legacy_folders=legacy_folders, legacy_placements=legacy_placements)
543
+
544
+
545
+ def reorder_route_folders(st, username, order, routes=(), *, legacy_folders=(), legacy_placements=None):
546
+ offered = [str(value) for value in order or ()]
547
+ def change(nav):
548
+ known = {item["id"] for item in nav["folders"]}
549
+ if len(offered) != len(set(offered)) or any(value not in known for value in offered):
550
+ return _NAV_REFUSED
551
+ rank = [*offered, *(item["id"] for item in nav["folders"] if item["id"] not in offered)]
552
+ positions = {folder_id: index for index, folder_id in enumerate(rank)}
553
+ nav["folders"].sort(key=lambda item: positions[item["id"]])
554
+ for index, item in enumerate(nav["folders"]):
555
+ item["order"] = index
556
+ return rank
557
+ return _mutate_nav(st, username, routes, change,
558
+ legacy_folders=legacy_folders, legacy_placements=legacy_placements)
559
+
560
+
561
+ def list_zones(st, rows=None):
562
+ return [copy.deepcopy(zone) for zone in read(st, rows).get("zones") or [] if isinstance(zone, dict)]
563
+
564
+
565
+ def put_route(st, raw, *, tenant_id, created_by):
566
+ """Dedicated normalized Route writer. Generic table endpoints cannot call this."""
567
+ wanted = str((raw or {}).get("id") or "").strip()
568
+
569
+ def mutate(state):
570
+ routes = list(state.get("routes") or [])
571
+ prior_index = next((index for index, item in enumerate(routes)
572
+ if isinstance(item, dict) and item.get("id") == wanted), None)
573
+ prior = routes[prior_index] if prior_index is not None else None
574
+ clean = _route(raw, ordinal=prior_index if prior_index is not None else len(routes),
575
+ created_by=created_by, tenant_id=tenant_id, prior=prior)
576
+ if clean is None:
577
+ return state, None
578
+ if prior_index is None:
579
+ routes.append(clean)
580
+ else:
581
+ routes[prior_index] = clean
582
+ state["routes"] = routes
583
+ return state, clean
584
+
585
+ return _persist(st, mutate)
586
+
587
+
588
+ def move_stop(st, route_id, customer_pid, order, *, tenant_id, created_by):
589
+ """Move one protected stop. Empty routes are valid and never manufacture a stop."""
590
+ pid = _pid(customer_pid)
591
+ try:
592
+ target = max(1, int(order))
593
+ except (TypeError, ValueError):
594
+ return None
595
+ if pid is None:
596
+ return None
597
+ route = next((item for item in list_routes(st) if item.get("id") == str(route_id)), None)
598
+ if route is None:
599
+ return None
600
+ ids = [stop.get("customerPid") for stop in ordered_stops(route)]
601
+ if pid not in ids:
602
+ return None
603
+ ids.remove(pid)
604
+ ids.insert(min(target - 1, len(ids)), pid)
605
+ return put_route(st, {**route, "stops": ids}, tenant_id=tenant_id, created_by=created_by)
606
+
607
+
608
+ def set_stop_membership(st, route_id, customer_pid, present, *, tenant_id, created_by):
609
+ """Add or remove exactly one protected stop without replacing the Route snapshot.
610
+
611
+ The mutation runs inside the store update so two concurrent pin confirmations cannot read the
612
+ same old stop list and then overwrite one another. In particular, callers never submit the
613
+ filtered ``visibleStopIds`` DTO as the full Route: every stop outside the current View remains
614
+ in its original relative order, and ``_route`` re-densifies the resulting relation.
615
+ """
616
+ pid = _pid(customer_pid)
617
+ route_id = str(route_id or "").strip()
618
+ if pid is None or not isinstance(present, bool) or not route_id:
619
+ return None
620
+
621
+ def mutate(state):
622
+ routes = list(state.get("routes") or [])
623
+ prior_index = next((index for index, item in enumerate(routes)
624
+ if isinstance(item, dict) and item.get("id") == route_id), None)
625
+ if prior_index is None:
626
+ return state, None
627
+ prior = routes[prior_index]
628
+ ids = [stop.get("customerPid") for stop in ordered_stops(prior)]
629
+ if present:
630
+ if pid not in ids:
631
+ ids.append(pid)
632
+ else:
633
+ ids = [item for item in ids if item != pid]
634
+ clean = _route({**prior, "stops": ids}, ordinal=prior_index, created_by=created_by,
635
+ tenant_id=tenant_id, prior=prior)
636
+ if clean is None:
637
+ return state, None
638
+ routes[prior_index] = clean
639
+ state["routes"] = routes
640
+ return state, clean
641
+
642
+ return _persist(st, mutate)
643
+
644
+
645
+ def delete_route(st, route_id):
646
+ route_id = str(route_id or "").strip()
647
+
648
+ def mutate(state):
649
+ prior = list(state.get("routes") or [])
650
+ removed_keys = {route_id}
651
+ for item in prior:
652
+ if isinstance(item, dict) and item.get("id") == route_id:
653
+ legacy_key = (item.get("migration") or {}).get("legacyField")
654
+ if legacy_key:
655
+ removed_keys.add(str(legacy_key))
656
+ state["routes"] = [item for item in prior if not (isinstance(item, dict) and item.get("id") == route_id)]
657
+ navigation = dict(state.get("routeNavigation") or {})
658
+ for username, raw in navigation.items():
659
+ if not isinstance(raw, dict):
660
+ continue
661
+ nav = dict(raw)
662
+ nav["placements"] = {key: value for key, value in (nav.get("placements") or {}).items()
663
+ if str(key) not in removed_keys}
664
+ nav["order"] = [value for value in nav.get("order") or () if str(value) != route_id]
665
+ navigation[username] = nav
666
+ state["routeNavigation"] = navigation
667
+ return state, len(prior) != len(state["routes"])
668
+
669
+ return bool(_persist(st, mutate))
670
+
671
+
672
+ def put_zone(st, raw, *, rows, tenant_id, created_by):
673
+ wanted = str((raw or {}).get("id") or "").strip()
674
+
675
+ def mutate(state):
676
+ zones = list(state.get("zones") or [])
677
+ prior_index = next((index for index, item in enumerate(zones)
678
+ if isinstance(item, dict) and item.get("id") == wanted), None)
679
+ prior = zones[prior_index] if prior_index is not None else None
680
+ clean = _zone(raw, ordinal=prior_index if prior_index is not None else len(zones),
681
+ created_by=created_by, tenant_id=tenant_id, prior=prior)
682
+ if clean is None:
683
+ return state, None
684
+ clean["memberPids"] = zone_members(clean, rows)
685
+ old_members = prior.get("memberPids") if isinstance(prior, dict) else None
686
+ clean["membershipRevision"] = int((prior or {}).get("membershipRevision") or 0) + (
687
+ 1 if old_members != clean["memberPids"] else 0)
688
+ if prior_index is None:
689
+ zones.append(clean)
690
+ else:
691
+ zones[prior_index] = clean
692
+ state["zones"] = zones
693
+ return state, clean
694
+
695
+ return _persist(st, mutate)
696
+
697
+
698
+ def delete_zone(st, zone_id):
699
+ zone_id = str(zone_id or "").strip()
700
+
701
+ def mutate(state):
702
+ prior = list(state.get("zones") or [])
703
+ state["zones"] = [item for item in prior if not (isinstance(item, dict) and item.get("id") == zone_id)]
704
+ return state, len(prior) != len(state["zones"])
705
+
706
+ return bool(_persist(st, mutate))
707
+
708
+
709
+ def customer_projections(routes, zones):
710
+ """Derived read-only customer multi-select values; stops are never generic Link cells."""
711
+ projections = {}
712
+ for route in routes or []:
713
+ for stop in ordered_stops(route):
714
+ projections.setdefault(stop.get("customerPid"), {"Routes": [], "Zone": []})["Routes"].append(route.get("name"))
715
+ for zone in zones or []:
716
+ for pid in zone.get("memberPids", zone.get("member_pids", ())) or ():
717
+ projections.setdefault(pid, {"Routes": [], "Zone": []})["Zone"].append(zone.get("name"))
718
+ return projections
719
+
720
+
721
+ def customer_projection_fields(routes, zones):
722
+ """The two read-only customer projection fields, never generic Link definitions."""
723
+ route_names = [str(route.get("name") or "") for route in routes or []
724
+ if str(route.get("name") or "")]
725
+ zone_names = [str(zone.get("name") or "") for zone in zones or []
726
+ if str(zone.get("name") or "")]
727
+ return [field_axes({"key": "routes", "label": "Routes", "type": "multiselect",
728
+ "source": "odoo", "derived": True, "readOnly": True,
729
+ "options": route_names}),
730
+ field_axes({"key": "zone", "label": "Zone", "type": "multiselect",
731
+ "source": "odoo", "derived": True, "readOnly": True,
732
+ "options": zone_names})]
733
+
734
+
735
+ def apply_customer_projections(rows, routes, zones):
736
+ """Layer normalized Route/Zone projections onto already scoped customer rows."""
737
+ projection = customer_projections(routes, zones)
738
+ out = []
739
+ for row in rows or []:
740
+ item = dict(row)
741
+ values = projection.get(item.get("pid"), projection.get(str(item.get("pid")), {})) or {}
742
+ item["routes"] = ", ".join(str(name) for name in values.get("Routes", ()) if name)
743
+ item["zone"] = ", ".join(str(name) for name in values.get("Zone", ()) if name)
744
+ out.append(item)
745
+ return out
746
+
747
+
748
+ def apply_managed_route_selection(view_state, route_ids, routes):
749
+ """Replace only Loopable's managed OR clause in an otherwise caller-owned View state.
750
+
751
+ The generic View writer remains the persistence authority. This narrow helper makes a
752
+ Route selection safe to compose: it neither reads nor rewrites the user's ordinary filter
753
+ tree and an empty selection removes only the managed clause it previously produced.
754
+ """
755
+ out = copy.deepcopy(view_state if isinstance(view_state, dict) else {})
756
+ out.pop("managedRouteClause", None)
757
+ wanted = {str(value) for value in route_ids or () if str(value)}
758
+ if not wanted:
759
+ return out
760
+ pids, known = [], set()
761
+ for route in routes or ():
762
+ if str(route.get("id")) not in wanted:
763
+ continue
764
+ for stop in ordered_stops(route):
765
+ pid = _pid(stop.get("customerPid"))
766
+ if pid is not None and pid not in known:
767
+ known.add(pid)
768
+ pids.append(pid)
769
+ out["managedRouteClause"] = {"managedBy": MANAGED_BY, "kind": "route-membership",
770
+ "operator": "or", "routeIds": sorted(wanted), "pids": pids}
771
+ return out
772
+
773
+
774
+ def legacy_route_plan(fields, cells, *, tenant_id, created_by, ordinal_offset=0):
775
+ """Project legacy route-order fields without writing the normalized store.
776
+
777
+ The same pure projection feeds the explicit parity migration and the compatibility read path.
778
+ A field key becomes the stable Route id, so repeated GETs cannot manufacture duplicate Routes.
779
+ """
780
+ plans = []
781
+ for key, definition in sorted((fields or {}).items(), key=lambda item: str(item[0])):
782
+ if not isinstance(definition, dict) or definition.get("kind") != "route_order":
783
+ continue
784
+ migration_mark = definition.get("legacyRouteMigration")
785
+ if isinstance(migration_mark, dict) and migration_mark.get("verified"):
786
+ continue
787
+ ranks = []
788
+ for raw_pid, values in (cells or {}).items():
789
+ try:
790
+ rank = int(str((values or {}).get(key) or "").strip())
791
+ except (TypeError, ValueError):
792
+ continue
793
+ pid = _pid(raw_pid)
794
+ if pid is not None and rank > 0:
795
+ ranks.append((rank, pid))
796
+ ranks.sort()
797
+ if len({rank for rank, _pid_value in ranks}) != len(ranks):
798
+ continue
799
+ plan = _route({"id": "legacy_" + str(key)[:72], "name": definition.get("label") or key,
800
+ "color": definition.get("color"),
801
+ "shareKey": key,
802
+ "sourceViewId": (definition.get("route") or {}).get("sourceViewId"),
803
+ "sourceViewRevision": (definition.get("route") or {}).get("inputsHash"),
804
+ "stops": [pid for _rank, pid in ranks],
805
+ "migration": {"legacyField": key, "verified": True}},
806
+ ordinal=max(0, int(ordinal_offset)) + len(plans),
807
+ tenant_id=tenant_id,
808
+ created_by=definition.get("createdBy") or created_by)
809
+ if plan is not None:
810
+ plans.append({"field": key, "route": plan,
811
+ "expected": {pid: rank for rank, pid in ranks}})
812
+ return plans
813
+
814
+
815
+ def compatible_routes(routes, fields, cells, *, tenant_id, created_by):
816
+ """Read-through view of normalized Routes plus still-live legacy route-order fields.
817
+
818
+ This function is intentionally store-free. Listing a Route must never mutate tenant data or
819
+ require an administrator to run a migration first. If an independently verified migration
820
+ already produced the same stable ``legacy_<field>`` id, the normalized record wins and the
821
+ compatibility projection disappears rather than rendering a duplicate.
822
+ """
823
+ out = [copy.deepcopy(route) for route in routes or () if isinstance(route, dict)]
824
+ existing_ids = {str(route.get("id") or "") for route in out}
825
+ last_number = max(
826
+ (int(route.get("number") or 0) for route in out
827
+ if str(route.get("number") or "").lstrip("-").isdigit()),
828
+ default=0,
829
+ )
830
+ plans = legacy_route_plan(
831
+ fields, cells, tenant_id=tenant_id, created_by=created_by,
832
+ ordinal_offset=last_number,
833
+ )
834
+ for plan in plans:
835
+ route = plan.get("route") if isinstance(plan, dict) else None
836
+ if not isinstance(route, dict) or str(route.get("id") or "") in existing_ids:
837
+ continue
838
+ existing_ids.add(str(route.get("id") or ""))
839
+ # Transient marker only: a compatibility projection has no normalized write target yet.
840
+ # A successfully migrated Route with this same stable id remains an ordinary editable
841
+ # normalized record because it wins above and never receives this marker.
842
+ out.append({**copy.deepcopy(route), "compatibility": "legacy-route-order"})
843
+ return out
844
+
845
+
846
+ def migrate_legacy_routes(st, fields, cells, *, tenant_id, created_by, zones=()):
847
+ """Persist copied Routes and prove count/member/order/projection parity before hiding fields."""
848
+ current_routes = list_routes(st)
849
+ last_number = max((int(route.get("number") or 0) for route in current_routes), default=0)
850
+ plans = legacy_route_plan(
851
+ fields, cells, tenant_id=tenant_id, created_by=created_by,
852
+ ordinal_offset=last_number,
853
+ )
854
+ if not plans:
855
+ return {"migrated": [], "verified": {}, "hide": []}
856
+
857
+ def mutate(state):
858
+ routes = list(state.get("routes") or [])
859
+ migrations = dict(state.get("legacyMigrations") or {})
860
+ migrated, verified, hide = [], {}, []
861
+ for plan in plans:
862
+ field, route = plan["field"], plan["route"]
863
+ existing_index = next((index for index, item in enumerate(routes)
864
+ if isinstance(item, dict) and item.get("id") == route["id"]), None)
865
+ if existing_index is None:
866
+ routes.append(route)
867
+ candidate = route
868
+ else:
869
+ candidate = routes[existing_index]
870
+ expected = plan["expected"]
871
+ observed = {stop["customerPid"]: stop["position"] for stop in ordered_stops(candidate)}
872
+ projections = customer_projections(routes, zones)
873
+ projection_ok = all(candidate.get("name") in (projections.get(pid) or {}).get("Routes", [])
874
+ for pid in expected)
875
+ parity = {"routeCount": len(expected) == len(observed),
876
+ "memberCount": set(expected) == set(observed), "order": expected == observed,
877
+ "projections": projection_ok}
878
+ verified[field] = parity
879
+ if all(parity.values()):
880
+ migrations[field] = {"routeId": candidate["id"], "verified": True, "at": _now()}
881
+ migrated.append(candidate["id"])
882
+ hide.append(field)
883
+ state["routes"], state["legacyMigrations"] = routes, migrations
884
+ return state, {"migrated": migrated, "verified": verified, "hide": hide}
885
+
886
+ return _persist(st, mutate)
platform/core/shared_overlay.py CHANGED
@@ -101,7 +101,8 @@ ALLOWED_FIELD_KEYS = frozenset({
101
  'note', 'description', '_note',
102
  # display and behaviour
103
  'format', 'agg', 'options', 'optionColors', 'colorCodeOptions', 'default', 'pinned',
104
- 'filterable', 'multi', 'max', 'derived', 'preset', 'custom', 'profile', 'link', 'recurrence',
 
105
  # the created strata's computation bags
106
  'formula', 'measure', 'metric', 'rollup', 'geocode', 'code', 'automation', 'aiEnrich',
107
  'scope',
@@ -148,6 +149,17 @@ def _read(table_key, st=None):
148
  'cells': dict(data.get('cells') or {})}
149
 
150
 
 
 
 
 
 
 
 
 
 
 
 
151
  def _write(table_key, change, st=None, flush='async'):
152
  """Read-modify-write one shared stratum.
153
 
@@ -188,14 +200,15 @@ def _value(value):
188
 
189
 
190
  # ----------------------------------------------------------------- the column DEFINITIONS
191
- def fields(table_key, st=None):
192
  """`{field_key: Field}` — the columns this topic shares tenant-wide.
193
 
194
  Unscoped on purpose, and it is the one thing here that is: a shared column's EXISTENCE is
195
  tenant-wide by definition — that is the whole feature, and it is what stops a shared view
196
  naming a column half the workspace lacks. Its VALUES are scoped by `cells()`.
197
  """
198
- return _read(table_key, st)['fields']
 
199
 
200
 
201
  def is_shared(table_key, field_key, st=None):
@@ -482,6 +495,90 @@ def put_cells_and_choice_options(table_key, pid, values, choice_values, st=None)
482
  return clean
483
 
484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
485
  def put_rows(table_key, rows, st=None):
486
  """Write shared cells on MANY rows in ONE store update. Returns `{row_id: {key: value}}`.
487
 
 
101
  'note', 'description', '_note',
102
  # display and behaviour
103
  'format', 'agg', 'options', 'optionColors', 'colorCodeOptions', 'default', 'pinned',
104
+ 'filterable', 'offerable', 'multi', 'max', 'derived', 'preset', 'custom', 'profile', 'link',
105
+ 'recurrence',
106
  # the created strata's computation bags
107
  'formula', 'measure', 'metric', 'rollup', 'geocode', 'code', 'automation', 'aiEnrich',
108
  'scope',
 
149
  'cells': dict(data.get('cells') or {})}
150
 
151
 
152
+ def document(table_key, st=None):
153
+ """One captured shared-stratum document for consumers in a single request.
154
+
155
+ A field-contract assembly asks three questions of the same small bucket: reconcile its
156
+ stored permission word, merge its definitions, and classify the resulting fields. They are
157
+ one request's view of one document, so reopening it for each question buys no freshness and
158
+ pays three deep copies. Callers that do not hold one keep the historical read path.
159
+ """
160
+ return _read(table_key, st=st)
161
+
162
+
163
  def _write(table_key, change, st=None, flush='async'):
164
  """Read-modify-write one shared stratum.
165
 
 
200
 
201
 
202
  # ----------------------------------------------------------------- the column DEFINITIONS
203
+ def fields(table_key, st=None, document=None):
204
  """`{field_key: Field}` — the columns this topic shares tenant-wide.
205
 
206
  Unscoped on purpose, and it is the one thing here that is: a shared column's EXISTENCE is
207
  tenant-wide by definition — that is the whole feature, and it is what stops a shared view
208
  naming a column half the workspace lacks. Its VALUES are scoped by `cells()`.
209
  """
210
+ data = document if isinstance(document, dict) else _read(table_key, st)
211
+ return dict(data.get('fields') or {})
212
 
213
 
214
  def is_shared(table_key, field_key, st=None):
 
495
  return clean
496
 
497
 
498
+ def transpose_rank(table_key, pid, field_key, rank, pids, st=None):
499
+ """Atomically assign one positive integer rank within an explicitly scoped row set.
500
+
501
+ If another scoped row holds ``rank``, that row receives this row's prior rank. A row that did
502
+ not previously have a rank sends the displaced holder to ``max + 1``. The returned ``swap``
503
+ is shaped for the HTTP caller that must invalidate the other row it changed.
504
+
505
+ The scope is required for the same reason it is required by :func:`cells`: this persistence
506
+ primitive must never discover or mutate a row the caller was not already allowed to see.
507
+
508
+ The read and both writes deliberately live inside ONE ``store.update`` callback. Reading the
509
+ ranks first and then calling :func:`put_rows` is not equivalent: two concurrent requests can
510
+ both choose a holder from the same stale snapshot, serialize their precomputed writes, and
511
+ leave duplicate ranks. Both the Postgres row lock and the HF conflict-replay path protect the
512
+ callback itself, so the second request computes against the first request's landed result.
513
+ """
514
+ row_id = _pid(pid)
515
+ key = str(field_key or '').strip()
516
+ if not key:
517
+ raise ValueError('shared_overlay.transpose_rank: a field key is required')
518
+ if isinstance(rank, bool):
519
+ raise ValueError('shared_overlay.transpose_rank: a rank is a positive whole number')
520
+ try:
521
+ want = int(rank)
522
+ except (TypeError, ValueError) as exc:
523
+ raise ValueError(
524
+ 'shared_overlay.transpose_rank: a rank is a positive whole number') from exc
525
+ if want < 1:
526
+ raise ValueError('shared_overlay.transpose_rank: a rank is a positive whole number')
527
+ try:
528
+ scope = {_pid(item) for item in pids}
529
+ except TypeError as exc:
530
+ raise ValueError(
531
+ 'shared_overlay.transpose_rank: scoped pids are required') from exc
532
+ if row_id not in scope:
533
+ raise ValueError(
534
+ 'shared_overlay.transpose_rank: the target pid must be in the scoped row set')
535
+
536
+ outcome = {}
537
+
538
+ def _transpose(data):
539
+ # Numeric pid order makes the holder deterministic if an already-corrupt document has
540
+ # more than one. A healthy route has at most one; this function preserves that invariant.
541
+ ordered_scope = sorted(scope, key=int)
542
+ held = {}
543
+ for scoped_pid in ordered_scope:
544
+ row = data['cells'].get(scoped_pid)
545
+ if not isinstance(row, dict):
546
+ continue
547
+ value = row.get(key)
548
+ if value in (None, ''):
549
+ continue
550
+ try:
551
+ held[scoped_pid] = int(str(value).strip())
552
+ except (TypeError, ValueError):
553
+ continue
554
+
555
+ prior = held.get(row_id)
556
+ max_rank = max(held.values(), default=0)
557
+ holder = None if prior == want else next(
558
+ (other_pid for other_pid in ordered_scope
559
+ if other_pid != row_id and held.get(other_pid) == want),
560
+ None)
561
+ moved = None
562
+
563
+ data['cells'].setdefault(row_id, {})[key] = str(want)
564
+ if holder is not None:
565
+ moved = prior if prior is not None else max_rank + 1
566
+ data['cells'].setdefault(holder, {})[key] = str(moved)
567
+
568
+ # ``store.update`` may replay this callback over a newer HF document. Replace, rather
569
+ # than append to, the captured outcome so the caller receives the final replay's truth.
570
+ outcome.clear()
571
+ outcome.update({
572
+ 'value': str(want),
573
+ 'prior': '' if prior is None else str(prior),
574
+ 'swap': ({'pid': int(holder), 'field': key, 'value': str(moved)}
575
+ if holder is not None else None),
576
+ })
577
+
578
+ _write(table_key, _transpose, st, flush='sync')
579
+ return dict(outcome)
580
+
581
+
582
  def put_rows(table_key, rows, st=None):
583
  """Write shared cells on MANY rows in ONE store update. Returns `{row_id: {key: value}}`.
584
 
platform/core/store_pg.py CHANGED
@@ -39,6 +39,7 @@ empty dict gets written back over real data.
39
  import json
40
  import os
41
  import threading
 
42
 
43
  import core.data_binding as data_binding
44
 
@@ -137,6 +138,8 @@ PRODUCTION_TENANTS = frozenset({
137
  #: one it did not name". That is `--data-repo`'s exact failure, which is the failure this file's
138
  #: existence is a response to.
139
  _SANDBOX_TENANTS_VAR = 'AIOS_SANDBOX_TENANTS'
 
 
140
 
141
 
142
  def sandbox_tenants():
@@ -145,6 +148,18 @@ def sandbox_tenants():
145
  return frozenset(s.strip().lower() for s in raw.split(',') if s.strip())
146
 
147
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  def write_refusal(tenant_slug=None):
149
  """`None` if this deployment may write this tenant's schema, else the sentence explaining why.
150
 
@@ -152,19 +167,19 @@ def write_refusal(tenant_slug=None):
152
  thing being classified changes, from a dataset repo to a tenant slug:
153
 
154
  1. the PRODUCTION deployment -> may write any tenant
155
- 2. any other deployment writing a PRODUCTION tenant -> REFUSED (a laptop may opt in)
156
  3. any other deployment writing a tenant it was HANDED -> allowed
157
  4. anything else -> REFUSED
158
 
159
- ⭐ RULE 2 BEATS RULE 3, deliberately, which is why the order above is the order below: an
160
- allowlist must not be able to re-open tenant #0. ⚠ And the Space/laptop asymmetry is carried
161
- over unchanged — a Space that is not production gets NO override, because that is the case the
162
- owner said "EVER" about.
163
  """
164
  slug = _effective_slug(tenant_slug)
165
  if data_binding.is_production_deployment():
166
  return None # rule 1
167
  if slug in PRODUCTION_TENANTS: # rule 2
 
 
168
  if data_binding.local_override():
169
  return None
170
  who = data_binding.deployment_id() or 'this machine (no Space identity)'
@@ -172,8 +187,8 @@ def write_refusal(tenant_slug=None):
172
  if data_binding.is_space():
173
  return (f'{who} is not the production deployment, so it may not write tenant {where}, '
174
  f'which holds real customer data. Point this deployment at its own database, '
175
- f'or name the sandbox tenants it may write in {_SANDBOX_TENANTS_VAR}. There is '
176
- f'no override for a Space: a build that is not live never writes live data.')
177
  return (f'{who} may not write tenant {where}, which holds real customer data. Set '
178
  f'AIOS_TENANT to a sandbox tenant, or set '
179
  f'{data_binding._LOCAL_OPT_IN_VAR}=1 to opt in deliberately.')
 
39
  import json
40
  import os
41
  import threading
42
+ from urllib.parse import urlparse
43
 
44
  import core.data_binding as data_binding
45
 
 
138
  #: one it did not name". That is `--data-repo`'s exact failure, which is the failure this file's
139
  #: existence is a response to.
140
  _SANDBOX_TENANTS_VAR = 'AIOS_SANDBOX_TENANTS'
141
+ _ISOLATED_DATABASE_HOST_VAR = 'AIOS_ISOLATED_DATABASE_HOST'
142
+ _STAGING_SPACE = 'fsanyoto/loopable'
143
 
144
 
145
  def sandbox_tenants():
 
148
  return frozenset(s.strip().lower() for s in raw.split(',') if s.strip())
149
 
150
 
151
+ def isolated_staging_database():
152
+ """Whether this process is staging on the exact isolated database host it was handed."""
153
+ if data_binding.deployment_id() != _STAGING_SPACE:
154
+ return False
155
+ allowed_host = str(os.environ.get(_ISOLATED_DATABASE_HOST_VAR) or '').strip().lower()
156
+ try:
157
+ current_host = (urlparse(str(os.environ.get('DATABASE_URL') or '')).hostname or '').lower()
158
+ except ValueError:
159
+ return False
160
+ return bool(allowed_host and current_host == allowed_host)
161
+
162
+
163
  def write_refusal(tenant_slug=None):
164
  """`None` if this deployment may write this tenant's schema, else the sentence explaining why.
165
 
 
167
  thing being classified changes, from a dataset repo to a tenant slug:
168
 
169
  1. the PRODUCTION deployment -> may write any tenant
170
+ 2. any other deployment writing a PRODUCTION tenant -> REFUSED, except exact isolated staging
171
  3. any other deployment writing a tenant it was HANDED -> allowed
172
  4. anything else -> REFUSED
173
 
174
+ Rule 2 permits one narrow exception: the exact staging Space, an explicitly handed tenant,
175
+ and a DATABASE_URL host matching the isolated host stamped by the deploy must all agree.
 
 
176
  """
177
  slug = _effective_slug(tenant_slug)
178
  if data_binding.is_production_deployment():
179
  return None # rule 1
180
  if slug in PRODUCTION_TENANTS: # rule 2
181
+ if slug in sandbox_tenants() and isolated_staging_database():
182
+ return None
183
  if data_binding.local_override():
184
  return None
185
  who = data_binding.deployment_id() or 'this machine (no Space identity)'
 
187
  if data_binding.is_space():
188
  return (f'{who} is not the production deployment, so it may not write tenant {where}, '
189
  f'which holds real customer data. Point this deployment at its own database, '
190
+ f'or bind exact isolated staging and name its writable tenants in '
191
+ f'{_SANDBOX_TENANTS_VAR}. A non-live build never writes the live database.')
192
  return (f'{who} may not write tenant {where}, which holds real customer data. Set '
193
  f'AIOS_TENANT to a sandbox tenant, or set '
194
  f'{data_binding._LOCAL_OPT_IN_VAR}=1 to opt in deliberately.')
platform/core/table_store.py CHANGED
@@ -595,7 +595,7 @@ class TableStore:
595
  return None
596
 
597
  # ---------------------------------------------------------------- read
598
- def workspace(self, username, consume_corrections=True):
599
  """One user's durable workspace: always the full three-strata shape."""
600
  try:
601
  data = self._st.get(self.table_key) or {}
@@ -673,7 +673,10 @@ class TableStore:
673
  # stratum, absent until the user first reorders — exactly "default order".
674
  if isinstance(ws.get('recordLayout'), dict):
675
  out['recordLayout'] = dict(ws['recordLayout'])
676
- return out
 
 
 
677
 
678
  # ---------------------------------------------------------------- write
679
  def _update(self, username, change, shared=None):
@@ -1150,25 +1153,44 @@ class TableStore:
1150
  """Persist cell updates and newly admitted choice labels in one workspace update.
1151
 
1152
  The event wall has already checked field visibility, edit permission, label size, and the
1153
- 50-choice cap. This method owns only residency and atomicity: an overlay value must never
1154
- commit while the field vocabulary remains stale, because a refresh would render a cell the
1155
- picker cannot select.
 
 
 
1156
  """
1157
  clean = dict(updates or {})
 
1158
  additions = {str(key): list(values or ()) for key, values in
1159
- (choice_values or {}).items() if str(key) and values}
 
1160
  if not clean:
1161
  return
1162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1163
  def _patch(ws):
1164
- ws['overlays'].setdefault(str(int(pid)), {}).update(clean)
1165
- if not additions:
1166
  return
1167
  # Import here rather than at module load: `aios_grid` is intentionally independent
1168
  # of `core`, while this lower persistence layer may use its pure canonical cleaner.
1169
  from aios_grid import merge_choice_options
1170
  fields = ws.setdefault('fields', {})
1171
- for key, values in additions.items():
1172
  prior = fields.get(key)
1173
  entry = dict(prior) if isinstance(prior, dict) else {}
1174
  entry['options'] = merge_choice_options(entry.get('options'), values)
 
595
  return None
596
 
597
  # ---------------------------------------------------------------- read
598
+ def workspace(self, username, consume_corrections=True, include_document=False):
599
  """One user's durable workspace: always the full three-strata shape."""
600
  try:
601
  data = self._st.get(self.table_key) or {}
 
673
  # stratum, absent until the user first reorders — exactly "default order".
674
  if isinstance(ws.get('recordLayout'), dict):
675
  out['recordLayout'] = dict(ws['recordLayout'])
676
+ # A `/rows` assembly already needs the whole workspace document to count field usage.
677
+ # Returning this request-local snapshot avoids a third identical store read; callers that
678
+ # only render the personal projection retain the original dict return shape.
679
+ return (out, data) if include_document else out
680
 
681
  # ---------------------------------------------------------------- write
682
  def _update(self, username, change, shared=None):
 
1153
  """Persist cell updates and newly admitted choice labels in one workspace update.
1154
 
1155
  The event wall has already checked field visibility, edit permission, label size, and the
1156
+ 50-choice cap. This method owns only residency and atomicity: each cell and its vocabulary
1157
+ must land together in the stratum that owns the field. A shared value written into the
1158
+ caller's private workspace is shadowed by the shared read layer and therefore appears to
1159
+ reset after refresh (D-423); a private option written into the shared schema leaks another
1160
+ user's vocabulary. Choice additions are admitted only beside an update for the same key,
1161
+ so a stale or mismatched additions bag cannot resurrect a field in either stratum.
1162
  """
1163
  clean = dict(updates or {})
1164
+ clean_keys = {str(key) for key in clean if str(key)}
1165
  additions = {str(key): list(values or ()) for key, values in
1166
+ (choice_values or {}).items()
1167
+ if str(key) in clean_keys and values}
1168
  if not clean:
1169
  return
1170
 
1171
+ wide = self._tenant_wide_keys()
1172
+ shared = {key: value for key, value in clean.items() if key in wide}
1173
+ personal = {key: value for key, value in clean.items() if key not in wide}
1174
+ shared_additions = {key: values for key, values in additions.items() if key in shared}
1175
+ personal_additions = {key: values for key, values in additions.items() if key in personal}
1176
+
1177
+ if shared:
1178
+ import core.shared_overlay as shared_overlay
1179
+ shared_overlay.put_cells_and_choice_options(
1180
+ self.table_key, pid, shared, shared_additions, st=self._st)
1181
+
1182
+ if not personal:
1183
+ return
1184
+
1185
  def _patch(ws):
1186
+ ws['overlays'].setdefault(str(int(pid)), {}).update(personal)
1187
+ if not personal_additions:
1188
  return
1189
  # Import here rather than at module load: `aios_grid` is intentionally independent
1190
  # of `core`, while this lower persistence layer may use its pure canonical cleaner.
1191
  from aios_grid import merge_choice_options
1192
  fields = ws.setdefault('fields', {})
1193
+ for key, values in personal_additions.items():
1194
  prior = fields.get(key)
1195
  entry = dict(prior) if isinstance(prior, dict) else {}
1196
  entry['options'] = merge_choice_options(entry.get('options'), values)
platform/core/user_tables.py CHANGED
@@ -52,6 +52,7 @@ 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'
@@ -491,6 +492,9 @@ def records_mutable(table_key, st=None):
491
  UT_FIELD_TYPES = {'text', 'select', 'multiselect', 'user', 'int', 'currency', 'pct', 'date',
492
  'checkbox', 'phone', 'email', 'url', 'rating', 'automation', 'json',
493
  'link', 'rollup', 'code', 'image', 'formula', 'ai_enrich'}
 
 
 
494
  #: A cell is still a scalar on the wire (`Row` values are strings/numbers) — what this bounds is
495
  #: the DOCUMENT inside it. Source data is one already-paid provider response; keep it whole so a
496
  #: provider field is never silently discarded merely because the response is rich. 32 MiB matches
@@ -811,10 +815,19 @@ FIELD_AGGS = ('sum', 'average', 'median', 'min', 'max', 'count')
811
  #: A choice colour, as the client's editor spells one. `#RRGGBB`, upper-cased on the way in so a
812
  #: stored value has exactly ONE spelling and two fields cannot disagree about `#ebf6ef`.
813
  _OPTION_COLOR_RE = re.compile(r'#[0-9A-F]{6}')
814
- _MAX_CHOICE_OPTIONS = 50
815
  _MAX_CHOICE_LABEL = 60
816
 
817
 
 
 
 
 
 
 
 
 
 
 
818
  def _clean_option_colors(raw, options):
819
  """`{option label → #RRGGBB}`, capped to the field's own option vocabulary (wave-29 C1).
820
 
@@ -887,7 +900,7 @@ def _hydrate_choice_options(fields, value_maps):
887
  continue
888
  for option in _choice_values(field, values[key]):
889
  folded = option.casefold()
890
- if folded in known or len(options) >= _MAX_CHOICE_OPTIONS:
891
  continue
892
  options.append(option)
893
  known.add(folded)
@@ -947,7 +960,17 @@ def clean_fields(raw):
947
  if not key or key in seen or ftype not in UT_FIELD_TYPES or not label:
948
  continue
949
  seen.add(key)
950
- entry = {'key': key, 'label': label, 'type': ftype, 'source': 'overlay'}
 
 
 
 
 
 
 
 
 
 
951
  # ⭐ 2026-08-10 — the DISPLAY format, carried through the CREATE door. See `_clean_format`:
952
  # this is the fifth time an entry built key-by-key has silently dropped a bag the editor
953
  # sends, and the fourth of those was `agg` on this very line one wave ago.
@@ -967,8 +990,12 @@ def clean_fields(raw):
967
  if note:
968
  entry['note'] = note
969
  if ftype in ('select', 'multiselect'):
 
 
970
  opts = [' '.join(str(o).split())[:60] for o in (f.get('options') or [])
971
- if str(o).strip()][:50]
 
 
972
  entry['options'] = opts
973
  if f.get('default') is True:
974
  entry['default'] = True
@@ -1146,7 +1173,9 @@ def get(table_key, st=None):
1146
  _ZONE_ID_RE = re.compile(r'^[A-Za-z0-9_-]{1,96}$')
1147
  _ZONE_FIELD_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_]{0,79}$')
1148
  _ZONE_COLOR_RE = re.compile(r'^#[0-9A-Fa-f]{6}$')
 
1149
  _ZONE_GEOMETRIES = frozenset({'Polygon', 'MultiPolygon'})
 
1150
 
1151
 
1152
  def _zone_position(raw):
@@ -1205,11 +1234,25 @@ def clean_zone(raw, field_keys=None, allowed_row_ids=None):
1205
  # cannot be legal inside one Zone label without making one Zone appear as two filter choices.
1206
  name = ' '.join(str(raw.get('name') or '').replace(',', ' ').split())[:120]
1207
  geometry = _clean_zone_geometry(raw.get('geometryGeoJson'))
1208
- if not name or geometry is None:
 
 
 
 
 
 
 
 
 
 
 
 
 
1209
  return None
1210
  out = {'name': name,
1211
  'color': (str(raw.get('color') or '#1F4E78').upper()),
1212
  'geometryGeoJson': geometry,
 
1213
  'visible': raw.get('visible') is not False}
1214
  if not _ZONE_COLOR_RE.fullmatch(out['color']):
1215
  return None
@@ -1371,12 +1414,22 @@ def is_user_table(table_key, st=None):
1371
  return str(table_key or '').startswith(KEY_PREFIX) and get(table_key, st) is not None
1372
 
1373
 
1374
- def create(label, username, fields=None, source=None, st=None):
 
 
 
 
 
 
1375
  """Create a blank table. Returns its key, or None if refused.
1376
 
1377
  Refuses rather than raises on the ordinary conditions (no name, duplicate, cap reached) —
1378
  the caller is a UI form and a refusal is a message, not an exception.
1379
  """
 
 
 
 
1380
  label = str(label or '').strip()[:MAX_LABEL]
1381
  if not label:
1382
  return None
@@ -1404,6 +1457,10 @@ def create(label, username, fields=None, source=None, st=None):
1404
  'source': 'overlay', 'default': True}],
1405
  'rows': {},
1406
  }
 
 
 
 
1407
 
1408
  def _add(cur):
1409
  cur[key] = defn
@@ -1429,6 +1486,8 @@ def delete(table_key, st=None):
1429
  Every family after the definition is best-effort: a store blip mid-sweep must not resurrect
1430
  the table, and an orphaned empty bucket is residue, not a leak."""
1431
  key = str(table_key)
 
 
1432
  s = _st(st)
1433
 
1434
  def _drop(cur):
@@ -1773,6 +1832,42 @@ def _clean_metric(raw):
1773
  #: ~3 KB — comfortably inside a text cell, and `MAX_ROWS` bounds the absolute worst case anyway.
1774
  LINK_MAX_IDS = 500
1775
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1776
  #: Airtable's 17 aggregations, minus the two that are meaningless over scalar cells.
1777
  #: ⛔ `arrayflatten` and `arrayslice` are NOT here: both operate on NESTED arrays, and a cell in
1778
  #: this product is a scalar — they could only ever return their own input, so offering them would
@@ -1883,6 +1978,117 @@ def is_linkable_target(table_key):
1883
  return key.startswith(KEY_PREFIX) and len(key) > len(KEY_PREFIX)
1884
 
1885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1886
  def _clean_link(raw):
1887
  """One `link` bag → the stored shape, or None (refused).
1888
 
@@ -1942,10 +2148,25 @@ def _clean_link(raw):
1942
  # than dropped: a bag half of which is silently ignored is [[wrong-parent-not-broken-control]]
1943
  # with the control still on screen.
1944
  return None
 
 
 
 
 
 
 
 
 
1945
  if reciprocal:
1946
  out['reciprocal'] = reciprocal
1947
  if raw.get('single') is True:
1948
  out['single'] = True
 
 
 
 
 
 
1949
  return out
1950
 
1951
 
@@ -2425,7 +2646,17 @@ def _clean_field(raw, previous=None):
2425
  ftype = str(raw.get('type') or prev.get('type') or 'text').strip().lower()
2426
  if not key or not label or ftype not in UT_FIELD_TYPES:
2427
  return None
2428
- out = {'key': key, 'label': label, 'type': ftype, 'source': 'overlay'}
 
 
 
 
 
 
 
 
 
 
2429
  # ⭐ 2026-08-10 — the DISPLAY format, on the add/patch door too. ⚠ `'format' in raw` rather than
2430
  # `raw.get('format')`, exactly like `description` below: an explicit `{}`/None CLEARS the
2431
  # format, while omitting the key keeps what is stored. A PATCH that sends only a label must not
@@ -2477,7 +2708,9 @@ def _clean_field(raw, previous=None):
2477
  # a valid, new select indistinguishable from a malformed text field on its read path.
2478
  # Keep the empty list deliberately: the type is the contract; options are its current
2479
  # vocabulary, not a prerequisite for the column to exist.
2480
- opts = [' '.join(str(o).split())[:60] for o in (opts_raw or []) if str(o).strip()][:50]
 
 
2481
  out['options'] = opts
2482
  # ⭐⭐ WAVE-29 CONTRACT C1 (owner item 13) — **THE OPTION COLOURS, WHICH THIS DOOR DROPPED.**
2483
  #
@@ -3191,6 +3424,8 @@ def delete_field_refusal(table_key, fkey, viewer, is_admin=False, st=None, *, fi
3191
  grant_topic=grant_topic)
3192
  if bag is None:
3193
  return FIELD_NOT_FOUND
 
 
3194
  # ⛔ ABOVE THE ADMIN BRANCH. Moving this below it is the mutation W41-T02's proof breaks on
3195
  # purpose, and R6a is the sentence it would violate.
3196
  if bag.get('origin') == 'preset':
@@ -3287,6 +3522,8 @@ def add_field(table_key, raw, st=None):
3287
  field = _clean_field(raw)
3288
  if not field or any(f.get('key') == field['key'] for f in have):
3289
  return None
 
 
3290
  if not flow_bound(field.get('automation'), st):
3291
  return None # C8: no field without a flow (400 at the route)
3292
  # C3 (wave 25, R7's first mitigation): AT MOST ONE profile field per table. Without it the
@@ -3490,6 +3727,8 @@ def patch_field(table_key, fkey, raw, st=None):
3490
  field = _clean_field(merged, fields[idx])
3491
  if not field:
3492
  return None
 
 
3493
  if 'automation' in merged and not flow_bound(field.get('automation'), st):
3494
  return None # C8: a patch cannot un-bind a column either
3495
  # C3: the one-per-table law on the PATCH door too — flagging a second column is the same act
@@ -3560,6 +3799,8 @@ def delete_field(table_key, fkey, st=None):
3560
  if len(fields) <= 1 or not any(f.get('key') == str(fkey) for f in fields):
3561
  return False
3562
  doomed = next((f for f in fields if f.get('key') == str(fkey)), {})
 
 
3563
  doomed_link = doomed.get('link') if isinstance(doomed.get('link'), dict) else {}
3564
  inverse_source = None
3565
  if doomed_link.get('inverse'):
 
52
  import uuid as _uuid
53
 
54
  import core.store as store
55
+ from core.route_system import MAX_OPTIONS
56
 
57
  STORE_KEY = 'user_tables'
58
  ZONE_STORE_KEY = 'table_zones'
 
492
  UT_FIELD_TYPES = {'text', 'select', 'multiselect', 'user', 'int', 'currency', 'pct', 'date',
493
  'checkbox', 'phone', 'email', 'url', 'rating', 'automation', 'json',
494
  'link', 'rollup', 'code', 'image', 'formula', 'ai_enrich'}
495
+ FIELD_ORIGINS = {'odoo', 'loopable', 'system', 'user', 'automation'}
496
+ FIELD_AUTHORITIES = {'source', 'derived', 'user-entered', 'computed'}
497
+ FIELD_SCOPES = {'source', 'tenant', 'view', 'record'}
498
  #: A cell is still a scalar on the wire (`Row` values are strings/numbers) — what this bounds is
499
  #: the DOCUMENT inside it. Source data is one already-paid provider response; keep it whole so a
500
  #: provider field is never silently discarded merely because the response is rich. 32 MiB matches
 
815
  #: A choice colour, as the client's editor spells one. `#RRGGBB`, upper-cased on the way in so a
816
  #: stored value has exactly ONE spelling and two fields cannot disagree about `#ebf6ef`.
817
  _OPTION_COLOR_RE = re.compile(r'#[0-9A-F]{6}')
 
818
  _MAX_CHOICE_LABEL = 60
819
 
820
 
821
+ def option_cap_refusal(raw_options):
822
+ """Name an over-cap choice declaration, including entered, limit, and rejected counts."""
823
+ entered = len([option for option in (raw_options or []) if str(option).strip()])
824
+ if entered <= MAX_OPTIONS:
825
+ return None
826
+ rejected = entered - MAX_OPTIONS
827
+ return (f'That column declares {entered} options; the server limit is {MAX_OPTIONS}, so '
828
+ f'{rejected} would be rejected. Remove {rejected} options, then save.')
829
+
830
+
831
  def _clean_option_colors(raw, options):
832
  """`{option label → #RRGGBB}`, capped to the field's own option vocabulary (wave-29 C1).
833
 
 
900
  continue
901
  for option in _choice_values(field, values[key]):
902
  folded = option.casefold()
903
+ if folded in known or len(options) >= MAX_OPTIONS:
904
  continue
905
  options.append(option)
906
  known.add(folded)
 
960
  if not key or key in seen or ftype not in UT_FIELD_TYPES or not label:
961
  continue
962
  seen.add(key)
963
+ origin = str(f.get('origin') or 'user')
964
+ authority = str(f.get('valueAuthority') or 'user-entered')
965
+ scope = str(f.get('scope') or 'tenant')
966
+ # C3: these are closed product vocabularies. Do not silently persist a word no
967
+ # renderer/permission door understands.
968
+ if origin not in FIELD_ORIGINS or authority not in FIELD_AUTHORITIES or scope not in FIELD_SCOPES:
969
+ continue
970
+ entry = {'key': key, 'label': label, 'type': ftype, 'source': 'overlay',
971
+ 'kind': ftype, 'origin': origin, 'valueAuthority': authority, 'scope': scope}
972
+ if ftype == 'json' and not f.get('label'):
973
+ entry['label'] = 'Table'
974
  # ⭐ 2026-08-10 — the DISPLAY format, carried through the CREATE door. See `_clean_format`:
975
  # this is the fifth time an entry built key-by-key has silently dropped a bag the editor
976
  # sends, and the fourth of those was `agg` on this very line one wave ago.
 
990
  if note:
991
  entry['note'] = note
992
  if ftype in ('select', 'multiselect'):
993
+ # Refuse the field instead of storing a silently shortened vocabulary. This list
994
+ # validator already drops one malformed field while preserving valid siblings.
995
  opts = [' '.join(str(o).split())[:60] for o in (f.get('options') or [])
996
+ if str(o).strip()]
997
+ if len(opts) > MAX_OPTIONS:
998
+ continue
999
  entry['options'] = opts
1000
  if f.get('default') is True:
1001
  entry['default'] = True
 
1173
  _ZONE_ID_RE = re.compile(r'^[A-Za-z0-9_-]{1,96}$')
1174
  _ZONE_FIELD_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_]{0,79}$')
1175
  _ZONE_COLOR_RE = re.compile(r'^#[0-9A-Fa-f]{6}$')
1176
+ _ZONE_ZIP_RE = re.compile(r'^\d{5}(?:-\d{4})?$')
1177
  _ZONE_GEOMETRIES = frozenset({'Polygon', 'MultiPolygon'})
1178
+ MAX_ZONE_ZIP_CODES = 500
1179
 
1180
 
1181
  def _zone_position(raw):
 
1234
  # cannot be legal inside one Zone label without making one Zone appear as two filter choices.
1235
  name = ' '.join(str(raw.get('name') or '').replace(',', ' ').split())[:120]
1236
  geometry = _clean_zone_geometry(raw.get('geometryGeoJson'))
1237
+ raw_zips = raw.get('zipCodes') or []
1238
+ if not isinstance(raw_zips, (list, tuple)) or len(raw_zips) > MAX_ZONE_ZIP_CODES:
1239
+ return None
1240
+ zip_codes, seen_zips = [], set()
1241
+ for value in raw_zips:
1242
+ zip_code = str(value or '').strip().upper()
1243
+ if not _ZONE_ZIP_RE.fullmatch(zip_code):
1244
+ return None
1245
+ if zip_code not in seen_zips:
1246
+ seen_zips.add(zip_code)
1247
+ zip_codes.append(zip_code)
1248
+ # Existing polygon Zones remain valid byte-for-byte. Wave 44 also permits a ZIP-only Zone;
1249
+ # the two shapes share this record rather than inventing a second persistence model.
1250
+ if not name or (geometry is None and not zip_codes):
1251
  return None
1252
  out = {'name': name,
1253
  'color': (str(raw.get('color') or '#1F4E78').upper()),
1254
  'geometryGeoJson': geometry,
1255
+ 'zipCodes': zip_codes,
1256
  'visible': raw.get('visible') is not False}
1257
  if not _ZONE_COLOR_RE.fullmatch(out['color']):
1258
  return None
 
1414
  return str(table_key or '').startswith(KEY_PREFIX) and get(table_key, st) is not None
1415
 
1416
 
1417
+ def is_managed_system_table(table_key, st=None, definition=None):
1418
+ """C1 policy predicate, intentionally separate from ordinary record mutability."""
1419
+ from core import route_system
1420
+ return route_system.is_managed(definition if definition is not None else (get(table_key, st) or table_key))
1421
+
1422
+
1423
+ def create(label, username, fields=None, source=None, st=None, *, managed_by=None, capability=None):
1424
  """Create a blank table. Returns its key, or None if refused.
1425
 
1426
  Refuses rather than raises on the ordinary conditions (no name, duplicate, cap reached) —
1427
  the caller is a UI form and a refusal is a message, not an exception.
1428
  """
1429
+ if managed_by is not None:
1430
+ from core import route_system
1431
+ if managed_by != route_system.MANAGED_BY or not route_system.is_internal_writer(capability):
1432
+ return None
1433
  label = str(label or '').strip()[:MAX_LABEL]
1434
  if not label:
1435
  return None
 
1457
  'source': 'overlay', 'default': True}],
1458
  'rows': {},
1459
  }
1460
+ if managed_by:
1461
+ from core import route_system
1462
+ defn.update({'managedBy': route_system.MANAGED_BY, 'folderId': route_system.LOOPABLE_FOLDER_ID,
1463
+ 'protected': True})
1464
 
1465
  def _add(cur):
1466
  cur[key] = defn
 
1486
  Every family after the definition is best-effort: a store blip mid-sweep must not resurrect
1487
  the table, and an orphaned empty bucket is residue, not a leak."""
1488
  key = str(table_key)
1489
+ if is_managed_system_table(key, st=st):
1490
+ return False
1491
  s = _st(st)
1492
 
1493
  def _drop(cur):
 
1832
  #: ~3 KB — comfortably inside a text cell, and `MAX_ROWS` bounds the absolute worst case anyway.
1833
  LINK_MAX_IDS = 500
1834
 
1835
+ # Link picker filters are schema, not a View selection: the leaf below constrains candidate rows
1836
+ # in the linked table. `sourceField` is explicitly a field on the current record; absence means
1837
+ # this is the static/literal form. Keeping the two shapes disjoint prevents a dynamic picker
1838
+ # value being mistaken for a saved View lock or a stale literal.
1839
+ LINK_FILTER_OPS = ('eq', 'neq', 'contains', 'not_contains', 'is_empty', 'is_not_empty')
1840
+
1841
+
1842
+ def _clean_link_filter(raw):
1843
+ if not isinstance(raw, dict):
1844
+ return None
1845
+ field = _field_key(raw.get('field', raw.get('colId')))
1846
+ op = str(raw.get('op') or '').strip()
1847
+ if not field or op not in LINK_FILTER_OPS:
1848
+ return None
1849
+ source = _field_key(raw.get('sourceField', raw.get('currentRecordField')))
1850
+ if source:
1851
+ # A dynamic leaf has no literal fallback. Retaining one would let an old/current record
1852
+ # value silently answer when the source field goes blank, a different filter under one UI.
1853
+ return {'field': field, 'op': op, 'sourceField': source}
1854
+ if op in ('is_empty', 'is_not_empty'):
1855
+ return {'field': field, 'op': op}
1856
+ if 'value' not in raw or isinstance(raw.get('value'), (dict, list, tuple, set)):
1857
+ return None
1858
+ return {'field': field, 'op': op, 'value': str(raw.get('value'))[:500]}
1859
+
1860
+
1861
+ def dynamic_link_filter_valid(field, fields):
1862
+ """Does every dynamic Link-filter source name another field on this current record?"""
1863
+ bag = field.get('link') if isinstance(field, dict) else None
1864
+ leaf = bag.get('filter') if isinstance(bag, dict) else None
1865
+ source = leaf.get('sourceField') if isinstance(leaf, dict) else None
1866
+ if not source:
1867
+ return True
1868
+ names = {str(item.get('key') or '') for item in fields or () if isinstance(item, dict)}
1869
+ return source in names and source != str(field.get('key') or '')
1870
+
1871
  #: Airtable's 17 aggregations, minus the two that are meaningless over scalar cells.
1872
  #: ⛔ `arrayflatten` and `arrayslice` are NOT here: both operate on NESTED arrays, and a cell in
1873
  #: this product is a scalar — they could only ever return their own input, so offering them would
 
1978
  return key.startswith(KEY_PREFIX) and len(key) > len(KEY_PREFIX)
1979
 
1980
 
1981
+ # W42-T03 / R1 / C1: a user-created link may carry exactly one governed semantic hop.
1982
+ # Keep this tuple tied to the literal reads in `_clean_via`: verify_pivot extracts those reads
1983
+ # from the AST and compares them to both this allow-list and the client emitter.
1984
+ LINK_VIA_KEYS = ('topic', 'source_dim', 'target_dim', 'target_key', 'scope_key', 'measure',
1985
+ 'filter', 'filterConj', 'window')
1986
+ LINK_VIA_CONJ = ('and', 'or')
1987
+ LINK_VIA_WINDOWS = ROLLUP_SOURCE_WINDOWS
1988
+
1989
+
1990
+ def _topic_dims(topic):
1991
+ """Return model-declared dimensions without opening a tenant store; fail closed."""
1992
+ if not topic:
1993
+ return None
1994
+ try:
1995
+ from harness import semantic as _sem
1996
+ definition = (_sem.topics() or {}).get(topic)
1997
+ except Exception:
1998
+ return None
1999
+ if not definition:
2000
+ return None
2001
+ dims = ((definition.get('store') or {}).get('dims')) or {}
2002
+ return frozenset(dims) or None
2003
+
2004
+
2005
+ def _clean_via_filter(raw, depth=1, budget=None):
2006
+ """Shape-check a hop filter without silently trimming a widening condition."""
2007
+ import aios_grid as _agv
2008
+ if budget is None:
2009
+ budget = [_agv.MAX_FILTER_NODES]
2010
+ if not isinstance(raw, list) or len(raw) > _agv.MAX_FILTER_SIBLINGS:
2011
+ return None
2012
+ out = []
2013
+ for node in raw:
2014
+ if not isinstance(node, dict):
2015
+ return None
2016
+ budget[0] -= 1
2017
+ if budget[0] < 0:
2018
+ return None
2019
+ children = node.get('children')
2020
+ if isinstance(children, list):
2021
+ if depth >= _agv.MAX_FILTER_DEPTH:
2022
+ return None
2023
+ kids = _clean_via_filter(children, depth + 1, budget)
2024
+ if kids is None:
2025
+ return None
2026
+ out.append({'conj': 'or' if node.get('conj') == 'or' else 'and',
2027
+ 'children': kids})
2028
+ continue
2029
+ leaf = {}
2030
+ for key, value in node.items():
2031
+ if not isinstance(key, str):
2032
+ return None
2033
+ if isinstance(value, str):
2034
+ leaf[key] = value[:500]
2035
+ elif isinstance(value, (int, float, bool)) or value is None:
2036
+ leaf[key] = value
2037
+ elif isinstance(value, (list, dict)):
2038
+ leaf[key] = value
2039
+ else:
2040
+ return None
2041
+ out.append(leaf)
2042
+ return out
2043
+
2044
+
2045
+ def _clean_via(raw):
2046
+ """One semantic `via` bag, or None. Nested hops and partial bags are refused."""
2047
+ if not isinstance(raw, dict):
2048
+ return None
2049
+ if 'via' in raw:
2050
+ return None
2051
+ for key in raw:
2052
+ if key not in LINK_VIA_KEYS:
2053
+ return None
2054
+ # These are deliberately literal reads: verify_pivot mechanically extracts the accepted set.
2055
+ topic = str(raw.get('topic') or '').strip()
2056
+ dims = _topic_dims(topic)
2057
+ if not dims:
2058
+ return None
2059
+ source_dim = str(raw.get('source_dim') or '').strip()
2060
+ target_dim = str(raw.get('target_dim') or '').strip()
2061
+ if source_dim not in dims or target_dim not in dims:
2062
+ return None
2063
+ # Required target/scope identities are not topic dimensions and are never defaulted.
2064
+ target_key = _field_key(raw.get('target_key'))
2065
+ scope_key = _field_key(raw.get('scope_key'))
2066
+ measure = _field_key(raw.get('measure'))
2067
+ if not target_key or not scope_key or not measure:
2068
+ return None
2069
+ out = {'topic': topic, 'source_dim': source_dim, 'target_dim': target_dim,
2070
+ 'target_key': target_key, 'scope_key': scope_key, 'measure': measure}
2071
+ raw_filter = raw.get('filter')
2072
+ if raw_filter is not None:
2073
+ nodes = _clean_via_filter(raw_filter)
2074
+ if nodes is None:
2075
+ return None
2076
+ out['filter'] = nodes
2077
+ raw_conj = raw.get('filterConj')
2078
+ if raw_conj is not None:
2079
+ conj = str(raw_conj).strip().lower()
2080
+ if conj not in LINK_VIA_CONJ:
2081
+ return None
2082
+ out['filterConj'] = conj
2083
+ raw_window = raw.get('window')
2084
+ if raw_window is not None:
2085
+ window = str(raw_window).strip().lower()
2086
+ if window not in LINK_VIA_WINDOWS:
2087
+ return None
2088
+ out['window'] = window
2089
+ return out
2090
+
2091
+
2092
  def _clean_link(raw):
2093
  """One `link` bag → the stored shape, or None (refused).
2094
 
 
2148
  # than dropped: a bag half of which is silently ignored is [[wrong-parent-not-broken-control]]
2149
  # with the control still on screen.
2150
  return None
2151
+ # A semantic hop is meaningful only on a derived link with a first join to travel from.
2152
+ # Its absence preserves the historical one-hop bag byte-for-byte.
2153
+ if raw.get('via') is not None:
2154
+ if 'on' not in out:
2155
+ return None
2156
+ via = _clean_via(raw.get('via'))
2157
+ if via is None:
2158
+ return None
2159
+ out['via'] = via
2160
  if reciprocal:
2161
  out['reciprocal'] = reciprocal
2162
  if raw.get('single') is True:
2163
  out['single'] = True
2164
+ supplied_filter = raw.get('filter', raw.get('where'))
2165
+ if supplied_filter is not None:
2166
+ leaf = _clean_link_filter(supplied_filter)
2167
+ if leaf is None:
2168
+ return None
2169
+ out['filter'] = leaf
2170
  return out
2171
 
2172
 
 
2646
  ftype = str(raw.get('type') or prev.get('type') or 'text').strip().lower()
2647
  if not key or not label or ftype not in UT_FIELD_TYPES:
2648
  return None
2649
+ origin = str(raw.get('origin') if 'origin' in raw else prev.get('origin') or 'user')
2650
+ authority = str(raw.get('valueAuthority') if 'valueAuthority' in raw else prev.get('valueAuthority') or 'user-entered')
2651
+ scope = str(raw.get('scope') if 'scope' in raw else prev.get('scope') or 'tenant')
2652
+ if origin not in FIELD_ORIGINS or authority not in FIELD_AUTHORITIES or scope not in FIELD_SCOPES:
2653
+ return None
2654
+ out = {'key': key, 'label': label, 'type': ftype, 'source': 'overlay', 'kind': ftype,
2655
+ 'origin': origin, 'valueAuthority': authority, 'scope': scope}
2656
+ if ftype == 'json':
2657
+ out['label'] = 'Table'
2658
+ if bool(raw.get('deletionLocked') if 'deletionLocked' in raw else prev.get('deletionLocked')):
2659
+ out['deletionLocked'] = True
2660
  # ⭐ 2026-08-10 — the DISPLAY format, on the add/patch door too. ⚠ `'format' in raw` rather than
2661
  # `raw.get('format')`, exactly like `description` below: an explicit `{}`/None CLEARS the
2662
  # format, while omitting the key keeps what is stored. A PATCH that sends only a label must not
 
2708
  # a valid, new select indistinguishable from a malformed text field on its read path.
2709
  # Keep the empty list deliberately: the type is the contract; options are its current
2710
  # vocabulary, not a prerequisite for the column to exist.
2711
+ opts = [' '.join(str(o).split())[:60] for o in (opts_raw or []) if str(o).strip()]
2712
+ if len(opts) > MAX_OPTIONS:
2713
+ return None
2714
  out['options'] = opts
2715
  # ⭐⭐ WAVE-29 CONTRACT C1 (owner item 13) — **THE OPTION COLOURS, WHICH THIS DOOR DROPPED.**
2716
  #
 
3424
  grant_topic=grant_topic)
3425
  if bag is None:
3426
  return FIELD_NOT_FOUND
3427
+ if bool((field or {}).get('deletionLocked')):
3428
+ return 'field_deletion_locked'
3429
  # ⛔ ABOVE THE ADMIN BRANCH. Moving this below it is the mutation W41-T02's proof breaks on
3430
  # purpose, and R6a is the sentence it would violate.
3431
  if bag.get('origin') == 'preset':
 
3522
  field = _clean_field(raw)
3523
  if not field or any(f.get('key') == field['key'] for f in have):
3524
  return None
3525
+ if not dynamic_link_filter_valid(field, have):
3526
+ return None
3527
  if not flow_bound(field.get('automation'), st):
3528
  return None # C8: no field without a flow (400 at the route)
3529
  # C3 (wave 25, R7's first mitigation): AT MOST ONE profile field per table. Without it the
 
3727
  field = _clean_field(merged, fields[idx])
3728
  if not field:
3729
  return None
3730
+ if not dynamic_link_filter_valid(field, fields):
3731
+ return None
3732
  if 'automation' in merged and not flow_bound(field.get('automation'), st):
3733
  return None # C8: a patch cannot un-bind a column either
3734
  # C3: the one-per-table law on the PATCH door too — flagging a second column is the same act
 
3799
  if len(fields) <= 1 or not any(f.get('key') == str(fkey) for f in fields):
3800
  return False
3801
  doomed = next((f for f in fields if f.get('key') == str(fkey)), {})
3802
+ if doomed.get('deletionLocked') is True:
3803
+ return False
3804
  doomed_link = doomed.get('link') if isinstance(doomed.get('link'), dict) else {}
3805
  inverse_source = None
3806
  if doomed_link.get('inverse'):
platform/harness/semantic.py CHANGED
@@ -71,6 +71,15 @@ class ModelError(Exception):
71
  """A model-file problem (unknown key, bad reference, unparseable expr)."""
72
 
73
 
 
 
 
 
 
 
 
 
 
74
  # ---------------------------------------------------------------- loading
75
 
76
  @functools.lru_cache(maxsize=1)
@@ -456,7 +465,7 @@ def _post_compute(row, key):
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,6 +479,9 @@ def _clean_tree(tree, cols):
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
@@ -544,6 +556,53 @@ def _clean_tree(tree, cols):
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
 
@@ -782,7 +841,8 @@ def store_query(topic, measures, group_by=None, grain=None, date_from=None, date
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"])
@@ -821,7 +881,8 @@ def store_query(topic, measures, group_by=None, grain=None, date_from=None, date
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):
@@ -953,7 +1014,9 @@ def store_rows(topic, date_from=None, date_to=None, team_id=None, filter_tree=No
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,7 +1090,7 @@ def store_field_values(topic, dim, search=None, limit=25):
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"]
 
71
  """A model-file problem (unknown key, bad reference, unparseable expr)."""
72
 
73
 
74
+ class UnknownColumnError(ModelError):
75
+ """A filter/group request named a column the topic does not declare."""
76
+
77
+ def __init__(self, message, column, columns=None):
78
+ super().__init__(message)
79
+ self.column = str(column)
80
+ self.columns = sorted({str(item) for item in (columns or [column])})
81
+
82
+
83
  # ---------------------------------------------------------------- loading
84
 
85
  @functools.lru_cache(maxsize=1)
 
465
  _FORMAT_TYPE = {"usd": "currency", "int": "int", "pct": "pct"}
466
 
467
 
468
+ def _clean_tree(tree, cols, tolerate=()):
469
  """Run a filter tree through the SAME validator the client's view state goes through.
470
 
471
  `filter_sql`'s documented input contract is "feed me CLEANED trees" — it is faithful to the
 
479
  module with zero imports of its own, so this cannot cycle.
480
  """
481
  from aios_grid import (clean_filter_tree, COHORT_FIELD as _COHORT_FIELD,
482
+ VIEW_FIELD as _VIEW_FIELD, FILTER_OPS as _FILTER_OPS,
483
+ COHORT_OPS as _COHORT_OPS, COHORT_OP_ALIASES as _COHORT_ALIASES,
484
+ VIEW_OPS as _VIEW_OPS,
485
  MAX_FILTER_DEPTH, MAX_FILTER_NODES, MAX_FILTER_SIBLINGS)
486
 
487
  # REFUSE an over-large tree rather than TRUNCATE it. clean_filter_tree caps siblings per
 
556
  f" — those are resolved to a set of ids by harness.measure_filter, not compiled into "
557
  f"this query. Refusing rather than dropping or mis-compiling them, either of which "
558
  f"would silently answer a different question under an authoritative count.")
559
+ # The UI cleaner drops unknown columns/operators for stale saved views. On a server query
560
+ # that would silently widen the result, so authoring faults are refused before normalization.
561
+ # `tolerate` covers deliberately narrower row projections.
562
+ tolerated = {str(column) for column in (tolerate or ())}
563
+ known = set(cols) | tolerated | {_COHORT_FIELD, _VIEW_FIELD}
564
+ unknown = []
565
+ bad_ops = []
566
+
567
+ def _inspect(nodes):
568
+ for node in nodes or []:
569
+ if not isinstance(node, dict):
570
+ continue
571
+ if isinstance(node.get('children'), list):
572
+ _inspect(node['children'])
573
+ continue
574
+ column = node.get('colId')
575
+ if column in (None, ''):
576
+ continue
577
+ column = str(column)
578
+ if column not in known:
579
+ unknown.append(column)
580
+ continue
581
+ if tolerated and column in tolerated and column not in cols:
582
+ continue
583
+ op = node.get('op')
584
+ if op in (None, ''):
585
+ continue
586
+ legal = (_COHORT_OPS | set(_COHORT_ALIASES) if column == _COHORT_FIELD
587
+ else _VIEW_OPS if column == _VIEW_FIELD
588
+ else _FILTER_OPS)
589
+ if str(op) not in legal:
590
+ bad_ops.append((column, str(op), sorted(legal)))
591
+
592
+ _inspect(tree)
593
+ if unknown:
594
+ bad = sorted(set(unknown))
595
+ extra = f" (and {bad[1:]})" if len(bad) > 1 else ""
596
+ raise UnknownColumnError(
597
+ f"filter rule names column {bad[0]!r}{extra}, which this topic does not have. "
598
+ f"Refusing rather than dropping the rule, which would silently widen the result.",
599
+ column=bad[0], columns=bad)
600
+ if bad_ops:
601
+ column, op, legal = bad_ops[0]
602
+ raise ModelError(
603
+ f"filter rule on column {column!r} carries operator {op!r}, which is not one this "
604
+ f"filter understands (use: {legal}). Refusing rather than dropping the rule, which "
605
+ f"would silently widen the result.")
606
  return clean_filter_tree(tree, set(cols))
607
 
608
 
 
841
  gb = [g for g in (group_by or []) if g]
842
  for g in gb:
843
  if g not in dims:
844
+ raise UnknownColumnError(
845
+ f"group_by {g!r} not a dim of {topic!r} (allowed: {list(dims)})", column=g)
846
  d = dims[g]
847
  select.append(f"{d['col']} AS {g}_id" if d.get("name_col") else f"{d['col']} AS {g}")
848
  group_cols.append(d["col"])
 
881
  where.append(render_scope(s["service_filter"]))
882
  for dim_key, vals in (filters or {}).items():
883
  if dim_key not in dims:
884
+ raise UnknownColumnError(
885
+ f"filter dim {dim_key!r} not allowed (use: {list(dims)})", column=dim_key)
886
  # id dims filter by int; TEXT dims (e.g. city) filter by the value itself — either way
887
  # every VALUE stays parameterized (the whitelist covers identifiers only)
888
  def _coerce(v):
 
1014
 
1015
  # --- the user's narrowing, on top of the scope --------------------------------------
1016
  narrow, narrow_params = [], []
1017
+ pred = _fs.compile_filter_tree(_clean_tree(filter_tree or [], cols,
1018
+ tolerate=store_columns(topic)),
1019
+ filter_conj, cols,
1020
  today=today,
1021
  member_ids=member_ids or None, id_sql=id_sql)
1022
  if pred is not None:
 
1090
  raise ModelError(f"topic {topic!r} has no store binding")
1091
  d = (t["store"].get("dims") or {}).get(dim)
1092
  if not d:
1093
+ raise UnknownColumnError(f"unknown dim {dim!r} for topic {topic!r}", column=dim)
1094
  if not d.get("name_col"):
1095
  raise ModelError(f"dim {dim!r} has no name column (filter by id)")
1096
  s = t["store"]
platform/model/topics/sales_lines.yml CHANGED
@@ -74,6 +74,14 @@ 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
 
78
  ai_context: >
79
  The wholesale sales dataset of Royal Imports / Fisch Floral Supply, at order-LINE grain.
@@ -117,3 +125,7 @@ ai_context: >
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.
 
 
 
 
 
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: status operands live on the parent order already joined as `o`. These are text
78
+ # codes, so the value and name expressions are intentionally identical; this keeps filtering
79
+ # and grouping on the exact raw Odoo state without inventing a numeric companion.
80
+ invoice_status: {col: "o.invoice_status", name_col: "o.invoice_status",
81
+ label: "Invoice status"}
82
+ # `scope_sql` already limits this to confirmed/locked orders (`sale`/`done`). This dimension
83
+ # distinguishes those states; it must never widen the topic to quotations or cancellations.
84
+ order_state: {col: "o.state", name_col: "o.state", label: "Order state"}
85
 
86
  ai_context: >
87
  The wholesale sales dataset of Royal Imports / Fisch Floral Supply, at order-LINE grain.
 
125
  has no address on file — present it as "no state on file", keep it in totals) and duplicate
126
  state records exist (two ids can share one name, e.g. New Jersey twice) — list them as the
127
  data shows and note the duplication rather than silently merging.
128
+ Invoicing questions use `invoice_status`, inherited from the parent order. Its raw values are
129
+ 'invoiced', 'to invoice', 'no', and 'upselling'. `order_state` is limited to 'sale' or 'done'
130
+ because this topic is confirmed-order scope; a missing quotation bucket is not evidence that
131
+ the tenant has no quotations.
web/public/sample_customers.json CHANGED
@@ -112,6 +112,7 @@
112
  "label": "Google Maps",
113
  "type": "url",
114
  "source": "odoo",
 
115
  "default": true,
116
  "description": "A Google Maps link to this customer's address."
117
  },
 
112
  "label": "Google Maps",
113
  "type": "url",
114
  "source": "odoo",
115
+ "valueOverride": "overlay",
116
  "default": true,
117
  "description": "A Google Maps link to this customer's address."
118
  },
web/src/automation/AutomationBuilder.tsx CHANGED
@@ -31,7 +31,7 @@
31
  // AutomationTrigger).
32
  // ---------------------------------------------------------------------------
33
  import type { ReactNode } from "react";
34
- import { useEffect, useRef, useState } from "react";
35
 
36
  // ⭐ WAVE 30 · ITEM 7 (R3 + R4) — connector identity, from the ONE module that owns it. Not a
37
  // second copy of two SVGs: the directory, this menu and the trigger picker all answer "which
@@ -50,6 +50,7 @@ import type {
50
  TriggerOption,
51
  UserTable,
52
  } from "./automationApi";
 
53
  // ⭐ WAVE 26 · ITEM 22 / D-70 — the Run guard, imported rather than re-derived. This file and
54
  // `AutomationDetail` each paint a Run button onto the same paid action; ONE function decides.
55
  // ITEM 9 / R11 — `createTable` + `AutomationError` for the in-place "+ New database".
@@ -100,8 +101,13 @@ interface Props {
100
  /** The server's trigger vocabulary (C3). Absent is a state this file states, never fills in. */
101
  triggers?: TriggerOption[];
102
  catalog: ActionCatalogRow[];
 
 
 
 
103
  vocab?: FlowVocab;
104
  tables: UserTable[];
 
105
  oauth: OAuthStatus | null;
106
  /** True while a write is in flight — drives the "All changes saved" stamp and disables edits. */
107
  busy: boolean;
@@ -197,13 +203,6 @@ interface Props {
197
  * (duplicate names are legal), and the automation still points at neither.
198
  */
199
  onTablesChanged: () => Promise<void> | void;
200
- /**
201
- * Is there an edit the HEADER's Save still owns? REQUIRED, and it exists so the panel's
202
- * "All changes saved" stamp can stop being a claim about fields it does not cover — the
203
- * machine steps' panels moved into Properties this wave and they commit with Save, not on
204
- * change.
205
- */
206
- dirty: boolean;
207
  }
208
 
209
  /*
@@ -436,8 +435,11 @@ export default function AutomationBuilder({
436
  onNameCommit,
437
  triggers,
438
  catalog,
 
 
439
  vocab,
440
  tables,
 
441
  oauth,
442
  busy,
443
  onPatch,
@@ -454,7 +456,6 @@ export default function AutomationBuilder({
454
  schedules,
455
  walkTable,
456
  onTablesChanged,
457
- dirty,
458
  }: Props) {
459
  const [sel, setSel] = useState<Sel>({ kind: "trigger", id: "" });
460
  const [picking, setPicking] = useState(false);
@@ -686,6 +687,8 @@ export default function AutomationBuilder({
686
  : null;
687
  if (kind === "find_records")
688
  return firstTable ? { table: firstTable.key, cond: null, limit: 25 } : null;
 
 
689
  /*
690
  ⭐⭐ WAVE 31 · T38 (contract C5, owner ruling R10) — THE WEB READ, and this branch is here
691
  because a gate demanded it rather than because anybody remembered.
@@ -943,6 +946,77 @@ export default function AutomationBuilder({
943
  `verify_steps` exercises the nest, which no amount of JSX here could be tested against. */
944
  const menuGroups = groupActions(catalog);
945
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
946
  /** ONE action row, so the nested and un-nested lists cannot render differently. */
947
  const actionRow = (c: ActionCatalogRow) => (
948
  <button
@@ -1439,43 +1513,52 @@ export default function AutomationBuilder({
1439
  them, and `clean_actions` refuses the unready ones at the door, so faded is a
1440
  wall rather than a decoration. */}
1441
  {adding ? (
1442
- <div className="autox-menu" role="menu">
1443
  {menuGroups.map((g) => (
1444
  <div className="autox-menu-group" key={g.key}>
1445
- <p className="autox-menu-head">{g.key}</p>
1446
  {/* ⭐ WAVE 27 · ITEM 33 / C4 — the group's OWN rows first, then one nest per
1447
  connector. `<details>` rather than a hand-built disclosure: it IS the
1448
  chevron-and-submenu the reference shows, it opens on Enter and Space
1449
  without a keydown handler, and it needs no open/closed state of its own
1450
  to get wrong. Closed by default — the reference shows collapsed rows,
1451
  and a connector nobody is using should cost one line, not six. */}
1452
- {[...g.rows, ...g.sub].map((entry) => ("rows" in entry ? (
1453
- <details className="autox-menu-nest" key={`sub:${entry.key}`}>
1454
- <summary className="autox-menu-row autox-menu-sum">
1455
- {/* ⭐ WAVE 30 · ITEM 7 / R4 — THE COLLAPSED ROW GETS AN IDENTITY.
1456
- This is the row the owner clicks before choosing Instagram or
1457
- TikTok, and until now it was the only row in the menu with
1458
- nothing on its left: the chevron, then a bare word. The mark is
1459
- resolved from the connector KEY, so a connector the server adds
1460
- tomorrow gets a slot for free and simply renders no logo. */}
1461
- {brandForConnector(entry.key) ? (
1462
- <span className="autox-card-mark is-brand">
1463
- {brandForConnector(entry.key)}
1464
- </span>
1465
- ) : null}
1466
- <span className="autox-menu-text">
1467
- <span className="autox-menu-label">{entry.label}</span>
1468
- <span className="autox-menu-detail">
1469
- {entry.rows.length} action{entry.rows.length === 1 ? "" : "s"}
1470
- </span>
1471
- </span>
1472
- </summary>
1473
- {entry.rows.map((c) => actionRow(c))}
1474
- </details>
1475
- ) : actionRow(entry)))}
 
 
 
 
 
 
 
 
 
1476
  </div>
1477
  ))}
1478
- </div>
1479
  ) : null}
1480
  </div>
1481
  </div>
@@ -1493,18 +1576,6 @@ export default function AutomationBuilder({
1493
  >
1494
  <div className="auto-panel-head">
1495
  {panelTabs}
1496
- {/*
1497
- THREE STATES, because this panel now holds two save disciplines. The discrete choices
1498
- (a trigger, an action, a switch, a branch) persist as they are made; the machine
1499
- steps' fields, which moved in here with item 5, commit with the header's Save. A
1500
- two-state stamp had to be wrong about one of them, and "All changes saved" printed
1501
- over an unsaved column map is the direction that loses work.
1502
- */}
1503
- <span
1504
- className={"autox-saved" + (busy ? " is-busy" : dirty ? " is-dirty" : "")}
1505
- >
1506
- {busy ? "Saving…" : dirty ? "Unsaved changes. Press Save" : "All changes saved"}
1507
- </span>
1508
  </div>
1509
 
1510
  {/*
@@ -1534,6 +1605,7 @@ export default function AutomationBuilder({
1534
  picked={picked}
1535
  table={table}
1536
  tables={tables}
 
1537
  ops={ops}
1538
  nullaryOps={nullaryOps}
1539
  vocab={vocab}
@@ -1700,6 +1772,7 @@ function TriggerProps({
1700
  picked: TriggerOption | null;
1701
  table: UserTable | null;
1702
  tables: UserTable[];
 
1703
  ops: string[];
1704
  nullaryOps: string[];
1705
  vocab?: FlowVocab;
@@ -2917,6 +2990,7 @@ export function ActionProps({
2917
  agentMark,
2918
  catalog,
2919
  tables,
 
2920
  onTablesChanged,
2921
  walkFields,
2922
  walkTable,
@@ -2951,6 +3025,7 @@ export function ActionProps({
2951
  agentMark?: { agent: string; agentName?: string; created?: string; by?: string } | null;
2952
  catalog: ActionCatalogRow[];
2953
  tables: UserTable[];
 
2954
  /** ITEM 9 / R11 — re-read the list after this panel's picker creates one. REQUIRED; see Props. */
2955
  onTablesChanged: () => Promise<void> | void;
2956
  /**
@@ -3076,7 +3151,15 @@ export function ActionProps({
3076
  />
3077
  ) : null}
3078
 
3079
- {readOnly ? null : action.kind === "group" ? (
 
 
 
 
 
 
 
 
3080
  <>
3081
  {/*
3082
  ⭐ ONE CONDITION EDITOR PER BRANCH (C-FORK). The group's own `config.cond` is GONE —
 
31
  // AutomationTrigger).
32
  // ---------------------------------------------------------------------------
33
  import type { ReactNode } from "react";
34
+ import { Fragment, useEffect, useRef, useState } from "react";
35
 
36
  // ⭐ WAVE 30 · ITEM 7 (R3 + R4) — connector identity, from the ONE module that owns it. Not a
37
  // second copy of two SVGs: the directory, this menu and the trigger picker all answer "which
 
50
  TriggerOption,
51
  UserTable,
52
  } from "./automationApi";
53
+ import type { VoiceAgent } from "./voiceAgentTypes";
54
  // ⭐ WAVE 26 · ITEM 22 / D-70 — the Run guard, imported rather than re-derived. This file and
55
  // `AutomationDetail` each paint a Run button onto the same paid action; ONE function decides.
56
  // ITEM 9 / R11 — `createTable` + `AutomationError` for the in-place "+ New database".
 
101
  /** The server's trigger vocabulary (C3). Absent is a state this file states, never fills in. */
102
  triggers?: TriggerOption[];
103
  catalog: ActionCatalogRow[];
104
+ /** Existing synthetic Field agents, already composed and permission-filtered by the server. */
105
+ fieldAgents: Automation[];
106
+ /** Open one of those existing agents; AI enrichment cannot be authored as a direct action. */
107
+ onOpenFieldAgent: (id: string) => void;
108
  vocab?: FlowVocab;
109
  tables: UserTable[];
110
+ voiceAgents?: VoiceAgent[];
111
  oauth: OAuthStatus | null;
112
  /** True while a write is in flight — drives the "All changes saved" stamp and disables edits. */
113
  busy: boolean;
 
203
  * (duplicate names are legal), and the automation still points at neither.
204
  */
205
  onTablesChanged: () => Promise<void> | void;
 
 
 
 
 
 
 
206
  }
207
 
208
  /*
 
435
  onNameCommit,
436
  triggers,
437
  catalog,
438
+ fieldAgents,
439
+ onOpenFieldAgent,
440
  vocab,
441
  tables,
442
+ voiceAgents,
443
  oauth,
444
  busy,
445
  onPatch,
 
456
  schedules,
457
  walkTable,
458
  onTablesChanged,
 
459
  }: Props) {
460
  const [sel, setSel] = useState<Sel>({ kind: "trigger", id: "" });
461
  const [picking, setPicking] = useState(false);
 
687
  : null;
688
  if (kind === "find_records")
689
  return firstTable ? { table: firstTable.key, cond: null, limit: 25 } : null;
690
+ if (kind === "voice_agent")
691
+ return { voiceAgentId: "" };
692
  /*
693
  ⭐⭐ WAVE 31 · T38 (contract C5, owner ruling R10) — THE WEB READ, and this branch is here
694
  because a gate demanded it rather than because anybody remembered.
 
946
  `verify_steps` exercises the nest, which no amount of JSX here could be tested against. */
947
  const menuGroups = groupActions(catalog);
948
 
949
+ /*
950
+ * `ai_enrich` deliberately rides the catalog with `menu:false`: it names synthetic steps but
951
+ * the ordinary action door refuses authorship because enrichment belongs to a field. Hiding it
952
+ * from the whole Agent catalog was the bug. This separate consumer uses the row's server-owned
953
+ * label/group/detail and opens only the synthetic Field-agent choices the list route supplied.
954
+ */
955
+ const fieldAgentCatalog = catalog.find((entry) => entry.kind === "ai_enrich") || null;
956
+
957
+ const fieldAgentChoice = fieldAgentCatalog ? (
958
+ fieldAgentCatalog.ready && fieldAgents.length ? (
959
+ <details className="autox-menu-nest" data-catalog-kind="ai_enrich">
960
+ <summary className="autox-menu-row autox-menu-sum">
961
+ <span
962
+ className={"autox-card-mark"
963
+ + (hasBrandKind(fieldAgentCatalog.kind) ? " is-brand" : "")}
964
+ >
965
+ <ActionMark kind={fieldAgentCatalog.kind} />
966
+ </span>
967
+ <span className="autox-menu-text">
968
+ <span className="autox-menu-label">{fieldAgentCatalog.label}</span>
969
+ <span className="autox-menu-detail">{fieldAgentCatalog.detail}</span>
970
+ </span>
971
+ </summary>
972
+ {fieldAgents.map((agent) => (
973
+ <button
974
+ key={agent.id}
975
+ type="button"
976
+ className="autox-menu-row"
977
+ onClick={() => {
978
+ setAdding(false);
979
+ onOpenFieldAgent(agent.id);
980
+ }}
981
+ >
982
+ <span
983
+ className={"autox-card-mark"
984
+ + (hasBrandKind(fieldAgentCatalog.kind) ? " is-brand" : "")}
985
+ >
986
+ <ActionMark kind={fieldAgentCatalog.kind} />
987
+ </span>
988
+ <span className="autox-menu-text">
989
+ <span className="autox-menu-label">{agent.name}</span>
990
+ <span className="autox-menu-detail">Open this field agent</span>
991
+ </span>
992
+ </button>
993
+ ))}
994
+ </details>
995
+ ) : (
996
+ <button
997
+ type="button"
998
+ className="autox-menu-row is-planned"
999
+ data-catalog-kind="ai_enrich"
1000
+ disabled
1001
+ title="Add an AI field to a database first."
1002
+ >
1003
+ <span
1004
+ className={"autox-card-mark"
1005
+ + (hasBrandKind(fieldAgentCatalog.kind) ? " is-brand" : "")}
1006
+ >
1007
+ <ActionMark kind={fieldAgentCatalog.kind} />
1008
+ </span>
1009
+ <span className="autox-menu-text">
1010
+ <span className="autox-menu-label">
1011
+ {fieldAgentCatalog.label}
1012
+ <span className="autox-soon">No field agents</span>
1013
+ </span>
1014
+ <span className="autox-menu-detail">Add an AI field to a database first.</span>
1015
+ </span>
1016
+ </button>
1017
+ )
1018
+ ) : null;
1019
+
1020
  /** ONE action row, so the nested and un-nested lists cannot render differently. */
1021
  const actionRow = (c: ActionCatalogRow) => (
1022
  <button
 
1513
  them, and `clean_actions` refuses the unready ones at the door, so faded is a
1514
  wall rather than a decoration. */}
1515
  {adding ? (
1516
+ <section className="autox-menu" aria-label="Action catalog">
1517
  {menuGroups.map((g) => (
1518
  <div className="autox-menu-group" key={g.key}>
1519
+ <h3 className="autox-menu-head">{g.key}</h3>
1520
  {/* ⭐ WAVE 27 · ITEM 33 / C4 — the group's OWN rows first, then one nest per
1521
  connector. `<details>` rather than a hand-built disclosure: it IS the
1522
  chevron-and-submenu the reference shows, it opens on Enter and Space
1523
  without a keydown handler, and it needs no open/closed state of its own
1524
  to get wrong. Closed by default — the reference shows collapsed rows,
1525
  and a connector nobody is using should cost one line, not six. */}
1526
+ {[...g.rows, ...g.sub].map((entry) => (
1527
+ <Fragment key={("rows" in entry ? `sub:${entry.key}` : entry.kind)}>
1528
+ {!("rows" in entry) && entry.kind === "voice_agent"
1529
+ && fieldAgentCatalog?.group === g.key ? fieldAgentChoice : null}
1530
+ {"rows" in entry ? (
1531
+ <details className="autox-menu-nest">
1532
+ <summary className="autox-menu-row autox-menu-sum">
1533
+ {/* ⭐ WAVE 30 · ITEM 7 / R4 — THE COLLAPSED ROW GETS AN IDENTITY.
1534
+ This is the row the owner clicks before choosing Instagram or
1535
+ TikTok, and until now it was the only row in the menu with
1536
+ nothing on its left: the chevron, then a bare word. The mark is
1537
+ resolved from the connector KEY, so a connector the server adds
1538
+ tomorrow gets a slot for free and simply renders no logo. */}
1539
+ {brandForConnector(entry.key) ? (
1540
+ <span className="autox-card-mark is-brand">
1541
+ {brandForConnector(entry.key)}
1542
+ </span>
1543
+ ) : null}
1544
+ <span className="autox-menu-text">
1545
+ <span className="autox-menu-label">{entry.label}</span>
1546
+ <span className="autox-menu-detail">
1547
+ {entry.rows.length} action{entry.rows.length === 1 ? "" : "s"}
1548
+ </span>
1549
+ </span>
1550
+ </summary>
1551
+ {entry.rows.map((c) => actionRow(c))}
1552
+ </details>
1553
+ ) : actionRow(entry)}
1554
+ </Fragment>
1555
+ ))}
1556
+ {fieldAgentCatalog?.group === g.key
1557
+ && !g.rows.some((entry) => entry.kind === "voice_agent")
1558
+ ? fieldAgentChoice : null}
1559
  </div>
1560
  ))}
1561
+ </section>
1562
  ) : null}
1563
  </div>
1564
  </div>
 
1576
  >
1577
  <div className="auto-panel-head">
1578
  {panelTabs}
 
 
 
 
 
 
 
 
 
 
 
 
1579
  </div>
1580
 
1581
  {/*
 
1605
  picked={picked}
1606
  table={table}
1607
  tables={tables}
1608
+ voiceAgents={voiceAgents}
1609
  ops={ops}
1610
  nullaryOps={nullaryOps}
1611
  vocab={vocab}
 
1772
  picked: TriggerOption | null;
1773
  table: UserTable | null;
1774
  tables: UserTable[];
1775
+ voiceAgents?: VoiceAgent[];
1776
  ops: string[];
1777
  nullaryOps: string[];
1778
  vocab?: FlowVocab;
 
2990
  agentMark,
2991
  catalog,
2992
  tables,
2993
+ voiceAgents,
2994
  onTablesChanged,
2995
  walkFields,
2996
  walkTable,
 
3025
  agentMark?: { agent: string; agentName?: string; created?: string; by?: string } | null;
3026
  catalog: ActionCatalogRow[];
3027
  tables: UserTable[];
3028
+ voiceAgents?: VoiceAgent[];
3029
  /** ITEM 9 / R11 — re-read the list after this panel's picker creates one. REQUIRED; see Props. */
3030
  onTablesChanged: () => Promise<void> | void;
3031
  /**
 
3151
  />
3152
  ) : null}
3153
 
3154
+ {readOnly ? null : action.kind === "voice_agent" ? (
3155
+ <label className="auto-field">
3156
+ Voice agent
3157
+ <select value={String((cfg as { voiceAgentId?: string }).voiceAgentId || "")} onChange={(event) => setCfg({ voiceAgentId: event.target.value })}>
3158
+ <option value="">Choose a Voice agent</option>
3159
+ {(voiceAgents || []).map((agent) => <option key={agent.automationId} value={agent.automationId}>{agent.displayName}</option>)}
3160
+ </select>
3161
+ </label>
3162
+ ) : action.kind === "group" ? (
3163
  <>
3164
  {/*
3165
  ⭐ ONE CONDITION EDITOR PER BRANCH (C-FORK). The group's own `config.cond` is GONE —
web/src/automation/AutomationDetail.tsx CHANGED
@@ -56,6 +56,7 @@ import type {
56
  TriggerOption,
57
  UserTable,
58
  } from "./automationApi";
 
59
  import {
60
  AutomationError,
61
  COUNT_LABELS,
@@ -101,6 +102,11 @@ interface Props {
101
  triggers?: TriggerOption[];
102
  /** The ACTION MENU and the builder's ceilings (C4). Same rule: absent is a state, not a gap. */
103
  catalog?: ActionCatalogRow[];
 
 
 
 
 
104
  vocab?: FlowVocab;
105
  /**
106
  * Can a schedule fire here? `null` = the server did not say (C6 amendment #1 is not live
@@ -196,6 +202,9 @@ export default function AutomationDetail({
196
  discover,
197
  triggers,
198
  catalog,
 
 
 
199
  vocab,
200
  tick,
201
  liveStep,
@@ -462,7 +471,7 @@ export default function AutomationDetail({
462
  );
463
  const viewTabs = (
464
  <div className="autox-views" role="radiogroup" aria-label="Editor view">
465
- {([["canvas", "Canvas"], ["chat", "Chat"]] as const).map(([k, label]) => (
466
  <button
467
  key={k}
468
  type="button"
@@ -1554,15 +1563,29 @@ export default function AutomationDetail({
1554
  The guard is `runBlock`, not `automation.running`: `running` is process state and is
1555
  FALSE for the whole 20-30 minute vendor wait, which is precisely the window in which
1556
  a second paid search was measured being bought. */}
1557
- <button
1558
- type="button"
1559
- className="auto-btn"
1560
- disabled={runState.blocked}
1561
- title={runState.why || undefined}
1562
- onClick={() => void start()}
1563
- >
1564
- {runState.blocked ? runState.label : "Run now"}
1565
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1566
  <button
1567
  type="button"
1568
  className="auto-btn is-primary"
@@ -1746,19 +1769,15 @@ export default function AutomationDetail({
1746
  name={name}
1747
  // ⚠ NOT `edit(setName)` — the name has its own immediate write (`commitName`), so
1748
  // marking the whole FORM dirty for it would leave `touched` true forever after a
1749
- // name edit and make the panel's stamp say "unsaved changes" about something it had
1750
- // just saved. `touched` now means exactly "a field the header's Save owns has been
1751
- // edited", which is what the stamp below reports.
1752
  onNameText={setName}
1753
  onNameCommit={() => void commitName()}
1754
- // ⭐ THE PANEL'S STAMP MUST NOT LIE, and item 5 is what made this urgent. "All changes
1755
- // saved" was honest while Properties held only immediate-write controls; the machine
1756
- // steps' panels moved in this wave and THOSE commit with the header's Save (url,
1757
- // extract, the column map, the discovery filters). A stamp promising they are saved,
1758
- // above the fields that are not, is the same defect as an unsaved name under it.
1759
- dirty={touched}
1760
  {...(triggers ? { triggers } : {})}
1761
  catalog={catalog || []}
 
 
 
1762
  {...(vocab ? { vocab } : {})}
1763
  tables={tables}
1764
  /* ⭐ ITEM 9 / R11 — an action's Database picker can now MINT one, so the list has to
 
56
  TriggerOption,
57
  UserTable,
58
  } from "./automationApi";
59
+ import type { VoiceAgent } from "./voiceAgentTypes";
60
  import {
61
  AutomationError,
62
  COUNT_LABELS,
 
102
  triggers?: TriggerOption[];
103
  /** The ACTION MENU and the builder's ceilings (C4). Same rule: absent is a state, not a gap. */
104
  catalog?: ActionCatalogRow[];
105
+ /** Permission-filtered synthetic agents derived from AI fields by the server. */
106
+ fieldAgents: Automation[];
107
+ /** Select one of those existing agents in the shared Agents rail. */
108
+ onOpenFieldAgent: (id: string) => void;
109
+ voiceAgents?: VoiceAgent[];
110
  vocab?: FlowVocab;
111
  /**
112
  * Can a schedule fire here? `null` = the server did not say (C6 amendment #1 is not live
 
202
  discover,
203
  triggers,
204
  catalog,
205
+ fieldAgents,
206
+ onOpenFieldAgent,
207
+ voiceAgents,
208
  vocab,
209
  tick,
210
  liveStep,
 
471
  );
472
  const viewTabs = (
473
  <div className="autox-views" role="radiogroup" aria-label="Editor view">
474
+ {([["chat", "Chat"], ["canvas", "Canvas"]] as const).map(([k, label]) => (
475
  <button
476
  key={k}
477
  type="button"
 
1563
  The guard is `runBlock`, not `automation.running`: `running` is process state and is
1564
  FALSE for the whole 20-30 minute vendor wait, which is precisely the window in which
1565
  a second paid search was measured being bought. */}
1566
+ <span className="auto-run-control">
1567
+ <span
1568
+ className={"autox-saved auto-save-receipt"
1569
+ + (saving || triggerBusy ? " is-busy" : touched ? " is-dirty" : "")}
1570
+ role="status"
1571
+ aria-live="polite"
1572
+ >
1573
+ {saving || triggerBusy
1574
+ ? "Saving…"
1575
+ : touched
1576
+ ? "Unsaved changes. Press Save"
1577
+ : "All changes saved"}
1578
+ </span>
1579
+ <button
1580
+ type="button"
1581
+ className="auto-btn"
1582
+ disabled={runState.blocked}
1583
+ title={runState.why || undefined}
1584
+ onClick={() => void start()}
1585
+ >
1586
+ {runState.blocked ? runState.label : "Run now"}
1587
+ </button>
1588
+ </span>
1589
  <button
1590
  type="button"
1591
  className="auto-btn is-primary"
 
1769
  name={name}
1770
  // ⚠ NOT `edit(setName)` — the name has its own immediate write (`commitName`), so
1771
  // marking the whole FORM dirty for it would leave `touched` true forever after a
1772
+ // name edit and make the header receipt say "unsaved changes" about something it had
1773
+ // just saved. `touched` means exactly "a field the header's Save owns was edited".
 
1774
  onNameText={setName}
1775
  onNameCommit={() => void commitName()}
 
 
 
 
 
 
1776
  {...(triggers ? { triggers } : {})}
1777
  catalog={catalog || []}
1778
+ fieldAgents={fieldAgents}
1779
+ onOpenFieldAgent={onOpenFieldAgent}
1780
+ voiceAgents={voiceAgents}
1781
  {...(vocab ? { vocab } : {})}
1782
  tables={tables}
1783
  /* ⭐ ITEM 9 / R11 — an action's Database picker can now MINT one, so the list has to
web/src/automation/AutomationSurface.tsx CHANGED
@@ -31,11 +31,15 @@ import {
31
  AutomationError,
32
  cachedAutomations,
33
  createAutomation,
 
34
  listAutomations,
35
  liveStepOf,
36
  patchAutomation,
37
  rememberAutomation,
 
38
  } from "./automationApi";
 
 
39
 
40
  /**
41
  * ⭐⭐ WAVE 30 · T21 (owner items 4 + 5) — THE EDITOR STOPS SHIPPING INSIDE THE LIST.
@@ -60,6 +64,10 @@ import {
60
  */
61
  const AutomationDetail = lazy(() => import("./AutomationDetail"));
62
 
 
 
 
 
63
  /**
64
  * The run poll's cadence (item 6). Named constants because they are a MEASURED trade-off, not a
65
  * taste: `POLL_MAX_MS` is the longest a finished run can still look live, and it is the only
@@ -136,6 +144,12 @@ function railSubtitle(a: Automation): string {
136
  return "Manual only";
137
  }
138
 
 
 
 
 
 
 
139
  /*
140
  * ⛔ W23-W5's LISTENER IS AT MODULE SCOPE, AND THAT IS THE POINT — not a stylistic choice.
141
  *
@@ -220,8 +234,11 @@ export default function AutomationSurface() {
220
  every render instead, which is the same value at needless cost. A cold start still returns
221
  null and still gets the skeleton: it is made rare, not removed (see `automationApi.ts`). */
222
  const [data, setData] = useState<AutomationList | null>(() => cachedAutomations());
 
 
223
  const [error, setError] = useState("");
224
  const [activeId, setActiveId] = useState<string>("");
 
225
  const [railShut, setRailShut] = useState(false);
226
  const [busy, setBusy] = useState("");
227
  /**
@@ -253,6 +270,13 @@ export default function AutomationSurface() {
253
  const select = useCallback((id: string, _stage = "") => {
254
  wantedId.current = id;
255
  setActiveId(id);
 
 
 
 
 
 
 
256
  }, []);
257
 
258
  /**
@@ -335,6 +359,24 @@ export default function AutomationSurface() {
335
  return () => ac.abort();
336
  }, [load]);
337
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338
  /**
339
  * ⭐⭐ WAVE 24 / C-CREATE (a) — CREATE AND OPEN. This REPLACED the three-step wizard.
340
  *
@@ -480,7 +522,15 @@ export default function AutomationSurface() {
480
  }, [openRequest, data, select]);
481
 
482
  const items = data?.automations || [];
 
 
 
 
 
 
 
483
  const active = items.find((a) => a.id === activeId) || null;
 
484
 
485
  /**
486
  * ⭐⭐ WAVE 32 · T43 (owner item 2) — TURNING AN AUTOMATION ON OR OFF STOPS TAKING FOREVER.
@@ -640,6 +690,41 @@ export default function AutomationSurface() {
640
  </div>
641
  );
642
  })}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643
  {/* ONE LINE (R13). It used to describe the kinds — "one reads a public web page…
644
  the other fills an automation column…" — which was two sentences, wrong by the
645
  time a third kind shipped, and printed inside a `--lp-rail-w` column. What the
@@ -671,6 +756,11 @@ export default function AutomationSurface() {
671
  {error}
672
  </div>
673
  ) : null}
 
 
 
 
 
674
  {data && !data.storeAvailable ? (
675
  <div className="auto-banner is-warn" role="status">
676
  The tenant store is unavailable, so nothing can be saved right now.
@@ -694,7 +784,17 @@ export default function AutomationSurface() {
694
  */}
695
  {/* T21: the editor's own Suspense boundary — see the `lazy()` above for why it cannot be
696
  `Shell.tsx`'s. `fallback={null}`, matching `Lazily`. */}
697
- {active ? (
 
 
 
 
 
 
 
 
 
 
698
  <Suspense fallback={null}>
699
  <AutomationDetail
700
  key={active.id}
@@ -715,6 +815,9 @@ export default function AutomationSurface() {
715
  // `triggers` is: absent must stay absent, so the builder can tell "the server
716
  // offered nothing" from "the server offered an empty list".
717
  catalog={data?.actionsCatalog}
 
 
 
718
  vocab={data?.flow}
719
  // `?? null` and never `|| {enabled:false}`: an absent tick bit is "the server did
720
  // not say", which Step 1 prints as its own sentence. Defaulting it here would
 
31
  AutomationError,
32
  cachedAutomations,
33
  createAutomation,
34
+ listVoiceAgents,
35
  listAutomations,
36
  liveStepOf,
37
  patchAutomation,
38
  rememberAutomation,
39
+ replaceVoiceAgent,
40
  } from "./automationApi";
41
+ import type { VoiceAgent } from "./voiceAgentTypes";
42
+ import "../styles/wave44/voice-agent.css";
43
 
44
  /**
45
  * ⭐⭐ WAVE 30 · T21 (owner items 4 + 5) — THE EDITOR STOPS SHIPPING INSIDE THE LIST.
 
64
  */
65
  const AutomationDetail = lazy(() => import("./AutomationDetail"));
66
 
67
+ // Voice properties are selected-detail work, never rail work. Keep their harness and form code
68
+ // behind the same local boundary so the first Agents paint remains within the rail chunk budget.
69
+ const VoiceAgentProperties = lazy(() => import("./VoiceAgentProperties"));
70
+
71
  /**
72
  * The run poll's cadence (item 6). Named constants because they are a MEASURED trade-off, not a
73
  * taste: `POLL_MAX_MS` is the longest a finished run can still look live, and it is the only
 
144
  return "Manual only";
145
  }
146
 
147
+ function voiceStatusLabel(value: string): string {
148
+ return String(value || "not reported")
149
+ .replace(/[_-]+/g, " ")
150
+ .replace(/\b\w/g, (letter) => letter.toUpperCase());
151
+ }
152
+
153
  /*
154
  * ⛔ W23-W5's LISTENER IS AT MODULE SCOPE, AND THAT IS THE POINT — not a stylistic choice.
155
  *
 
234
  every render instead, which is the same value at needless cost. A cold start still returns
235
  null and still gets the skeleton: it is made rare, not removed (see `automationApi.ts`). */
236
  const [data, setData] = useState<AutomationList | null>(() => cachedAutomations());
237
+ const [voiceAgents, setVoiceAgents] = useState<VoiceAgent[]>([]);
238
+ const [voiceLoadError, setVoiceLoadError] = useState("");
239
  const [error, setError] = useState("");
240
  const [activeId, setActiveId] = useState<string>("");
241
+ const [activeVoiceId, setActiveVoiceId] = useState<string>("");
242
  const [railShut, setRailShut] = useState(false);
243
  const [busy, setBusy] = useState("");
244
  /**
 
270
  const select = useCallback((id: string, _stage = "") => {
271
  wantedId.current = id;
272
  setActiveId(id);
273
+ setActiveVoiceId("");
274
+ }, []);
275
+
276
+ const selectVoice = useCallback((id: string) => {
277
+ wantedId.current = "";
278
+ setActiveId("");
279
+ setActiveVoiceId(id);
280
  }, []);
281
 
282
  /**
 
359
  return () => ac.abort();
360
  }, [load]);
361
 
362
+ useEffect(() => {
363
+ const ac = new AbortController();
364
+ void listVoiceAgents(ac.signal)
365
+ .then((next) => {
366
+ setVoiceAgents(next?.voiceAgents || []);
367
+ setVoiceLoadError("");
368
+ })
369
+ .catch((reason) => {
370
+ if ((reason as Error)?.name === "AbortError") return;
371
+ setVoiceLoadError(
372
+ reason instanceof AutomationError
373
+ ? reason.message
374
+ : "Voice configuration could not be loaded."
375
+ );
376
+ });
377
+ return () => ac.abort();
378
+ }, []);
379
+
380
  /**
381
  * ⭐⭐ WAVE 24 / C-CREATE (a) — CREATE AND OPEN. This REPLACED the three-step wizard.
382
  *
 
522
  }, [openRequest, data, select]);
523
 
524
  const items = data?.automations || [];
525
+ /*
526
+ * W44 QA: AI field agents are derived from field definitions, so they cannot be added as
527
+ * ordinary flow actions. The list endpoint already composed and permission-filtered the safe
528
+ * choices as synthetic `field_agent` rows. Pass those rows down instead of inventing a second
529
+ * database/field picker or exposing their encoded ids as user input.
530
+ */
531
+ const fieldAgents = items.filter((agent) => agent.system === "field_agent");
532
  const active = items.find((a) => a.id === activeId) || null;
533
+ const activeVoice = voiceAgents.find((agent) => agent.automationId === activeVoiceId) || null;
534
 
535
  /**
536
  * ⭐⭐ WAVE 32 · T43 (owner item 2) — TURNING AN AUTOMATION ON OR OFF STOPS TAKING FOREVER.
 
690
  </div>
691
  );
692
  })}
693
+ {voiceAgents.map((agent) => {
694
+ const isActive = agent.lifecycle === "active";
695
+ return (
696
+ <div
697
+ key={agent.automationId}
698
+ className={"auto-row" + (agent.automationId === activeVoiceId ? " is-active" : "")}
699
+ >
700
+ <button
701
+ type="button"
702
+ className="auto-row-main"
703
+ onClick={() => selectVoice(agent.automationId)}
704
+ >
705
+ <span className="auto-loopmark">
706
+ <Mark size={15} />
707
+ </span>
708
+ <span className="auto-row-text">
709
+ <span className="auto-row-name">{agent.displayName}</span>
710
+ <span className="auto-row-desc">
711
+ Voice · {voiceStatusLabel(agent.connectionStatus)}
712
+ </span>
713
+ </span>
714
+ </button>
715
+ <button
716
+ type="button"
717
+ className={"auto-row-switch voice-agent-row-toggle" + (isActive ? " is-on" : "")}
718
+ disabled
719
+ aria-pressed={isActive}
720
+ aria-label={`${agent.displayName}: ${voiceStatusLabel(agent.lifecycle)}. Server controlled.`}
721
+ title="Voice activation is controlled on the server."
722
+ >
723
+ <span className="auto-row-switch-knob" />
724
+ </button>
725
+ </div>
726
+ );
727
+ })}
728
  {/* ONE LINE (R13). It used to describe the kinds — "one reads a public web page…
729
  the other fills an automation column…" — which was two sentences, wrong by the
730
  time a third kind shipped, and printed inside a `--lp-rail-w` column. What the
 
756
  {error}
757
  </div>
758
  ) : null}
759
+ {voiceLoadError ? (
760
+ <div className="auto-banner is-warn" role="status">
761
+ {voiceLoadError}
762
+ </div>
763
+ ) : null}
764
  {data && !data.storeAvailable ? (
765
  <div className="auto-banner is-warn" role="status">
766
  The tenant store is unavailable, so nothing can be saved right now.
 
784
  */}
785
  {/* T21: the editor's own Suspense boundary — see the `lazy()` above for why it cannot be
786
  `Shell.tsx`'s. `fallback={null}`, matching `Lazily`. */}
787
+ {activeVoice ? (
788
+ <Suspense fallback={null}>
789
+ <VoiceAgentProperties
790
+ key={activeVoice.automationId}
791
+ agent={activeVoice}
792
+ onSaved={(fresh) => {
793
+ setVoiceAgents((current) => replaceVoiceAgent(current, fresh));
794
+ }}
795
+ />
796
+ </Suspense>
797
+ ) : active ? (
798
  <Suspense fallback={null}>
799
  <AutomationDetail
800
  key={active.id}
 
815
  // `triggers` is: absent must stay absent, so the builder can tell "the server
816
  // offered nothing" from "the server offered an empty list".
817
  catalog={data?.actionsCatalog}
818
+ fieldAgents={fieldAgents}
819
+ onOpenFieldAgent={select}
820
+ voiceAgents={voiceAgents}
821
  vocab={data?.flow}
822
  // `?? null` and never `|| {enabled:false}`: an absent tick bit is "the server did
823
  // not say", which Step 1 prints as its own sentence. Defaulting it here would
web/src/automation/VoiceAgentProperties.tsx ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* oxlint-disable react/only-export-components -- pure helpers are executed by the UI contract tests. */
2
+ import { useState } from "react";
3
+
4
+ import {
5
+ AutomationError,
6
+ dryRunVoiceAgent,
7
+ patchVoiceAgent,
8
+ } from "./automationApi";
9
+ import type {
10
+ VoiceAgent,
11
+ VoiceAgentDraft,
12
+ VoiceAudienceOption,
13
+ VoiceHarnessInput,
14
+ VoiceHarnessResult,
15
+ } from "./voiceAgentTypes";
16
+
17
+ interface Props {
18
+ agent: VoiceAgent;
19
+ onSaved: (agent: VoiceAgent) => void;
20
+ }
21
+
22
+ type PersistVoiceAgent = (voiceId: string, draft: VoiceAgentDraft) => Promise<VoiceAgent>;
23
+
24
+ const READINESS_REASON_LABELS: Record<string, string> = {
25
+ connection: "Connection",
26
+ provider_connection: "Provider connection",
27
+ audience: "Audience",
28
+ knowledge_profile: "Knowledge profile",
29
+ inbound_binding: "Inbound binding",
30
+ activation_gate: "Activation gate",
31
+ };
32
+
33
+ function statusLabel(value: string): string {
34
+ return String(value || "not reported")
35
+ .replace(/[_-]+/g, " ")
36
+ .replace(/\b\w/g, (letter) => letter.toUpperCase());
37
+ }
38
+
39
+ function readinessReasonLabel(value: string): string {
40
+ return READINESS_REASON_LABELS[value] || "Additional setup";
41
+ }
42
+
43
+ export function voiceDraftFromAgent(agent: VoiceAgent): VoiceAgentDraft {
44
+ return {
45
+ portableConfig: { ...agent.portableConfig },
46
+ audience: { ...agent.audience },
47
+ };
48
+ }
49
+
50
+ export function voiceDraftWithTable(
51
+ draft: VoiceAgentDraft,
52
+ tableKey: string
53
+ ): VoiceAgentDraft {
54
+ return {
55
+ ...draft,
56
+ audience: {
57
+ ...draft.audience,
58
+ tableKey,
59
+ viewId: "",
60
+ viewRevision: "",
61
+ phoneFieldKey: "",
62
+ },
63
+ };
64
+ }
65
+
66
+ export function voiceDraftWithView(
67
+ draft: VoiceAgentDraft,
68
+ table: VoiceAudienceOption | undefined,
69
+ viewId: string
70
+ ): VoiceAgentDraft {
71
+ const view = table?.views.find((candidate) => candidate.id === viewId);
72
+ return {
73
+ ...draft,
74
+ audience: {
75
+ ...draft.audience,
76
+ viewId,
77
+ viewRevision: view?.revision || "",
78
+ phoneFieldKey: "",
79
+ },
80
+ };
81
+ }
82
+
83
+ /** Validate against the vocabulary that accompanied this exact DTO, never a client limit table. */
84
+ export function voiceDraftValidationIssue(
85
+ agent: VoiceAgent,
86
+ draft: VoiceAgentDraft
87
+ ): string {
88
+ const policyIsOffered = agent.audienceOptions.emptyPolicies.some(
89
+ (option) => option.key === draft.audience.emptyPolicy
90
+ );
91
+ if (!policyIsOffered) {
92
+ return "Choose an empty-value policy currently offered by the server.";
93
+ }
94
+ const ceiling = agent.audienceOptions.maxRecipientsCeiling;
95
+ const maximum = draft.audience.maxRecipients;
96
+ if (!Number.isInteger(maximum) || ceiling < 1 || maximum < 1 || maximum > ceiling) {
97
+ return ceiling > 0
98
+ ? `Maximum recipients must be between 1 and ${ceiling}.`
99
+ : "The recipient limit is not available from the server.";
100
+ }
101
+ return "";
102
+ }
103
+
104
+ /** One write, followed by adoption of the exact DTO returned by that write. */
105
+ export async function saveVoiceAgentDraft(
106
+ agent: VoiceAgent,
107
+ draft: VoiceAgentDraft,
108
+ onSaved: (fresh: VoiceAgent) => void,
109
+ persist: PersistVoiceAgent = patchVoiceAgent
110
+ ): Promise<VoiceAgent> {
111
+ const issue = voiceDraftValidationIssue(agent, draft);
112
+ if (issue) throw new AutomationError(issue, 400);
113
+ const next = await persist(agent.automationId, draft);
114
+ onSaved(next);
115
+ return next;
116
+ }
117
+
118
+ export default function VoiceAgentProperties({ agent, onSaved }: Props) {
119
+ const [draft, setDraft] = useState<VoiceAgentDraft>(() => voiceDraftFromAgent(agent));
120
+ const [input, setInput] = useState<VoiceHarnessInput>(() => ({
121
+ table: agent.audience.tableKey,
122
+ viewId: agent.audience.viewId,
123
+ phoneField: agent.audience.phoneFieldKey,
124
+ }));
125
+ const [result, setResult] = useState<VoiceHarnessResult | null>(null);
126
+ const [error, setError] = useState("");
127
+ const [saveError, setSaveError] = useState("");
128
+ const [saveReceipt, setSaveReceipt] = useState("");
129
+ const [checking, setChecking] = useState(false);
130
+ const [saving, setSaving] = useState(false);
131
+
132
+ const tables = agent.audienceOptions.tables;
133
+ const selectedTable = tables.find((table) => table.key === draft.audience.tableKey);
134
+ const views = selectedTable?.views || [];
135
+ const selectedView = views.find((view) => view.id === draft.audience.viewId);
136
+ const phoneFields = selectedTable?.phoneFields || [];
137
+ const harnessTable = tables.find((table) => table.key === input.table);
138
+ const harnessViews = harnessTable?.views || [];
139
+ const harnessView = harnessViews.find((view) => view.id === input.viewId);
140
+ const harnessPhoneFields = harnessTable?.phoneFields || [];
141
+ const canCheck = !!input.table.trim() && !!input.viewId.trim() && !!input.phoneField.trim();
142
+ const dirty = JSON.stringify(draft) !== JSON.stringify(voiceDraftFromAgent(agent));
143
+ const emptyPolicies = agent.audienceOptions.emptyPolicies;
144
+ const recipientCeiling = agent.audienceOptions.maxRecipientsCeiling;
145
+ const selectedPolicyIsOffered = emptyPolicies.some(
146
+ (option) => option.key === draft.audience.emptyPolicy
147
+ );
148
+ const validationIssue = voiceDraftValidationIssue(agent, draft);
149
+ const visibleSaveError = saveError || (dirty ? validationIssue : "");
150
+
151
+ const changeDraft = (next: VoiceAgentDraft) => {
152
+ setDraft(next);
153
+ setSaveError("");
154
+ setSaveReceipt("");
155
+ };
156
+
157
+ const saveConfiguration = async () => {
158
+ if (!dirty || validationIssue || saving) return;
159
+ setSaving(true);
160
+ setSaveError("");
161
+ setSaveReceipt("");
162
+ try {
163
+ const next = await saveVoiceAgentDraft(agent, draft, onSaved);
164
+ setDraft(voiceDraftFromAgent(next));
165
+ setInput({
166
+ table: next.audience.tableKey,
167
+ viewId: next.audience.viewId,
168
+ phoneField: next.audience.phoneFieldKey,
169
+ });
170
+ setSaveReceipt("Configuration saved");
171
+ } catch (reason) {
172
+ setSaveError(
173
+ reason instanceof AutomationError
174
+ ? reason.message
175
+ : "The Voice configuration could not be saved."
176
+ );
177
+ } finally {
178
+ setSaving(false);
179
+ }
180
+ };
181
+
182
+ const updateHarnessInput = (key: keyof VoiceHarnessInput, value: string) => {
183
+ setInput((current) => ({ ...current, [key]: value }));
184
+ setError("");
185
+ setResult(null);
186
+ };
187
+
188
+ const checkHarness = async () => {
189
+ if (!canCheck || checking) return;
190
+ setChecking(true);
191
+ setError("");
192
+ setResult(null);
193
+ try {
194
+ const next = await dryRunVoiceAgent(agent.automationId, {
195
+ table: input.table.trim(),
196
+ viewId: input.viewId.trim(),
197
+ phoneField: input.phoneField.trim(),
198
+ });
199
+ setResult(next);
200
+ } catch (reason) {
201
+ setError(
202
+ reason instanceof AutomationError
203
+ ? reason.message
204
+ : "The Voice harness could not validate this selection."
205
+ );
206
+ } finally {
207
+ setChecking(false);
208
+ }
209
+ };
210
+
211
+ return (
212
+ <section className="voice-agent-properties" aria-label={`${agent.displayName} properties`}>
213
+ <header className="voice-agent-heading">
214
+ <div>
215
+ <p className="voice-agent-eyebrow">Agent</p>
216
+ <h1>{agent.displayName}</h1>
217
+ </div>
218
+ <span
219
+ className={`voice-agent-status${agent.readiness.state === "configured" ? " is-ready" : ""}`}
220
+ title="Readiness"
221
+ >
222
+ {statusLabel(agent.readiness.state)}
223
+ </span>
224
+ </header>
225
+
226
+ <div className="voice-agent-grid">
227
+ <section className="voice-agent-section" aria-labelledby="voice-status-heading">
228
+ <h2 id="voice-status-heading">Status</h2>
229
+ <dl className="voice-agent-details">
230
+ <div>
231
+ <dt>Lifecycle</dt>
232
+ <dd>{statusLabel(agent.lifecycle)}</dd>
233
+ </div>
234
+ <div>
235
+ <dt>Readiness</dt>
236
+ <dd>{statusLabel(agent.readiness.state)}</dd>
237
+ </div>
238
+ <div>
239
+ <dt>Connection</dt>
240
+ <dd>{statusLabel(agent.connectionStatus)}</dd>
241
+ </div>
242
+ </dl>
243
+ {agent.readiness.reasons.length ? (
244
+ <ul className="voice-agent-reasons" aria-label="Readiness reasons">
245
+ {agent.readiness.reasons.map((reason) => (
246
+ <li key={reason}>{readinessReasonLabel(reason)}</li>
247
+ ))}
248
+ </ul>
249
+ ) : (
250
+ <p className="voice-agent-note">No readiness issues reported.</p>
251
+ )}
252
+ <button type="button" className="voice-agent-disabled-control" disabled>
253
+ Voice runs unavailable
254
+ </button>
255
+ <p className="voice-agent-note">
256
+ Voice stays inactive until Loopable explicitly activates it.
257
+ </p>
258
+ </section>
259
+
260
+ <section className="voice-agent-section" aria-labelledby="voice-knowledge-heading">
261
+ <h2 id="voice-knowledge-heading">Knowledge</h2>
262
+ {agent.knowledgeProfile ? (
263
+ <dl className="voice-agent-details">
264
+ <div>
265
+ <dt>Approval</dt>
266
+ <dd>{statusLabel(agent.knowledgeProfile.approvalState)}</dd>
267
+ </div>
268
+ <div>
269
+ <dt>Version</dt>
270
+ <dd>{agent.knowledgeProfile.version || "Not set"}</dd>
271
+ </div>
272
+ <div>
273
+ <dt>Classification</dt>
274
+ <dd>{agent.knowledgeProfile.classification || "Not set"}</dd>
275
+ </div>
276
+ </dl>
277
+ ) : (
278
+ <p className="voice-agent-note">No knowledge profile is assigned.</p>
279
+ )}
280
+ </section>
281
+ </div>
282
+
283
+ <section className="voice-agent-section" aria-labelledby="voice-config-heading">
284
+ <div className="voice-agent-section-head">
285
+ <h2 id="voice-config-heading">Configuration</h2>
286
+ <span className="voice-agent-section-state">Draft settings</span>
287
+ </div>
288
+ <div className="voice-agent-config-fields">
289
+ <label className="voice-agent-field is-wide" htmlFor="voice-purpose">
290
+ Purpose
291
+ <textarea
292
+ id="voice-purpose"
293
+ value={draft.portableConfig.purpose}
294
+ onChange={(event) => changeDraft({
295
+ ...draft,
296
+ portableConfig: { ...draft.portableConfig, purpose: event.target.value },
297
+ })}
298
+ maxLength={500}
299
+ />
300
+ </label>
301
+ <label className="voice-agent-field is-wide" htmlFor="voice-callback-policy">
302
+ Callback policy
303
+ <input
304
+ id="voice-callback-policy"
305
+ value={draft.portableConfig.callbackPolicy}
306
+ onChange={(event) => changeDraft({
307
+ ...draft,
308
+ portableConfig: { ...draft.portableConfig, callbackPolicy: event.target.value },
309
+ })}
310
+ maxLength={240}
311
+ />
312
+ </label>
313
+ <label className="voice-agent-field" htmlFor="voice-audience-table">
314
+ Database
315
+ <select
316
+ id="voice-audience-table"
317
+ value={draft.audience.tableKey}
318
+ onChange={(event) => changeDraft(voiceDraftWithTable(draft, event.target.value))}
319
+ >
320
+ <option value="">Choose a database</option>
321
+ {tables.map((table) => (
322
+ <option key={table.key} value={table.key}>{table.label}</option>
323
+ ))}
324
+ </select>
325
+ </label>
326
+ <label className="voice-agent-field" htmlFor="voice-audience-view">
327
+ Saved View
328
+ <select
329
+ id="voice-audience-view"
330
+ value={draft.audience.viewId}
331
+ onChange={(event) => changeDraft(
332
+ voiceDraftWithView(draft, selectedTable, event.target.value)
333
+ )}
334
+ disabled={!selectedTable}
335
+ >
336
+ <option value="">Choose a View</option>
337
+ {views.map((view) => (
338
+ <option key={view.id} value={view.id}>{view.label}</option>
339
+ ))}
340
+ </select>
341
+ </label>
342
+ <label className="voice-agent-field" htmlFor="voice-audience-phone">
343
+ Phone field
344
+ <select
345
+ id="voice-audience-phone"
346
+ value={draft.audience.phoneFieldKey}
347
+ onChange={(event) => changeDraft({
348
+ ...draft,
349
+ audience: { ...draft.audience, phoneFieldKey: event.target.value },
350
+ })}
351
+ disabled={!selectedView}
352
+ >
353
+ <option value="">Choose a phone field</option>
354
+ {phoneFields.map((field) => (
355
+ <option key={field.key} value={field.key}>{field.label}</option>
356
+ ))}
357
+ </select>
358
+ </label>
359
+ <label className="voice-agent-field" htmlFor="voice-empty-policy">
360
+ Empty phone values
361
+ <select
362
+ id="voice-empty-policy"
363
+ value={draft.audience.emptyPolicy}
364
+ onChange={(event) => changeDraft({
365
+ ...draft,
366
+ audience: {
367
+ ...draft.audience,
368
+ emptyPolicy: event.target.value === "refuse" ? "refuse" : "skip",
369
+ },
370
+ })}
371
+ disabled={!emptyPolicies.length}
372
+ >
373
+ {!selectedPolicyIsOffered ? (
374
+ <option value={draft.audience.emptyPolicy} disabled>
375
+ Current policy is unavailable
376
+ </option>
377
+ ) : null}
378
+ {emptyPolicies.map((option) => (
379
+ <option key={option.key} value={option.key}>{option.label}</option>
380
+ ))}
381
+ </select>
382
+ </label>
383
+ <label className="voice-agent-field" htmlFor="voice-max-recipients">
384
+ Maximum recipients
385
+ <input
386
+ id="voice-max-recipients"
387
+ type="number"
388
+ min={1}
389
+ max={recipientCeiling || undefined}
390
+ step={1}
391
+ value={draft.audience.maxRecipients}
392
+ onChange={(event) => changeDraft({
393
+ ...draft,
394
+ audience: {
395
+ ...draft.audience,
396
+ maxRecipients: Number(event.target.value),
397
+ },
398
+ })}
399
+ disabled={recipientCeiling < 1}
400
+ aria-describedby="voice-max-recipients-range"
401
+ />
402
+ <span id="voice-max-recipients-range" className="voice-agent-field-note">
403
+ {recipientCeiling > 0
404
+ ? `Allowed range: 1 to ${recipientCeiling}`
405
+ : "Recipient limit unavailable"}
406
+ </span>
407
+ </label>
408
+ <div className="voice-agent-field voice-agent-revision">
409
+ <span>Saved revision</span>
410
+ <output id="voice-view-revision">{draft.audience.viewRevision || "Not set"}</output>
411
+ </div>
412
+ </div>
413
+ <div className="voice-agent-save-row">
414
+ <button
415
+ type="button"
416
+ className="voice-agent-save"
417
+ disabled={!dirty || !!validationIssue || saving}
418
+ onClick={() => void saveConfiguration()}
419
+ >
420
+ {saving ? "Saving…" : "Save configuration"}
421
+ </button>
422
+ <span
423
+ className={`voice-agent-save-state${visibleSaveError ? " is-error" : saveReceipt ? " is-saved" : ""}`}
424
+ role={visibleSaveError ? "alert" : "status"}
425
+ >
426
+ {visibleSaveError || saveReceipt}
427
+ </span>
428
+ </div>
429
+ </section>
430
+
431
+ <section className="voice-agent-section" aria-labelledby="voice-bindings-heading">
432
+ <h2 id="voice-bindings-heading">Phone binding</h2>
433
+ {agent.phoneBinding ? (
434
+ <dl className="voice-agent-details">
435
+ <div>
436
+ <dt>Number</dt>
437
+ <dd className="voice-agent-number">{agent.phoneBinding.maskedDisplay}</dd>
438
+ </div>
439
+ <div>
440
+ <dt>Inbound</dt>
441
+ <dd>{agent.phoneBinding.routeStatus === "active" ? "Active inbound" : "Inactive"}</dd>
442
+ </div>
443
+ <div>
444
+ <dt>Number state</dt>
445
+ <dd>{statusLabel(agent.phoneBinding.numberStatus)}</dd>
446
+ </div>
447
+ </dl>
448
+ ) : (
449
+ <p className="voice-agent-note">No phone binding is available.</p>
450
+ )}
451
+ {agent.capabilities.numberProvisioning === "contact_loopable" ? (
452
+ <p className="voice-agent-contact">
453
+ Phone setup: <strong>Contact Loopable</strong>
454
+ </p>
455
+ ) : null}
456
+ </section>
457
+
458
+ <section className="voice-agent-section" aria-labelledby="voice-harness-heading">
459
+ <div className="voice-agent-section-head">
460
+ <div>
461
+ <h2 id="voice-harness-heading">Test harness</h2>
462
+ <p className="voice-agent-note">
463
+ Validate a saved View and phone-type field without external dispatch.
464
+ </p>
465
+ </div>
466
+ <span className="voice-agent-harness-state">No external dispatch</span>
467
+ </div>
468
+ <div className="voice-agent-harness-fields">
469
+ <label>
470
+ Database
471
+ <select
472
+ value={input.table}
473
+ onChange={(event) => {
474
+ setInput({ table: event.target.value, viewId: "", phoneField: "" });
475
+ setError("");
476
+ setResult(null);
477
+ }}
478
+ aria-label="Voice harness database"
479
+ >
480
+ <option value="">Choose a database</option>
481
+ {tables.map((table) => (
482
+ <option key={table.key} value={table.key}>{table.label}</option>
483
+ ))}
484
+ </select>
485
+ </label>
486
+ <label>
487
+ Saved View
488
+ <select
489
+ value={input.viewId}
490
+ onChange={(event) => {
491
+ setInput((current) => ({
492
+ ...current,
493
+ viewId: event.target.value,
494
+ phoneField: "",
495
+ }));
496
+ setError("");
497
+ setResult(null);
498
+ }}
499
+ aria-label="Voice harness saved View"
500
+ disabled={!harnessTable}
501
+ >
502
+ <option value="">Choose a View</option>
503
+ {harnessViews.map((view) => (
504
+ <option key={view.id} value={view.id}>{view.label}</option>
505
+ ))}
506
+ </select>
507
+ </label>
508
+ <label>
509
+ Phone field
510
+ <select
511
+ value={input.phoneField}
512
+ onChange={(event) => updateHarnessInput("phoneField", event.target.value)}
513
+ aria-label="Voice harness phone field"
514
+ disabled={!harnessView}
515
+ >
516
+ <option value="">Choose a phone field</option>
517
+ {harnessPhoneFields.map((field) => (
518
+ <option key={field.key} value={field.key}>{field.label}</option>
519
+ ))}
520
+ </select>
521
+ </label>
522
+ </div>
523
+ <button
524
+ type="button"
525
+ className="voice-agent-harness-submit"
526
+ disabled={!canCheck || checking || !agent.capabilities.dryRun}
527
+ onClick={() => void checkHarness()}
528
+ >
529
+ {checking ? "Checking…" : "Validate dry run"}
530
+ </button>
531
+ {error ? <p className="voice-agent-result is-error" role="alert">{error}</p> : null}
532
+ {result ? (
533
+ <p className="voice-agent-result" role="status">
534
+ {result.noExternalDispatch
535
+ ? "Dry run complete. No external dispatch occurred."
536
+ : "The server did not confirm the no-external-dispatch safety check."}
537
+ </p>
538
+ ) : null}
539
+ </section>
540
+ </section>
541
+ );
542
+ }
web/src/automation/automationApi.ts CHANGED
@@ -22,6 +22,17 @@ import {
22
  checkTenant,
23
  signal,
24
  } from "../apiContract";
 
 
 
 
 
 
 
 
 
 
 
25
 
26
  /**
27
  * ⭐ WAVE 24 / R6 — `plain` IS A REAL KIND, and it is the default for every new automation.
@@ -1011,6 +1022,223 @@ export function listAutomations(abort?: AbortSignal): Promise<AutomationList> {
1011
  });
1012
  }
1013
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1014
  /**
1015
  * ⭐⭐ WAVE 31 · T31 — fold ONE freshly-written automation into the memo, and hand back the list.
1016
  *
 
22
  checkTenant,
23
  signal,
24
  } from "../apiContract";
25
+ import type {
26
+ VoiceAgent,
27
+ VoiceAgentDraft,
28
+ VoiceAgentList,
29
+ VoiceAgentPatchInput,
30
+ VoiceAudience,
31
+ VoiceAudienceOptions,
32
+ VoiceEmptyPolicyOption,
33
+ VoiceHarnessInput,
34
+ VoiceHarnessResult,
35
+ } from "./voiceAgentTypes";
36
 
37
  /**
38
  * ⭐ WAVE 24 / R6 — `plain` IS A REAL KIND, and it is the default for every new automation.
 
1022
  });
1023
  }
1024
 
1025
+ /**
1026
+ * The Voice control plane has its own narrow browser contract. It is deliberately not folded
1027
+ * into `/automations`: ordinary Agents and Voice Agent configuration have different safety doors.
1028
+ */
1029
+ function voiceRecord(value: unknown): Record<string, unknown> {
1030
+ return value && typeof value === "object" && !Array.isArray(value)
1031
+ ? (value as Record<string, unknown>)
1032
+ : {};
1033
+ }
1034
+
1035
+ function voiceText(value: unknown, limit = 500): string {
1036
+ if (typeof value !== "string" && typeof value !== "number") return "";
1037
+ return String(value).trim().slice(0, limit);
1038
+ }
1039
+
1040
+ function voiceWhole(value: unknown, fallback: number): number {
1041
+ const parsed = typeof value === "number" ? value : Number(value);
1042
+ return Number.isFinite(parsed) ? Math.trunc(parsed) : fallback;
1043
+ }
1044
+
1045
+ function voiceMaskedDisplay(value: unknown): string {
1046
+ const display = voiceText(value, 80);
1047
+ const digitCount = (display.match(/\d/g) || []).length;
1048
+ // Treat masking as a phone-shaped grammar, not as the presence of a masking character.
1049
+ // In particular, a lone `x` is common extension notation and must never make raw digits safe.
1050
+ const starOrBulletMask = /^(?:\+\d{1,3}[\s.-]?)?(?:\([*\u2022]{2,4}\)|[*\u2022]{2,4})[\s.-]+[*\u2022]{2,4}[\s.-]+\d{2,6}$/u;
1051
+ const xMask = /^(?:\+\d{1,3}[\s.-]?)?(?:\([xX]{2,4}\)|[xX]{2,4})[\s.-]+[xX]{2,4}[\s.-]+\d{2,6}$/;
1052
+ return digitCount <= 6 && (starOrBulletMask.test(display) || xMask.test(display)) ? display : "";
1053
+ }
1054
+
1055
+ function voiceAudience(value: unknown): VoiceAudience {
1056
+ const row = voiceRecord(value);
1057
+ return {
1058
+ tableKey: voiceText(row.tableKey, 120),
1059
+ viewId: voiceText(row.viewId, 120),
1060
+ viewRevision: voiceText(row.viewRevision, 120),
1061
+ phoneFieldKey: voiceText(row.phoneFieldKey, 120),
1062
+ emptyPolicy: row.emptyPolicy === "refuse" ? "refuse" : "skip",
1063
+ maxRecipients: voiceWhole(row.maxRecipients, 100),
1064
+ };
1065
+ }
1066
+
1067
+ function voiceAudienceOptions(value: unknown): VoiceAudienceOptions {
1068
+ const options = voiceRecord(value);
1069
+ const rawTables = options.tables;
1070
+ const tables = (Array.isArray(rawTables) ? rawTables : []).flatMap((candidate) => {
1071
+ const row = voiceRecord(candidate);
1072
+ const key = voiceText(row.key, 120);
1073
+ if (!key) return [];
1074
+ const rawViews = Array.isArray(row.views) ? row.views : [];
1075
+ const rawFields = Array.isArray(row.phoneFields) ? row.phoneFields : [];
1076
+ const views = rawViews.flatMap((item) => {
1077
+ const view = voiceRecord(item);
1078
+ const id = voiceText(view.id, 120);
1079
+ return id ? [{
1080
+ id,
1081
+ label: voiceText(view.label, 160) || id,
1082
+ revision: voiceText(view.revision, 120),
1083
+ }] : [];
1084
+ });
1085
+ const phoneFields = rawFields.flatMap((item) => {
1086
+ const field = voiceRecord(item);
1087
+ const fieldKey = voiceText(field.key, 120);
1088
+ return fieldKey ? [{
1089
+ key: fieldKey,
1090
+ label: voiceText(field.label, 160) || fieldKey,
1091
+ }] : [];
1092
+ });
1093
+ return [{ key, label: voiceText(row.label, 160) || key, views, phoneFields }];
1094
+ });
1095
+ const seenPolicies = new Set<string>();
1096
+ const rawPolicies = Array.isArray(options.emptyPolicies) ? options.emptyPolicies : [];
1097
+ const emptyPolicies = rawPolicies.flatMap((candidate) => {
1098
+ const row = voiceRecord(candidate);
1099
+ const key = row.key === "skip" || row.key === "refuse" ? row.key : "";
1100
+ const label = voiceText(row.label, 160);
1101
+ if (!key || !label || seenPolicies.has(key)) return [];
1102
+ seenPolicies.add(key);
1103
+ return [{ key, label } as VoiceEmptyPolicyOption];
1104
+ });
1105
+ const parsedCeiling = voiceWhole(options.maxRecipientsCeiling, 0);
1106
+ return {
1107
+ tables,
1108
+ emptyPolicies,
1109
+ maxRecipientsCeiling: parsedCeiling > 0 ? parsedCeiling : 0,
1110
+ };
1111
+ }
1112
+
1113
+ /**
1114
+ * Reduce the server response to the browser's explicit allow-list before React state sees it.
1115
+ * The route may carry server-only compatibility fields; spreading that object here would make a
1116
+ * later JSX autocomplete capable of rendering provider identities or opaque references.
1117
+ */
1118
+ export function parseVoiceAgent(value: unknown): VoiceAgent | null {
1119
+ const row = voiceRecord(value);
1120
+ const automationId = voiceText(row.automationId, 120);
1121
+ const displayName = voiceText(row.displayName, 120);
1122
+ if (!automationId || !displayName || row.agentType !== "voice") return null;
1123
+
1124
+ const readiness = voiceRecord(row.readiness);
1125
+ const reasons = (Array.isArray(readiness.reasons) ? readiness.reasons : [])
1126
+ .map((reason) => voiceText(reason, 120))
1127
+ .filter(Boolean);
1128
+ const portable = voiceRecord(row.portableConfig);
1129
+ const knowledge = voiceRecord(row.knowledgeProfile);
1130
+ const hasKnowledge = Object.keys(knowledge).length > 0;
1131
+ const binding = voiceRecord(row.phoneBinding);
1132
+ const maskedDisplay = voiceMaskedDisplay(binding.maskedDisplay);
1133
+ const hasBinding = Object.keys(binding).length > 0 && !!maskedDisplay;
1134
+ const capabilities = voiceRecord(row.capabilities);
1135
+
1136
+ const safeAgent: VoiceAgent = {
1137
+ automationId,
1138
+ displayName,
1139
+ agentType: "voice",
1140
+ connectionStatus: voiceText(row.connectionStatus, 80) || "unconfigured",
1141
+ lifecycle: voiceText(row.lifecycle, 80) || "draft",
1142
+ readiness: {
1143
+ state: voiceText(readiness.state, 80) || "needs_attention",
1144
+ reasons,
1145
+ },
1146
+ portableConfig: {
1147
+ purpose: voiceText(portable.purpose, 500),
1148
+ callbackPolicy: voiceText(portable.callbackPolicy, 240),
1149
+ },
1150
+ knowledgeProfile: hasKnowledge ? {
1151
+ version: voiceText(knowledge.version, 80),
1152
+ classification: voiceText(knowledge.classification, 80),
1153
+ approvalState: voiceText(knowledge.approvalState, 80) || "draft",
1154
+ } : null,
1155
+ phoneBinding: hasBinding ? {
1156
+ maskedDisplay,
1157
+ numberStatus: voiceText(binding.numberStatus, 80) || "unconfigured",
1158
+ routeStatus: voiceText(binding.routeStatus, 80) || "inactive",
1159
+ } : null,
1160
+ audience: voiceAudience(row.audience),
1161
+ capabilities: {
1162
+ dryRun: capabilities.dryRun === true,
1163
+ ...(capabilities.numberProvisioning === "contact_loopable"
1164
+ ? { numberProvisioning: "contact_loopable" as const }
1165
+ : {}),
1166
+ },
1167
+ audienceOptions: voiceAudienceOptions(row.audienceOptions),
1168
+ };
1169
+ return safeAgent;
1170
+ }
1171
+
1172
+ export function parseVoiceAgentList(value: unknown): VoiceAgentList {
1173
+ const rows = voiceRecord(value).voiceAgents;
1174
+ return {
1175
+ voiceAgents: (Array.isArray(rows) ? rows : [])
1176
+ .map(parseVoiceAgent)
1177
+ .filter((row): row is VoiceAgent => row !== null),
1178
+ };
1179
+ }
1180
+
1181
+ export function listVoiceAgents(abort?: AbortSignal): Promise<VoiceAgentList> {
1182
+ return send<unknown>("/voice-agents", { signal: abort }).then(parseVoiceAgentList);
1183
+ }
1184
+
1185
+ /** Build the complete PATCH body field-by-field. No server DTO or caller extras may hitch a ride. */
1186
+ export function buildVoiceAgentPatch(draft: VoiceAgentDraft): VoiceAgentPatchInput {
1187
+ return {
1188
+ portableConfig: {
1189
+ purpose: voiceText(draft.portableConfig.purpose, 500),
1190
+ callbackPolicy: voiceText(draft.portableConfig.callbackPolicy, 240),
1191
+ },
1192
+ audience: {
1193
+ tableKey: voiceText(draft.audience.tableKey, 120),
1194
+ viewId: voiceText(draft.audience.viewId, 120),
1195
+ viewRevision: voiceText(draft.audience.viewRevision, 120),
1196
+ phoneFieldKey: voiceText(draft.audience.phoneFieldKey, 120),
1197
+ emptyPolicy: draft.audience.emptyPolicy === "refuse" ? "refuse" : "skip",
1198
+ maxRecipients: voiceWhole(draft.audience.maxRecipients, 0),
1199
+ },
1200
+ };
1201
+ }
1202
+
1203
+ export function patchVoiceAgent(
1204
+ voiceId: string,
1205
+ draft: VoiceAgentDraft
1206
+ ): Promise<VoiceAgent> {
1207
+ return send<unknown>(`/voice-agents/${encodeURIComponent(voiceId)}`, {
1208
+ method: "PATCH",
1209
+ body: JSON.stringify(buildVoiceAgentPatch(draft)),
1210
+ }).then((payload) => {
1211
+ const next = parseVoiceAgent(voiceRecord(payload).voiceAgent);
1212
+ if (!next) throw new AutomationError("The server returned an invalid Voice agent.", 502);
1213
+ return next;
1214
+ });
1215
+ }
1216
+
1217
+ /** Adopt the exact PATCH receipt; a follow-up list read can only be older than that write. */
1218
+ export function replaceVoiceAgent(current: VoiceAgent[], fresh: VoiceAgent): VoiceAgent[] {
1219
+ let found = false;
1220
+ const next = current.map((agent) => {
1221
+ if (agent.automationId !== fresh.automationId) return agent;
1222
+ found = true;
1223
+ return fresh;
1224
+ });
1225
+ return found ? next : [...next, fresh];
1226
+ }
1227
+
1228
+ /**
1229
+ * Validates only the server-authorized saved View and phone-type field. It cannot dispatch or
1230
+ * mutate provider state; the server returns an explicit no-external-dispatch receipt.
1231
+ */
1232
+ export function dryRunVoiceAgent(
1233
+ voiceId: string,
1234
+ input: VoiceHarnessInput
1235
+ ): Promise<VoiceHarnessResult> {
1236
+ return send<VoiceHarnessResult>(
1237
+ `/voice-agents/${encodeURIComponent(voiceId)}/harness/dry-run`,
1238
+ { method: "POST", body: JSON.stringify(input) }
1239
+ );
1240
+ }
1241
+
1242
  /**
1243
  * ⭐⭐ WAVE 31 · T31 — fold ONE freshly-written automation into the memo, and hand back the list.
1244
  *
web/src/automation/voiceAgentTypes.ts ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Browser-safe Voice control-plane shapes. Provider identifiers, provider extensions,
2
+ // credentials, knowledge identifiers, SIP/routing material, and raw phone values deliberately
3
+ // have no representation in this client module.
4
+
5
+ export type VoiceEmptyPolicy = "skip" | "refuse";
6
+
7
+ export interface VoicePortableConfig {
8
+ purpose: string;
9
+ callbackPolicy: string;
10
+ }
11
+
12
+ export interface VoiceReadiness {
13
+ state: string;
14
+ reasons: string[];
15
+ }
16
+
17
+ export interface VoiceKnowledgeProfile {
18
+ version: string;
19
+ classification: string;
20
+ approvalState: string;
21
+ }
22
+
23
+ export interface VoicePhoneBinding {
24
+ maskedDisplay: string;
25
+ numberStatus: string;
26
+ routeStatus: string;
27
+ }
28
+
29
+ export interface VoiceAudience {
30
+ tableKey: string;
31
+ viewId: string;
32
+ viewRevision: string;
33
+ phoneFieldKey: string;
34
+ emptyPolicy: VoiceEmptyPolicy;
35
+ maxRecipients: number;
36
+ }
37
+
38
+ export interface VoiceCapabilities {
39
+ dryRun: boolean;
40
+ numberProvisioning?: "contact_loopable";
41
+ }
42
+
43
+ export interface VoiceAudienceOption {
44
+ key: string;
45
+ label: string;
46
+ views: { id: string; label: string; revision: string }[];
47
+ phoneFields: { key: string; label: string }[];
48
+ }
49
+
50
+ export interface VoiceEmptyPolicyOption {
51
+ key: VoiceEmptyPolicy;
52
+ label: string;
53
+ }
54
+
55
+ export interface VoiceAudienceOptions {
56
+ tables: VoiceAudienceOption[];
57
+ emptyPolicies: VoiceEmptyPolicyOption[];
58
+ maxRecipientsCeiling: number;
59
+ }
60
+
61
+ export interface VoiceAgent {
62
+ automationId: string;
63
+ displayName: string;
64
+ agentType: "voice";
65
+ connectionStatus: string;
66
+ lifecycle: string;
67
+ readiness: VoiceReadiness;
68
+ portableConfig: VoicePortableConfig;
69
+ knowledgeProfile: VoiceKnowledgeProfile | null;
70
+ phoneBinding: VoicePhoneBinding | null;
71
+ audience: VoiceAudience;
72
+ capabilities: VoiceCapabilities;
73
+ /** Server-composed choices; the browser never invents identifiers, policies, or limits. */
74
+ audienceOptions: VoiceAudienceOptions;
75
+ }
76
+
77
+ export interface VoiceAgentList {
78
+ voiceAgents: VoiceAgent[];
79
+ }
80
+
81
+ /** The complete browser PATCH allow-list. Never construct this by spreading a server DTO. */
82
+ export interface VoiceAgentDraft {
83
+ portableConfig: VoicePortableConfig;
84
+ audience: VoiceAudience;
85
+ }
86
+
87
+ export type VoiceAgentPatchInput = VoiceAgentDraft;
88
+
89
+ export interface VoiceHarnessInput {
90
+ table: string;
91
+ viewId: string;
92
+ phoneField: string;
93
+ }
94
+
95
+ export interface VoiceHarnessResult {
96
+ noExternalDispatch: boolean;
97
+ preview?: {
98
+ displayName?: string;
99
+ maskedBindingCount?: number;
100
+ };
101
+ }
web/src/customer-grid/CatalogView.tsx CHANGED
@@ -31,6 +31,7 @@
31
 
32
  import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
33
  import { createPortal } from "react-dom";
 
34
  import {
35
  CATALOG_COLS,
36
  CATALOG_NAME_MAX,
@@ -1034,7 +1035,7 @@ export const CatalogView = memo(function CatalogView({
1034
  // ----------------------------------------------------------------- paint
1035
  if (!catalogs.length)
1036
  return (
1037
- <div className="cg-cat cg-cat-blank">
1038
  <div className="cg-cat-blank-in">
1039
  <CrownMark className="cg-cat-blank-mark" />
1040
  <h3>No catalogs yet</h3>
@@ -1053,7 +1054,7 @@ export const CatalogView = memo(function CatalogView({
1053
  const used = cat ? codesUsed(cat) : 0;
1054
 
1055
  return (
1056
- <div className="cg-cat">
1057
  {/* ------------------------------------------------------------ rail */}
1058
  <aside className="cg-cat-rail">
1059
  <div className="cg-cat-rail-head">
 
31
 
32
  import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
33
  import { createPortal } from "react-dom";
34
+ import { foldNavOnWorkSurface } from "./navFold";
35
  import {
36
  CATALOG_COLS,
37
  CATALOG_NAME_MAX,
 
1035
  // ----------------------------------------------------------------- paint
1036
  if (!catalogs.length)
1037
  return (
1038
+ <div className="cg-cat cg-cat-blank" onPointerDown={foldNavOnWorkSurface}>
1039
  <div className="cg-cat-blank-in">
1040
  <CrownMark className="cg-cat-blank-mark" />
1041
  <h3>No catalogs yet</h3>
 
1054
  const used = cat ? codesUsed(cat) : 0;
1055
 
1056
  return (
1057
+ <div className="cg-cat" onPointerDown={foldNavOnWorkSurface}>
1058
  {/* ------------------------------------------------------------ rail */}
1059
  <aside className="cg-cat-rail">
1060
  <div className="cg-cat-rail-head">
web/src/customer-grid/ColumnMenu.tsx CHANGED
@@ -18,14 +18,17 @@ 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, 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.
@@ -53,6 +56,7 @@ import { AGG_LABELS, aggOptions } from "./aggregations";
53
  import { validateFormula } from "./formulaEngine";
54
  import { BRAND_SWATCHES, defaultOptionColor, nearestSwatch, normalizeOptionColor,
55
  OPTION_PALETTE } from "./choiceColors";
 
56
 
57
  export interface ColumnMenuState {
58
  fieldKey: string;
@@ -100,7 +104,14 @@ interface FieldConfigExtra {
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; selectionMode?: "manual" | "automatic" };
 
 
 
 
 
 
 
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,6 +173,8 @@ interface ColumnMenuProps {
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;
@@ -294,6 +307,10 @@ interface ColumnMenuProps {
294
  * the control is not rendered at all, so a base field cannot even be offered the action.
295
  */
296
  onDelete?: () => void;
 
 
 
 
297
  /**
298
  * ⭐⭐ W41-T29 (R6(b)) — DROP A COLUMN SOMEBODY ELSE SHARED WITH ME, off my own list. A
299
  * DIFFERENT ACT from `onDelete`, and therefore a different door: it destroys no definition and
@@ -303,7 +320,7 @@ interface ColumnMenuProps {
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
@@ -321,10 +338,10 @@ interface ColumnMenuProps {
321
  onAggregate?: (agg: AggName | undefined) => void;
322
  /** Wave-5 item 1 — Sort by this field (replaces the view's sort), and the conditional
323
  * clears (item 3). All of these mutate the EXISTING view config — no new host surface. */
324
- onSort: (dir: "asc" | "desc") => void;
325
- onClearSort: () => void;
326
- onFilterBy: () => void;
327
- onClearFilter: () => void;
328
  onGroupByField: () => void;
329
  onClearGroup: () => void;
330
  /** Assignable people, from the host's real user list. Empty = the host did not supply one,
@@ -682,12 +699,14 @@ function optionDrafts(
682
 
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,7 +722,7 @@ function optionSettings(
703
  if (color && color !== normalizeOptionColor(defaultOptionColor(option)))
704
  colors[option] = color;
705
  }
706
- return { options, colors };
707
  }
708
 
709
  function optionAppearanceSignature(
@@ -815,6 +834,7 @@ function OptionsEditor({
815
  colorCode,
816
  onColorCode,
817
  type,
 
818
  }: {
819
  idPrefix: string;
820
  drafts: OptionDraft[];
@@ -822,10 +842,11 @@ function OptionsEditor({
822
  colorCode: boolean;
823
  onColorCode: (next: boolean) => void;
824
  type: CreateKind;
 
825
  }) {
826
  const update = (id: string, patch: Partial<OptionDraft>) =>
827
  onDrafts(drafts.map((draft) => (draft.id === id ? { ...draft, ...patch } : draft)));
828
- const settings = optionSettings(drafts, type);
829
  return (
830
  <div className="cg-options-editor">
831
  <div className="cg-options-head">
@@ -913,6 +934,11 @@ function OptionsEditor({
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
  }
@@ -944,6 +970,8 @@ function ChoicePreview({ field }: { field: Field }) {
944
  * switch that renders cells.
945
  */
946
  type CreateKind = FieldType | "measure" | "geocode";
 
 
947
 
948
  /**
949
  * ⭐⭐ W37-T22 (R4 / C7) — the geocode pseudo-kind's picker label, and the address-column families
@@ -979,10 +1007,12 @@ function TypePicker({
979
  onPick,
980
  offerMeasure,
981
  offerGeocode,
 
 
982
  only,
983
  }: {
984
- value: CreateKind;
985
- onPick: (k: CreateKind) => void;
986
  offerMeasure: boolean;
987
  /**
988
  * ⭐⭐ W37-T22 (R4 / C7) — offer the geocode pseudo-kind. REQUIRED, not optional: an optional
@@ -1000,17 +1030,25 @@ function TypePicker({
1000
  * "has an address column", which is what W37-T22's `done-when` asks for.
1001
  */
1002
  offerGeocode: boolean;
 
 
 
 
1003
  /** Restrict the list (the Edit-field pane passes RETYPE_TYPES — the overlay-editable
1004
  * strata a created field may become). Absent = every creatable type. */
1005
  only?: readonly FieldType[];
1006
  }) {
1007
  const [q, setQ] = useState("");
1008
  const needle = q.trim().toLowerCase();
1009
- const base = only
1010
  ? FIELD_TYPES.filter((r) => (only as readonly string[]).includes(r.value))
1011
  : FIELD_TYPES;
1012
- const rows: { value: CreateKind; label: string }[] = [
 
1013
  ...base,
 
 
 
1014
  // C-NAME (item 9, 2026-08-02): "Formula measure (over a period)" -> "Metric". Two words
1015
  // of jargon and a parenthetical, replaced by the word people already use for the thing.
1016
  // The internal key stays `measure` — see the C-NAME amendment in the wave doc.
@@ -1082,11 +1120,15 @@ function TypePicker({
1082
  rather than inventing a glyph no column ever shows (the iconShapes ruling). */}
1083
  <FieldTypeIcon
1084
  type={
1085
- r.value === "measure" ? "currency" : r.value === "geocode" ? "text" : r.value
 
1086
  }
1087
  size={16}
1088
  />
1089
- <span className="cg-type-label">{r.label}</span>
 
 
 
1090
  </button>
1091
  ))}
1092
  </Fragment>
@@ -1210,6 +1252,92 @@ function ScopeControl({
1210
  * time and a nested draft makes every setter a two-level spread, which is where a patcher drops a
1211
  * sibling key. `extraFor` does the one nesting at the moment of sending.
1212
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1213
  interface AiEnrichDraft {
1214
  prompt: string;
1215
  model: string;
@@ -1264,6 +1392,8 @@ function ExtraTypeEditor({
1264
  onLinkSingle,
1265
  linkSelectionMode = "manual",
1266
  onLinkSelectionMode,
 
 
1267
  rollupMode = "link",
1268
  onRollupMode,
1269
  rollupSourceOffer = { topics: [], windows: [] },
@@ -1332,6 +1462,9 @@ function ExtraTypeEditor({
1332
  onLinkSingle?: (v: boolean) => void;
1333
  linkSelectionMode?: "manual" | "automatic";
1334
  onLinkSelectionMode?: (v: "manual" | "automatic") => void;
 
 
 
1335
  /** ⭐ 2026-08-09 — which KIND of rollup is being built. `"link"` folds workspace rows;
1336
  * `"source"` reads through to a governed Odoo topic without copying a row into the store. */
1337
  rollupMode?: "link" | "source";
@@ -1365,7 +1498,7 @@ function ExtraTypeEditor({
1365
  if (kind === "formula") {
1366
  // 2026-07-31 (owner item 2): other FORMULA fields are referencable now — evaluation is
1367
  // topological and a cycle is refused at validation, so the old exclusion is gone.
1368
- const referencable = fields.filter((f) => f.key !== "__proto__");
1369
  return (
1370
  <>
1371
  <label>
@@ -1622,7 +1755,9 @@ function ExtraTypeEditor({
1622
  // thing it reads. The schedule and the Run-now button are NOT here — they belong to the
1623
  // automation itself, on the Automation surface, because one job can fill a column across
1624
  // many records and its cadence is a property of the job, not of the column.
1625
- const urlish = fields.filter((f) => f.type === "url" || f.type === "text");
 
 
1626
  const chosen = AUTOMATION_KINDS.find((k) => k.key === automationKind)
1627
  ?? AUTOMATION_KINDS[0];
1628
  return (
@@ -1680,6 +1815,11 @@ function ExtraTypeEditor({
1680
  if (kind === "link") {
1681
  // ⭐ 2026-08-07 — Airtable's "Link to another record", and the whole editor is ONE question:
1682
  // which database. The relation itself is then the cell (a set of linked rows).
 
 
 
 
 
1683
  return (
1684
  <>
1685
  <label>
@@ -1689,7 +1829,10 @@ function ExtraTypeEditor({
1689
  className="cg-input"
1690
  value={linkTable}
1691
  aria-label="Database to link to"
1692
- onChange={(event) => onLinkTable?.(event.target.value)}
 
 
 
1693
  >
1694
  <option value="">Choose a database…</option>
1695
  {linkTargets.map((t) => (
@@ -1709,6 +1852,7 @@ function ExtraTypeEditor({
1709
  className="cg-input"
1710
  value={linkSelectionMode}
1711
  aria-label="How linked records are selected"
 
1712
  onPointerDown={(event) => event.stopPropagation()}
1713
  onChange={(event) => onLinkSelectionMode?.(
1714
  event.target.value === "automatic" ? "automatic" : "manual"
@@ -1718,6 +1862,136 @@ function ExtraTypeEditor({
1718
  <option value="automatic">Set links automatically</option>
1719
  </select>
1720
  </label>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1721
  <label className="cg-cond-line">
1722
  <input
1723
  type="checkbox"
@@ -1728,10 +2002,12 @@ function ExtraTypeEditor({
1728
  />
1729
  <span>Allow only one linked record</span>
1730
  </label>
1731
- <div className="cg-field-hint">
1732
- A cell here holds the records you pick. Add a Rollup column afterwards to summarise a
1733
- column of those records — an average, a total, a count.
1734
- </div>
 
 
1735
  </>
1736
  );
1737
  }
@@ -1742,10 +2018,10 @@ function ExtraTypeEditor({
1742
  // WHICH column, folded HOW, and across WHICH records. That last control is the owner's
1743
  // headline ("average Views over last N posts") and Airtable cannot express it — its rollup
1744
  // conditions filter by predicate, never by rank.
1745
- const linkFields = fields.filter((f) => f.type === "link");
1746
  const chosenLink = linkFields.find((f) => f.key === rollupLink);
1747
  const target = linkTargets.find((t) => t.key === chosenLink?.link?.table);
1748
- const targetFields = target?.fields ?? [];
1749
  // ⛔ COUNTALL IS THE ONE FUNCTION WITH NO SOURCE COLUMN — it counts linked RECORDS, so the
1750
  // field picker would be a control that configures nothing. Airtable's rule, and ours.
1751
  const needsField = rollupFn !== "countall";
@@ -1760,7 +2036,7 @@ function ExtraTypeEditor({
1760
  onRollupSource?.({ ...rollupSource, ...patch });
1761
  // ⚠ A join column must hold a SCALAR the group key can equal. Link and rollup columns hold a
1762
  // comma-joined id list and a computed value respectively, so neither can ever match.
1763
- const joinable = fields.filter(
1764
  (f) => f.type !== "link" && f.type !== "rollup" && f.key !== "__proto__"
1765
  );
1766
  const sourceEditor = (
@@ -1873,6 +2149,9 @@ function ExtraTypeEditor({
1873
  );
1874
  const linkEditor = (
1875
  <>
 
 
 
1876
  <label>
1877
  <span>Through</span>
1878
  <select
@@ -1894,6 +2173,7 @@ function ExtraTypeEditor({
1894
  link, so add one of those first.
1895
  </div>
1896
  ) : null}
 
1897
  <label>
1898
  <span>Fold</span>
1899
  <select
@@ -1908,6 +2188,7 @@ function ExtraTypeEditor({
1908
  ))}
1909
  </select>
1910
  </label>
 
1911
  {needsField ? (
1912
  <label>
1913
  <span>Column</span>
@@ -1966,6 +2247,8 @@ function ExtraTypeEditor({
1966
  reading what the server does, in sequence. The post-filter list used to sit HERE, above
1967
  the window it runs after, which is the one arrangement that teaches the wrong model.
1968
  */}
 
 
1969
  <RollupConditionList
1970
  idPrefix={`${idPrefix}-rollup-where`}
1971
  title="Include records"
@@ -2064,6 +2347,8 @@ function ExtraTypeEditor({
2064
  targetFields={targetFields}
2065
  allowRef
2066
  />
 
 
2067
  <div className="cg-field-hint">
2068
  Computed for you and refreshed as the linked records change — the cell cannot be typed
2069
  into.
@@ -2074,7 +2359,7 @@ function ExtraTypeEditor({
2074
  // connected source the offer is empty, and a two-way toggle whose second option can never
2075
  // work is a control that configures nothing ([[wrong-parent-not-broken-control]]). The link
2076
  // editor is then simply what a rollup is, exactly as it was before this existed.
2077
- if (!sourceTopics.length) return linkEditor;
2078
  return (
2079
  <>
2080
  <label>
@@ -2108,6 +2393,7 @@ export default function ColumnMenu({
2108
  fields,
2109
  linkTargets = [],
2110
  rollupSourceOffer = { topics: [], windows: [] },
 
2111
  geocodable,
2112
  locked,
2113
  schemaLocked = false,
@@ -2138,6 +2424,8 @@ export default function ColumnMenu({
2138
  onUnpin,
2139
  onPeriod,
2140
  onDelete,
 
 
2141
  onRemoveFromMine,
2142
  onEnrich,
2143
  onDuplicate,
@@ -2153,6 +2441,14 @@ export default function ColumnMenu({
2153
  measures = [],
2154
  tableKey,
2155
  }: ColumnMenuProps) {
 
 
 
 
 
 
 
 
2156
  /**
2157
  * ⭐⭐ W40-T24 (owner instruction 18, contract C2) — the pre-set DEFINITION lock, read from the
2158
  * one place that states it. `display.ts` carries the whole argument, including the measured
@@ -2266,7 +2562,7 @@ export default function ColumnMenu({
2266
  /** C5-AUTOFIELD — the create form's automation config. */
2267
  const [automationKind, setAutomationKind] = useState(AUTOMATION_KINDS[0].key);
2268
  const [automationUrlField, setAutomationUrlField] = useState(
2269
- () => fields.find((f) => f.type === "url")?.key ?? ""
2270
  );
2271
  /**
2272
  * ⭐ 2026-08-07 — the create form's LINK and ROLLUP configuration.
@@ -2279,6 +2575,9 @@ export default function ColumnMenu({
2279
  const [linkTable, setLinkTable] = useState("");
2280
  const [linkSingle, setLinkSingle] = useState(false);
2281
  const [linkSelectionMode, setLinkSelectionMode] = useState<"manual" | "automatic">("manual");
 
 
 
2282
  /** ⭐ 2026-08-09 — the read-through half. `rollupMode` decides which bag `extraFor` builds;
2283
  * the two are mutually exclusive because the host's `_clean_rollup` returns the `source`
2284
  * shape before it ever reads `link`. */
@@ -2297,6 +2596,24 @@ export default function ColumnMenu({
2297
  const [rollupWhereConj, setRollupWhereConj] = useState<"and" | "or">("and");
2298
  const [rollupConditions, setRollupConditions] = useState<RollupCondition[]>([]);
2299
  const [rollupConditionConj, setRollupConditionConj] = useState<"and" | "or">("and");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2300
  const [swapTo, setSwapTo] = useState("");
2301
  /** The "New field" half of Change-field keeps its own name/options — a half-typed insert
2302
  * form must not leak into a swap and vice versa. */
@@ -2400,19 +2717,23 @@ export default function ColumnMenu({
2400
  const [editLinkSelectionMode, setEditLinkSelectionMode] = useState<"manual" | "automatic">(
2401
  () => field.link?.selectionMode === "automatic" ? "automatic" : "manual"
2402
  );
 
 
 
2403
 
2404
  const swapToNewType = swapTo.startsWith(NEW_PREFIX)
2405
  ? (swapTo.slice(NEW_PREFIX.length) as FieldType)
2406
  : null;
2407
 
2408
- const createChoice = optionSettings(createOptionDrafts, kind);
2409
  const options = createChoice.options;
2410
  const swapChoice = swapToNewType
2411
- ? optionSettings(swapOptionDrafts, swapToNewType)
2412
- : { options: [] as string[], colors: {} as Record<string, string> };
 
2413
  const swapNewOptions = swapChoice.options;
2414
  /** Owner item 8 — the Edit pane's parsed choices for the drafted type. */
2415
- const editChoice = optionSettings(editOptionDrafts, editType);
2416
  const editOptions = editChoice.options;
2417
 
2418
  // Wave-5 item 9, amended 2026-07-31 (owner item 2) — live formula validation for BOTH
@@ -2459,7 +2780,9 @@ export default function ColumnMenu({
2459
  * permanently unable to run.
2460
  */
2461
  const addressFields = useMemo(
2462
- () => fields.filter((f) => (GEOCODE_ADDRESS_TYPES as readonly string[]).includes(f.type)),
 
 
2463
  [fields]
2464
  );
2465
  const offerGeocode = geocodable && addressFields.length > 0;
@@ -2476,6 +2799,7 @@ export default function ColumnMenu({
2476
  // unparseable formula would be a permanently blank column, refused here rather than shipped.
2477
  const canCreate =
2478
  effectiveLabel.trim() !== "" &&
 
2479
  (kind !== "measure" || !!chosenMeasure) &&
2480
  // ⭐⭐ W37-T22 (R4 / C7) — a geocode column with no address column to read is a column no run
2481
  // can ever fill: the identical argument the `automation` URL-column rule below makes, and the
@@ -2496,7 +2820,7 @@ export default function ColumnMenu({
2496
  // `ai_enrich` column with no prompt, so creating one without this gate produces a column that
2497
  // is named, configured and simply absent on the next read.
2498
  (kind !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
2499
- (kind !== "link" || linkTable !== "") &&
2500
  (kind !== "rollup" || (rollupMode === "source"
2501
  // ⭐ 2026-08-09 — the read-through bag. ALL FOUR keys are required by `_clean_rollup`
2502
  // (`if not (topic and measure and group_by and on): return None`), and `on` is the one a
@@ -2515,7 +2839,8 @@ export default function ColumnMenu({
2515
  t: CreateKind,
2516
  src: string,
2517
  starCount: number,
2518
- lang: string
 
2519
  ): FieldConfigExtra | undefined => {
2520
  if (t === "formula") return { formula: src.trim() };
2521
  if (t === "rating") return { max: starCount };
@@ -2557,8 +2882,12 @@ export default function ColumnMenu({
2557
  // picks records). The DERIVED mode is the automation's, spawned with its join declared —
2558
  // offering "join on a column of the other table" here would be a second, harder mental
2559
  // model for the same button.
2560
- if (t === "link") return { link: { table: linkTable, selectionMode: linkSelectionMode,
2561
- ...(linkSingle ? { single: true } : {}) } };
 
 
 
 
2562
  if (t === "rollup" && rollupMode === "source")
2563
  // ⛔ THE SOURCE BAG TRAVELS ALONE. `_clean_rollup` reads `source` first and returns
2564
  // immediately, so sending `link`/`fn` alongside it would ship keys the store drops —
@@ -2653,7 +2982,7 @@ export default function ColumnMenu({
2653
  onCreate(clean, kind, position === "end" ? null : field.key, position,
2654
  needsOptions(kind) ? options : undefined, undefined,
2655
  withScope({
2656
- ...extraFor(kind, formulaText, maxValue, codeLanguage),
2657
  ...optionExtraFor(kind, createChoice.colors, createColorCode),
2658
  }));
2659
  onClose();
@@ -2662,6 +2991,7 @@ export default function ColumnMenu({
2662
  const canCreateSwap =
2663
  swapToNewType != null &&
2664
  swapLabel.trim() !== "" &&
 
2665
  (swapToNewType !== "formula" || swapFormulaCheck.ok) &&
2666
  // ⭐⭐ Wave-34 (R13) — the SAME completeness gate `canCreate` carries, on this door too.
2667
  //
@@ -2684,7 +3014,7 @@ export default function ColumnMenu({
2684
  swapToNewType,
2685
  needsOptions(swapToNewType) ? swapNewOptions : undefined,
2686
  withScope({
2687
- ...extraFor(swapToNewType, swapFormulaText, swapMaxValue, swapCodeLanguage),
2688
  ...optionExtraFor(swapToNewType, swapChoice.colors, swapColorCode),
2689
  })
2690
  );
@@ -2743,7 +3073,8 @@ export default function ColumnMenu({
2743
  // and silently drop the half-finished type change beside it.
2744
  const editBlocked =
2745
  (editRetypeTouched && !editRetypeValid) ||
2746
- (editFormulaTouched && !editFormulaCheck.ok);
 
2747
  // Item 21 (2026-08-02) — the PERIOD moved into this pane, so its dirty-check has to be
2748
  // computed before the pane's save gate rather than beside the menu's own button. Same three
2749
  // lines, hoisted: `canSaveEdit` reads `periodChanged`, and a `const` read before its
@@ -2795,7 +3126,9 @@ export default function ColumnMenu({
2795
  ? JSON.stringify(editRollup) !== JSON.stringify(field.rollup ?? {})
2796
  : editLinkTable !== (field.link?.table ?? "") ||
2797
  editLinkSingle !== (field.link?.single === true) ||
2798
- editLinkSelectionMode !== (field.link?.selectionMode === "automatic" ? "automatic" : "manual"));
 
 
2799
  const canSaveEdit =
2800
  /**
2801
  * ⭐ W41-T31 — THE DESCRIPTION-ONLY PANE'S WHOLE SAVE CONDITION, and it is one dirty flag
@@ -2821,7 +3154,8 @@ export default function ColumnMenu({
2821
  (editType !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
2822
  (editingRelational
2823
  ? (editRollupValid && (editRelationalTouched || editNameDirty || editNoteDirty) &&
2824
- (field.type !== "link" || editLinkTable !== ""))
 
2825
  : (editNameDirty || editRetypeTouched || editFormulaTouched ||
2826
  (canPeriod && periodChanged) || editNoteDirty)));
2827
  /**
@@ -2860,6 +3194,7 @@ export default function ColumnMenu({
2860
  */
2861
  if (!canEditDescription &&
2862
  editingRelational && onFieldConfig && (editRelationalTouched || editNameDirty)) {
 
2863
  // ⛔ THE WHOLE BAG, EVERY SAVE. `_clean_rollup` is a pure cleaner over what it receives —
2864
  // it does not merge with the stored bag — so a partial patch is a REBUILD, and an omitted
2865
  // `limit` would silently become "no limit" rather than "unchanged".
@@ -2869,7 +3204,14 @@ export default function ColumnMenu({
2869
  ? { rollup: editRollup as Record<string, unknown> }
2870
  : { link: { table: editLinkTable,
2871
  selectionMode: editLinkSelectionMode,
2872
- ...(editLinkSingle ? { single: true } : {}) } }),
 
 
 
 
 
 
 
2873
  });
2874
  if (editNoteDirty) onNote(note);
2875
  onClose();
@@ -2952,7 +3294,7 @@ export default function ColumnMenu({
2952
  * would contain; `swapOffered` is whether the picker exists at all, and it is read twice (the
2953
  * control itself, and the focus fallback that has to know whether the control is there).
2954
  */
2955
- const swapOptions = fields.filter((f) => f.key !== field.key);
2956
  const presetSwap = swapOptions.filter((f) => f.source === "odoo" && !f.custom);
2957
  const yourSwap = swapOptions.filter((f) => !(f.source === "odoo" && !f.custom));
2958
  const swapOffered = offer.swap && swapOptions.length > 0;
@@ -3084,7 +3426,7 @@ export default function ColumnMenu({
3084
  onAccept={(proposal: FieldProposal) => {
3085
  setLabel(proposal.label);
3086
  setLabelTouched(true);
3087
- setKind(proposal.kind);
3088
  if (proposal.options && proposal.options.length)
3089
  setCreateOptionDrafts(optionDrafts(proposal.options));
3090
  setAskAgent(false);
@@ -3121,10 +3463,12 @@ export default function ColumnMenu({
3121
  rows, Airtable-style. The measure row appears exactly when the host offers
3122
  measures — the same availability rule as the filter's measure conditions. */}
3123
  <TypePicker
3124
- value={kind}
3125
- onPick={setKind}
3126
  offerMeasure={measures.length > 0}
3127
  offerGeocode={offerGeocode}
 
 
3128
  />
3129
  </div>
3130
  {kind === "measure" && (
@@ -3229,6 +3573,14 @@ export default function ColumnMenu({
3229
  onLinkSingle={setLinkSingle}
3230
  linkSelectionMode={linkSelectionMode}
3231
  onLinkSelectionMode={setLinkSelectionMode}
 
 
 
 
 
 
 
 
3232
  rollupMode={rollupMode}
3233
  onRollupMode={setRollupMode}
3234
  rollupSourceOffer={rollupSourceOffer}
@@ -3273,6 +3625,7 @@ export default function ColumnMenu({
3273
  colorCode={createColorCode}
3274
  onColorCode={setCreateColorCode}
3275
  type={kind}
 
3276
  />
3277
  )}
3278
  {kind === "user" && (
@@ -3522,6 +3875,14 @@ export default function ColumnMenu({
3522
  onLinkSingle={setEditLinkSingle}
3523
  linkSelectionMode={editLinkSelectionMode}
3524
  onLinkSelectionMode={setEditLinkSelectionMode}
 
 
 
 
 
 
 
 
3525
  rollupSourceOffer={rollupSourceOffer}
3526
  rollupMode={editRollup.source ? "source" : "link"}
3527
  // ⛔ A MODE SWITCH REPLACES THE BAG, it does not merge into it. `_clean_rollup`
@@ -3607,6 +3968,8 @@ export default function ColumnMenu({
3607
  value={editType}
3608
  onPick={(k) => setEditType(k as FieldType)}
3609
  offerMeasure={false}
 
 
3610
  offerGeocode={
3611
  /* ⛔ FALSE ON PURPOSE, and stated rather than omitted: this is the RETYPE
3612
  picker, and a geocode column is not a type an existing column can BECOME.
@@ -3702,6 +4065,7 @@ export default function ColumnMenu({
3702
  colorCode={editColorCode}
3703
  onColorCode={setEditColorCode}
3704
  type={editType}
 
3705
  />
3706
  )}
3707
  {editType !== field.type && (
@@ -3874,6 +4238,7 @@ export default function ColumnMenu({
3874
  colorCode={swapColorCode}
3875
  onColorCode={setSwapColorCode}
3876
  type={swapToNewType}
 
3877
  />
3878
  )}
3879
  {swapToNewType === "user" && (
@@ -4174,11 +4539,13 @@ export default function ColumnMenu({
4174
  * `preset`, its Delete goes — which is R6(a) working, and worth a look before the wave closes.
4175
  */
4176
  const fieldC1 = fieldClassOf(field);
 
4177
  const presetRefusal = deleteRefusalReason(fieldC1, viewer);
4178
  const canRemoveFromMine = mayRemoveField(fieldC1, viewer);
4179
  const rightsKnown = fieldC1 !== null && !!viewer;
4180
  const c1AllowsDelete =
4181
- !presetRefusal && !canRemoveFromMine && (!rightsKnown || mayDeleteFieldRight(fieldC1, viewer));
 
4182
  const deleteImpact = deleteImpactTitle(fieldC1, fieldUsageOf(field));
4183
 
4184
  return (
@@ -4192,6 +4559,7 @@ export default function ColumnMenu({
4192
  dataKind="column-menu"
4193
  >
4194
  <PaneHead title={field.label} sub={typeLine} onClose={onClose} />
 
4195
 
4196
  {/* Item 8c — any measure-carrying column exposes its PERIOD, the property that defines
4197
  it. Item 21 (2026-08-02) moved the EDITOR into the Edit-field pane; what stays here
@@ -4248,6 +4616,20 @@ export default function ColumnMenu({
4248
  row would leave a collaborator guessing why the column they can see is not theirs to
4249
  pass on. The one thing that DOES withdraw it is a missing server table key, because
4250
  without one the id cannot be built. */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4251
  {shareOid && (
4252
  <button
4253
  type="button"
@@ -4351,19 +4733,21 @@ export default function ColumnMenu({
4351
  <div className="cg-menu-sep" role="separator" aria-hidden />
4352
 
4353
  {/* Group 3 — sort. Direction wording stays the shipped per-type directionLabel. */}
4354
- <button type="button" onClick={() => { onSort("asc"); onClose(); }}>
4355
- <MenuLabel
4356
- icon="sortAsc"
4357
- text={`Sort ${directionLabel(field.type, "asc")}`}
4358
- />
4359
- </button>
4360
- <button type="button" onClick={() => { onSort("desc"); onClose(); }}>
4361
- <MenuLabel
4362
- icon="sortDesc"
4363
- text={`Sort ${directionLabel(field.type, "desc")}`}
4364
- />
4365
- </button>
4366
- {sortedDir != null && (
 
 
4367
  <button type="button" onClick={() => { onClearSort(); onClose(); }}>
4368
  <MenuLabel icon="off" text="Don't sort by this field" />
4369
  </button>
@@ -4377,13 +4761,13 @@ export default function ColumnMenu({
4377
  column itself (offered only while the host serves measures, the same
4378
  availability rule as measure conditions). Everything else keeps the plain
4379
  filterable check. */}
4380
- {(field.filterable !== false ||
4381
  (field.measure != null && measures.length > 0)) && (
4382
  <button type="button" onClick={() => { onFilterBy(); onClose(); }}>
4383
  <MenuLabel icon="filter" text="Filter by this field" />
4384
  </button>
4385
  )}
4386
- {isFiltered && (
4387
  <button type="button" onClick={() => { onClearFilter(); onClose(); }}>
4388
  <MenuLabel icon="off" text="Don't filter by this field" />
4389
  </button>
@@ -4514,6 +4898,11 @@ export default function ColumnMenu({
4514
  {presetRefusal}
4515
  </p>
4516
  )}
 
 
 
 
 
4517
  {!schemaLocked && offer.remove && onDelete && c1AllowsDelete && (
4518
  <button
4519
  type="button"
 
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
+ isOfferableField, isProfileField, offerableCreateKind, parseOptions, ratingMax,
22
+ ROLLUP_FN_LABELS, ROLLUP_FNS, ROLLUP_PRESET_FNS, ROLLUP_PRESETS, rollupPresetOf,
23
+ serverOptionLimit,
24
+ filterTreeConj, filterTreeNodes, offerableFields, TYPE_DESCRIPTIONS,
25
  ROLLUP_REF_OPS, mayEditFieldDefinition } from "./types";
26
+ import type { AggName, Conjunction, Field, FieldFormat, FieldScope, FieldType, FilterNode, Measure,
27
+ RollupCondition, RollupFn, RollupPreset, RollupRefOp, RollupSource, Viewer } from "./types";
28
+ import type { HopTopic, HopTopicOffer, LinkTarget, RollupSourceOffer } from "./apiBridge";
29
  import type { WindowSpec } from "./windows";
30
  import { normalizeWindow, windowLabel } from "./windows";
31
+ import { FilterBuilderPanel, WindowPicker } from "../filter-kit";
32
  // ⭐⭐ W41-T29 (R6, contract C2) — the ONE pair of rights predicates plus the copy that says what
33
  // they refused, read from the same module the Fields manager reads. C2: no surface re-implements
34
  // either test, so this menu asks rather than deriving a second answer of its own.
 
56
  import { validateFormula } from "./formulaEngine";
57
  import { BRAND_SWATCHES, defaultOptionColor, nearestSwatch, normalizeOptionColor,
58
  OPTION_PALETTE } from "./choiceColors";
59
+ import { FieldProperties, fieldDeletionLocked } from "./FieldProperties";
60
 
61
  export interface ColumnMenuState {
62
  fieldKey: string;
 
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
+ link?: {
108
+ table: string;
109
+ on?: string;
110
+ from?: string;
111
+ single?: boolean;
112
+ selectionMode?: "manual" | "automatic";
113
+ via?: HopViaBag;
114
+ };
115
  /** ⭐ 2026-08-07 — a `rollup` column's aggregate. Same requirement, same reason.
116
  * ⭐ 2026-08-09 — or, INSTEAD, a `source` binding: the read-through kind, which summarises
117
  * rows that were never copied into the workspace. The host's `_clean_rollup` reads `source`
 
173
  * as it was before this existed. So this prop is what turns the second kind ON, not a flag.
174
  */
175
  rollupSourceOffer?: RollupSourceOffer;
176
+ /** Dedicated typed offer from GET /grid/hop-topics; never derived from rollup sources. */
177
+ hopTopicOffer?: HopTopicOffer;
178
  locked: boolean;
179
  /** Product-owned preset fields may still drive view actions, but their schema is immutable. */
180
  schemaLocked?: boolean;
 
307
  * the control is not rendered at all, so a base field cannot even be offered the action.
308
  */
309
  onDelete?: () => void;
310
+ /** Owner-only change to C3's server-owned deletion lock. */
311
+ onSetDeletionLock?: (locked: boolean) => void;
312
+ /** Copies a canonical Data path that opens this field's properties. */
313
+ onCopyFieldLink?: () => void;
314
  /**
315
  * ⭐⭐ W41-T29 (R6(b)) — DROP A COLUMN SOMEBODY ELSE SHARED WITH ME, off my own list. A
316
  * DIFFERENT ACT from `onDelete`, and therefore a different door: it destroys no definition and
 
320
  * file and no endpoint unshares a field yet. The half of R6(b) that holds without it is the
321
  * REFUSAL: a shared-with-me column loses its Delete row whether or not this handler arrives.
322
  */
323
+ onRemoveFromMine: () => void;
324
  /** ⭐⭐ Wave-34 (R13) — run this AI enrichment column over many rows.
325
  * `scope` is `"blank"` (only cells still empty) or `"always"` (every row the AI
326
  * wrote). OPTIONAL for `onDelete`'s reason: a host that has not wired the door shows
 
338
  onAggregate?: (agg: AggName | undefined) => void;
339
  /** Wave-5 item 1 — Sort by this field (replaces the view's sort), and the conditional
340
  * clears (item 3). All of these mutate the EXISTING view config — no new host surface. */
341
+ onSort?: (dir: "asc" | "desc") => void;
342
+ onClearSort?: () => void;
343
+ onFilterBy?: () => void;
344
+ onClearFilter?: () => void;
345
  onGroupByField: () => void;
346
  onClearGroup: () => void;
347
  /** Assignable people, from the host's real user list. Empty = the host did not supply one,
 
699
 
700
  function optionSettings(
701
  drafts: OptionDraft[],
702
+ type: CreateKind,
703
+ maxOptions: number | null
704
+ ): { options: string[]; colors: Record<string, string>; capMessage: string | null } {
705
  const clean = drafts.map((draft) =>
706
  type === "multiselect" ? draft.label.replace(/,/g, " ") : draft.label
707
  );
708
+ const parsed = parseOptions(clean.join("\n"), maxOptions);
709
+ const options = parsed.options;
710
  const firstByLabel = new Map<string, OptionDraft>();
711
  drafts.forEach((draft, index) => {
712
  const label = clean[index].trim();
 
722
  if (color && color !== normalizeOptionColor(defaultOptionColor(option)))
723
  colors[option] = color;
724
  }
725
+ return { options, colors, capMessage: parsed.message };
726
  }
727
 
728
  function optionAppearanceSignature(
 
834
  colorCode,
835
  onColorCode,
836
  type,
837
+ maxOptions,
838
  }: {
839
  idPrefix: string;
840
  drafts: OptionDraft[];
 
842
  colorCode: boolean;
843
  onColorCode: (next: boolean) => void;
844
  type: CreateKind;
845
+ maxOptions: number | null;
846
  }) {
847
  const update = (id: string, patch: Partial<OptionDraft>) =>
848
  onDrafts(drafts.map((draft) => (draft.id === id ? { ...draft, ...patch } : draft)));
849
+ const settings = optionSettings(drafts, type, maxOptions);
850
  return (
851
  <div className="cg-options-editor">
852
  <div className="cg-options-head">
 
934
  {settings.options.length} option{settings.options.length === 1 ? "" : "s"}.
935
  {type === "multiselect" && " Commas inside an option are not supported."}
936
  </span>
937
+ {settings.capMessage && (
938
+ <span className="cg-field-hint is-refusal" role="alert">
939
+ {settings.capMessage}
940
+ </span>
941
+ )}
942
  </div>
943
  );
944
  }
 
970
  * switch that renders cells.
971
  */
972
  type CreateKind = FieldType | "measure" | "geocode";
973
+ type PickerKind = CreateKind | RollupPreset;
974
+ const PRESET_LABELS: Record<RollupPreset, string> = { count: "Count", lookup: "Lookup" };
975
 
976
  /**
977
  * ⭐⭐ W37-T22 (R4 / C7) — the geocode pseudo-kind's picker label, and the address-column families
 
1007
  onPick,
1008
  offerMeasure,
1009
  offerGeocode,
1010
+ offerPresets,
1011
+ isUserTable,
1012
  only,
1013
  }: {
1014
+ value: PickerKind;
1015
+ onPick: (k: PickerKind) => void;
1016
  offerMeasure: boolean;
1017
  /**
1018
  * ⭐⭐ W37-T22 (R4 / C7) — offer the geocode pseudo-kind. REQUIRED, not optional: an optional
 
1030
  * "has an address column", which is what W37-T22's `done-when` asks for.
1031
  */
1032
  offerGeocode: boolean;
1033
+ /** Presets author a rollup bag and are create-only, never retype options. */
1034
+ offerPresets: boolean;
1035
+ /** Runtime database surfaces withhold create kinds their server refuses. */
1036
+ isUserTable: boolean;
1037
  /** Restrict the list (the Edit-field pane passes RETYPE_TYPES — the overlay-editable
1038
  * strata a created field may become). Absent = every creatable type. */
1039
  only?: readonly FieldType[];
1040
  }) {
1041
  const [q, setQ] = useState("");
1042
  const needle = q.trim().toLowerCase();
1043
+ const offerable = only
1044
  ? FIELD_TYPES.filter((r) => (only as readonly string[]).includes(r.value))
1045
  : FIELD_TYPES;
1046
+ const base = offerable.filter((row) => offerableCreateKind(row.value, isUserTable));
1047
+ const rows: { value: PickerKind; label: string }[] = [
1048
  ...base,
1049
+ ...(offerPresets
1050
+ ? ROLLUP_PRESETS.map((preset) => ({ value: preset, label: PRESET_LABELS[preset] }))
1051
+ : []),
1052
  // C-NAME (item 9, 2026-08-02): "Formula measure (over a period)" -> "Metric". Two words
1053
  // of jargon and a parenthetical, replaced by the word people already use for the thing.
1054
  // The internal key stays `measure` — see the C-NAME amendment in the wave doc.
 
1120
  rather than inventing a glyph no column ever shows (the iconShapes ruling). */}
1121
  <FieldTypeIcon
1122
  type={
1123
+ r.value === "measure" ? "currency" : r.value === "geocode" ? "text"
1124
+ : r.value === "count" || r.value === "lookup" ? "rollup" : r.value
1125
  }
1126
  size={16}
1127
  />
1128
+ <span className="cg-type-label" style={{ whiteSpace: "normal" }}>
1129
+ <span>{r.label}</span>
1130
+ <span className="cg-field-hint">{TYPE_DESCRIPTIONS[r.value]}</span>
1131
+ </span>
1132
  </button>
1133
  ))}
1134
  </Fragment>
 
1252
  * time and a nested draft makes every setter a two-level spread, which is where a patcher drops a
1253
  * sibling key. `extraFor` does the one nesting at the moment of sending.
1254
  */
1255
+ // W42-T08: the governed semantic hop optionally carried by a Link field.
1256
+ export interface HopViaBag {
1257
+ topic: string;
1258
+ source_dim: string;
1259
+ target_dim: string;
1260
+ target_key: string;
1261
+ scope_key: string;
1262
+ measure: string;
1263
+ filter: FilterNode[];
1264
+ filterConj: Conjunction;
1265
+ window: string;
1266
+ }
1267
+
1268
+ export interface HopDraft {
1269
+ topic: string;
1270
+ sourceDim: string;
1271
+ targetDim: string;
1272
+ targetKey: string;
1273
+ measure: string;
1274
+ filter: FilterNode[];
1275
+ filterConj: Conjunction;
1276
+ window: string;
1277
+ scopeKey: string;
1278
+ }
1279
+
1280
+ export const HOP_WINDOW_ALL = "all_time";
1281
+
1282
+ export const emptyHopDraft = (): HopDraft => ({
1283
+ topic: "", sourceDim: "", targetDim: "", targetKey: "", measure: "",
1284
+ filter: [], filterConj: "and", window: HOP_WINDOW_ALL, scopeKey: "",
1285
+ });
1286
+
1287
+ interface HopOffer {
1288
+ topics: HopTopic[];
1289
+ windows: { key: string; label: string }[];
1290
+ scopeKey: string;
1291
+ draft: HopDraft;
1292
+ onDraft: (patch: Partial<HopDraft>) => void;
1293
+ }
1294
+
1295
+ export function hopVia(
1296
+ draft: HopDraft | null | undefined,
1297
+ scopeKey: string
1298
+ ): HopViaBag | null {
1299
+ if (!draft) return null;
1300
+ const topic = draft.topic.trim();
1301
+ const sourceDim = draft.sourceDim.trim();
1302
+ const targetDim = draft.targetDim.trim();
1303
+ const targetKey = draft.targetKey.trim();
1304
+ const measure = draft.measure.trim();
1305
+ const scope = (draft.scopeKey || scopeKey || "").trim();
1306
+ if (!topic || !sourceDim || !targetDim || !targetKey || !measure || !scope) return null;
1307
+ return {
1308
+ topic,
1309
+ source_dim: sourceDim,
1310
+ target_dim: targetDim,
1311
+ target_key: targetKey,
1312
+ scope_key: scope,
1313
+ measure,
1314
+ filter: draft.filter,
1315
+ filterConj: draft.filterConj,
1316
+ window: draft.window || HOP_WINDOW_ALL,
1317
+ };
1318
+ }
1319
+
1320
+ export const hopIncomplete = (draft: HopDraft | null | undefined, scopeKey: string): boolean =>
1321
+ !!draft && draft.topic.trim() !== "" && hopVia(draft, scopeKey) === null;
1322
+
1323
+ export function hopDraftFrom(link: unknown): HopDraft {
1324
+ const via = (link as { via?: Record<string, unknown> } | null | undefined)?.via;
1325
+ const draft = emptyHopDraft();
1326
+ if (!via || typeof via !== "object") return draft;
1327
+ const text = (value: unknown) => (typeof value === "string" ? value : "");
1328
+ return {
1329
+ topic: text(via.topic),
1330
+ sourceDim: text(via.source_dim),
1331
+ targetDim: text(via.target_dim),
1332
+ targetKey: text(via.target_key),
1333
+ measure: text(via.measure),
1334
+ filter: Array.isArray(via.filter) ? (via.filter as FilterNode[]) : [],
1335
+ filterConj: via.filterConj === "or" ? "or" : "and",
1336
+ window: text(via.window) || HOP_WINDOW_ALL,
1337
+ scopeKey: text(via.scope_key),
1338
+ };
1339
+ }
1340
+
1341
  interface AiEnrichDraft {
1342
  prompt: string;
1343
  model: string;
 
1392
  onLinkSingle,
1393
  linkSelectionMode = "manual",
1394
  onLinkSelectionMode,
1395
+ hop = null,
1396
+ rollupPreset = null,
1397
  rollupMode = "link",
1398
  onRollupMode,
1399
  rollupSourceOffer = { topics: [], windows: [] },
 
1462
  onLinkSingle?: (v: boolean) => void;
1463
  linkSelectionMode?: "manual" | "automatic";
1464
  onLinkSelectionMode?: (v: "manual" | "automatic") => void;
1465
+ hop?: HopOffer | null;
1466
+ /** Count/Lookup presets reopen in their reduced editor only when the stored bag is exact. */
1467
+ rollupPreset?: RollupPreset | null;
1468
  /** ⭐ 2026-08-09 — which KIND of rollup is being built. `"link"` folds workspace rows;
1469
  * `"source"` reads through to a governed Odoo topic without copying a row into the store. */
1470
  rollupMode?: "link" | "source";
 
1498
  if (kind === "formula") {
1499
  // 2026-07-31 (owner item 2): other FORMULA fields are referencable now — evaluation is
1500
  // topological and a cycle is refused at validation, so the old exclusion is gone.
1501
+ const referencable = offerableFields(fields).filter((f) => f.key !== "__proto__");
1502
  return (
1503
  <>
1504
  <label>
 
1755
  // thing it reads. The schedule and the Run-now button are NOT here — they belong to the
1756
  // automation itself, on the Automation surface, because one job can fill a column across
1757
  // many records and its cadence is a property of the job, not of the column.
1758
+ const urlish = offerableFields(fields).filter(
1759
+ (f) => f.type === "url" || f.type === "text"
1760
+ );
1761
  const chosen = AUTOMATION_KINDS.find((k) => k.key === automationKind)
1762
  ?? AUTOMATION_KINDS[0];
1763
  return (
 
1815
  if (kind === "link") {
1816
  // ⭐ 2026-08-07 — Airtable's "Link to another record", and the whole editor is ONE question:
1817
  // which database. The relation itself is then the cell (a set of linked rows).
1818
+ const hopTopic = hop?.topics.find((topic) => topic.key === hop.draft.topic);
1819
+ const hopTargetFields = linkTargets.find((target) => target.key === linkTable)?.fields
1820
+ .filter((candidate) => candidate.type !== "link" && candidate.type !== "rollup") ?? [];
1821
+ const hopWindow = hop?.draft.window || HOP_WINDOW_ALL;
1822
+ const hopWindowOffered = !!hop?.windows.some((candidate) => candidate.key === hopWindow);
1823
  return (
1824
  <>
1825
  <label>
 
1829
  className="cg-input"
1830
  value={linkTable}
1831
  aria-label="Database to link to"
1832
+ onChange={(event) => {
1833
+ onLinkTable?.(event.target.value);
1834
+ hop?.onDraft({ targetKey: "" });
1835
+ }}
1836
  >
1837
  <option value="">Choose a database…</option>
1838
  {linkTargets.map((t) => (
 
1852
  className="cg-input"
1853
  value={linkSelectionMode}
1854
  aria-label="How linked records are selected"
1855
+ disabled={!!hop?.draft.topic}
1856
  onPointerDown={(event) => event.stopPropagation()}
1857
  onChange={(event) => onLinkSelectionMode?.(
1858
  event.target.value === "automatic" ? "automatic" : "manual"
 
1862
  <option value="automatic">Set links automatically</option>
1863
  </select>
1864
  </label>
1865
+ {hop ? (
1866
+ <div className="cg-hop">
1867
+ <label className="cg-hop-question">
1868
+ <span>Through</span>
1869
+ <select
1870
+ id={`${idPrefix}-hop-topic`}
1871
+ className="cg-input"
1872
+ value={hop.draft.topic}
1873
+ aria-label="Data to travel through"
1874
+ onChange={(event) => {
1875
+ const topic = event.target.value;
1876
+ onLinkSelectionMode?.(topic ? "automatic" : "manual");
1877
+ hop.onDraft({
1878
+ topic,
1879
+ sourceDim: "",
1880
+ targetDim: "",
1881
+ measure: "",
1882
+ filter: [],
1883
+ filterConj: "and",
1884
+ });
1885
+ }}
1886
+ >
1887
+ <option value="">Nothing, link the records directly</option>
1888
+ {hop.topics.map((topic) => (
1889
+ <option key={topic.key} value={topic.key}>{topic.label}</option>
1890
+ ))}
1891
+ </select>
1892
+ </label>
1893
+ {hop.topics.length === 0 ? (
1894
+ <div className="cg-field-hint">No governed data is available to travel through.</div>
1895
+ ) : null}
1896
+ {hopTopic ? (
1897
+ <div className="cg-hop-body">
1898
+ <label>
1899
+ <span>Matched from</span>
1900
+ <select
1901
+ id={`${idPrefix}-hop-source-dim`}
1902
+ className="cg-input"
1903
+ value={hop.draft.sourceDim}
1904
+ aria-label="What names a row of this database"
1905
+ onChange={(event) => hop.onDraft({ sourceDim: event.target.value })}
1906
+ >
1907
+ <option value="">Choose the starting match</option>
1908
+ {hopTopic.dims.map((dim) => (
1909
+ <option key={dim.key} value={dim.key}>{dim.label}</option>
1910
+ ))}
1911
+ </select>
1912
+ </label>
1913
+ <label>
1914
+ <span>Matched to</span>
1915
+ <select
1916
+ id={`${idPrefix}-hop-target-dim`}
1917
+ className="cg-input"
1918
+ value={hop.draft.targetDim}
1919
+ aria-label="What names a row of the other database"
1920
+ onChange={(event) => hop.onDraft({ targetDim: event.target.value })}
1921
+ >
1922
+ <option value="">Choose the destination match</option>
1923
+ {hopTopic.dims.map((dim) => (
1924
+ <option key={dim.key} value={dim.key}>{dim.label}</option>
1925
+ ))}
1926
+ </select>
1927
+ </label>
1928
+ <label>
1929
+ <span>Column over there</span>
1930
+ <select
1931
+ id={`${idPrefix}-hop-target-key`}
1932
+ className="cg-input"
1933
+ value={hop.draft.targetKey}
1934
+ aria-label="Column in the other database holding that value"
1935
+ onChange={(event) => hop.onDraft({ targetKey: event.target.value })}
1936
+ >
1937
+ <option value="">Choose the destination column</option>
1938
+ {hopTargetFields.map((candidate) => (
1939
+ <option key={candidate.key} value={candidate.key}>{candidate.label}</option>
1940
+ ))}
1941
+ </select>
1942
+ </label>
1943
+ <label>
1944
+ <span>Measure</span>
1945
+ <select
1946
+ id={`${idPrefix}-hop-measure`}
1947
+ className="cg-input"
1948
+ value={hop.draft.measure}
1949
+ aria-label="Measure"
1950
+ onChange={(event) => hop.onDraft({ measure: event.target.value })}
1951
+ >
1952
+ <option value="">Choose a measure</option>
1953
+ {hopTopic.measures.map((measure) => (
1954
+ <option key={measure.key} value={measure.key}>{measure.label}</option>
1955
+ ))}
1956
+ </select>
1957
+ </label>
1958
+ {hop.windows.length > 0 ? (
1959
+ <label>
1960
+ <span>Over</span>
1961
+ <select
1962
+ id={`${idPrefix}-hop-window`}
1963
+ className="cg-input"
1964
+ value={hopWindow}
1965
+ aria-label="Date window"
1966
+ onChange={(event) => hop.onDraft({ window: event.target.value })}
1967
+ >
1968
+ {hopWindowOffered ? null : <option value={hopWindow}>{hopWindow}</option>}
1969
+ {hop.windows.map((candidate) => (
1970
+ <option key={candidate.key} value={candidate.key}>{candidate.label}</option>
1971
+ ))}
1972
+ </select>
1973
+ </label>
1974
+ ) : null}
1975
+ <div className="cg-hop-filter">
1976
+ <span className="cg-type-title">Keep only</span>
1977
+ <FilterBuilderPanel
1978
+ fields={hopTopic.dims}
1979
+ filters={{ conj: hop.draft.filterConj, nodes: hop.draft.filter }}
1980
+ onChange={(next) => hop.onDraft({
1981
+ filter: filterTreeNodes(next),
1982
+ filterConj: filterTreeConj(next),
1983
+ })}
1984
+ />
1985
+ </div>
1986
+ {(hop.draft.scopeKey || hop.scopeKey).trim() === "" ? (
1987
+ <div className="cg-field-hint">
1988
+ This database has no usable starting scope, so the hop cannot be saved.
1989
+ </div>
1990
+ ) : null}
1991
+ </div>
1992
+ ) : null}
1993
+ </div>
1994
+ ) : null}
1995
  <label className="cg-cond-line">
1996
  <input
1997
  type="checkbox"
 
2002
  />
2003
  <span>Allow only one linked record</span>
2004
  </label>
2005
+ {hop?.draft.topic ? null : (
2006
+ <div className="cg-field-hint">
2007
+ A cell here holds the records you pick. Add a Rollup column afterwards to summarise a
2008
+ column of those records — an average, a total, a count.
2009
+ </div>
2010
+ )}
2011
  </>
2012
  );
2013
  }
 
2018
  // WHICH column, folded HOW, and across WHICH records. That last control is the owner's
2019
  // headline ("average Views over last N posts") and Airtable cannot express it — its rollup
2020
  // conditions filter by predicate, never by rank.
2021
+ const linkFields = offerableFields(fields).filter((f) => f.type === "link");
2022
  const chosenLink = linkFields.find((f) => f.key === rollupLink);
2023
  const target = linkTargets.find((t) => t.key === chosenLink?.link?.table);
2024
+ const targetFields = offerableFields(target?.fields ?? []);
2025
  // ⛔ COUNTALL IS THE ONE FUNCTION WITH NO SOURCE COLUMN — it counts linked RECORDS, so the
2026
  // field picker would be a control that configures nothing. Airtable's rule, and ours.
2027
  const needsField = rollupFn !== "countall";
 
2036
  onRollupSource?.({ ...rollupSource, ...patch });
2037
  // ⚠ A join column must hold a SCALAR the group key can equal. Link and rollup columns hold a
2038
  // comma-joined id list and a computed value respectively, so neither can ever match.
2039
+ const joinable = offerableFields(fields).filter(
2040
  (f) => f.type !== "link" && f.type !== "rollup" && f.key !== "__proto__"
2041
  );
2042
  const sourceEditor = (
 
2149
  );
2150
  const linkEditor = (
2151
  <>
2152
+ {rollupPreset ? (
2153
+ <div className="cg-field-hint">{TYPE_DESCRIPTIONS[rollupPreset]}</div>
2154
+ ) : null}
2155
  <label>
2156
  <span>Through</span>
2157
  <select
 
2173
  link, so add one of those first.
2174
  </div>
2175
  ) : null}
2176
+ {rollupPreset ? null : (
2177
  <label>
2178
  <span>Fold</span>
2179
  <select
 
2188
  ))}
2189
  </select>
2190
  </label>
2191
+ )}
2192
  {needsField ? (
2193
  <label>
2194
  <span>Column</span>
 
2247
  reading what the server does, in sequence. The post-filter list used to sit HERE, above
2248
  the window it runs after, which is the one arrangement that teaches the wrong model.
2249
  */}
2250
+ {rollupPreset ? null : (
2251
+ <>
2252
  <RollupConditionList
2253
  idPrefix={`${idPrefix}-rollup-where`}
2254
  title="Include records"
 
2347
  targetFields={targetFields}
2348
  allowRef
2349
  />
2350
+ </>
2351
+ )}
2352
  <div className="cg-field-hint">
2353
  Computed for you and refreshed as the linked records change — the cell cannot be typed
2354
  into.
 
2359
  // connected source the offer is empty, and a two-way toggle whose second option can never
2360
  // work is a control that configures nothing ([[wrong-parent-not-broken-control]]). The link
2361
  // editor is then simply what a rollup is, exactly as it was before this existed.
2362
+ if (rollupPreset || !sourceTopics.length) return linkEditor;
2363
  return (
2364
  <>
2365
  <label>
 
2393
  fields,
2394
  linkTargets = [],
2395
  rollupSourceOffer = { topics: [], windows: [] },
2396
+ hopTopicOffer = { topics: [], windows: [], omissions: [] },
2397
  geocodable,
2398
  locked,
2399
  schemaLocked = false,
 
2424
  onUnpin,
2425
  onPeriod,
2426
  onDelete,
2427
+ onSetDeletionLock,
2428
+ onCopyFieldLink,
2429
  onRemoveFromMine,
2430
  onEnrich,
2431
  onDuplicate,
 
2441
  measures = [],
2442
  tableKey,
2443
  }: ColumnMenuProps) {
2444
+ const optionLimit = serverOptionLimit(fields);
2445
+ const fieldOfferable = isOfferableField(field);
2446
+ const hopScopeKey = tableKey === "customer_data"
2447
+ ? "customer"
2448
+ : tableKey === "product_data"
2449
+ ? "product"
2450
+ : tableKey ?? "";
2451
+ const hopTopics: HopTopic[] = hopTopicOffer.topics;
2452
  /**
2453
  * ⭐⭐ W40-T24 (owner instruction 18, contract C2) — the pre-set DEFINITION lock, read from the
2454
  * one place that states it. `display.ts` carries the whole argument, including the measured
 
2562
  /** C5-AUTOFIELD — the create form's automation config. */
2563
  const [automationKind, setAutomationKind] = useState(AUTOMATION_KINDS[0].key);
2564
  const [automationUrlField, setAutomationUrlField] = useState(
2565
+ () => offerableFields(fields).find((f) => f.type === "url")?.key ?? ""
2566
  );
2567
  /**
2568
  * ⭐ 2026-08-07 — the create form's LINK and ROLLUP configuration.
 
2575
  const [linkTable, setLinkTable] = useState("");
2576
  const [linkSingle, setLinkSingle] = useState(false);
2577
  const [linkSelectionMode, setLinkSelectionMode] = useState<"manual" | "automatic">("manual");
2578
+ const [hopDraft, setHopDraft] = useState<HopDraft>(emptyHopDraft);
2579
+ const patchHopDraft = (patch: Partial<HopDraft>) =>
2580
+ setHopDraft((current) => ({ ...current, ...patch }));
2581
  /** ⭐ 2026-08-09 — the read-through half. `rollupMode` decides which bag `extraFor` builds;
2582
  * the two are mutually exclusive because the host's `_clean_rollup` returns the `source`
2583
  * shape before it ever reads `link`. */
 
2596
  const [rollupWhereConj, setRollupWhereConj] = useState<"and" | "or">("and");
2597
  const [rollupConditions, setRollupConditions] = useState<RollupCondition[]>([]);
2598
  const [rollupConditionConj, setRollupConditionConj] = useState<"and" | "or">("and");
2599
+ const [rollupPreset, setRollupPreset] = useState<RollupPreset | null>(null);
2600
+ const pickKind = (picked: PickerKind) => {
2601
+ const preset = picked === "count" || picked === "lookup" ? picked : null;
2602
+ setRollupPreset(preset);
2603
+ if (!preset) {
2604
+ setKind(picked as CreateKind);
2605
+ return;
2606
+ }
2607
+ setKind("rollup");
2608
+ setRollupMode("link");
2609
+ setRollupFn(ROLLUP_PRESET_FNS[preset]);
2610
+ if (preset === "count") setRollupField("");
2611
+ setRollupLimit(0);
2612
+ setRollupSortBy("");
2613
+ setRollupDistinctBy("");
2614
+ setRollupWhere([]);
2615
+ setRollupConditions([]);
2616
+ };
2617
  const [swapTo, setSwapTo] = useState("");
2618
  /** The "New field" half of Change-field keeps its own name/options — a half-typed insert
2619
  * form must not leak into a swap and vice versa. */
 
2717
  const [editLinkSelectionMode, setEditLinkSelectionMode] = useState<"manual" | "automatic">(
2718
  () => field.link?.selectionMode === "automatic" ? "automatic" : "manual"
2719
  );
2720
+ const [editHopDraft, setEditHopDraft] = useState<HopDraft>(() => hopDraftFrom(field.link));
2721
+ const patchEditHopDraft = (patch: Partial<HopDraft>) =>
2722
+ setEditHopDraft((current) => ({ ...current, ...patch }));
2723
 
2724
  const swapToNewType = swapTo.startsWith(NEW_PREFIX)
2725
  ? (swapTo.slice(NEW_PREFIX.length) as FieldType)
2726
  : null;
2727
 
2728
+ const createChoice = optionSettings(createOptionDrafts, kind, optionLimit);
2729
  const options = createChoice.options;
2730
  const swapChoice = swapToNewType
2731
+ ? optionSettings(swapOptionDrafts, swapToNewType, optionLimit)
2732
+ : { options: [] as string[], colors: {} as Record<string, string>,
2733
+ capMessage: null as string | null };
2734
  const swapNewOptions = swapChoice.options;
2735
  /** Owner item 8 — the Edit pane's parsed choices for the drafted type. */
2736
+ const editChoice = optionSettings(editOptionDrafts, editType, optionLimit);
2737
  const editOptions = editChoice.options;
2738
 
2739
  // Wave-5 item 9, amended 2026-07-31 (owner item 2) — live formula validation for BOTH
 
2780
  * permanently unable to run.
2781
  */
2782
  const addressFields = useMemo(
2783
+ () => offerableFields(fields).filter(
2784
+ (f) => (GEOCODE_ADDRESS_TYPES as readonly string[]).includes(f.type)
2785
+ ),
2786
  [fields]
2787
  );
2788
  const offerGeocode = geocodable && addressFields.length > 0;
 
2799
  // unparseable formula would be a permanently blank column, refused here rather than shipped.
2800
  const canCreate =
2801
  effectiveLabel.trim() !== "" &&
2802
+ (!needsOptions(kind) || createChoice.capMessage === null) &&
2803
  (kind !== "measure" || !!chosenMeasure) &&
2804
  // ⭐⭐ W37-T22 (R4 / C7) — a geocode column with no address column to read is a column no run
2805
  // can ever fill: the identical argument the `automation` URL-column rule below makes, and the
 
2820
  // `ai_enrich` column with no prompt, so creating one without this gate produces a column that
2821
  // is named, configured and simply absent on the next read.
2822
  (kind !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
2823
+ (kind !== "link" || (linkTable !== "" && !hopIncomplete(hopDraft, hopScopeKey))) &&
2824
  (kind !== "rollup" || (rollupMode === "source"
2825
  // ⭐ 2026-08-09 — the read-through bag. ALL FOUR keys are required by `_clean_rollup`
2826
  // (`if not (topic and measure and group_by and on): return None`), and `on` is the one a
 
2839
  t: CreateKind,
2840
  src: string,
2841
  starCount: number,
2842
+ lang: string,
2843
+ hopSource: HopDraft | null
2844
  ): FieldConfigExtra | undefined => {
2845
  if (t === "formula") return { formula: src.trim() };
2846
  if (t === "rating") return { max: starCount };
 
2882
  // picks records). The DERIVED mode is the automation's, spawned with its join declared —
2883
  // offering "join on a column of the other table" here would be a second, harder mental
2884
  // model for the same button.
2885
+ if (t === "link") {
2886
+ const via = hopVia(hopSource, hopScopeKey);
2887
+ return { link: { table: linkTable, selectionMode: linkSelectionMode,
2888
+ ...(linkSingle ? { single: true } : {}),
2889
+ ...(via ? { from: "pid", on: via.target_key, via } : {}) } };
2890
+ }
2891
  if (t === "rollup" && rollupMode === "source")
2892
  // ⛔ THE SOURCE BAG TRAVELS ALONE. `_clean_rollup` reads `source` first and returns
2893
  // immediately, so sending `link`/`fn` alongside it would ship keys the store drops —
 
2982
  onCreate(clean, kind, position === "end" ? null : field.key, position,
2983
  needsOptions(kind) ? options : undefined, undefined,
2984
  withScope({
2985
+ ...extraFor(kind, formulaText, maxValue, codeLanguage, hopDraft),
2986
  ...optionExtraFor(kind, createChoice.colors, createColorCode),
2987
  }));
2988
  onClose();
 
2991
  const canCreateSwap =
2992
  swapToNewType != null &&
2993
  swapLabel.trim() !== "" &&
2994
+ (!needsOptions(swapToNewType) || swapChoice.capMessage === null) &&
2995
  (swapToNewType !== "formula" || swapFormulaCheck.ok) &&
2996
  // ⭐⭐ Wave-34 (R13) — the SAME completeness gate `canCreate` carries, on this door too.
2997
  //
 
3014
  swapToNewType,
3015
  needsOptions(swapToNewType) ? swapNewOptions : undefined,
3016
  withScope({
3017
+ ...extraFor(swapToNewType, swapFormulaText, swapMaxValue, swapCodeLanguage, null),
3018
  ...optionExtraFor(swapToNewType, swapChoice.colors, swapColorCode),
3019
  })
3020
  );
 
3073
  // and silently drop the half-finished type change beside it.
3074
  const editBlocked =
3075
  (editRetypeTouched && !editRetypeValid) ||
3076
+ (editFormulaTouched && !editFormulaCheck.ok) ||
3077
+ (needsOptions(editType) && editChoice.capMessage !== null);
3078
  // Item 21 (2026-08-02) — the PERIOD moved into this pane, so its dirty-check has to be
3079
  // computed before the pane's save gate rather than beside the menu's own button. Same three
3080
  // lines, hoisted: `canSaveEdit` reads `periodChanged`, and a `const` read before its
 
3126
  ? JSON.stringify(editRollup) !== JSON.stringify(field.rollup ?? {})
3127
  : editLinkTable !== (field.link?.table ?? "") ||
3128
  editLinkSingle !== (field.link?.single === true) ||
3129
+ editLinkSelectionMode !== (field.link?.selectionMode === "automatic" ? "automatic" : "manual") ||
3130
+ JSON.stringify(hopVia(editHopDraft, hopScopeKey)) !==
3131
+ JSON.stringify(hopVia(hopDraftFrom(field.link), hopScopeKey)));
3132
  const canSaveEdit =
3133
  /**
3134
  * ⭐ W41-T31 — THE DESCRIPTION-ONLY PANE'S WHOLE SAVE CONDITION, and it is one dirty flag
 
3154
  (editType !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
3155
  (editingRelational
3156
  ? (editRollupValid && (editRelationalTouched || editNameDirty || editNoteDirty) &&
3157
+ (field.type !== "link" ||
3158
+ (editLinkTable !== "" && !hopIncomplete(editHopDraft, hopScopeKey))))
3159
  : (editNameDirty || editRetypeTouched || editFormulaTouched ||
3160
  (canPeriod && periodChanged) || editNoteDirty)));
3161
  /**
 
3194
  */
3195
  if (!canEditDescription &&
3196
  editingRelational && onFieldConfig && (editRelationalTouched || editNameDirty)) {
3197
+ const editVia = hopVia(editHopDraft, hopScopeKey);
3198
  // ⛔ THE WHOLE BAG, EVERY SAVE. `_clean_rollup` is a pure cleaner over what it receives —
3199
  // it does not merge with the stored bag — so a partial patch is a REBUILD, and an omitted
3200
  // `limit` would silently become "no limit" rather than "unchanged".
 
3204
  ? { rollup: editRollup as Record<string, unknown> }
3205
  : { link: { table: editLinkTable,
3206
  selectionMode: editLinkSelectionMode,
3207
+ ...(field.link?.on
3208
+ ? { on: field.link.on }
3209
+ : editVia ? { on: editVia.target_key } : {}),
3210
+ ...(field.link?.from
3211
+ ? { from: field.link.from }
3212
+ : editVia ? { from: "pid" } : {}),
3213
+ ...(editLinkSingle ? { single: true } : {}),
3214
+ ...(editVia ? { via: editVia } : {}) } }),
3215
  });
3216
  if (editNoteDirty) onNote(note);
3217
  onClose();
 
3294
  * would contain; `swapOffered` is whether the picker exists at all, and it is read twice (the
3295
  * control itself, and the focus fallback that has to know whether the control is there).
3296
  */
3297
+ const swapOptions = offerableFields(fields).filter((f) => f.key !== field.key);
3298
  const presetSwap = swapOptions.filter((f) => f.source === "odoo" && !f.custom);
3299
  const yourSwap = swapOptions.filter((f) => !(f.source === "odoo" && !f.custom));
3300
  const swapOffered = offer.swap && swapOptions.length > 0;
 
3426
  onAccept={(proposal: FieldProposal) => {
3427
  setLabel(proposal.label);
3428
  setLabelTouched(true);
3429
+ pickKind(proposal.kind);
3430
  if (proposal.options && proposal.options.length)
3431
  setCreateOptionDrafts(optionDrafts(proposal.options));
3432
  setAskAgent(false);
 
3463
  rows, Airtable-style. The measure row appears exactly when the host offers
3464
  measures — the same availability rule as the filter's measure conditions. */}
3465
  <TypePicker
3466
+ value={rollupPreset ?? kind}
3467
+ onPick={pickKind}
3468
  offerMeasure={measures.length > 0}
3469
  offerGeocode={offerGeocode}
3470
+ offerPresets
3471
+ isUserTable={isUserTable}
3472
  />
3473
  </div>
3474
  {kind === "measure" && (
 
3573
  onLinkSingle={setLinkSingle}
3574
  linkSelectionMode={linkSelectionMode}
3575
  onLinkSelectionMode={setLinkSelectionMode}
3576
+ hop={{
3577
+ topics: hopTopics,
3578
+ windows: hopTopicOffer.windows,
3579
+ scopeKey: hopScopeKey,
3580
+ draft: hopDraft,
3581
+ onDraft: patchHopDraft,
3582
+ }}
3583
+ rollupPreset={rollupPreset}
3584
  rollupMode={rollupMode}
3585
  onRollupMode={setRollupMode}
3586
  rollupSourceOffer={rollupSourceOffer}
 
3625
  colorCode={createColorCode}
3626
  onColorCode={setCreateColorCode}
3627
  type={kind}
3628
+ maxOptions={optionLimit}
3629
  />
3630
  )}
3631
  {kind === "user" && (
 
3875
  onLinkSingle={setEditLinkSingle}
3876
  linkSelectionMode={editLinkSelectionMode}
3877
  onLinkSelectionMode={setEditLinkSelectionMode}
3878
+ hop={{
3879
+ topics: hopTopics,
3880
+ windows: hopTopicOffer.windows,
3881
+ scopeKey: hopScopeKey,
3882
+ draft: editHopDraft,
3883
+ onDraft: patchEditHopDraft,
3884
+ }}
3885
+ rollupPreset={rollupPresetOf(editRollup)}
3886
  rollupSourceOffer={rollupSourceOffer}
3887
  rollupMode={editRollup.source ? "source" : "link"}
3888
  // ⛔ A MODE SWITCH REPLACES THE BAG, it does not merge into it. `_clean_rollup`
 
3968
  value={editType}
3969
  onPick={(k) => setEditType(k as FieldType)}
3970
  offerMeasure={false}
3971
+ offerPresets={false}
3972
+ isUserTable={isUserTable}
3973
  offerGeocode={
3974
  /* ⛔ FALSE ON PURPOSE, and stated rather than omitted: this is the RETYPE
3975
  picker, and a geocode column is not a type an existing column can BECOME.
 
4065
  colorCode={editColorCode}
4066
  onColorCode={setEditColorCode}
4067
  type={editType}
4068
+ maxOptions={optionLimit}
4069
  />
4070
  )}
4071
  {editType !== field.type && (
 
4238
  colorCode={swapColorCode}
4239
  onColorCode={setSwapColorCode}
4240
  type={swapToNewType}
4241
+ maxOptions={optionLimit}
4242
  />
4243
  )}
4244
  {swapToNewType === "user" && (
 
4539
  * `preset`, its Delete goes — which is R6(a) working, and worth a look before the wave closes.
4540
  */
4541
  const fieldC1 = fieldClassOf(field);
4542
+ const deletionLocked = fieldDeletionLocked(field);
4543
  const presetRefusal = deleteRefusalReason(fieldC1, viewer);
4544
  const canRemoveFromMine = mayRemoveField(fieldC1, viewer);
4545
  const rightsKnown = fieldC1 !== null && !!viewer;
4546
  const c1AllowsDelete =
4547
+ !deletionLocked && !presetRefusal && !canRemoveFromMine &&
4548
+ (!rightsKnown || mayDeleteFieldRight(fieldC1, viewer));
4549
  const deleteImpact = deleteImpactTitle(fieldC1, fieldUsageOf(field));
4550
 
4551
  return (
 
4559
  dataKind="column-menu"
4560
  >
4561
  <PaneHead title={field.label} sub={typeLine} onClose={onClose} />
4562
+ <FieldProperties field={field} />
4563
 
4564
  {/* Item 8c — any measure-carrying column exposes its PERIOD, the property that defines
4565
  it. Item 21 (2026-08-02) moved the EDITOR into the Edit-field pane; what stays here
 
4616
  row would leave a collaborator guessing why the column they can see is not theirs to
4617
  pass on. The one thing that DOES withdraw it is a missing server table key, because
4618
  without one the id cannot be built. */}
4619
+ {onSetDeletionLock && (
4620
+ <button type="button" onClick={() => onSetDeletionLock(!deletionLocked)}>
4621
+ <MenuLabel
4622
+ icon={deletionLocked ? "unlock" : "permissions"}
4623
+ text={deletionLocked ? "Clear deletion lock" : "Lock deletion"}
4624
+ />
4625
+ </button>
4626
+ )}
4627
+ {onCopyFieldLink && (
4628
+ <button type="button" onClick={onCopyFieldLink}>
4629
+ <MenuLabel icon="duplicate" text="Copy link to field" />
4630
+ </button>
4631
+ )}
4632
+
4633
  {shareOid && (
4634
  <button
4635
  type="button"
 
4733
  <div className="cg-menu-sep" role="separator" aria-hidden />
4734
 
4735
  {/* Group 3 — sort. Direction wording stays the shipped per-type directionLabel. */}
4736
+ {onSort && fieldOfferable && <>
4737
+ <button type="button" onClick={() => { onSort("asc"); onClose(); }}>
4738
+ <MenuLabel
4739
+ icon="sortAsc"
4740
+ text={`Sort ${directionLabel(field.type, "asc")}`}
4741
+ />
4742
+ </button>
4743
+ <button type="button" onClick={() => { onSort("desc"); onClose(); }}>
4744
+ <MenuLabel
4745
+ icon="sortDesc"
4746
+ text={`Sort ${directionLabel(field.type, "desc")}`}
4747
+ />
4748
+ </button>
4749
+ </>}
4750
+ {onClearSort && sortedDir != null && (
4751
  <button type="button" onClick={() => { onClearSort(); onClose(); }}>
4752
  <MenuLabel icon="off" text="Don't sort by this field" />
4753
  </button>
 
4761
  column itself (offered only while the host serves measures, the same
4762
  availability rule as measure conditions). Everything else keeps the plain
4763
  filterable check. */}
4764
+ {onFilterBy && fieldOfferable && (field.filterable !== false ||
4765
  (field.measure != null && measures.length > 0)) && (
4766
  <button type="button" onClick={() => { onFilterBy(); onClose(); }}>
4767
  <MenuLabel icon="filter" text="Filter by this field" />
4768
  </button>
4769
  )}
4770
+ {onClearFilter && isFiltered && (
4771
  <button type="button" onClick={() => { onClearFilter(); onClose(); }}>
4772
  <MenuLabel icon="off" text="Don't filter by this field" />
4773
  </button>
 
4898
  {presetRefusal}
4899
  </p>
4900
  )}
4901
+ {deletionLocked && !schemaLocked && offer.remove && onDelete && (
4902
+ <p className="cg-field-hint" style={{ padding: "2px 8px 4px" }}>
4903
+ Deletion is locked. An Owner must clear the deletion lock before this field can be deleted.
4904
+ </p>
4905
+ )}
4906
  {!schemaLocked && offer.remove && onDelete && c1AllowsDelete && (
4907
  <button
4908
  type="button"
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -7,6 +7,7 @@ import {
7
  useRef,
8
  useState,
9
  } from "react";
 
10
  import { DataEditor, GridCellKind } from "@glideapps/glide-data-grid";
11
  import type {
12
  CellClickedEventArgs,
@@ -94,9 +95,9 @@ import { API_V1, CREDENTIALS, NAV_MINIMIZE_EVENT, ROWS_STALE_EVENT, TOAST_EVENT,
94
  from "../apiContract";
95
  import type { ViewOpenDetail } from "../apiContract";
96
  import { addTableField, addTableRow, clearTopicRowsCache, deleteRouteOrderField, deleteTableField,
97
- deleteTableRow, dropTableRowsCache, fetchLinkTargets, refusalMessage,
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";
@@ -104,8 +105,11 @@ import type { FormSpec } from "./FormInterface";
104
  // Owner item 16 / R4 / C-UNDO — the stack and every inverse. Pure, so a node gate can run it.
105
  import { describe, directed, popRedo, popUndo, pushUndo, stackFor } from "./undoStack";
106
  import type { CellChange, UndoBook, UndoEntry, UndoRow, UndoValue } from "./undoStack";
107
- import { exportFilename, groupingApplies, runExport, toExportGroups, triggerDownload } from "./export";
108
  import type { ExportFormat, ExportGrouping } from "./export";
 
 
 
109
  // owner item 3 (2026-08-03) — a time-series view exports its SHEET, not the rows under it.
110
  import { buildTsCsv, tsSheetToTable } from "./timeSeriesData";
111
  import type { TsSheet } from "./timeSeriesData";
@@ -137,6 +141,7 @@ import type { RouteSourceView } from "./MapView";
137
  /* ═══ W18-C CATALOG ═══ (owner item 4, contract C6) */
138
  import { CatalogView } from "./CatalogView";
139
  import { GalleryView, TimelineView } from "./GalleryTimelineViews";
 
140
  import { CATALOG_CODE_FIELD } from "./catalogData";
141
  import type { CatalogSpec } from "./types";
142
  /* ═══ end W18-C CATALOG ═══ */
@@ -170,6 +175,7 @@ import { ALL_VIEW_ID, MAX_CALENDAR_METRICS, allViewName,
170
  measureColumnIndex, ratingMax, ruleColumnKeys,
171
  shouldAdoptEmbeddedSelection,
172
  tableMode, uniqueDisplayName,
 
173
  /* ⭐ W41-T38 — the rail's OWN name resolver, so a collision test compares what the reader
174
  actually sees. The rail has always drawn `viewDisplayName(view)`; `renameView` was testing
175
  `view.name`, and for the default view those two are different strings. */
@@ -181,7 +187,7 @@ import { ALL_VIEW_ID, MAX_CALENDAR_METRICS, allViewName,
181
  and only consumed here, because W41-T43 (this file) and W41-T44 (`RecordDetail.tsx`) open the
182
  same feature through other doors and neither of them may edit `types.ts`. */
183
  import { buildPivotRequest, cleanSecondaryView, emptyViewConfig, PIVOT_PATH, PIVOT_WINDOW_LABELS,
184
- pivotResponse, relationalTargets } from "./types";
185
  import type {
186
  DisplayMode,
187
  DisplaySpec,
@@ -192,10 +198,12 @@ import type {
192
  FilterNode,
193
  FilterRule,
194
  PivotResponse,
 
195
  PivotWindow,
196
  Row,
197
  RowHeightMode,
198
  SavedView,
 
199
  ViewConfig,
200
  } from "./types";
201
  // Item 7 (C-TS). Default-exported because it is a leaf VIEW like MapView, and because RECORD
@@ -443,6 +451,61 @@ function sameConfig(a: ViewConfig, b: ViewConfig): boolean {
443
  return JSON.stringify(a) === JSON.stringify(b);
444
  }
445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
446
  /**
447
  * ⭐ W41-T42 — the pivot's four states, and the fourth one is the point.
448
  *
@@ -455,6 +518,7 @@ type PivotState =
455
  | { status: "idle" }
456
  | { status: "loading" }
457
  | { status: "absent" }
 
458
  | { status: "ok"; answer: PivotResponse };
459
 
460
  /**
@@ -632,6 +696,177 @@ function withColorField(config: ViewConfig, key: string): ViewConfig {
632
  return { ...config, colorBy: key || null, display: cleanDisplay(display) };
633
  }
634
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
635
  function readLocal(storageKey: string): LocalWorkspace | null {
636
  try {
637
  const raw = localStorage.getItem(`aios-grid:${storageKey}`);
@@ -926,6 +1161,17 @@ function buildOverlayField(
926
  * re-renders for its own state (edits, resize) and remounts on route change via `key`. */
927
  interface CustomerGridProps {
928
  scope?: SurfaceScope;
 
 
 
 
 
 
 
 
 
 
 
929
  /** A Query-owned immutable artefact. `scope` remains the renderer's mapped data scope. */
930
  queryBinding?: QueryVirtualBinding;
931
  /** Read-only Grid view embedded in a linked-record modal. It keeps the standard
@@ -937,6 +1183,25 @@ interface CustomerGridProps {
937
  embeddedSelectable?: boolean;
938
  embeddedSelectedIds?: readonly number[];
939
  onEmbeddedSelectionChange?: (recordIds: number[]) => void;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
940
  }
941
 
942
  interface LinkGridModalProps {
@@ -945,12 +1210,13 @@ interface LinkGridModalProps {
945
  recordIds: readonly number[];
946
  editable?: boolean;
947
  single?: boolean;
 
948
  onSave?: (recordIds: number[]) => void;
949
  onClose: () => void;
950
  }
951
 
952
  function LinkGridModal({ label, table, recordIds, editable = false, single = false,
953
- onSave, onClose }: LinkGridModalProps) {
954
  const panelRef = useRef<HTMLDivElement>(null);
955
  const [selectedIds, setSelectedIds] = useState<number[]>(() => [...recordIds]);
956
  const changeSelectedIds = useCallback((ids: number[]) => {
@@ -1002,6 +1268,7 @@ function LinkGridModal({ label, table, recordIds, editable = false, single = fal
1002
  scope={table}
1003
  embedded
1004
  embeddedRecordIds={editable ? undefined : recordIds}
 
1005
  embeddedSelectable={editable}
1006
  embeddedSelectedIds={selectedIds}
1007
  onEmbeddedSelectionChange={changeSelectedIds}
@@ -1072,12 +1339,23 @@ function CustomerGrid(props: CustomerGridProps = {}) {
1072
 
1073
  function CustomerGridSurface({
1074
  scope = "customer",
 
 
 
 
 
 
 
 
 
 
1075
  queryBinding,
1076
  embedded = false,
1077
  embeddedRecordIds,
1078
  embeddedSelectable = false,
1079
  embeddedSelectedIds = [],
1080
  onEmbeddedSelectionChange,
 
1081
  }: CustomerGridProps = {}) {
1082
  const isQueryPreview = queryBinding !== undefined;
1083
  /**
@@ -1144,16 +1422,19 @@ function CustomerGridSurface({
1144
  */
1145
  const [pendingRows, setPendingRows] = useState<Row[]>([]);
1146
  const rawRows = useMemo(() => {
1147
- const base = embeddedRecordIds
1148
  ? fetchedRows.filter((row) => new Set(embeddedRecordIds).has(row.pid))
1149
  : fetchedRows;
 
 
 
1150
  if (!pendingRows.length) return base;
1151
  const known = new Set(base.map((r) => r.pid));
1152
  const extra = pendingRows.filter((r) => !known.has(r.pid));
1153
  return extra.length ? [...base, ...extra] : base;
1154
  // The scalar key keeps this stable when a caller reconstructs the same id list.
1155
  // eslint-disable-next-line react-hooks/exhaustive-deps
1156
- }, [fetchedRows, embeddedIdsKey, pendingRows]);
1157
  useEffect(() => {
1158
  // ⚠ PRUNED AGAINST THE FETCHED PAYLOAD, not against `rawRows` — `rawRows` contains the
1159
  // pending rows, so it can never report that one has been absorbed. Pruning against the
@@ -1264,6 +1545,9 @@ function CustomerGridSurface({
1264
  const [views, setViews] = useState<SavedView[]>([]);
1265
  const [activeViewId, setActiveViewId] = useState(ALL_VIEW_ID);
1266
  const [config, setConfig] = useState<ViewConfig>(() => defaultViewConfig([]));
 
 
 
1267
  /** W36-T02 — the live `config`, readable from an effect that must not DEPEND on it. The
1268
  * after-mount reconcile needs to know whether an edit is unsaved before it re-seeds the open
1269
  * view; taking `config` as a dependency would re-run that whole pass on every drag and
@@ -1832,6 +2116,20 @@ function CustomerGridSurface({
1832
  },
1833
  [config.groupBy, isQueryPreview, queryBinding]
1834
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1835
  useEffect(() => {
1836
  if (!config.fullscreen) return;
1837
  const onKey = (event: KeyboardEvent) => {
@@ -1932,6 +2230,19 @@ function CustomerGridSurface({
1932
  const isUserTable = !embedded && scope.startsWith("ut_");
1933
  const recordsMutable = payload?.recordsMutable !== false;
1934
  const canMutateRecords = isUserTable && recordsMutable;
 
 
 
 
 
 
 
 
 
 
 
 
 
1935
  /**
1936
  * ⭐ 2026-08-07 — the databases a `link` column may point at, fetched when the column menu
1937
  * OPENS rather than on every render of the grid.
@@ -1992,6 +2303,25 @@ function CustomerGridSurface({
1992
  live = false;
1993
  };
1994
  }, [columnMenu, plusMenu]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1995
  /**
1996
  * ⭐ WAVE 27 · OWNER ITEM 22 — the values the ACTIVE VIEW forces on a new record.
1997
  *
@@ -2184,6 +2514,12 @@ function CustomerGridSurface({
2184
  useEffect(() => {
2185
  if (displayMode !== "map") setRoutePanelOpen(false);
2186
  }, [displayMode]);
 
 
 
 
 
 
2187
 
2188
  // ═══════════════════════════════════════════════════════════════════════════════════════
2189
  // ⭐⭐ WAVE 30 · W30-T42 (contract C2) — PAGING A READ-THROUGH GRID.
@@ -2449,6 +2785,10 @@ function CustomerGridSurface({
2449
  */
2450
  const applyFilters = useCallback(
2451
  (filters: FilterNode[]) => {
 
 
 
 
2452
  const id = activeViewId;
2453
  if (id) {
2454
  const cycle = viewFilterCycle(id, filters, (other) =>
@@ -2504,6 +2844,12 @@ function CustomerGridSurface({
2504
  : computedRows,
2505
  [cohortMode, computedRows, cohortMemberSet]
2506
  );
 
 
 
 
 
 
2507
 
2508
  const { visibleRows, pidToIndex } = useVisibleRows(
2509
  scopedRows,
@@ -2514,7 +2860,7 @@ function CustomerGridSurface({
2514
  // grouping a WINDOW would headline a page's count/subtotals as the group's
2515
  serverWindowed ? null : config.groupBy,
2516
  collapsed,
2517
- config.memberPids,
2518
  config.filterConj,
2519
  serverWindowed,
2520
  measureSets,
@@ -4223,7 +4569,7 @@ function CustomerGridSurface({
4223
  if (!row) return;
4224
  // Owner item 10: clicking into the cells is "I am working now" — the frame folds its
4225
  // navigation rail to the slim strip (a no-op in the embed; the shell listens).
4226
- signal(NAV_MINIMIZE_EVENT);
4227
  if (row.kind === "group-header") {
4228
  event.preventDefault();
4229
  setCollapsed((current) => {
@@ -4286,7 +4632,7 @@ function CustomerGridSurface({
4286
  // The large modal mounts the same Grid surface over exactly these pids, so its standard
4287
  // search, Filters, Sort, Fields, and column menus keep working for every database kind.
4288
  if (row.kind === "data" && field?.type === "link" && field.link?.table) {
4289
- if (field.link.table.startsWith("ut_")) {
4290
  event.preventDefault();
4291
  setActiveCell(cell[0], cell[1]);
4292
  setLinkAt({ pid: row.record.pid, fieldKey: field.key });
@@ -4361,10 +4707,10 @@ function CustomerGridSurface({
4361
  const row = displayRows[cell[1]];
4362
  const column = visibleCols[cell[0]];
4363
  const field = column ? fieldByKey.get(column.id!) : undefined;
4364
- if (row?.kind === "data" && field?.source !== "overlay")
4365
  setDetailPid(row.record.pid);
4366
  },
4367
- [displayRows, visibleCols, fieldByKey]
4368
  );
4369
  const onCellEdited = useCallback(
4370
  (cell: Item, value: EditableGridCell) => {
@@ -4763,6 +5109,12 @@ function CustomerGridSurface({
4763
  setSearch("");
4764
  setDetailPid(null);
4765
  setDisplayCap(DISPLAY_PAGE);
 
 
 
 
 
 
4766
  // Owner item 3 (2026-07-31): tell the host WHERE THE USER IS, so a fresh browser (no
4767
  // localStorage copy) resumes on this view instead of the system default. Presentation
4768
  // state — the host stores the id and the read side re-validates it.
@@ -4771,9 +5123,16 @@ function CustomerGridSurface({
4771
  signal(NAV_MINIMIZE_EVENT);
4772
  },
4773
  [views, activeViewId, config, persistView, fields, isQueryPreview, recordStars.stars.view,
4774
- scriptProjections]
4775
  );
4776
 
 
 
 
 
 
 
 
4777
  /**
4778
  * A-S4-3 (item 25) — a notification's click-through. The SHELL routes to the table and fires
4779
  * this; the GRID owns view selection, so neither learns the other's state.
@@ -4793,6 +5152,32 @@ function CustomerGridSurface({
4793
  window.addEventListener(VIEW_OPEN_EVENT, onOpen);
4794
  return () => window.removeEventListener(VIEW_OPEN_EVENT, onOpen);
4795
  }, [scope, views, selectView]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4796
  const createView = useCallback(
4797
  (name: string, mode: DisplayMode, permissions: ViewPermissions) => {
4798
  if (queryBinding) {
@@ -5058,7 +5443,7 @@ function CustomerGridSurface({
5058
  // Never echo the SOURCE's creator: the host stamps and ignores what the browser
5059
  // sends, but sending someone else's name is a laundering attempt on its face.
5060
  createdBy: undefined,
5061
- config: { ...source.config },
5062
  };
5063
  persistView(copy);
5064
  setActiveViewId(copy.id);
@@ -5725,6 +6110,78 @@ function CustomerGridSurface({
5725
  [views, fields, computedRows, exportRows, activeViewId, today]
5726
  );
5727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5728
  /**
5729
  * The selection bar's "Add to locked view": exactly the CHECKED customers, not a view's
5730
  * matches.
@@ -6101,6 +6558,20 @@ function CustomerGridSurface({
6101
  [isUserTable, scope]
6102
  );
6103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6104
  /**
6105
  * Owner item 9 — "Change field": the clicked column starts showing another field, in place.
6106
  * The new field takes the old one's slot in `order`; the old field is HIDDEN, not lost — it
@@ -6140,17 +6611,7 @@ function CustomerGridSurface({
6140
  const f = fieldByKey.get(key);
6141
  if (!f?.custom || key === lockedKey) return;
6142
  setFields((current) => current.filter((item) => item.key !== key));
6143
- const nextWidths = { ...(config.widths ?? {}) };
6144
- delete nextWidths[key];
6145
- updateConfig({
6146
- ...config,
6147
- order: order.filter((k) => k !== key),
6148
- visible: [...visible].filter((k) => k !== key),
6149
- widths: nextWidths,
6150
- sorts: (config.sorts ?? []).filter((s) => s.colId !== key),
6151
- groupBy: config.groupBy === key ? null : config.groupBy,
6152
- colorBy: config.colorBy === key ? null : config.colorBy,
6153
- });
6154
  stampFieldDelete(key);
6155
  emitHostEvent({ id: eventId("fielddel"), type: "field_delete", key });
6156
  },
@@ -6193,17 +6654,7 @@ function CustomerGridSurface({
6193
  void deleteRouteOrderField(key).then((ok) => {
6194
  if (!ok) return; // the bridge has already said why
6195
  setFields((current) => current.filter((item) => item.key !== key));
6196
- const nextWidths = { ...(config.widths ?? {}) };
6197
- delete nextWidths[key];
6198
- updateConfig({
6199
- ...config,
6200
- order: order.filter((k) => k !== key),
6201
- visible: [...visible].filter((k) => k !== key),
6202
- widths: nextWidths,
6203
- sorts: (config.sorts ?? []).filter((s) => s.colId !== key),
6204
- groupBy: config.groupBy === key ? null : config.groupBy,
6205
- colorBy: config.colorBy === key ? null : config.colorBy,
6206
- });
6207
  // ⛔ AND THE ROWS CACHE, for the reason `revealRouteField` states above: the values went
6208
  // with the definition (`shared_overlay.drop_field` scrubs the cells), so a refetch served
6209
  // from the pre-delete window would repaint the numbers of a column that no longer exists.
@@ -6255,17 +6706,7 @@ function CustomerGridSurface({
6255
  void deleteTableField(scope, key).then((ok) => {
6256
  if (!ok) return; // the bridge has already said why
6257
  setFields((current) => current.filter((item) => item.key !== key));
6258
- const nextWidths = { ...(config.widths ?? {}) };
6259
- delete nextWidths[key];
6260
- updateConfig({
6261
- ...config,
6262
- order: order.filter((k) => k !== key),
6263
- visible: [...visible].filter((k) => k !== key),
6264
- widths: nextWidths,
6265
- sorts: (config.sorts ?? []).filter((s) => s.colId !== key),
6266
- groupBy: config.groupBy === key ? null : config.groupBy,
6267
- colorBy: config.colorBy === key ? null : config.colorBy,
6268
- });
6269
  signal(WORKSPACE_STALE_EVENT);
6270
  signal(ROWS_STALE_EVENT);
6271
  });
@@ -7166,7 +7607,9 @@ function CustomerGridSurface({
7166
  });
7167
  if (!live) return;
7168
  if (!res.ok) {
7169
- setPivot({ status: "absent" });
 
 
7170
  return;
7171
  }
7172
  const answer = pivotResponse(await res.json().catch(() => null));
@@ -7183,6 +7626,22 @@ function CustomerGridSurface({
7183
  };
7184
  }, [pivotRequestBody]);
7185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7186
  if (loading || !workspaceReady) {
7187
  /* wave17 GRID — item 3 / owner R6: one small bare rotating icon, NO WORDS. `aria-label`
7188
  is not a word on screen and stays: `.lp-spin` is an empty span, so without it the wait
@@ -7203,13 +7662,15 @@ function CustomerGridSurface({
7203
  name: viewDisplayName(activeView),
7204
  // The API compares this complete saved config to its visible View and mints the durable
7205
  // revision itself. A browser may carry provenance, never choose it.
7206
- config: activeView.config,
7207
  }
7208
  : null;
 
 
7209
  // Cohort mode's toolbar control (rendered by Toolbar via the `cohortAction` slot; the popover
7210
  // it opens is with the other overlays at the bottom). Disabled without an active cohort —
7211
  // zero cohorts is the host page's near-empty state, not this button's error to explain.
7212
- const cohortAction = cohortMode ? (
7213
  <button
7214
  type="button"
7215
  className="cg-tb-btn cg-tb-addcust"
@@ -7247,7 +7708,11 @@ function CustomerGridSurface({
7247
  */
7248
  const deletableKeys = new Set(
7249
  fields
7250
- .filter((f) => (f.custom || (f.shared && f.kind === "route_order")) && f.key !== lockedKey)
 
 
 
 
7251
  .map((f) => f.key)
7252
  );
7253
  const menuField = columnMenu ? fieldByKey.get(columnMenu.fieldKey) : undefined;
@@ -7327,6 +7792,9 @@ function CustomerGridSurface({
7327
  ?? (linkField && linkRow ? linkRow[linkField.key] : "")
7328
  ?? ""
7329
  );
 
 
 
7330
  const linkedRecordIds = [...new Set(
7331
  linkValue.split(",").map((part) => Number(part.trim())).filter(
7332
  (pid) => Number.isInteger(pid) && pid > 0
@@ -7436,7 +7904,9 @@ function CustomerGridSurface({
7436
 
7437
  const pivotOn = !!secondary;
7438
  const pivotAnswer = pivot.status === "ok" ? pivot.answer : null;
7439
- const pivotRefusal = pivotAnswer?.refusal ?? null;
 
 
7440
  /**
7441
  * ⭐ W41-T43 — THE SAVED PIVOT NAMES A LINK COLUMN THIS READER WAS NOT SERVED. No request went
7442
  * out (`pivotRequestBody` is empty), so `pivot` stays `idle` and every other branch below is
@@ -7524,7 +7994,14 @@ function CustomerGridSurface({
7524
  */
7525
  const secondaryToolbar = pivotOn && pivotServed && secondary ? (
7526
  <Toolbar
 
7527
  nouns={pivotTarget?.label ?? "records"}
 
 
 
 
 
 
7528
  sourceLabel={topic.nouns}
7529
  fields={pivotFields}
7530
  visible={pivotVisible}
@@ -7606,6 +8083,15 @@ function CustomerGridSurface({
7606
  `QueryPage`. */}
7607
  {!hideViews && (
7608
  <ViewSidebar
 
 
 
 
 
 
 
 
 
7609
  /* ⭐⭐ W36-T05 (owner item 6 · R3 · R14) — the View agent, and the ONE class that
7610
  folds the main rail. ⛔ `null` when closed, never a hidden node: `index.css` folds
7611
  on `.shell-root:has(.cg-agent-panel)`, and `:has()` matches what EXISTS. */
@@ -7696,6 +8182,10 @@ function CustomerGridSurface({
7696
  onAddToList={serverWindowed ? undefined : addToList}
7697
  today={today}
7698
  onExport={serverWindowed ? undefined : exportViewData}
 
 
 
 
7699
  folders={folders}
7700
  folderIdOf={folderIdOf}
7701
  /**
@@ -7978,7 +8468,14 @@ function CustomerGridSurface({
7978
  )}
7979
  <main className="cg-main">
7980
  <Toolbar
 
7981
  nouns={topic.nouns}
 
 
 
 
 
 
7982
  // Item 12 (C-LOCK) — the banner's copy. ⚠ BOTH fields are omitted when this reader
7983
  // cannot see the locked set, and that omission is the SIGNAL, not an oversight: it
7984
  // is what selects RECORD's second sentence ("locked to a set you cannot see").
@@ -8045,9 +8542,35 @@ function CustomerGridSurface({
8045
  filters={config.filters}
8046
  onFilters={applyFilters}
8047
  filterConj={config.filterConj ?? "and"}
8048
- onFilterConj={(filterConj) => updateConfig({ ...config, filterConj })}
 
 
 
 
 
 
 
8049
  sorts={config.sorts}
8050
- onSorts={(sorts) => updateConfig({ ...config, sorts })}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8051
  // the toolbar must not advertise a grouping the pipeline is not applying
8052
  groupBy={serverWindowed ? null : config.groupBy}
8053
  onGroupBy={(groupBy) => updateConfig({ ...config, groupBy })}
@@ -8094,15 +8617,9 @@ function CustomerGridSurface({
8094
  onRelationalWindow={setPivotWindow}
8095
  sourceLabel={topic.nouns}
8096
  onViewActions={setViewActionsAnchor}
 
 
8097
  />
8098
- <button
8099
- type="button"
8100
- className="cg-fullscreen-toggle"
8101
- aria-pressed={!!config.fullscreen}
8102
- onClick={() => updateConfig({ ...config, fullscreen: !config.fullscreen })}
8103
- >
8104
- {config.fullscreen ? "Exit fullscreen" : "Fullscreen"}
8105
- </button>
8106
  {/* ⭐ R11's SECOND ROW — live, on the pivoted database. It renders only once the pivot has
8107
  actually been SERVED, which is the house posture for a control whose other half may
8108
  not be wired yet: absent beats present-and-inert. A control row over a database whose
@@ -8121,11 +8638,10 @@ function CustomerGridSurface({
8121
  onToggleRoute={() => setRoutePanelOpen((open) => !open)}
8122
  />
8123
  )}
8124
- {/* ⭐⭐ WAVE 42 · W42-T19 (owner instruction 11) — CALENDAR'S SECOND ROW, MOUNTED EMPTY IN
8125
- THE BASELINE COMMIT. `CalendarSettings` renders `null` until lane D fills it; the mount
8126
- lands here, now, because this file belongs to a DIFFERENT lane and a cross-lane mount is
8127
- exactly how wave 41 shipped features nothing ever rendered. Same position and the same
8128
- guard shape as `MapSettings` directly above, which is the pattern the owner named. */}
8129
  {displayMode === "calendar" && !pivotOn && (
8130
  <CalendarSettings
8131
  dateField={calendarField}
@@ -8359,7 +8875,7 @@ function CustomerGridSurface({
8359
  * a record that then appears twice while scrolling, which reads as duplicated data
8360
  * rather than as a layout bug.
8361
  */
8362
- freezeTrailingRows={showTotals ? 1 : 0}
8363
  rowHeight={rowHeight}
8364
  headerHeight={36}
8365
  rowMarkers="both"
@@ -8837,6 +9353,12 @@ function CustomerGridSurface({
8837
  routePanelOpen={routePanelOpen}
8838
  activeView={routeSourceView}
8839
  tableKey={topic.key}
 
 
 
 
 
 
8840
  /* ⭐ OWNER ITEM 9 — the route's "Add a record" search reaches PAST the view's own
8841
  filter, so it is handed `scopedRows`: the book after the row wall (`allowed_pids`
8842
  plus the business-unit scope) and before `useVisibleRows` applies filters, search
@@ -9055,7 +9577,7 @@ function CustomerGridSurface({
9055
  : `Delete ${selectedPids.size === 1 ? "record" : "records"}`}
9056
  </button>
9057
  )}
9058
- {cohortMode ? (
9059
  // Item 2c: on the Cohort page the selection EDITS MEMBERSHIP of the fixed set —
9060
  // "Remove from cohort" replaces "Add to cohort". Direct (no popover): the
9061
  // checked set is explicit, the button says what it does, and re-adding is one
@@ -9088,13 +9610,13 @@ function CustomerGridSurface({
9088
  >
9089
  Add to cohort
9090
  </button>
9091
- )}
9092
  {/* ⭐ Owner item 9 — the counterpart, and it renders ONLY when it can do
9093
  something: the checked rows have to be in a cohort this viewer may edit for
9094
  "Remove from cohort…" to mean anything. Same bar, same selection, opposite
9095
  direction — the ellipsis says a picker follows, because unlike cohort mode
9096
  the target is not implied by where you are standing. */}
9097
- {!cohortMode && removableLists.length > 0 && (
9098
  <button
9099
  type="button"
9100
  className="cg-btn cg-selbar-remove-pick"
@@ -9208,6 +9730,7 @@ function CustomerGridSurface({
9208
  */
9209
  linkTargets={linkTargets}
9210
  rollupSourceOffer={rollupSourceOffer}
 
9211
  locked={menuField.key === lockedKey}
9212
  schemaLocked={isSchemaLocked(menuField)}
9213
  /* ⭐⭐ W40-T24 — the menu's `columnDefinitionOffer` (display.ts) needs the same stratum
@@ -9266,6 +9789,12 @@ function CustomerGridSurface({
9266
  }
9267
  onProfileFlag={isUserTable ? setProfileFlag : undefined}
9268
  onFieldConfig={isUserTable ? (patch) => setFieldConfig(menuField.key, patch) : undefined}
 
 
 
 
 
 
9269
  onRetype={
9270
  // Item 2 — a CREATED field retypes IN PLACE from the pane.
9271
  //
@@ -9426,6 +9955,10 @@ function CustomerGridSurface({
9426
  }
9427
  : undefined
9428
  }
 
 
 
 
9429
  onDuplicate={
9430
  // Creatable strata only — a base Odoo field offers no Duplicate (contract).
9431
  menuField.custom && !menuField.shared ? () => duplicateField(menuField) : undefined
@@ -9454,16 +9987,31 @@ function CustomerGridSurface({
9454
  ? setFieldConfig(menuField.key, { agg: agg ?? "" })
9455
  : saveField({ ...menuField, agg })
9456
  }
9457
- onSort={(dir) =>
9458
- updateConfig({ ...config, sorts: [{ colId: menuField.key, dir }] })
 
 
 
 
 
 
 
 
 
 
 
 
 
9459
  }
9460
- onClearSort={() =>
9461
- updateConfig({
9462
- ...config,
9463
- sorts: config.sorts.filter((s) => s.colId !== menuField.key),
9464
- })
 
 
9465
  }
9466
- onFilterBy={() =>
9467
  // Item 6c — a MEASURE-carrying column seeds the equivalent MEASURE condition
9468
  // (same measure key + window, value empty); every other filterable column seeds
9469
  // an ordinary column condition. Same signal, one consumer (the Toolbar).
@@ -9483,11 +10031,13 @@ function CustomerGridSurface({
9483
  }
9484
  onUnpin={frozenN > 1 ? unpinFields : undefined}
9485
  scopeChoice={scopeChoice}
9486
- onClearFilter={() =>
9487
- updateConfig({
9488
- ...config,
9489
- filters: dropFieldFromTree(config.filters, menuField.key, measureCols),
9490
- })
 
 
9491
  }
9492
  onGroupByField={() => updateConfig({ ...config, groupBy: menuField.key })}
9493
  onClearGroup={() => updateConfig({ ...config, groupBy: null })}
@@ -9521,6 +10071,7 @@ function CustomerGridSurface({
9521
  field={fieldByKey.get(lockedKey)!}
9522
  fields={fields}
9523
  locked
 
9524
  viewer={viewer}
9525
  sortedDir={null}
9526
  isFiltered={false}
@@ -9531,6 +10082,10 @@ function CustomerGridSurface({
9531
  onNote={() => undefined}
9532
  onHide={() => undefined}
9533
  onCreate={createField}
 
 
 
 
9534
  /* The SAME answer as the sibling instance above, stated rather than defaulted: this is
9535
  the "+" menu and it creates through the identical `createField`, so a different value
9536
  here would mean one door offers the kind and its twin does not. The note above the
@@ -9562,6 +10117,7 @@ function CustomerGridSurface({
9562
  // either way. See the sibling's note for why self-links are offered now.
9563
  linkTargets={linkTargets}
9564
  rollupSourceOffer={rollupSourceOffer}
 
9565
  />
9566
  )}
9567
 
@@ -9601,7 +10157,7 @@ function CustomerGridSurface({
9601
 
9602
  {/* The selection bar's cohort picker: existing cohorts, or a new one by name. Mirrors the
9603
  view menu's Add-to-list surface so the two ways of building a cohort read identically. */}
9604
- {selAddOpen && selAddRef.current && selectedPids.size > 0 && (
9605
  <AnchoredOverlay
9606
  anchor={selAddRef.current}
9607
  className="cg-pop cg-add-list-pop"
@@ -9690,7 +10246,7 @@ function CustomerGridSurface({
9690
  </AnchoredOverlay>
9691
  )}
9692
 
9693
- {selRemoveOpen && selRemoveRef.current && removableLists.length > 0 && (
9694
  <AnchoredOverlay
9695
  anchor={selRemoveRef.current}
9696
  className="cg-pop cg-add-list-pop"
@@ -9726,7 +10282,7 @@ function CustomerGridSurface({
9726
  once. Candidates exclude current members; picks ACCUMULATE across searches, so the
9727
  confirm button carries the running total. The 50-row render cap is stated beside the
9728
  list — nothing silently truncated. */}
9729
- {cohortMode && addCustOpen && addCustRef.current && activeCohortId && (
9730
  <AnchoredOverlay
9731
  anchor={addCustRef.current}
9732
  className="cg-pop cg-addcust-pop"
@@ -9823,13 +10379,14 @@ function CustomerGridSurface({
9823
  onClose={closeJson}
9824
  />
9825
  )}
9826
- {linkField?.type === "link" && linkField.link?.table.startsWith("ut_") && linkAt && (
9827
  <LinkGridModal
9828
  label={linkField.label}
9829
- table={linkField.link.table as SurfaceScope}
9830
  recordIds={linkedRecordIds}
9831
  editable={canEditField(linkField) && !isDerivedLink(linkField)}
9832
- single={linkField.link.single === true}
 
9833
  onSave={(ids) => patchAndRecord(
9834
  linkAt.pid,
9835
  { [linkField.key]: ids.join(",") },
 
7
  useRef,
8
  useState,
9
  } from "react";
10
+ import type { ReactNode } from "react";
11
  import { DataEditor, GridCellKind } from "@glideapps/glide-data-grid";
12
  import type {
13
  CellClickedEventArgs,
 
95
  from "../apiContract";
96
  import type { ViewOpenDetail } from "../apiContract";
97
  import { addTableField, addTableRow, clearTopicRowsCache, deleteRouteOrderField, deleteTableField,
98
+ deleteTableFields, deleteTableRow, dropTableRowsCache, fetchLinkTargets, refusalMessage,
99
+ fetchHopTopics, fetchRollupSources, patchRouteOrderField, patchTableField, enrichField } from "./apiBridge";
100
+ import type { FieldDeleteResult, HopTopicOffer, LinkTarget, RollupSourceOffer } from "./apiBridge";
101
  import SelectFromFile from "./SelectFromFile";
102
  import ImportDialog from "./ImportDialog";
103
  import { FormInterface } from "./FormInterface";
 
105
  // Owner item 16 / R4 / C-UNDO — the stack and every inverse. Pure, so a node gate can run it.
106
  import { describe, directed, popRedo, popUndo, pushUndo, stackFor } from "./undoStack";
107
  import type { CellChange, UndoBook, UndoEntry, UndoRow, UndoValue } from "./undoStack";
108
+ import { buildXlsxWorkbook, exportFilename, groupingApplies, runExport, toExportGroups, triggerDownload } from "./export";
109
  import type { ExportFormat, ExportGrouping } from "./export";
110
+ import { dataPathHash } from "./dataPath";
111
+ import type { DataDatabase, DataDatabaseFolder, DataPath } from "./dataPath";
112
+ import "../styles/wave44/data-workspace.css";
113
  // owner item 3 (2026-08-03) — a time-series view exports its SHEET, not the rows under it.
114
  import { buildTsCsv, tsSheetToTable } from "./timeSeriesData";
115
  import type { TsSheet } from "./timeSeriesData";
 
141
  /* ═══ W18-C CATALOG ═══ (owner item 4, contract C6) */
142
  import { CatalogView } from "./CatalogView";
143
  import { GalleryView, TimelineView } from "./GalleryTimelineViews";
144
+ import { foldGridCell } from "./navFold";
145
  import { CATALOG_CODE_FIELD } from "./catalogData";
146
  import type { CatalogSpec } from "./types";
147
  /* ═══ end W18-C CATALOG ═══ */
 
175
  measureColumnIndex, ratingMax, ruleColumnKeys,
176
  shouldAdoptEmbeddedSelection,
177
  tableMode, uniqueDisplayName,
178
+ routeSortRefusal,
179
  /* ⭐ W41-T38 — the rail's OWN name resolver, so a collision test compares what the reader
180
  actually sees. The rail has always drawn `viewDisplayName(view)`; `renameView` was testing
181
  `view.name`, and for the default view those two are different strings. */
 
187
  and only consumed here, because W41-T43 (this file) and W41-T44 (`RecordDetail.tsx`) open the
188
  same feature through other doors and neither of them may edit `types.ts`. */
189
  import { buildPivotRequest, cleanSecondaryView, emptyViewConfig, PIVOT_PATH, PIVOT_WINDOW_LABELS,
190
+ pivotRefusalFromBody, pivotResponse, relationalTargets } from "./types";
191
  import type {
192
  DisplayMode,
193
  DisplaySpec,
 
198
  FilterNode,
199
  FilterRule,
200
  PivotResponse,
201
+ PivotRefusal,
202
  PivotWindow,
203
  Row,
204
  RowHeightMode,
205
  SavedView,
206
+ SortRule,
207
  ViewConfig,
208
  } from "./types";
209
  // Item 7 (C-TS). Default-exported because it is a leaf VIEW like MapView, and because RECORD
 
451
  return JSON.stringify(a) === JSON.stringify(b);
452
  }
453
 
454
+ /** C3 locks are present on the server projection, while the long-lived shared type remains
455
+ * deliberately backward-compatible. Keep that wire detail additive here rather than widening a
456
+ * cross-lane contract just to paint one property. */
457
+ type LockedFilterRule = FilterRule & { locked?: boolean };
458
+ type LockedSortRule = SortRule & { locked?: boolean };
459
+ type ManagedRouteClause = {
460
+ managedBy: "loopable";
461
+ kind: "route-membership";
462
+ operator: "or";
463
+ pids: number[];
464
+ };
465
+
466
+ function hasLockedFilter(nodes: FilterNode[]): boolean {
467
+ return nodes.some((node) =>
468
+ isFilterGroup(node)
469
+ ? hasLockedFilter(node.children)
470
+ : (node as LockedFilterRule).locked === true
471
+ );
472
+ }
473
+
474
+ function hasLockedSort(sorts: SortRule[]): boolean {
475
+ return sorts.some((sort) => (sort as LockedSortRule).locked === true);
476
+ }
477
+
478
+ /** A duplicate has a new View id, the one C3 alteration path. Preserve the actual rules but
479
+ * remove the immutable-record mark, so the new View does not inherit a false in-place refusal. */
480
+ function unlockedFilterCopy(nodes: FilterNode[]): FilterNode[] {
481
+ return nodes.map((node) => {
482
+ if (isFilterGroup(node)) return { ...node, children: unlockedFilterCopy(node.children) };
483
+ const { locked: _locked, ...rule } = node as LockedFilterRule;
484
+ return rule;
485
+ });
486
+ }
487
+
488
+ function unlockedViewConfigCopy(config: ViewConfig): ViewConfig {
489
+ return {
490
+ ...config,
491
+ filters: unlockedFilterCopy(config.filters),
492
+ sorts: config.sorts.map((sort) => {
493
+ const { locked: _locked, ...rule } = sort as LockedSortRule;
494
+ return rule;
495
+ }),
496
+ };
497
+ }
498
+
499
+ /** C2's server-issued clause is an OR inclusion. This reader validates only its declared shape;
500
+ * it never derives route membership from Map rows or ids. */
501
+ function managedRoutePids(value: unknown): number[] {
502
+ if (!value || typeof value !== "object") return [];
503
+ const clause = value as Partial<ManagedRouteClause>;
504
+ if (clause.managedBy !== "loopable" || clause.kind !== "route-membership" ||
505
+ clause.operator !== "or" || !Array.isArray(clause.pids)) return [];
506
+ return [...new Set(clause.pids.filter((pid): pid is number => Number.isInteger(pid)))];
507
+ }
508
+
509
  /**
510
  * ⭐ W41-T42 — the pivot's four states, and the fourth one is the point.
511
  *
 
518
  | { status: "idle" }
519
  | { status: "loading" }
520
  | { status: "absent" }
521
+ | { status: "refused"; refusal: PivotRefusal }
522
  | { status: "ok"; answer: PivotResponse };
523
 
524
  /**
 
696
  return { ...config, colorBy: key || null, display: cleanDisplay(display) };
697
  }
698
 
699
+ /** Atomically scrub every view reference to the fields the server actually removed. */
700
+ export function configWithoutFields(
701
+ config: ViewConfig,
702
+ removed: readonly string[],
703
+ ): ViewConfig {
704
+ const gone = new Set(removed.filter((key) => typeof key === "string" && key !== ""));
705
+ if (gone.size === 0) return config;
706
+ const widths = { ...(config.widths ?? {}) };
707
+ for (const key of gone) delete widths[key];
708
+ const next: ViewConfig = {
709
+ ...config,
710
+ order: (config.order ?? []).filter((key) => !gone.has(key)),
711
+ visible: (config.visible ?? []).filter((key) => !gone.has(key)),
712
+ widths,
713
+ sorts: (config.sorts ?? []).filter((sort) => !gone.has(sort.colId)),
714
+ groupBy: config.groupBy && gone.has(config.groupBy) ? null : config.groupBy,
715
+ colorBy: config.colorBy && gone.has(config.colorBy) ? null : config.colorBy,
716
+ };
717
+ const spec = next.display;
718
+ if (spec?.colorField && gone.has(spec.colorField)) {
719
+ const display: DisplaySpec = { ...spec };
720
+ delete display.colorField;
721
+ next.display = cleanDisplay(display);
722
+ }
723
+ return next;
724
+ }
725
+
726
+ export type FieldDeleteDoor = "overlay" | "definition" | "route";
727
+
728
+ export function fieldDeleteDoor(
729
+ field: Field | undefined,
730
+ opts: { isUserTable: boolean; lockedKey: string },
731
+ ): FieldDeleteDoor | null {
732
+ if (!field || field.key === opts.lockedKey) return null;
733
+ if (field.custom && !field.shared) return "overlay";
734
+ if (opts.isUserTable && !field.custom &&
735
+ (field.type === "link" || field.type === "rollup" || field.type === "formula")) {
736
+ return "definition";
737
+ }
738
+ if (field.shared && field.kind === "route_order") return "route";
739
+ return null;
740
+ }
741
+
742
+ export interface FieldBulkDoorDeps {
743
+ config: ViewConfig;
744
+ updateConfig: (next: ViewConfig) => void;
745
+ order: string[];
746
+ visible: Set<string>;
747
+ lockedKey: string;
748
+ fieldByKey: Map<string, Field>;
749
+ isUserTable: boolean;
750
+ scope: string;
751
+ rowsPath: string;
752
+ setFields: (update: (current: Field[]) => Field[]) => void;
753
+ stampFieldDelete: (key: string) => void;
754
+ }
755
+
756
+ export interface FieldBulkDoors {
757
+ onSetFieldsHidden: (keys: string[], hidden: boolean) => void;
758
+ onShareFields: (keys: string[]) => void;
759
+ onReassignFields: (keys: string[]) => void;
760
+ onDeleteFields: (keys: string[]) => void;
761
+ onRemoveField: (key: string) => void;
762
+ }
763
+
764
+ function reportFieldDeleteRefusals(
765
+ results: readonly FieldDeleteResult[],
766
+ fieldByKey: Map<string, Field>,
767
+ ): void {
768
+ const refused = results.filter((item) => item.status === "refused");
769
+ if (refused.length === 0) return;
770
+ const explained = refused.find((item) =>
771
+ typeof item.reason === "string" && item.reason.trim().length > 0);
772
+ if (!explained) {
773
+ signal(TOAST_EVENT, refused.length === 1
774
+ ? "That column was left alone, and the server gave no reason."
775
+ : `${refused.length} of those columns were left alone, and the server gave no reason.`);
776
+ return;
777
+ }
778
+ const label = fieldByKey.get(explained.key)?.label ?? explained.key;
779
+ signal(TOAST_EVENT, refused.length === 1
780
+ ? `${label} was left alone. ${explained.reason}`
781
+ : `${refused.length} of those columns were left alone. ${label}: ${explained.reason}`);
782
+ }
783
+
784
+ export function useFieldBulkDoors(deps: FieldBulkDoorDeps): FieldBulkDoors {
785
+ const { config, updateConfig, order, visible, lockedKey, fieldByKey, isUserTable, scope,
786
+ rowsPath, setFields, stampFieldDelete } = deps;
787
+ const onSetFieldsHidden = useCallback((keys: string[], hidden: boolean) => {
788
+ const next = new Set(visible);
789
+ for (const key of keys) {
790
+ if (hidden) {
791
+ if (key !== lockedKey) next.delete(key);
792
+ } else next.add(key);
793
+ }
794
+ updateConfig({ ...config, visible: [...new Set([lockedKey, ...next])] });
795
+ }, [config, lockedKey, updateConfig, visible]);
796
+
797
+ const onDeleteFields = useCallback((keys: string[]) => {
798
+ const overlay: string[] = [];
799
+ const definition: string[] = [];
800
+ const route: string[] = [];
801
+ const noDoor: string[] = [];
802
+ for (const key of keys) {
803
+ const door = fieldDeleteDoor(fieldByKey.get(key), { isUserTable, lockedKey });
804
+ if (door === "overlay") overlay.push(key);
805
+ else if (door === "definition") definition.push(key);
806
+ else if (door === "route") route.push(key);
807
+ else noDoor.push(key);
808
+ }
809
+ void (async () => {
810
+ const gone = [...overlay];
811
+ let touchedServer = false;
812
+ let unreadableAnswer = false;
813
+ if (definition.length > 0) {
814
+ const outcome = await deleteTableFields(scope, definition);
815
+ gone.push(...outcome.deleted);
816
+ touchedServer = outcome.deleted.length > 0;
817
+ unreadableAnswer = outcome.unreadable;
818
+ reportFieldDeleteRefusals(outcome.results, fieldByKey);
819
+ }
820
+ for (const key of route) {
821
+ // Route fields retain their dedicated lifecycle wall; execute serially so refusal toasts
822
+ // do not race each other into one slot.
823
+ // eslint-disable-next-line no-await-in-loop
824
+ const ok = await deleteRouteOrderField(key);
825
+ if (ok) {
826
+ gone.push(key);
827
+ touchedServer = true;
828
+ }
829
+ }
830
+ if (noDoor.length > 0) {
831
+ signal(TOAST_EVENT, noDoor.length === 1
832
+ ? "One of those columns cannot be deleted here, so it was left alone."
833
+ : `${noDoor.length} of those columns cannot be deleted here, so they were left alone.`);
834
+ }
835
+ if (gone.length > 0) {
836
+ const goneSet = new Set(gone);
837
+ setFields((current) => current.filter((item) => !goneSet.has(item.key)));
838
+ updateConfig(configWithoutFields({ ...config, order, visible: [...visible] }, gone));
839
+ for (const key of overlay) {
840
+ stampFieldDelete(key);
841
+ emitHostEvent({ id: eventId("fielddel"), type: "field_delete", key });
842
+ }
843
+ }
844
+ if (touchedServer || unreadableAnswer) {
845
+ clearTopicRowsCache(rowsPath);
846
+ signal(WORKSPACE_STALE_EVENT);
847
+ signal(ROWS_STALE_EVENT);
848
+ }
849
+ })();
850
+ }, [config, fieldByKey, isUserTable, lockedKey, order, rowsPath, scope, setFields,
851
+ stampFieldDelete, updateConfig, visible]);
852
+
853
+ const onShareFields = useCallback((keys: string[]) => {
854
+ if (keys.length > 0) signal(TOAST_EVENT,
855
+ "Sharing several fields in one go is not available yet, so share them one at a time from each column's own menu.");
856
+ }, []);
857
+ const onReassignFields = useCallback((keys: string[]) => {
858
+ if (keys.length > 0) signal(TOAST_EVENT,
859
+ "Handing several fields to a new owner in one go is not available yet, so change the owner one column at a time from its share panel.");
860
+ }, []);
861
+ const onRemoveField = useCallback((key: string) => {
862
+ if (key) signal(TOAST_EVENT,
863
+ "Taking a shared field off your own list is not available yet, so hide it or ask the person who owns it to withdraw it.");
864
+ }, []);
865
+ return useMemo(() => ({ onSetFieldsHidden, onShareFields, onReassignFields,
866
+ onDeleteFields, onRemoveField }),
867
+ [onDeleteFields, onReassignFields, onRemoveField, onSetFieldsHidden, onShareFields]);
868
+ }
869
+
870
  function readLocal(storageKey: string): LocalWorkspace | null {
871
  try {
872
  const raw = localStorage.getItem(`aios-grid:${storageKey}`);
 
1161
  * re-renders for its own state (edits, resize) and remounts on route change via `key`. */
1162
  interface CustomerGridProps {
1163
  scope?: SurfaceScope;
1164
+ /** Shell-owned Data workspace location; grid resolves its view/field, never the global rail. */
1165
+ dataPath?: DataPath;
1166
+ databases?: readonly DataDatabase[];
1167
+ activeDatabaseKey?: string;
1168
+ databaseFolders?: readonly DataDatabaseFolder[];
1169
+ onSelectDatabase?: (key: string) => void;
1170
+ onDatabaseMove?: (key: string, folderId: string | null) => void;
1171
+ onDatabaseFolderRename?: (folderId: string, name: string) => void;
1172
+ onDatabaseFolderDelete?: (folderId: string) => void;
1173
+ renderDatabaseActions?: (database: DataDatabase) => ReactNode;
1174
+ databaseCreateControl?: ReactNode;
1175
  /** A Query-owned immutable artefact. `scope` remains the renderer's mapped data scope. */
1176
  queryBinding?: QueryVirtualBinding;
1177
  /** Read-only Grid view embedded in a linked-record modal. It keeps the standard
 
1183
  embeddedSelectable?: boolean;
1184
  embeddedSelectedIds?: readonly number[];
1185
  onEmbeddedSelectionChange?: (recordIds: number[]) => void;
1186
+ /** Source record withheld from an editable picker over its own database. */
1187
+ embeddedExcludeRecordId?: number;
1188
+ }
1189
+
1190
+ /** Exact client mirror of core.user_tables.is_linkable_target. */
1191
+ const LINKABLE_MODULE_KEYS = ["customer_data", "product_data"] as const;
1192
+
1193
+ export function isLinkableTarget(table: unknown): boolean {
1194
+ if (typeof table !== "string") return false;
1195
+ if (table.startsWith("ut_") && table.length > 3) return true;
1196
+ return (LINKABLE_MODULE_KEYS as readonly string[]).includes(table);
1197
+ }
1198
+
1199
+ /** Resolve storage keys to renderer scopes without treating an arbitrary key as a scope. */
1200
+ export function scopeForLinkTable(table: unknown): SurfaceScope | undefined {
1201
+ if (!isLinkableTarget(table)) return undefined;
1202
+ if (table === "customer_data") return "customer";
1203
+ if (table === "product_data") return "product";
1204
+ return table as `ut_${string}`;
1205
  }
1206
 
1207
  interface LinkGridModalProps {
 
1210
  recordIds: readonly number[];
1211
  editable?: boolean;
1212
  single?: boolean;
1213
+ excludeRecordId?: number;
1214
  onSave?: (recordIds: number[]) => void;
1215
  onClose: () => void;
1216
  }
1217
 
1218
  function LinkGridModal({ label, table, recordIds, editable = false, single = false,
1219
+ excludeRecordId, onSave, onClose }: LinkGridModalProps) {
1220
  const panelRef = useRef<HTMLDivElement>(null);
1221
  const [selectedIds, setSelectedIds] = useState<number[]>(() => [...recordIds]);
1222
  const changeSelectedIds = useCallback((ids: number[]) => {
 
1268
  scope={table}
1269
  embedded
1270
  embeddedRecordIds={editable ? undefined : recordIds}
1271
+ embeddedExcludeRecordId={editable ? excludeRecordId : undefined}
1272
  embeddedSelectable={editable}
1273
  embeddedSelectedIds={selectedIds}
1274
  onEmbeddedSelectionChange={changeSelectedIds}
 
1339
 
1340
  function CustomerGridSurface({
1341
  scope = "customer",
1342
+ dataPath,
1343
+ databases,
1344
+ activeDatabaseKey,
1345
+ databaseFolders,
1346
+ onSelectDatabase,
1347
+ onDatabaseMove,
1348
+ onDatabaseFolderRename,
1349
+ onDatabaseFolderDelete,
1350
+ renderDatabaseActions,
1351
+ databaseCreateControl,
1352
  queryBinding,
1353
  embedded = false,
1354
  embeddedRecordIds,
1355
  embeddedSelectable = false,
1356
  embeddedSelectedIds = [],
1357
  onEmbeddedSelectionChange,
1358
+ embeddedExcludeRecordId,
1359
  }: CustomerGridProps = {}) {
1360
  const isQueryPreview = queryBinding !== undefined;
1361
  /**
 
1422
  */
1423
  const [pendingRows, setPendingRows] = useState<Row[]>([]);
1424
  const rawRows = useMemo(() => {
1425
+ const projected = embeddedRecordIds
1426
  ? fetchedRows.filter((row) => new Set(embeddedRecordIds).has(row.pid))
1427
  : fetchedRows;
1428
+ const base = embeddedExcludeRecordId !== undefined
1429
+ ? projected.filter((row) => row.pid !== embeddedExcludeRecordId)
1430
+ : projected;
1431
  if (!pendingRows.length) return base;
1432
  const known = new Set(base.map((r) => r.pid));
1433
  const extra = pendingRows.filter((r) => !known.has(r.pid));
1434
  return extra.length ? [...base, ...extra] : base;
1435
  // The scalar key keeps this stable when a caller reconstructs the same id list.
1436
  // eslint-disable-next-line react-hooks/exhaustive-deps
1437
+ }, [fetchedRows, embeddedIdsKey, embeddedExcludeRecordId, pendingRows]);
1438
  useEffect(() => {
1439
  // ⚠ PRUNED AGAINST THE FETCHED PAYLOAD, not against `rawRows` — `rawRows` contains the
1440
  // pending rows, so it can never report that one has been absorbed. Pruning against the
 
1545
  const [views, setViews] = useState<SavedView[]>([]);
1546
  const [activeViewId, setActiveViewId] = useState(ALL_VIEW_ID);
1547
  const [config, setConfig] = useState<ViewConfig>(() => defaultViewConfig([]));
1548
+ /** C2 membership is a server-approved, active-View-only inclusion. It deliberately does not
1549
+ * live in `config`: that object has a generic autosave effect for authored View changes. */
1550
+ const [managedRouteClause, setManagedRouteClause] = useState<unknown>(undefined);
1551
  /** W36-T02 — the live `config`, readable from an effect that must not DEPEND on it. The
1552
  * after-mount reconcile needs to know whether an edit is unsaved before it re-seeds the open
1553
  * view; taking `config` as a dependency would re-run that whole pass on every drag and
 
2116
  },
2117
  [config.groupBy, isQueryPreview, queryBinding]
2118
  );
2119
+ /** C2 returns the entire state so it can prove it did not rewrite user clauses. B consumes
2120
+ * exactly its managed addition/removal; filters, conjunction, user membership and every other
2121
+ * authored View key remain untouched. */
2122
+ const applyManagedRouteViewState = useCallback(
2123
+ (viewState: Record<string, unknown>) => {
2124
+ if (Object.prototype.hasOwnProperty.call(viewState, "managedRouteClause"))
2125
+ setManagedRouteClause(viewState.managedRouteClause);
2126
+ else
2127
+ setManagedRouteClause(undefined);
2128
+ },
2129
+ []
2130
+ );
2131
+ // A managed selection belongs to precisely one active View; opening another cannot carry it.
2132
+ useEffect(() => setManagedRouteClause(undefined), [activeViewId]);
2133
  useEffect(() => {
2134
  if (!config.fullscreen) return;
2135
  const onKey = (event: KeyboardEvent) => {
 
2230
  const isUserTable = !embedded && scope.startsWith("ut_");
2231
  const recordsMutable = payload?.recordsMutable !== false;
2232
  const canMutateRecords = isUserTable && recordsMutable;
2233
+ const fieldBulkDoors = useFieldBulkDoors({
2234
+ config,
2235
+ updateConfig,
2236
+ order,
2237
+ visible,
2238
+ lockedKey,
2239
+ fieldByKey,
2240
+ isUserTable,
2241
+ scope,
2242
+ rowsPath: topic.rowsPath,
2243
+ setFields,
2244
+ stampFieldDelete,
2245
+ });
2246
  /**
2247
  * ⭐ 2026-08-07 — the databases a `link` column may point at, fetched when the column menu
2248
  * OPENS rather than on every render of the grid.
 
2303
  live = false;
2304
  };
2305
  }, [columnMenu, plusMenu]);
2306
+ /**
2307
+ * The hop editor has a separate server vocabulary from source rollups. In particular its
2308
+ * dimensions publish date and number types used by the operator picker, so deriving it from
2309
+ * /tables/rollup-sources (and repainting everything as text) is a functional data loss.
2310
+ */
2311
+ const [hopTopicOffer, setHopTopicOffer] =
2312
+ useState<HopTopicOffer>({ topics: [], windows: [], omissions: [] });
2313
+ const hopOfferAsked = useRef(false);
2314
+ useEffect(() => {
2315
+ if ((!columnMenu && !plusMenu) || hopOfferAsked.current) return;
2316
+ hopOfferAsked.current = true;
2317
+ let live = true;
2318
+ void fetchHopTopics().then((offer) => {
2319
+ if (live) setHopTopicOffer(offer);
2320
+ });
2321
+ return () => {
2322
+ live = false;
2323
+ };
2324
+ }, [columnMenu, plusMenu]);
2325
  /**
2326
  * ⭐ WAVE 27 · OWNER ITEM 22 — the values the ACTIVE VIEW forces on a new record.
2327
  *
 
2514
  useEffect(() => {
2515
  if (displayMode !== "map") setRoutePanelOpen(false);
2516
  }, [displayMode]);
2517
+ useEffect(() => {
2518
+ if (!routePanelOpen) return;
2519
+ setSelAddOpen(false);
2520
+ setSelRemoveOpen(false);
2521
+ setAddCustOpen(false);
2522
+ }, [routePanelOpen]);
2523
 
2524
  // ═══════════════════════════════════════════════════════════════════════════════════════
2525
  // ⭐⭐ WAVE 30 · W30-T42 (contract C2) — PAGING A READ-THROUGH GRID.
 
2785
  */
2786
  const applyFilters = useCallback(
2787
  (filters: FilterNode[]) => {
2788
+ if (hasLockedFilter(config.filters)) {
2789
+ signal(TOAST_EVENT, "These filters are locked. Copy this View to change them.");
2790
+ return;
2791
+ }
2792
  const id = activeViewId;
2793
  if (id) {
2794
  const cycle = viewFilterCycle(id, filters, (other) =>
 
2844
  : computedRows,
2845
  [cohortMode, computedRows, cohortMemberSet]
2846
  );
2847
+ // C2's server-minted membership is an OR inclusion, like the pipeline's view-pinned members,
2848
+ // but never becomes a user-authored `memberPids` edit.
2849
+ const effectiveMemberPids = useMemo(
2850
+ () => [...new Set([...(config.memberPids ?? []), ...managedRoutePids(managedRouteClause)])],
2851
+ [config.memberPids, managedRouteClause]
2852
+ );
2853
 
2854
  const { visibleRows, pidToIndex } = useVisibleRows(
2855
  scopedRows,
 
2860
  // grouping a WINDOW would headline a page's count/subtotals as the group's
2861
  serverWindowed ? null : config.groupBy,
2862
  collapsed,
2863
+ effectiveMemberPids,
2864
  config.filterConj,
2865
  serverWindowed,
2866
  measureSets,
 
4569
  if (!row) return;
4570
  // Owner item 10: clicking into the cells is "I am working now" — the frame folds its
4571
  // navigation rail to the slim strip (a no-op in the embed; the shell listens).
4572
+ foldGridCell();
4573
  if (row.kind === "group-header") {
4574
  event.preventDefault();
4575
  setCollapsed((current) => {
 
4632
  // The large modal mounts the same Grid surface over exactly these pids, so its standard
4633
  // search, Filters, Sort, Fields, and column menus keep working for every database kind.
4634
  if (row.kind === "data" && field?.type === "link" && field.link?.table) {
4635
+ if (isLinkableTarget(field.link.table)) {
4636
  event.preventDefault();
4637
  setActiveCell(cell[0], cell[1]);
4638
  setLinkAt({ pid: row.record.pid, fieldKey: field.key });
 
4707
  const row = displayRows[cell[1]];
4708
  const column = visibleCols[cell[0]];
4709
  const field = column ? fieldByKey.get(column.id!) : undefined;
4710
+ if (row?.kind === "data" && field && !canEditField(field))
4711
  setDetailPid(row.record.pid);
4712
  },
4713
+ [displayRows, visibleCols, fieldByKey, canEditField]
4714
  );
4715
  const onCellEdited = useCallback(
4716
  (cell: Item, value: EditableGridCell) => {
 
5109
  setSearch("");
5110
  setDetailPid(null);
5111
  setDisplayCap(DISPLAY_PAGE);
5112
+ // A Data path is the shell's shareable location, not a second routing model. Keep it
5113
+ // canonical when a person switches views, while ordinary grid mounts remain hash-neutral.
5114
+ if (dataPath && typeof window !== "undefined") {
5115
+ const nextHash = dataPathHash({ ...dataPath, view: id });
5116
+ if (window.location.hash !== nextHash) window.location.hash = nextHash;
5117
+ }
5118
  // Owner item 3 (2026-07-31): tell the host WHERE THE USER IS, so a fresh browser (no
5119
  // localStorage copy) resumes on this view instead of the system default. Presentation
5120
  // state — the host stores the id and the read side re-validates it.
 
5123
  signal(NAV_MINIMIZE_EVENT);
5124
  },
5125
  [views, activeViewId, config, persistView, fields, isQueryPreview, recordStars.stars.view,
5126
+ scriptProjections, dataPath]
5127
  );
5128
 
5129
+ useEffect(() => {
5130
+ const viewId = dataPath?.view;
5131
+ if (!viewId || viewId === activeViewId) return;
5132
+ if (!views.some((view) => view.id === viewId)) return;
5133
+ selectView(viewId);
5134
+ }, [dataPath?.view, activeViewId, views, selectView]);
5135
+
5136
  /**
5137
  * A-S4-3 (item 25) — a notification's click-through. The SHELL routes to the table and fires
5138
  * this; the GRID owns view selection, so neither learns the other's state.
 
5152
  window.addEventListener(VIEW_OPEN_EVENT, onOpen);
5153
  return () => window.removeEventListener(VIEW_OPEN_EVENT, onOpen);
5154
  }, [scope, views, selectView]);
5155
+
5156
+ const addressedFieldRef = useRef<string | null>(null);
5157
+ useEffect(() => {
5158
+ const fieldKey = dataPath?.field;
5159
+ const address = fieldKey ? `${dataPath.database}:${fieldKey}` : null;
5160
+ if (!fieldKey || !address) {
5161
+ addressedFieldRef.current = null;
5162
+ return;
5163
+ }
5164
+ if (addressedFieldRef.current === address) return;
5165
+ if (!fields.some((field) => field.key === fieldKey)) return;
5166
+ const rect = gridBoxRef.current?.getBoundingClientRect();
5167
+ if (!rect) return;
5168
+ addressedFieldRef.current = address;
5169
+ setColumnMenu({
5170
+ fieldKey,
5171
+ anchor: {
5172
+ left: rect.left,
5173
+ top: rect.top,
5174
+ right: rect.right,
5175
+ bottom: rect.bottom,
5176
+ width: rect.width,
5177
+ height: rect.height,
5178
+ },
5179
+ });
5180
+ }, [dataPath?.database, dataPath?.field, fields]);
5181
  const createView = useCallback(
5182
  (name: string, mode: DisplayMode, permissions: ViewPermissions) => {
5183
  if (queryBinding) {
 
5443
  // Never echo the SOURCE's creator: the host stamps and ignores what the browser
5444
  // sends, but sending someone else's name is a laundering attempt on its face.
5445
  createdBy: undefined,
5446
+ config: unlockedViewConfigCopy(source.config),
5447
  };
5448
  persistView(copy);
5449
  setActiveViewId(copy.id);
 
6110
  [views, fields, computedRows, exportRows, activeViewId, today]
6111
  );
6112
 
6113
+ /** C3's selected-View export is evaluated server-side. The browser receives one already
6114
+ * evaluated fields/rows pair per requested View and gives those pairs, unchanged, to the sole
6115
+ * XLSX assembly writer. It never reuses the active View's loaded rows for another tab. */
6116
+ const exportSelectedViews = useCallback(
6117
+ async (viewIds: string[]) => {
6118
+ const ids = [...new Set(viewIds)];
6119
+ const visibleIds = new Set(views.map((view) => view.id));
6120
+ if (scope !== "customer" || embedded || isQueryPreview || ids.length < 1 || ids.length > 20 ||
6121
+ ids.some((id) => !visibleIds.has(id))) {
6122
+ signal(TOAST_EVENT, "Choose between one and twenty visible Views to export.");
6123
+ return;
6124
+ }
6125
+ try {
6126
+ const response = await fetch(`${API_V1}/customers/view-export`, {
6127
+ method: "POST",
6128
+ credentials: CREDENTIALS,
6129
+ headers: { "Content-Type": "application/json" },
6130
+ body: JSON.stringify({ viewIds: ids }),
6131
+ });
6132
+ const payload = await response.json().catch(() => null) as {
6133
+ today?: unknown;
6134
+ exports?: unknown;
6135
+ error?: { message?: unknown };
6136
+ } | null;
6137
+ if (!response.ok) {
6138
+ const message = typeof payload?.error?.message === "string"
6139
+ ? payload.error.message
6140
+ : "Selected Views could not be exported.";
6141
+ signal(TOAST_EVENT, message);
6142
+ return;
6143
+ }
6144
+ if (!Array.isArray(payload?.exports)) throw new Error("missing evaluated Views");
6145
+ const received = new Map<string, { name: string; fields: Field[]; rows: Row[] }>();
6146
+ for (const item of payload.exports) {
6147
+ if (!item || typeof item !== "object") throw new Error("invalid evaluated View");
6148
+ const candidate = item as {
6149
+ viewId?: unknown;
6150
+ name?: unknown;
6151
+ columns?: unknown;
6152
+ rows?: unknown;
6153
+ view?: unknown;
6154
+ };
6155
+ if (typeof candidate.viewId !== "string" || typeof candidate.name !== "string" ||
6156
+ !Array.isArray(candidate.columns) || !Array.isArray(candidate.rows) ||
6157
+ !candidate.view || typeof candidate.view !== "object" || received.has(candidate.viewId))
6158
+ throw new Error("invalid evaluated View");
6159
+ received.set(candidate.viewId, {
6160
+ name: candidate.name,
6161
+ fields: candidate.columns as Field[],
6162
+ rows: candidate.rows as Row[],
6163
+ });
6164
+ }
6165
+ if (received.size !== ids.length || ids.some((id) => !received.has(id)))
6166
+ throw new Error("incomplete evaluated Views");
6167
+ const sheets = ids.map((id) => received.get(id)!);
6168
+ const exportToday = typeof payload?.today === "string" ? payload.today : undefined;
6169
+ const bytes = buildXlsxWorkbook(sheets, exportToday);
6170
+ const blobBytes = new Uint8Array(bytes.byteLength);
6171
+ blobBytes.set(bytes);
6172
+ triggerDownload(
6173
+ exportFilename("Selected Views", exportToday, "xlsx"),
6174
+ new Blob([blobBytes.buffer], {
6175
+ type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
6176
+ })
6177
+ );
6178
+ } catch {
6179
+ signal(TOAST_EVENT, "Selected Views could not be exported.");
6180
+ }
6181
+ },
6182
+ [views, scope, embedded, isQueryPreview]
6183
+ );
6184
+
6185
  /**
6186
  * The selection bar's "Add to locked view": exactly the CHECKED customers, not a view's
6187
  * matches.
 
6558
  [isUserTable, scope]
6559
  );
6560
 
6561
+ // C3 owns both the state and the wall. `session.admin` is its current Owner mapping;
6562
+ // this client gate only avoids advertising a PATCH the server will refuse.
6563
+ const setDeletionLock = useCallback(
6564
+ (key: string, deletionLocked: boolean) => {
6565
+ if (!isUserTable || !viewer?.isAdmin) return;
6566
+ void patchTableField(scope, key, { deletionLocked }).then((made) => {
6567
+ if (!made) return;
6568
+ setFields((current) => current.map((f) => (f.key === made.key ? made : f)));
6569
+ signal(WORKSPACE_STALE_EVENT);
6570
+ });
6571
+ },
6572
+ [isUserTable, scope, viewer?.isAdmin]
6573
+ );
6574
+
6575
  /**
6576
  * Owner item 9 — "Change field": the clicked column starts showing another field, in place.
6577
  * The new field takes the old one's slot in `order`; the old field is HIDDEN, not lost — it
 
6611
  const f = fieldByKey.get(key);
6612
  if (!f?.custom || key === lockedKey) return;
6613
  setFields((current) => current.filter((item) => item.key !== key));
6614
+ updateConfig(configWithoutFields({ ...config, order, visible: [...visible] }, [key]));
 
 
 
 
 
 
 
 
 
 
6615
  stampFieldDelete(key);
6616
  emitHostEvent({ id: eventId("fielddel"), type: "field_delete", key });
6617
  },
 
6654
  void deleteRouteOrderField(key).then((ok) => {
6655
  if (!ok) return; // the bridge has already said why
6656
  setFields((current) => current.filter((item) => item.key !== key));
6657
+ updateConfig(configWithoutFields({ ...config, order, visible: [...visible] }, [key]));
 
 
 
 
 
 
 
 
 
 
6658
  // ⛔ AND THE ROWS CACHE, for the reason `revealRouteField` states above: the values went
6659
  // with the definition (`shared_overlay.drop_field` scrubs the cells), so a refetch served
6660
  // from the pre-delete window would repaint the numbers of a column that no longer exists.
 
6706
  void deleteTableField(scope, key).then((ok) => {
6707
  if (!ok) return; // the bridge has already said why
6708
  setFields((current) => current.filter((item) => item.key !== key));
6709
+ updateConfig(configWithoutFields({ ...config, order, visible: [...visible] }, [key]));
 
 
 
 
 
 
 
 
 
 
6710
  signal(WORKSPACE_STALE_EVENT);
6711
  signal(ROWS_STALE_EVENT);
6712
  });
 
7607
  });
7608
  if (!live) return;
7609
  if (!res.ok) {
7610
+ const refusal = pivotRefusalFromBody(await res.json().catch(() => null));
7611
+ if (!live) return;
7612
+ setPivot(refusal ? { status: "refused", refusal } : { status: "absent" });
7613
  return;
7614
  }
7615
  const answer = pivotResponse(await res.json().catch(() => null));
 
7626
  };
7627
  }, [pivotRequestBody]);
7628
 
7629
+ const copyFieldDataLink = useCallback(
7630
+ (fieldKey: string) => {
7631
+ if (typeof window === "undefined" || !navigator.clipboard) {
7632
+ signal(TOAST_EVENT, "Copying a field link is unavailable in this browser.");
7633
+ return;
7634
+ }
7635
+ const hash = dataPathHash({ database: topic.key, view: activeViewId, field: fieldKey });
7636
+ const url = new URL(hash, window.location.href).toString();
7637
+ void navigator.clipboard.writeText(url).then(
7638
+ () => signal(TOAST_EVENT, "Copied link to field."),
7639
+ () => signal(TOAST_EVENT, "Could not copy the field link.")
7640
+ );
7641
+ },
7642
+ [topic.key, activeViewId]
7643
+ );
7644
+
7645
  if (loading || !workspaceReady) {
7646
  /* wave17 GRID — item 3 / owner R6: one small bare rotating icon, NO WORDS. `aria-label`
7647
  is not a word on screen and stays: `.lp-spin` is an empty span, so without it the wait
 
7662
  name: viewDisplayName(activeView),
7663
  // The API compares this complete saved config to its visible View and mints the durable
7664
  // revision itself. A browser may carry provenance, never choose it.
7665
+ config,
7666
  }
7667
  : null;
7668
+ const activeFiltersLocked = hasLockedFilter(config.filters);
7669
+ const activeSortsLocked = hasLockedSort(config.sorts);
7670
  // Cohort mode's toolbar control (rendered by Toolbar via the `cohortAction` slot; the popover
7671
  // it opens is with the other overlays at the bottom). Disabled without an active cohort —
7672
  // zero cohorts is the host page's near-empty state, not this button's error to explain.
7673
+ const cohortAction = cohortMode && !routePanelOpen ? (
7674
  <button
7675
  type="button"
7676
  className="cg-tb-btn cg-tb-addcust"
 
7708
  */
7709
  const deletableKeys = new Set(
7710
  fields
7711
+ .filter(
7712
+ (f) =>
7713
+ !((f as Field & { deletionLocked?: boolean }).deletionLocked) &&
7714
+ (f.custom || (f.shared && f.kind === "route_order")) && f.key !== lockedKey
7715
+ )
7716
  .map((f) => f.key)
7717
  );
7718
  const menuField = columnMenu ? fieldByKey.get(columnMenu.fieldKey) : undefined;
 
7792
  ?? (linkField && linkRow ? linkRow[linkField.key] : "")
7793
  ?? ""
7794
  );
7795
+ const linkTargetScope = linkField?.type === "link"
7796
+ ? scopeForLinkTable(linkField.link?.table)
7797
+ : undefined;
7798
  const linkedRecordIds = [...new Set(
7799
  linkValue.split(",").map((part) => Number(part.trim())).filter(
7800
  (pid) => Number.isInteger(pid) && pid > 0
 
7904
 
7905
  const pivotOn = !!secondary;
7906
  const pivotAnswer = pivot.status === "ok" ? pivot.answer : null;
7907
+ const pivotRefusal = pivot.status === "refused"
7908
+ ? pivot.refusal
7909
+ : pivotAnswer?.refusal ?? null;
7910
  /**
7911
  * ⭐ W41-T43 — THE SAVED PIVOT NAMES A LINK COLUMN THIS READER WAS NOT SERVED. No request went
7912
  * out (`pivotRequestBody` is empty), so `pivot` stays `idle` and every other branch below is
 
7994
  */
7995
  const secondaryToolbar = pivotOn && pivotServed && secondary ? (
7996
  <Toolbar
7997
+ manager={true}
7998
  nouns={pivotTarget?.label ?? "records"}
7999
+ viewer={viewer}
8000
+ onSetFieldsHidden={null}
8001
+ onShareFields={null}
8002
+ onReassignFields={null}
8003
+ onDeleteFields={null}
8004
+ onRemoveField={null}
8005
  sourceLabel={topic.nouns}
8006
  fields={pivotFields}
8007
  visible={pivotVisible}
 
8083
  `QueryPage`. */}
8084
  {!hideViews && (
8085
  <ViewSidebar
8086
+ databases={databases}
8087
+ activeDatabaseKey={activeDatabaseKey}
8088
+ databaseFolders={databaseFolders}
8089
+ onSelectDatabase={onSelectDatabase}
8090
+ onDatabaseMove={onDatabaseMove}
8091
+ onDatabaseFolderRename={onDatabaseFolderRename}
8092
+ onDatabaseFolderDelete={onDatabaseFolderDelete}
8093
+ renderDatabaseActions={renderDatabaseActions}
8094
+ databaseCreateControl={databaseCreateControl}
8095
  /* ⭐⭐ W36-T05 (owner item 6 · R3 · R14) — the View agent, and the ONE class that
8096
  folds the main rail. ⛔ `null` when closed, never a hidden node: `index.css` folds
8097
  on `.shell-root:has(.cg-agent-panel)`, and `:has()` matches what EXISTS. */
 
8182
  onAddToList={serverWindowed ? undefined : addToList}
8183
  today={today}
8184
  onExport={serverWindowed ? undefined : exportViewData}
8185
+ onExportXlsxViews={
8186
+ scope === "customer" && !embedded && !isQueryPreview ? exportSelectedViews : undefined
8187
+ }
8188
+ exportableViewIds={views.map((view) => view.id)}
8189
  folders={folders}
8190
  folderIdOf={folderIdOf}
8191
  /**
 
8468
  )}
8469
  <main className="cg-main">
8470
  <Toolbar
8471
+ manager={true}
8472
  nouns={topic.nouns}
8473
+ viewer={viewer}
8474
+ onSetFieldsHidden={fieldBulkDoors.onSetFieldsHidden}
8475
+ onShareFields={fieldBulkDoors.onShareFields}
8476
+ onReassignFields={fieldBulkDoors.onReassignFields}
8477
+ onDeleteFields={fieldBulkDoors.onDeleteFields}
8478
+ onRemoveField={fieldBulkDoors.onRemoveField}
8479
  // Item 12 (C-LOCK) — the banner's copy. ⚠ BOTH fields are omitted when this reader
8480
  // cannot see the locked set, and that omission is the SIGNAL, not an oversight: it
8481
  // is what selects RECORD's second sentence ("locked to a set you cannot see").
 
8542
  filters={config.filters}
8543
  onFilters={applyFilters}
8544
  filterConj={config.filterConj ?? "and"}
8545
+ onFilterConj={(filterConj) => {
8546
+ if (activeFiltersLocked) {
8547
+ signal(TOAST_EVENT, "These filters are locked. Copy this View to change them.");
8548
+ return;
8549
+ }
8550
+ updateConfig({ ...config, filterConj });
8551
+ }}
8552
+ filtersLocked={activeFiltersLocked}
8553
  sorts={config.sorts}
8554
+ onSorts={(sorts) => {
8555
+ if (activeSortsLocked) {
8556
+ signal(TOAST_EVENT, "These sorts are locked. Copy this View to change them.");
8557
+ return;
8558
+ }
8559
+ const refusal = sorts
8560
+ .map((sort) => routeSortRefusal(
8561
+ sort.colId,
8562
+ { nodes: config.filters, conj: config.filterConj },
8563
+ fields,
8564
+ ))
8565
+ .find((message): message is string => message !== null);
8566
+ if (refusal) {
8567
+ signal(TOAST_EVENT, refusal);
8568
+ return;
8569
+ }
8570
+ updateConfig({ ...config, sorts });
8571
+ }}
8572
+ sortsLocked={activeSortsLocked}
8573
+ onCopyToChange={() => duplicateView(activeViewId)}
8574
  // the toolbar must not advertise a grouping the pipeline is not applying
8575
  groupBy={serverWindowed ? null : config.groupBy}
8576
  onGroupBy={(groupBy) => updateConfig({ ...config, groupBy })}
 
8617
  onRelationalWindow={setPivotWindow}
8618
  sourceLabel={topic.nouns}
8619
  onViewActions={setViewActionsAnchor}
8620
+ fullscreen={!!config.fullscreen}
8621
+ onFullscreen={() => updateConfig({ ...config, fullscreen: !config.fullscreen })}
8622
  />
 
 
 
 
 
 
 
 
8623
  {/* ⭐ R11's SECOND ROW — live, on the pivoted database. It renders only once the pivot has
8624
  actually been SERVED, which is the house posture for a control whose other half may
8625
  not be wired yet: absent beats present-and-inert. A control row over a database whose
 
8638
  onToggleRoute={() => setRoutePanelOpen((open) => !open)}
8639
  />
8640
  )}
8641
+ {/* ⭐⭐ WAVE 42 · W42-T19 (owner instruction 11) — CALENDAR'S SECOND ROW. The real
8642
+ `CalendarSettings` render stays in the same position and guard shape as `MapSettings`:
8643
+ after the primary Toolbar, before the grid. The primary mode trigger therefore stays
8644
+ on row one while Calendar's date, Day cells, and Totals controls live here. */}
 
8645
  {displayMode === "calendar" && !pivotOn && (
8646
  <CalendarSettings
8647
  dateField={calendarField}
 
8875
  * a record that then appears twice while scrolling, which reads as duplicated data
8876
  * rather than as a layout bug.
8877
  */
8878
+ freezeTrailingRows={totalsRowShown ? 1 : 0}
8879
  rowHeight={rowHeight}
8880
  headerHeight={36}
8881
  rowMarkers="both"
 
9353
  routePanelOpen={routePanelOpen}
9354
  activeView={routeSourceView}
9355
  tableKey={topic.key}
9356
+ onManagedRouteViewState={applyManagedRouteViewState}
9357
+ onZoneChanged={() => {
9358
+ clearTopicRowsCache(topic.rowsPath);
9359
+ dropTableRowsCache(topic.key);
9360
+ signal(ROWS_STALE_EVENT);
9361
+ }}
9362
  /* ⭐ OWNER ITEM 9 — the route's "Add a record" search reaches PAST the view's own
9363
  filter, so it is handed `scopedRows`: the book after the row wall (`allowed_pids`
9364
  plus the business-unit scope) and before `useVisibleRows` applies filters, search
 
9577
  : `Delete ${selectedPids.size === 1 ? "record" : "records"}`}
9578
  </button>
9579
  )}
9580
+ {!routePanelOpen && (cohortMode ? (
9581
  // Item 2c: on the Cohort page the selection EDITS MEMBERSHIP of the fixed set —
9582
  // "Remove from cohort" replaces "Add to cohort". Direct (no popover): the
9583
  // checked set is explicit, the button says what it does, and re-adding is one
 
9610
  >
9611
  Add to cohort
9612
  </button>
9613
+ ))}
9614
  {/* ⭐ Owner item 9 — the counterpart, and it renders ONLY when it can do
9615
  something: the checked rows have to be in a cohort this viewer may edit for
9616
  "Remove from cohort…" to mean anything. Same bar, same selection, opposite
9617
  direction — the ellipsis says a picker follows, because unlike cohort mode
9618
  the target is not implied by where you are standing. */}
9619
+ {!routePanelOpen && !cohortMode && removableLists.length > 0 && (
9620
  <button
9621
  type="button"
9622
  className="cg-btn cg-selbar-remove-pick"
 
9730
  */
9731
  linkTargets={linkTargets}
9732
  rollupSourceOffer={rollupSourceOffer}
9733
+ hopTopicOffer={hopTopicOffer}
9734
  locked={menuField.key === lockedKey}
9735
  schemaLocked={isSchemaLocked(menuField)}
9736
  /* ⭐⭐ W40-T24 — the menu's `columnDefinitionOffer` (display.ts) needs the same stratum
 
9789
  }
9790
  onProfileFlag={isUserTable ? setProfileFlag : undefined}
9791
  onFieldConfig={isUserTable ? (patch) => setFieldConfig(menuField.key, patch) : undefined}
9792
+ onSetDeletionLock={
9793
+ isUserTable && viewer?.isAdmin
9794
+ ? (deletionLocked) => setDeletionLock(menuField.key, deletionLocked)
9795
+ : undefined
9796
+ }
9797
+ onCopyFieldLink={() => copyFieldDataLink(menuField.key)}
9798
  onRetype={
9799
  // Item 2 — a CREATED field retypes IN PLACE from the pane.
9800
  //
 
9955
  }
9956
  : undefined
9957
  }
9958
+ onRemoveFromMine={() => {
9959
+ fieldBulkDoors.onRemoveField(menuField.key);
9960
+ setColumnMenu(null);
9961
+ }}
9962
  onDuplicate={
9963
  // Creatable strata only — a base Odoo field offers no Duplicate (contract).
9964
  menuField.custom && !menuField.shared ? () => duplicateField(menuField) : undefined
 
9987
  ? setFieldConfig(menuField.key, { agg: agg ?? "" })
9988
  : saveField({ ...menuField, agg })
9989
  }
9990
+ onSort={
9991
+ activeSortsLocked
9992
+ ? undefined
9993
+ : (dir) => {
9994
+ const refusal = routeSortRefusal(
9995
+ menuField.key,
9996
+ { nodes: config.filters, conj: config.filterConj },
9997
+ fields,
9998
+ );
9999
+ if (refusal) {
10000
+ signal(TOAST_EVENT, refusal);
10001
+ return;
10002
+ }
10003
+ updateConfig({ ...config, sorts: [{ colId: menuField.key, dir }] });
10004
+ }
10005
  }
10006
+ onClearSort={
10007
+ activeSortsLocked
10008
+ ? undefined
10009
+ : () => updateConfig({
10010
+ ...config,
10011
+ sorts: config.sorts.filter((s) => s.colId !== menuField.key),
10012
+ })
10013
  }
10014
+ onFilterBy={activeFiltersLocked ? undefined : () =>
10015
  // Item 6c — a MEASURE-carrying column seeds the equivalent MEASURE condition
10016
  // (same measure key + window, value empty); every other filterable column seeds
10017
  // an ordinary column condition. Same signal, one consumer (the Toolbar).
 
10031
  }
10032
  onUnpin={frozenN > 1 ? unpinFields : undefined}
10033
  scopeChoice={scopeChoice}
10034
+ onClearFilter={
10035
+ activeFiltersLocked
10036
+ ? undefined
10037
+ : () => updateConfig({
10038
+ ...config,
10039
+ filters: dropFieldFromTree(config.filters, menuField.key, measureCols),
10040
+ })
10041
  }
10042
  onGroupByField={() => updateConfig({ ...config, groupBy: menuField.key })}
10043
  onClearGroup={() => updateConfig({ ...config, groupBy: null })}
 
10071
  field={fieldByKey.get(lockedKey)!}
10072
  fields={fields}
10073
  locked
10074
+ isUserTable={isUserTable}
10075
  viewer={viewer}
10076
  sortedDir={null}
10077
  isFiltered={false}
 
10082
  onNote={() => undefined}
10083
  onHide={() => undefined}
10084
  onCreate={createField}
10085
+ onRemoveFromMine={() => {
10086
+ fieldBulkDoors.onRemoveField(lockedKey);
10087
+ setPlusMenu(null);
10088
+ }}
10089
  /* The SAME answer as the sibling instance above, stated rather than defaulted: this is
10090
  the "+" menu and it creates through the identical `createField`, so a different value
10091
  here would mean one door offers the kind and its twin does not. The note above the
 
10117
  // either way. See the sibling's note for why self-links are offered now.
10118
  linkTargets={linkTargets}
10119
  rollupSourceOffer={rollupSourceOffer}
10120
+ hopTopicOffer={hopTopicOffer}
10121
  />
10122
  )}
10123
 
 
10157
 
10158
  {/* The selection bar's cohort picker: existing cohorts, or a new one by name. Mirrors the
10159
  view menu's Add-to-list surface so the two ways of building a cohort read identically. */}
10160
+ {!routePanelOpen && selAddOpen && selAddRef.current && selectedPids.size > 0 && (
10161
  <AnchoredOverlay
10162
  anchor={selAddRef.current}
10163
  className="cg-pop cg-add-list-pop"
 
10246
  </AnchoredOverlay>
10247
  )}
10248
 
10249
+ {!routePanelOpen && selRemoveOpen && selRemoveRef.current && removableLists.length > 0 && (
10250
  <AnchoredOverlay
10251
  anchor={selRemoveRef.current}
10252
  className="cg-pop cg-add-list-pop"
 
10282
  once. Candidates exclude current members; picks ACCUMULATE across searches, so the
10283
  confirm button carries the running total. The 50-row render cap is stated beside the
10284
  list — nothing silently truncated. */}
10285
+ {!routePanelOpen && cohortMode && addCustOpen && addCustRef.current && activeCohortId && (
10286
  <AnchoredOverlay
10287
  anchor={addCustRef.current}
10288
  className="cg-pop cg-addcust-pop"
 
10379
  onClose={closeJson}
10380
  />
10381
  )}
10382
+ {linkField && linkTargetScope && linkAt && (
10383
  <LinkGridModal
10384
  label={linkField.label}
10385
+ table={linkTargetScope}
10386
  recordIds={linkedRecordIds}
10387
  editable={canEditField(linkField) && !isDerivedLink(linkField)}
10388
+ single={linkField.link?.single === true}
10389
+ excludeRecordId={linkTargetScope === scope ? linkAt.pid : undefined}
10390
  onSave={(ids) => patchAndRecord(
10391
  linkAt.pid,
10392
  { [linkField.key]: ids.join(",") },
web/src/customer-grid/FieldProperties.tsx ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { isPickType } from "./types";
2
+ import type { Field } from "./types";
3
+
4
+ /** C3's server-owned field facts are intentionally read, never inferred client-side. */
5
+ type ContractField = Field & {
6
+ origin?: string;
7
+ valueAuthority?: string;
8
+ scope?: string;
9
+ deletionLocked?: boolean;
10
+ };
11
+
12
+ const unknown = "Not provided";
13
+
14
+ export function FieldProperties({ field }: { field: Field }) {
15
+ const contract = field as ContractField;
16
+ const axes = [
17
+ ["Kind", contract.kind === "json" ? "Table" : contract.kind],
18
+ ["Origin", contract.origin],
19
+ ["Value authority", contract.valueAuthority],
20
+ ["Scope", contract.scope],
21
+ ];
22
+ return (
23
+ <section className="cg-field-properties" aria-label={`${field.label} properties`}>
24
+ <h3>Field properties</h3>
25
+ <dl>
26
+ {axes.map(([label, value]) => (
27
+ <div key={label}>
28
+ <dt>{label}</dt>
29
+ <dd>{value || unknown}</dd>
30
+ </div>
31
+ ))}
32
+ <div>
33
+ <dt>Deletion lock</dt>
34
+ <dd>{contract.deletionLocked ? "Locked" : "Not locked"}</dd>
35
+ </div>
36
+ {isPickType(field.type) && typeof field.limits?.maxOptions === "number" && (
37
+ <div>
38
+ <dt>Maximum options</dt>
39
+ <dd>{field.limits.maxOptions}</dd>
40
+ </div>
41
+ )}
42
+ </dl>
43
+ </section>
44
+ );
45
+ }
46
+
47
+ export function fieldDeletionLocked(field: Field): boolean {
48
+ return Boolean((field as ContractField).deletionLocked);
49
+ }
web/src/customer-grid/FormInterface.tsx CHANGED
@@ -26,6 +26,7 @@ import { useCallback, useEffect, useMemo, useState } from "react";
26
  import { API_V1, CREDENTIALS } from "../apiContract";
27
  import type { Field, FieldType, FormSpec } from "./types";
28
  import { TYPE_LABELS } from "./iconShapes";
 
29
  import "./FormInterface.css";
30
 
31
  /**
@@ -226,7 +227,7 @@ export function FormInterface({
226
  // ---- the states that are not a form -------------------------------------------------------
227
  if (!viewId) {
228
  return (
229
- <div className="cg-form-empty">
230
  A form belongs to a saved view. Save this view first, then build the form on it.
231
  </div>
232
  );
@@ -236,7 +237,7 @@ export function FormInterface({
236
  // (a locked one accepts no new records, so a form could only ever collect refusals), while
237
  // `readOnlyReason` is about the VIEWER's grant.
238
  return (
239
- <div className="cg-form-empty">
240
  This database does not accept new records, so a form has nowhere to put an answer.
241
  </div>
242
  );
@@ -245,7 +246,7 @@ export function FormInterface({
245
  const diverged = spec === null && (link.stored?.fields ?? 0) > 0;
246
 
247
  return (
248
- <div className="cg-form-build">
249
  <div className="cg-form-pane">
250
  <h2 className="cg-form-h">Form</h2>
251
  {!canEdit && readOnlyReason && <p className="cg-form-note">{readOnlyReason}</p>}
 
26
  import { API_V1, CREDENTIALS } from "../apiContract";
27
  import type { Field, FieldType, FormSpec } from "./types";
28
  import { TYPE_LABELS } from "./iconShapes";
29
+ import { foldNavOnWorkSurface } from "./navFold";
30
  import "./FormInterface.css";
31
 
32
  /**
 
227
  // ---- the states that are not a form -------------------------------------------------------
228
  if (!viewId) {
229
  return (
230
+ <div className="cg-form-empty" onPointerDown={foldNavOnWorkSurface}>
231
  A form belongs to a saved view. Save this view first, then build the form on it.
232
  </div>
233
  );
 
237
  // (a locked one accepts no new records, so a form could only ever collect refusals), while
238
  // `readOnlyReason` is about the VIEWER's grant.
239
  return (
240
+ <div className="cg-form-empty" onPointerDown={foldNavOnWorkSurface}>
241
  This database does not accept new records, so a form has nowhere to put an answer.
242
  </div>
243
  );
 
246
  const diverged = spec === null && (link.stored?.fields ?? 0) > 0;
247
 
248
  return (
249
+ <div className="cg-form-build" onPointerDown={foldNavOnWorkSurface}>
250
  <div className="cg-form-pane">
251
  <h2 className="cg-form-h">Form</h2>
252
  {!canEdit && readOnlyReason && <p className="cg-form-note">{readOnlyReason}</p>}
web/src/customer-grid/MapView.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/RecordDetail.tsx CHANGED
@@ -1627,7 +1627,7 @@ export default function RecordDetail({
1627
  <section className="cg-detail-section cg-detail-relsec">
1628
  <h3 className="cg-detail-sechead">
1629
  {relTargets.length === 0 ? (
1630
- <span>Relational</span>
1631
  ) : (
1632
  <button
1633
  type="button"
@@ -1635,7 +1635,7 @@ export default function RecordDetail({
1635
  aria-expanded={relOpen}
1636
  onClick={() => setRelOpen((open) => !open)}
1637
  >
1638
- Relational
1639
  </button>
1640
  )}
1641
  <span className="cg-detail-seccount">
 
1627
  <section className="cg-detail-section cg-detail-relsec">
1628
  <h3 className="cg-detail-sechead">
1629
  {relTargets.length === 0 ? (
1630
+ <span>Related</span>
1631
  ) : (
1632
  <button
1633
  type="button"
 
1635
  aria-expanded={relOpen}
1636
  onClick={() => setRelOpen((open) => !open)}
1637
  >
1638
+ Related
1639
  </button>
1640
  )}
1641
  <span className="cg-detail-seccount">
web/src/customer-grid/RouteNav.tsx ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useMemo, useState } from "react";
2
+ import { folderPath, levelAt, resolveStoredPath } from "./dataPath";
3
+ import type { NormalizedRouteMapLink } from "./routeLinks";
4
+ import { submitRouteStopMove } from "./routeStopMove";
5
+ import { boundedGoogleMapsUrl } from "./routeZoneTypes";
6
+ import type {
7
+ MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate,
8
+ RouteDeliveryDto, RouteDeliveryRequest,
9
+ } from "./routeZoneTypes";
10
+ import "../styles/wave42/route-nav.css";
11
+
12
+ type Result = Promise<string | null>;
13
+
14
+ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources, storageKey,
15
+ createdRoute, onCreatedDismiss, onToggle, onActiveRouteChange, onOpenRecord, onCreate,
16
+ onMoveToOrder, onUpdate, onDuplicate, onDelete, onShare, onRouteMove, onRouteReorder,
17
+ onFolderCreate, onFolderUpdate, onFolderDelete, onFolderReorder, filteredRecordCount,
18
+ onSelectFiltered, onCreateStart, mapLinks, mapLinkRefusal, deliveries, onSchedule,
19
+ onDeleteDelivery }: {
20
+ routes: MapRouteDto[];
21
+ folders: MapRouteFolderDto[];
22
+ selectedIds: ReadonlySet<string>;
23
+ activeRouteId: string | null;
24
+ sources: MapRouteSource[];
25
+ storageKey: string;
26
+ createdRoute: MapRouteDto | null;
27
+ onCreatedDismiss: () => void;
28
+ onToggle: (route: MapRouteDto) => void;
29
+ onActiveRouteChange: (routeId: string | null) => void;
30
+ onOpenRecord: (pid: number) => void;
31
+ onCreate: (name: string, source: MapRouteSource) => Result;
32
+ onMoveToOrder: (route: MapRouteDto, customerPid: number, order: number) => Result;
33
+ onUpdate: (route: MapRouteDto, patch: MapRouteUpdate) => Result;
34
+ onDuplicate: (route: MapRouteDto) => Result;
35
+ onDelete: (route: MapRouteDto) => Promise<string | null>;
36
+ onShare: (route: MapRouteDto) => Result;
37
+ onRouteMove: (route: MapRouteDto, folderId: string | null) => Result;
38
+ onRouteReorder: (order: string[]) => Result;
39
+ onFolderCreate: (name: string, parent: string | null) => Result;
40
+ onFolderUpdate: (folder: MapRouteFolderDto, patch: { name?: string; parent?: string | null }) => Result;
41
+ onFolderDelete: (folder: MapRouteFolderDto) => Result;
42
+ onFolderReorder: (order: string[]) => Result;
43
+ filteredRecordCount: number;
44
+ onSelectFiltered: () => void;
45
+ onCreateStart: () => void;
46
+ mapLinks: NormalizedRouteMapLink[];
47
+ mapLinkRefusal: string | null;
48
+ deliveries: RouteDeliveryDto[] | null;
49
+ onSchedule: (route: MapRouteDto, request: RouteDeliveryRequest) => Result;
50
+ onDeleteDelivery: (route: MapRouteDto, delivery: RouteDeliveryDto) => Result;
51
+ }) {
52
+ const routePathKey = `aios-routes-at-${storageKey}`;
53
+ const [at, setAt] = useState<string | null>(() => {
54
+ if (typeof window === "undefined") return null;
55
+ try { return window.localStorage.getItem(routePathKey); } catch { return null; }
56
+ });
57
+ const [creating, setCreating] = useState(false);
58
+ const [creatingFolder, setCreatingFolder] = useState(false);
59
+ const [name, setName] = useState("");
60
+ const [folderName, setFolderName] = useState("");
61
+ const [sourceId, setSourceId] = useState<MapRouteSource["id"]>("selection");
62
+ const [error, setError] = useState<string | null>(null);
63
+ const [orderDrafts, setOrderDrafts] = useState<Record<number, string>>({});
64
+ const [orderErrors, setOrderErrors] = useState<Record<number, string>>({});
65
+ const [editName, setEditName] = useState("");
66
+ const [editMapsUrl, setEditMapsUrl] = useState("");
67
+ const [deleteConfirm, setDeleteConfirm] = useState(false);
68
+ const [menuId, setMenuId] = useState<string | null>(null);
69
+ const [renameId, setRenameId] = useState<string | null>(null);
70
+ const [renameDraft, setRenameDraft] = useState("");
71
+ const [busy, setBusy] = useState(false);
72
+ const [deliveryRecipient, setDeliveryRecipient] = useState("");
73
+ const [deliveryMapsPerLink, setDeliveryMapsPerLink] = useState(10);
74
+ const [deliveryNotice, setDeliveryNotice] = useState<string | null>(null);
75
+ const [deliveryError, setDeliveryError] = useState<string | null>(null);
76
+ const [deliveryBusy, setDeliveryBusy] = useState(false);
77
+ const [mapCopyNotice, setMapCopyNotice] = useState<string | null>(null);
78
+ const [mapCopyError, setMapCopyError] = useState<string | null>(null);
79
+ const route = activeRouteId ? routes.find((item) => item.id === activeRouteId) : null;
80
+ const source = sources.find((item) => item.id === sourceId) || sources[0];
81
+ const mapsUrl = boundedGoogleMapsUrl(route?.mapsUrl);
82
+ const knownFolders = useMemo(() => new Set(folders.map((folder) => folder.id)), [folders]);
83
+ const validAt = resolveStoredPath(at, knownFolders);
84
+ const level = useMemo(
85
+ () => levelAt(validAt, folders, routes, (item) => item.folderId),
86
+ [folders, routes, validAt]
87
+ );
88
+ const crumbs = useMemo(() => folderPath(validAt, folders), [folders, validAt]);
89
+ const deliveryTimezone = useMemo(() => {
90
+ try { return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; }
91
+ catch { return "UTC"; }
92
+ }, []);
93
+
94
+ const navigate = (folderId: string | null) => {
95
+ setAt(folderId);
96
+ setMenuId(null);
97
+ setError(null);
98
+ try {
99
+ if (folderId) window.localStorage.setItem(routePathKey, folderId);
100
+ else window.localStorage.removeItem(routePathKey);
101
+ } catch { /* Navigation remains usable when storage is unavailable. */ }
102
+ };
103
+
104
+ useEffect(() => {
105
+ if (at && !validAt) navigate(null);
106
+ // `navigate` deliberately remains a local action; validity is the only reactive input.
107
+ // eslint-disable-next-line react-hooks/exhaustive-deps
108
+ }, [at, validAt]);
109
+ useEffect(() => {
110
+ setEditName(route?.name || "");
111
+ setEditMapsUrl(route?.mapsUrl || "");
112
+ setOrderDrafts({});
113
+ setOrderErrors({});
114
+ setDeleteConfirm(false);
115
+ setError(null);
116
+ setDeliveryNotice(null);
117
+ setDeliveryError(null);
118
+ setMapCopyNotice(null);
119
+ setMapCopyError(null);
120
+ }, [route?.id, route?.mapsUrl, route?.name]);
121
+
122
+ const copyMapLinks = () => {
123
+ setMapCopyNotice(null);
124
+ setMapCopyError(null);
125
+ const clipboard = typeof navigator === "undefined" ? null : navigator.clipboard;
126
+ if (!mapLinks.length || !clipboard?.writeText) {
127
+ setMapCopyError("Maps links could not be copied in this browser.");
128
+ return;
129
+ }
130
+ void clipboard.writeText(mapLinks.map((link) => link.url).join("\n"))
131
+ .then(() => setMapCopyNotice(
132
+ `${mapLinks.length.toLocaleString()} Maps link${mapLinks.length === 1 ? "" : "s"} copied.`
133
+ ))
134
+ .catch(() => setMapCopyError("Maps links could not be copied. Open each link instead."));
135
+ };
136
+
137
+ const scheduleDelivery = (target: MapRouteDto) => {
138
+ const recipient = deliveryRecipient.trim();
139
+ if (!recipient) {
140
+ setDeliveryError("Choose an active Inbox recipient.");
141
+ return;
142
+ }
143
+ setDeliveryBusy(true);
144
+ setDeliveryError(null);
145
+ setDeliveryNotice(null);
146
+ void onSchedule(target, {
147
+ recipient,
148
+ timezone: deliveryTimezone,
149
+ mapsPerLink: deliveryMapsPerLink,
150
+ }).then((message) => {
151
+ if (message) setDeliveryError(message);
152
+ else setDeliveryNotice(`${target.name} will be delivered to ${recipient} daily at 08:00.`);
153
+ }).finally(() => setDeliveryBusy(false));
154
+ };
155
+
156
+ const removeDelivery = (target: MapRouteDto, delivery: RouteDeliveryDto) => {
157
+ setDeliveryBusy(true);
158
+ setDeliveryError(null);
159
+ setDeliveryNotice(null);
160
+ void onDeleteDelivery(target, delivery).then((message) => {
161
+ if (message) setDeliveryError(message);
162
+ else setDeliveryNotice(`${delivery.name} was removed.`);
163
+ }).finally(() => setDeliveryBusy(false));
164
+ };
165
+
166
+ const finish = (operation: Result) => {
167
+ setBusy(true);
168
+ void operation.then(setError).finally(() => setBusy(false));
169
+ };
170
+ const commitStopMove = (target: MapRouteDto, pid: number, raw: string) => {
171
+ setBusy(true);
172
+ setOrderErrors((current) => {
173
+ const next = { ...current };
174
+ delete next[pid];
175
+ return next;
176
+ });
177
+ void submitRouteStopMove(target, pid, raw, onMoveToOrder).then((result) => {
178
+ if (result.error) {
179
+ const message = result.error;
180
+ setOrderErrors((current) => ({ ...current, [pid]: message }));
181
+ return;
182
+ }
183
+ setOrderDrafts((current) => {
184
+ const next = { ...current };
185
+ delete next[pid];
186
+ return next;
187
+ });
188
+ setOrderErrors((current) => {
189
+ const next = { ...current };
190
+ delete next[pid];
191
+ return next;
192
+ });
193
+ }).finally(() => setBusy(false));
194
+ };
195
+ const swap = (ids: string[], id: string, delta: number) => {
196
+ const index = ids.indexOf(id);
197
+ const other = index + delta;
198
+ if (index < 0 || other < 0 || other >= ids.length) return null;
199
+ const next = [...ids];
200
+ [next[index], next[other]] = [next[other], next[index]];
201
+ return next;
202
+ };
203
+
204
+ if (route) {
205
+ const canEdit = route.permission.canEdit && route.compatibility !== "legacy-route-order";
206
+ return (
207
+ <section className="cg-w44-route-nav" aria-label={`${route.name} route`}>
208
+ <button type="button" className="cg-w44-route-back" onClick={() => onActiveRouteChange(null)}>
209
+ Back to routes
210
+ </button>
211
+ <div className="cg-w44-route-title">
212
+ <i style={{ backgroundColor: route.color }} aria-hidden="true" />
213
+ {route.number}. {route.name}
214
+ </div>
215
+ <p className="cg-w44-route-meta">
216
+ {route.shared ? `Shared by ${route.owner || "another user"}` : route.sharedOut ? "Shared with others" : "Private"}
217
+ </p>
218
+ {route.visibleStopIds.length ? (
219
+ <ol className="cg-w44-route-stops">
220
+ {route.visibleStopIds.map((pid, index) => (
221
+ <li key={pid}>
222
+ <button type="button" className="cg-w44-route-stop-open"
223
+ aria-label={`Open stop ${index + 1} record`} onClick={() => onOpenRecord(pid)}>
224
+ Stop {index + 1}
225
+ </button>
226
+ {canEdit && (
227
+ <span className="cg-w44-route-stop-actions">
228
+ <button type="button" className="cg-w44-route-step" disabled={busy || index === 0}
229
+ aria-label={`Move stop ${index + 1} earlier`}
230
+ title="Move earlier" onClick={() => commitStopMove(route, pid, String(index))}>
231
+ <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M10 3 5 8l5 5" /></svg>
232
+ </button>
233
+ <label className="cg-w44-route-position"><span>Position</span>
234
+ <input className="cg-w44-route-order" type="text" inputMode="numeric" pattern="[0-9]*"
235
+ disabled={busy}
236
+ value={orderDrafts[pid] ?? String(index + 1)}
237
+ aria-invalid={orderErrors[pid] ? true : undefined}
238
+ aria-describedby={orderErrors[pid] ? `cg-route-order-error-${pid}` : undefined}
239
+ onFocus={(event) => event.currentTarget.select()}
240
+ onChange={(event) => {
241
+ const raw = event.target.value;
242
+ setOrderDrafts((current) => ({ ...current, [pid]: raw }));
243
+ setOrderErrors((current) => {
244
+ const next = { ...current };
245
+ delete next[pid];
246
+ return next;
247
+ });
248
+ }}
249
+ onKeyDown={(event) => {
250
+ if (event.key === "Enter") {
251
+ event.preventDefault();
252
+ commitStopMove(route, pid, event.currentTarget.value);
253
+ } else if (event.key === "Escape") {
254
+ event.preventDefault();
255
+ setOrderDrafts((current) => {
256
+ const next = { ...current };
257
+ delete next[pid];
258
+ return next;
259
+ });
260
+ setOrderErrors((current) => {
261
+ const next = { ...current };
262
+ delete next[pid];
263
+ return next;
264
+ });
265
+ }
266
+ }} />
267
+ </label>
268
+ <button type="button" className="cg-w44-route-position-apply" disabled={busy}
269
+ onClick={() => commitStopMove(route, pid, orderDrafts[pid] ?? String(index + 1))}>
270
+ Move
271
+ </button>
272
+ <button type="button" className="cg-w44-route-step"
273
+ disabled={busy || index === route.visibleStopIds.length - 1}
274
+ aria-label={`Move stop ${index + 1} later`}
275
+ title="Move later" onClick={() => commitStopMove(route, pid, String(index + 2))}>
276
+ <svg viewBox="0 0 16 16" aria-hidden="true"><path d="m6 3 5 5-5 5" /></svg>
277
+ </button>
278
+ </span>
279
+ )}
280
+ {orderErrors[pid] && <span id={`cg-route-order-error-${pid}`}
281
+ className="cg-w44-route-order-error" role="alert">{orderErrors[pid]}</span>}
282
+ </li>
283
+ ))}
284
+ </ol>
285
+ ) : <p className="cg-w44-route-empty">No stops yet. Add customers from a route source.</p>}
286
+ {mapsUrl && <a className="cg-w44-route-maps" href={mapsUrl} target="_blank" rel="noopener noreferrer">Open Maps</a>}
287
+ {route.mapsUrl && !mapsUrl && <span className="cg-w44-route-empty">Maps link is unavailable.</span>}
288
+ <section className="cg-w44-route-map-links" aria-labelledby="cg-route-map-links-title">
289
+ <div>
290
+ <h3 id="cg-route-map-links-title">Google Maps</h3>
291
+ <p>Current ordered Route stops, split into links of at most 10 stops.</p>
292
+ </div>
293
+ {mapLinkRefusal ? (
294
+ <span className="cg-w44-route-warning" role="alert">{mapLinkRefusal}</span>
295
+ ) : mapLinks.length ? <>
296
+ <ol>
297
+ {mapLinks.map((link) => (
298
+ <li key={`${link.index}:${link.start}:${link.end}`}>
299
+ <a href={link.url} target="_blank" rel="noopener noreferrer">
300
+ Link {link.index} - Stops {link.start + 1} to {link.end}
301
+ </a>
302
+ <small>{link.stopIds.length.toLocaleString()} stops</small>
303
+ </li>
304
+ ))}
305
+ </ol>
306
+ <button type="button" className="cg-route-copy-links" onClick={copyMapLinks}>
307
+ Copy Maps links
308
+ </button>
309
+ </> : (
310
+ <span className="cg-w44-route-empty">Add at least two located stops to open this Route in Maps.</span>
311
+ )}
312
+ {mapCopyNotice && <span className="cg-w44-route-empty" role="status">{mapCopyNotice}</span>}
313
+ {mapCopyError && <span className="cg-w44-route-warning" role="alert">{mapCopyError}</span>}
314
+ </section>
315
+ {canEdit ? (
316
+ <div className="cg-w44-route-edit" aria-label="Edit Route">
317
+ <label className="cg-w44-route-label">Route name
318
+ <input className="cg-input" value={editName} maxLength={120} onChange={(event) => setEditName(event.target.value)} />
319
+ </label>
320
+ <label className="cg-w44-route-label">Google Maps URL
321
+ <input className="cg-input" type="url" value={editMapsUrl} maxLength={2048}
322
+ placeholder="https://www.google.com/maps/..." onChange={(event) => setEditMapsUrl(event.target.value)} />
323
+ </label>
324
+ <div className="cg-form-actions">
325
+ <button type="button" className="cg-btn cg-btn--primary" disabled={busy || !editName.trim()}
326
+ onClick={() => finish(onUpdate(route, { name: editName.trim(), mapsUrl: editMapsUrl.trim() }))}>
327
+ Save Route
328
+ </button>
329
+ <button type="button" className="cg-btn" disabled={busy} onClick={() => finish(onShare(route))}>Share</button>
330
+ <button type="button" className="cg-btn" disabled={busy} onClick={() => setDeleteConfirm(true)}>Delete Route</button>
331
+ </div>
332
+ {deleteConfirm && (
333
+ <div role="alertdialog" aria-label={`Delete ${route.name} Route`} aria-describedby="cg-route-delete-copy">
334
+ <p id="cg-route-delete-copy">Delete this Route and its saved stop order?</p>
335
+ <div className="cg-form-actions">
336
+ <button type="button" className="cg-btn cg-btn--danger" disabled={busy}
337
+ onClick={() => { setBusy(true); void onDelete(route).then((message) => {
338
+ setError(message); if (!message) onActiveRouteChange(null);
339
+ }).finally(() => setBusy(false)); }}>Confirm delete</button>
340
+ <button type="button" className="cg-btn" disabled={busy} onClick={() => setDeleteConfirm(false)}>Cancel</button>
341
+ </div>
342
+ </div>
343
+ )}
344
+ </div>
345
+ ) : <p className="cg-w44-route-empty">{route.compatibility === "legacy-route-order"
346
+ ? "This legacy Route is read-only." : "Only the owner and an editor of the source View can change this Route."}</p>}
347
+ {canEdit && (
348
+ <section className="cg-w44-route-delivery" aria-labelledby="cg-route-delivery-title">
349
+ <div>
350
+ <h3 id="cg-route-delivery-title">Daily delivery</h3>
351
+ <p>Freeze this Route now and send it to Inbox each day at 08:00 ({deliveryTimezone}).</p>
352
+ </div>
353
+ <label className="cg-w44-route-label">Inbox recipient
354
+ <input className="cg-input" value={deliveryRecipient} autoComplete="username"
355
+ placeholder="Account username" onChange={(event) => setDeliveryRecipient(event.target.value)} />
356
+ </label>
357
+ <label className="cg-w44-route-label">Stops per Maps link
358
+ <input className="cg-input" type="number" min={2} max={10} value={deliveryMapsPerLink}
359
+ onChange={(event) => setDeliveryMapsPerLink(
360
+ Math.max(2, Math.min(10, Number(event.target.value) || 2))
361
+ )} />
362
+ </label>
363
+ <button type="button" className="cg-btn cg-btn--primary"
364
+ disabled={deliveryBusy || route.visibleStopIds.length < 2 || !deliveryRecipient.trim()}
365
+ onClick={() => scheduleDelivery(route)}>
366
+ {deliveryBusy ? "Scheduling" : "Schedule delivery"}
367
+ </button>
368
+ {route.visibleStopIds.length < 2 && (
369
+ <span className="cg-w44-route-empty">Add at least two stops before scheduling.</span>
370
+ )}
371
+ <div className="cg-w44-route-delivery-list" aria-label="Existing Route deliveries">
372
+ {deliveries === null ? (
373
+ <span className="cg-w44-route-empty">Loading deliveries.</span>
374
+ ) : deliveries.length === 0 ? (
375
+ <span className="cg-w44-route-empty">No deliveries scheduled.</span>
376
+ ) : (
377
+ <ul>
378
+ {deliveries.map((delivery) => (
379
+ <li key={delivery.id}>
380
+ <div className="cg-w44-route-delivery-audit">
381
+ <strong>{delivery.name}</strong>
382
+ <dl>
383
+ <div><dt>Source View</dt><dd>{delivery.snapshot.sourceViewName} <code>{delivery.snapshot.sourceViewId}</code></dd></div>
384
+ <div><dt>Pinned revision</dt><dd><code>{delivery.snapshot.sourceViewRevision}</code></dd></div>
385
+ <div><dt>Schedule</dt><dd>{delivery.schedule.cron || "Not scheduled"} - {delivery.schedule.enabled === false ? "Paused" : "Active"}</dd></div>
386
+ <div><dt>Timezone</dt><dd>{delivery.snapshot.timezone}</dd></div>
387
+ <div><dt>Recipient</dt><dd>{delivery.recipient}</dd></div>
388
+ <div><dt>Ordered stop IDs</dt><dd><code>{delivery.snapshot.orderedStopIds.join(", ")}</code></dd></div>
389
+ <div><dt>Maps link cap</dt><dd>{delivery.snapshot.mapsPerLink} stops per link</dd></div>
390
+ </dl>
391
+ </div>
392
+ <button type="button" className="cg-btn" disabled={deliveryBusy}
393
+ aria-label={`Remove ${delivery.name}`} onClick={() => removeDelivery(route, delivery)}>
394
+ Remove
395
+ </button>
396
+ </li>
397
+ ))}
398
+ </ul>
399
+ )}
400
+ </div>
401
+ {deliveryNotice && <span className="cg-w44-route-empty" role="status">{deliveryNotice}</span>}
402
+ {deliveryError && <span className="cg-w44-route-warning" role="alert">{deliveryError}</span>}
403
+ </section>
404
+ )}
405
+ {error && <span className="cg-w44-route-empty" role="status">{error}</span>}
406
+ </section>
407
+ );
408
+ }
409
+
410
+ if (creating) {
411
+ return (
412
+ <section className="cg-w44-route-nav" aria-label="Create route">
413
+ <button type="button" className="cg-w44-route-back" onClick={() => setCreating(false)}>Back to routes</button>
414
+ <label className="cg-w44-route-label">Route name
415
+ <input className="cg-input" value={name} maxLength={120} onChange={(event) => setName(event.target.value)} />
416
+ </label>
417
+ <fieldset className="cg-w44-route-sources"><legend>Route source</legend>
418
+ {sources.map((item) => <label key={item.id}><input type="radio" name="route-source"
419
+ checked={sourceId === item.id} onChange={() => setSourceId(item.id)} />
420
+ {item.label} ({item.pids.length.toLocaleString()})</label>)}
421
+ </fieldset>
422
+ <button type="button" className="cg-btn cg-btn--primary" disabled={busy || !name.trim() || !source || source.pids.length === 0}
423
+ onClick={() => { if (!source) return; setBusy(true); void onCreate(name.trim(), source).then((message) => {
424
+ setError(message); if (!message) { setName(""); setCreating(false); }
425
+ }).finally(() => setBusy(false)); }}>Create route</button>
426
+ {error && <span className="cg-w44-route-empty" role="status">{error}</span>}
427
+ </section>
428
+ );
429
+ }
430
+
431
+ const routeIds = level.leaves.map((item) => item.id);
432
+ const folderIds = level.folders.map((item) => item.id);
433
+ return (
434
+ <section className="cg-w44-route-nav" aria-label="Named routes">
435
+ <div className="cg-w44-route-head">
436
+ <div className="cg-w44-route-title">Routes</div>
437
+ <button type="button" className="cg-w44-route-detail" onClick={() => {
438
+ setError(null); onCreateStart(); setCreating(true);
439
+ }}>Create route</button>
440
+ </div>
441
+ <button type="button" className="cg-w44-route-filtered" disabled={filteredRecordCount === 0}
442
+ onClick={onSelectFiltered}>
443
+ Select all {filteredRecordCount.toLocaleString()} filtered records
444
+ </button>
445
+ <nav className="cg-w44-route-path" aria-label="Route folder path">
446
+ <button type="button" aria-current={!validAt ? "page" : undefined} onClick={() => navigate(null)}>Routes</button>
447
+ {crumbs.map((folder) => <span key={folder.id}><b aria-hidden="true">›</b>
448
+ <button type="button" aria-current={validAt === folder.id ? "page" : undefined}
449
+ onClick={() => navigate(folder.id)}>{folder.name}</button></span>)}
450
+ </nav>
451
+ <div className="cg-w44-route-folder-tools">
452
+ {validAt && <button type="button" className="cg-w44-route-back" onClick={() => navigate(level.parent)}>Up</button>}
453
+ <button type="button" className="cg-w44-route-detail" onClick={() => setCreatingFolder((value) => !value)}>New folder</button>
454
+ </div>
455
+ {creatingFolder && <div className="cg-w44-route-folder-create">
456
+ <input className="cg-input" value={folderName} maxLength={80} aria-label="New Route folder name"
457
+ onChange={(event) => setFolderName(event.target.value)} />
458
+ <button type="button" className="cg-btn cg-btn--primary" disabled={busy || !folderName.trim()}
459
+ onClick={() => { setBusy(true); void onFolderCreate(folderName.trim(), validAt).then((message) => {
460
+ setError(message); if (!message) { setFolderName(""); setCreatingFolder(false); }
461
+ }).finally(() => setBusy(false)); }}>Create</button>
462
+ </div>}
463
+ <div className="cg-w44-route-level" aria-label={level.folder ? `${level.folder.name} contents` : "Route folder contents"}>
464
+ {level.folders.map((folder, index) => (
465
+ <div key={folder.id} className="cg-w44-route-folder-row">
466
+ {renameId === `folder:${folder.id}` ? <>
467
+ <input className="cg-input" value={renameDraft} maxLength={80} aria-label={`Rename ${folder.name}`}
468
+ onChange={(event) => setRenameDraft(event.target.value)} />
469
+ <button type="button" disabled={!renameDraft.trim() || busy}
470
+ onClick={() => { setBusy(true); void onFolderUpdate(folder, { name: renameDraft.trim() }).then((message) => {
471
+ setError(message); if (!message) setRenameId(null);
472
+ }).finally(() => setBusy(false)); }}>Save</button>
473
+ </> : <button type="button" className="cg-w44-route-folder-open" onClick={() => navigate(folder.id)}>
474
+ <span className="cg-w44-route-folder-mark" aria-hidden="true" />{folder.name}
475
+ </button>}
476
+ <button type="button" className="cg-w44-route-more" aria-label={`Actions for ${folder.name}`}
477
+ aria-expanded={menuId === `folder:${folder.id}`}
478
+ onClick={() => setMenuId(menuId === `folder:${folder.id}` ? null : `folder:${folder.id}`)}>...</button>
479
+ {menuId === `folder:${folder.id}` && <div className="cg-w44-route-menu" role="menu">
480
+ <button type="button" role="menuitem"
481
+ onClick={() => { setRenameId(`folder:${folder.id}`); setRenameDraft(folder.name); setMenuId(null); }}>Rename</button>
482
+ <button type="button" role="menuitem" disabled={index === 0 || busy}
483
+ onClick={() => { const next = swap(folderIds, folder.id, -1); if (next) finish(onFolderReorder(next)); }}>Move up</button>
484
+ <button type="button" role="menuitem" disabled={index === folderIds.length - 1 || busy}
485
+ onClick={() => { const next = swap(folderIds, folder.id, 1); if (next) finish(onFolderReorder(next)); }}>Move down</button>
486
+ {folder.parent && <button type="button" role="menuitem"
487
+ onClick={() => { setMenuId(null); finish(onFolderUpdate(folder, { parent: level.parent })); }}>Move out one level</button>}
488
+ {folders.filter((target) => target.id !== folder.id).map((target) =>
489
+ <button type="button" role="menuitem" key={target.id}
490
+ onClick={() => { setMenuId(null); finish(onFolderUpdate(folder, { parent: target.id })); }}>
491
+ Move into {target.name}
492
+ </button>)}
493
+ <button type="button" role="menuitem"
494
+ onClick={() => { setMenuId(null); if (window.confirm(`Delete ${folder.name}? Its contents move to Routes.`)) finish(onFolderDelete(folder)); }}>Delete</button>
495
+ </div>}
496
+ </div>
497
+ ))}
498
+ {level.leaves.map((item, index) => (
499
+ <div key={item.id} className={`cg-w44-route-row${item.outsideFilter ? " is-outside" : ""}`}>
500
+ <button type="button" className="cg-w44-route-toggle" aria-pressed={selectedIds.has(item.id)}
501
+ aria-label={`${selectedIds.has(item.id) ? "Remove" : "Include"} ${item.name}`}
502
+ onClick={() => onToggle(item)}><i style={{ backgroundColor: item.color }} aria-hidden="true" /></button>
503
+ {renameId === item.id ? <>
504
+ <input className="cg-input" value={renameDraft} maxLength={120} aria-label={`Rename ${item.name}`}
505
+ onChange={(event) => setRenameDraft(event.target.value)} />
506
+ <button type="button" disabled={!renameDraft.trim() || busy}
507
+ onClick={() => { setBusy(true); void onUpdate(item, { name: renameDraft.trim(), mapsUrl: item.mapsUrl }).then((message) => {
508
+ setError(message); if (!message) setRenameId(null);
509
+ }).finally(() => setBusy(false)); }}>Save</button>
510
+ </> : <button type="button" className="cg-w44-route-open" onClick={() => {
511
+ setError(null); setCreating(false); onActiveRouteChange(item.id);
512
+ }}>{item.number}. {item.name}</button>}
513
+ {(item.shared || item.sharedOut) && <span className="cg-w44-route-share-mark">
514
+ {item.shared ? `Shared by ${item.owner || "another user"}` : "Shared"}
515
+ </span>}
516
+ {item.outsideFilter && <span className="cg-w44-route-outside">Outside filter</span>}
517
+ <button type="button" className="cg-w44-route-more" aria-label={`Actions for ${item.name}`}
518
+ aria-expanded={menuId === item.id} onClick={() => setMenuId(menuId === item.id ? null : item.id)}>...</button>
519
+ {menuId === item.id && <div className="cg-w44-route-menu" role="menu">
520
+ <button type="button" role="menuitem" disabled={!item.permission.canEdit}
521
+ onClick={() => { setRenameId(item.id); setRenameDraft(item.name); setMenuId(null); }}>Rename</button>
522
+ <button type="button" role="menuitem" onClick={() => { setMenuId(null); finish(onDuplicate(item)); }}>Duplicate</button>
523
+ <button type="button" role="menuitem" disabled={!item.permission.canEdit}
524
+ onClick={() => { setMenuId(null); finish(onShare(item)); }}>Share</button>
525
+ {folders.map((folder) => <button type="button" role="menuitem" key={folder.id}
526
+ onClick={() => { setMenuId(null); finish(onRouteMove(item, folder.id)); }}>Move to {folder.name}</button>)}
527
+ {item.folderId && <button type="button" role="menuitem"
528
+ onClick={() => { setMenuId(null); finish(onRouteMove(item, null)); }}>Move to Routes</button>}
529
+ <button type="button" role="menuitem" disabled={index === 0 || busy}
530
+ onClick={() => { const next = swap(routeIds, item.id, -1); if (next) finish(onRouteReorder(next)); }}>Move up</button>
531
+ <button type="button" role="menuitem" disabled={index === routeIds.length - 1 || busy}
532
+ onClick={() => { const next = swap(routeIds, item.id, 1); if (next) finish(onRouteReorder(next)); }}>Move down</button>
533
+ <button type="button" role="menuitem" disabled={!item.permission.canEdit}
534
+ onClick={() => { setMenuId(null); if (window.confirm(`Delete ${item.name}?`)) finish(onDelete(item)); }}>Delete</button>
535
+ </div>}
536
+ </div>
537
+ ))}
538
+ {!level.folders.length && !level.leaves.length && <p className="cg-w44-route-empty">
539
+ {folders.length || routes.length ? "This folder is empty." : "No routes yet. Create one from selected Zones or records."}
540
+ </p>}
541
+ </div>
542
+ {createdRoute && <div className="cg-w44-route-created" role="dialog" aria-label="Route privacy choice">
543
+ <p><strong>{createdRoute.name}</strong> was created. Keep it private or share it now?</p>
544
+ <div className="cg-form-actions">
545
+ <button type="button" className="cg-btn cg-btn--primary" disabled={busy}
546
+ onClick={() => { setBusy(true); void onShare(createdRoute).then((message) => {
547
+ setError(message); if (!message) onCreatedDismiss();
548
+ }).finally(() => setBusy(false)); }}>Share route</button>
549
+ <button type="button" className="cg-btn" disabled={busy} onClick={onCreatedDismiss}>Keep private</button>
550
+ </div>
551
+ </div>}
552
+ {error && <span className="cg-w44-route-empty" role="status">{error}</span>}
553
+ </section>
554
+ );
555
+ }
web/src/customer-grid/ScriptViewPanel.tsx CHANGED
@@ -13,6 +13,7 @@
13
  // ---------------------------------------------------------------------------
14
 
15
  import { memo, useEffect, useRef, useState } from "react";
 
16
  import { barScale, renderableSpec, specKindName } from "./scriptViews";
17
  import type { DrawableSpec, ScriptRun, ScriptView as ScriptViewRecord } from "./scriptViews";
18
 
@@ -225,14 +226,14 @@ export const ScriptView = memo(function ScriptView({
225
  // product a QA pass one wave ago [[a-store-outage-renames-itself-at-every-layer]].
226
  if (view === null)
227
  return (
228
- <div className="cg-script">
229
  <p className="cg-script-empty cg-script-empty--pad">
230
  {loading === true ? "Opening this view." : "This script view could not be opened."}
231
  </p>
232
  </div>
233
  );
234
  return (
235
- <div className="cg-script">
236
  <div className="cg-script-body">
237
  <section className="cg-script-pane" aria-label="Script source">
238
  <div className="cg-script-pane-head">
 
13
  // ---------------------------------------------------------------------------
14
 
15
  import { memo, useEffect, useRef, useState } from "react";
16
+ import { foldNavOnWorkSurface } from "./navFold";
17
  import { barScale, renderableSpec, specKindName } from "./scriptViews";
18
  import type { DrawableSpec, ScriptRun, ScriptView as ScriptViewRecord } from "./scriptViews";
19
 
 
226
  // product a QA pass one wave ago [[a-store-outage-renames-itself-at-every-layer]].
227
  if (view === null)
228
  return (
229
+ <div className="cg-script" onPointerDown={foldNavOnWorkSurface}>
230
  <p className="cg-script-empty cg-script-empty--pad">
231
  {loading === true ? "Opening this view." : "This script view could not be opened."}
232
  </p>
233
  </div>
234
  );
235
  return (
236
+ <div className="cg-script" onPointerDown={foldNavOnWorkSurface}>
237
  <div className="cg-script-body">
238
  <section className="cg-script-pane" aria-label="Script source">
239
  <div className="cg-script-pane-head">
web/src/customer-grid/TimeSeriesPanel.tsx CHANGED
@@ -32,6 +32,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
32
  import { fetchTimeseries } from "./apiBridge";
33
  import type { SurfaceScope } from "./apiBridge";
34
  import { isStreamlitComponent } from "./hostBridge";
 
35
  import {
36
  DEFAULT_TS_BUCKET,
37
  DEFAULT_TS_LAST_N,
@@ -367,7 +368,7 @@ export default function TimeSeriesPanel({
367
  // component — the grid still runs inside app.py and a throw here would take the page.
368
  if (embedded) {
369
  return (
370
- <div className="cg-mode-empty">
371
  The time-series view runs in the web app. Open Loopable in a browser tab to see it.
372
  </div>
373
  );
@@ -375,7 +376,7 @@ export default function TimeSeriesPanel({
375
 
376
  if (!eligible.length) {
377
  return (
378
- <div className="cg-mode-empty">
379
  This table has no number fields to plot. A time series needs either a metric with a
380
  period, or a numeric column to snapshot — add one from a column menu, then pick it here.
381
  </div>
@@ -392,7 +393,7 @@ export default function TimeSeriesPanel({
392
  snapshotSelected.length > 0 && sheet.columns.length === 0 && state !== "loading";
393
 
394
  return (
395
- <div className="cg-ts">
396
  <div className="cg-ts-bar">
397
  <label className="cg-ts-ctl">
398
  <span className="cg-ts-ctl-k">Period</span>
 
32
  import { fetchTimeseries } from "./apiBridge";
33
  import type { SurfaceScope } from "./apiBridge";
34
  import { isStreamlitComponent } from "./hostBridge";
35
+ import { foldNavOnWorkSurface } from "./navFold";
36
  import {
37
  DEFAULT_TS_BUCKET,
38
  DEFAULT_TS_LAST_N,
 
368
  // component — the grid still runs inside app.py and a throw here would take the page.
369
  if (embedded) {
370
  return (
371
+ <div className="cg-mode-empty" onPointerDown={foldNavOnWorkSurface}>
372
  The time-series view runs in the web app. Open Loopable in a browser tab to see it.
373
  </div>
374
  );
 
376
 
377
  if (!eligible.length) {
378
  return (
379
+ <div className="cg-mode-empty" onPointerDown={foldNavOnWorkSurface}>
380
  This table has no number fields to plot. A time series needs either a metric with a
381
  period, or a numeric column to snapshot — add one from a column menu, then pick it here.
382
  </div>
 
393
  snapshotSelected.length > 0 && sheet.columns.length === 0 && state !== "loading";
394
 
395
  return (
396
+ <div className="cg-ts" onPointerDown={foldNavOnWorkSurface}>
397
  <div className="cg-ts-bar">
398
  <label className="cg-ts-ctl">
399
  <span className="cg-ts-ctl-k">Period</span>
web/src/customer-grid/Toolbar.tsx CHANGED
@@ -27,6 +27,7 @@ import type {
27
  ScopeCounts,
28
  SortRule,
29
  SortSpec,
 
30
  ViewConfig,
31
  } from "./types";
32
  import { viewDisplayMode } from "./types";
@@ -35,7 +36,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
  from "./types";
40
  import type { WindowSpec } from "./windows";
41
  import { AnchoredOverlay } from "./OverlaySurface";
@@ -52,8 +54,10 @@ import { FilterBuilderPanel, FieldsHidePanel, Popover } from "../filter-kit";
52
  import { MEASURE_OP_LIST, countConditions, newRuleId, opsForType } from "../filter-kit/ops";
53
  import "./filters.css";
54
 
55
- export interface ToolbarProps {
56
  fields: Field[];
 
 
57
  visible: Set<string>;
58
  /** Wave 16 C-TOPIC — the plural noun for what a row IS ("customers" / "products"). Only
59
  * copy that NAMES the row uses it; structural words ("record", "view") stay shared. */
@@ -74,6 +78,12 @@ export interface ToolbarProps {
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
@@ -100,8 +110,15 @@ export interface ToolbarProps {
100
  /** conjunction joining the ROOT-level conditions */
101
  filterConj: Conjunction;
102
  onFilterConj: (c: Conjunction) => void;
 
 
 
103
  sorts: SortSpec;
104
  onSorts: (s: SortSpec) => void;
 
 
 
 
105
  // grouping — Batch 4: bucket rows by a text/status field (null = ungrouped)
106
  groupBy: string | null;
107
  onGroupBy: (key: string | null) => void;
@@ -244,8 +261,27 @@ export interface ToolbarProps {
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) -----------------------
250
  const ic = { width: 14, height: 14, viewBox: "0 0 16 16", fill: "none" } as const;
251
  const stroke = {
@@ -299,16 +335,23 @@ function IconRows() {
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() {
313
  return (
314
  <svg {...ic} aria-hidden>
@@ -547,12 +590,13 @@ function SortBuilder({
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
  };
@@ -580,7 +624,7 @@ function SortBuilder({
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
  />
@@ -625,6 +669,30 @@ function SortBuilder({
625
  );
626
  }
627
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
628
  const ROW_OPTIONS: { mode: RowHeightMode; label: string }[] = [
629
  { mode: "short", label: "Short" },
630
  { mode: "medium", label: "Medium" },
@@ -633,6 +701,7 @@ const ROW_OPTIONS: { mode: RowHeightMode; label: string }[] = [
633
 
634
  export default function Toolbar({
635
  fields,
 
636
  visible,
637
  nouns = "customers",
638
  lockedKey,
@@ -643,6 +712,12 @@ export default function Toolbar({
643
  deletableKeys,
644
  onDeleteField,
645
  onEditField,
 
 
 
 
 
 
646
  colorField,
647
  colorChoices,
648
  onColorField,
@@ -652,8 +727,11 @@ export default function Toolbar({
652
  onFilters,
653
  filterConj,
654
  onFilterConj,
 
655
  sorts,
656
  onSorts,
 
 
657
  groupBy,
658
  onGroupBy,
659
  statusValues,
@@ -683,8 +761,11 @@ export default function Toolbar({
683
  onRelationalWindow,
684
  sourceLabel,
685
  onViewActions,
 
 
686
  }: ToolbarProps) {
687
  const shownCount = fields.filter((f) => visible.has(f.key)).length;
 
688
 
689
  const fieldByKey = useMemo(() => {
690
  const m = new Map<string, Field>();
@@ -775,7 +856,7 @@ export default function Toolbar({
775
  return;
776
  }
777
  const f = filterSeed.key ? fieldByKey.get(filterSeed.key) : undefined;
778
- if (!f || f.filterable === false) return;
779
  onFilters([...filters, { colId: f.key, op: opsForType(f.type)[0], value: "" }]);
780
  }, [filterSeed, fieldByKey, measureByKey, filters, onFilters]);
781
 
@@ -791,8 +872,12 @@ export default function Toolbar({
791
  : n.rhs != null && n.rhs.kind !== "stat"));
792
  return walk(filters);
793
  }, [filters]);
794
- const filterLabel = conditionCount ? `Filter · ${conditionCount}` : "Filter";
795
- const sortLabel = sorts.length ? `Sort · ${sorts.length}` : "Sort";
 
 
 
 
796
  const groupLabel = groupBy
797
  ? `Group: ${fieldByKey.get(groupBy)?.label ?? "?"}`
798
  : "Group";
@@ -804,7 +889,7 @@ export default function Toolbar({
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
@@ -847,6 +932,17 @@ export default function Toolbar({
847
  deletableKeys={deletableKeys}
848
  onDeleteField={onDeleteField}
849
  onEditField={onEditField}
 
 
 
 
 
 
 
 
 
 
 
850
  />
851
  )}
852
  </Popover>
@@ -867,7 +963,9 @@ export default function Toolbar({
867
  pairWide={hasComparand}
868
  forceOpenSignal={filterSeed?.n}
869
  >
870
- {(close) => (
 
 
871
  <FilterBuilderPanel
872
  // The COMPLETE list: the kit narrows the picker to the filterable ones itself and
873
  // keeps the full map for resolving a condition saved against a column that has
@@ -897,7 +995,9 @@ export default function Toolbar({
897
  {/* Sort — multi-level. Deliberately over ALL fields: "rank by estimated missed dollars"
898
  is exactly what a score is FOR, even though a condition on it is not. */}
899
  <Popover label={sortLabel} icon={<IconSort />} active={sorts.length > 0} tone="sort" wide>
900
- {() => (
 
 
901
  <SortBuilder
902
  fields={fields}
903
  fieldByKey={fieldByKey}
@@ -1047,6 +1147,7 @@ export default function Toolbar({
1047
 
1048
  ⚠ RADIO ROWS, the same markup "Group by" and "Color by" use for the same
1049
  "which one?" question. DESIGN §4: new nav joins the existing rhythm. */}
 
1050
  <Popover
1051
  label={relationalLabel}
1052
  icon={<IconRelational />}
@@ -1110,16 +1211,32 @@ export default function Toolbar({
1110
  </div>
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
 
 
27
  ScopeCounts,
28
  SortRule,
29
  SortSpec,
30
+ Viewer,
31
  ViewConfig,
32
  } from "./types";
33
  import { viewDisplayMode } from "./types";
 
36
  import { PIVOT_WINDOWS, PIVOT_WINDOW_LABELS } from "./types";
37
  import { COPY_PARTS, COPY_PART_KEYS, copyViewConfig } from "./copyConfig";
38
  import type { CopyPart } from "./copyConfig";
39
+ import { directionLabel, filterTreeConj, filterTreeNodes, isFilterGroup, isGroupableField,
40
+ isOfferableField, offerableFields }
41
  from "./types";
42
  import type { WindowSpec } from "./windows";
43
  import { AnchoredOverlay } from "./OverlaySurface";
 
54
  import { MEASURE_OP_LIST, countConditions, newRuleId, opsForType } from "../filter-kit/ops";
55
  import "./filters.css";
56
 
57
+ interface ToolbarBaseProps {
58
  fields: Field[];
59
+ /** Identity used only to classify shared fields into ownership sections. */
60
+ viewer?: Viewer;
61
  visible: Set<string>;
62
  /** Wave 16 C-TOPIC — the plural noun for what a row IS ("customers" / "products"). Only
63
  * copy that NAMES the row uses it; structural words ("record", "view") stay shared. */
 
78
  onDeleteField?: (key: string) => void;
79
  /** The Hide fields edit icon reuses ColumnMenu's existing normal field editor. */
80
  onEditField?: (key: string, anchor: DOMRect) => void;
81
+ onSetFieldsHidden?: ((keys: string[], hidden: boolean) => void) | null;
82
+ onShareFields?: ((keys: string[]) => void) | null;
83
+ onReassignFields?: ((keys: string[]) => void) | null;
84
+ onDeleteFields?: ((keys: string[]) => void) | null;
85
+ onRemoveField?: ((key: string) => void) | null;
86
+ manager?: boolean;
87
 
88
  /**
89
  * ⭐⭐ W38-T07 (owner instruction 12) — THE ONE COLOUR CONTROL, and it names a FIELD rather than
 
110
  /** conjunction joining the ROOT-level conditions */
111
  filterConj: Conjunction;
112
  onFilterConj: (c: Conjunction) => void;
113
+ /** A server-projected locked leaf freezes the whole tree: moving a group or changing the
114
+ * root conjunction rewrites that leaf's semantics too. */
115
+ filtersLocked?: boolean;
116
  sorts: SortSpec;
117
  onSorts: (s: SortSpec) => void;
118
+ /** A locked sort preserves the ordered sort list as one immutable record. */
119
+ sortsLocked?: boolean;
120
+ /** Duplicate the active View; the new id is C3's only alteration path. */
121
+ onCopyToChange?: () => void;
122
  // grouping — Batch 4: bucket rows by a text/status field (null = ungrouped)
123
  groupBy: string | null;
124
  onGroupBy: (key: string | null) => void;
 
261
  sourceLabel?: string;
262
  /** Opens the active view's existing ellipsis menu. */
263
  onViewActions?: (anchor: HTMLButtonElement) => void;
264
+ /** The active view's fullscreen door belongs beside Edit, not below the whole toolbar. */
265
+ fullscreen?: boolean;
266
+ onFullscreen?: () => void;
267
  }
268
 
269
+ export interface ToolbarManagerProps extends ToolbarBaseProps {
270
+ manager: true;
271
+ viewer: Viewer | undefined;
272
+ onSetFieldsHidden: ((keys: string[], hidden: boolean) => void) | null;
273
+ onShareFields: ((keys: string[]) => void) | null;
274
+ onReassignFields: ((keys: string[]) => void) | null;
275
+ onDeleteFields: ((keys: string[]) => void) | null;
276
+ onRemoveField: ((key: string) => void) | null;
277
+ }
278
+
279
+ export interface ToolbarPlainProps extends ToolbarBaseProps {
280
+ manager?: false;
281
+ }
282
+
283
+ export type ToolbarProps = ToolbarManagerProps | ToolbarPlainProps;
284
+
285
  // --- tiny inline icons (14px, stroke = currentColor) -----------------------
286
  const ic = { width: 14, height: 14, viewBox: "0 0 16 16", fill: "none" } as const;
287
  const stroke = {
 
335
  </svg>
336
  );
337
  }
338
+ function IconEdit() {
339
  return (
340
  <svg {...ic} aria-hidden>
341
+ <path d="m3 11.8.7-2.5L10.5 2.5l2.9 2.9-6.8 6.8L4 13Z" {...stroke} />
342
+ <path d="m9.5 3.5 2.9 2.9" {...stroke} />
343
  </svg>
344
  );
345
  }
346
  // W41-T42 — two nodes and the edge between them, at the same 14px/1.5 stroke weight every other
347
  // button in this strip wears. The relation is the LINE, which is the whole idea of the control.
348
+ function IconFullScreen() {
349
+ return (
350
+ <svg {...ic} aria-hidden>
351
+ <path d="M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10" {...stroke} />
352
+ </svg>
353
+ );
354
+ }
355
  function IconRelational() {
356
  return (
357
  <svg {...ic} aria-hidden>
 
590
  sorts: SortSpec;
591
  onSorts: (s: SortSpec) => void;
592
  }) {
593
+ const offered = useMemo(() => offerableFields(fields), [fields]);
594
  const update = (i: number, patch: Partial<SortRule>) =>
595
  onSorts(sorts.map((s, j) => (j === i ? { ...s, ...patch } : s)));
596
  const remove = (i: number) => onSorts(sorts.filter((_, j) => j !== i));
597
  const add = () => {
598
  const used = new Set(sorts.map((s) => s.colId));
599
+ const f = offered.find((fl) => !used.has(fl.key)) ?? offered[0];
600
  if (!f) return;
601
  onSorts([...sorts, { colId: f.key, dir: "asc" }]);
602
  };
 
624
  ariaLabel="Sort field"
625
  value={rule.colId}
626
  onChange={(key) => update(i, { colId: key })}
627
+ fields={offered.map((fl) => ({
628
  key: fl.key, label: fl.label, type: fl.type,
629
  }))}
630
  />
 
669
  );
670
  }
671
 
672
+ function ImmutableViewConfigNotice({
673
+ subject,
674
+ onCopyToChange,
675
+ }: {
676
+ subject: "filters" | "sorts";
677
+ onCopyToChange?: () => void;
678
+ }) {
679
+ return (
680
+ <div className="cg-pop-body">
681
+ <div className="cg-pop-title">{subject === "filters" ? "Filters locked" : "Sorts locked"}</div>
682
+ <div className="cg-pop-note">
683
+ These {subject} are immutable on this View. Copy it to make changes.
684
+ </div>
685
+ {onCopyToChange && (
686
+ <div className="cg-pop-footer cg-builder-footer">
687
+ <button type="button" className="cg-btn" onClick={onCopyToChange}>
688
+ Copy to change
689
+ </button>
690
+ </div>
691
+ )}
692
+ </div>
693
+ );
694
+ }
695
+
696
  const ROW_OPTIONS: { mode: RowHeightMode; label: string }[] = [
697
  { mode: "short", label: "Short" },
698
  { mode: "medium", label: "Medium" },
 
701
 
702
  export default function Toolbar({
703
  fields,
704
+ viewer,
705
  visible,
706
  nouns = "customers",
707
  lockedKey,
 
712
  deletableKeys,
713
  onDeleteField,
714
  onEditField,
715
+ manager = false,
716
+ onSetFieldsHidden,
717
+ onShareFields,
718
+ onReassignFields,
719
+ onDeleteFields,
720
+ onRemoveField,
721
  colorField,
722
  colorChoices,
723
  onColorField,
 
727
  onFilters,
728
  filterConj,
729
  onFilterConj,
730
+ filtersLocked = false,
731
  sorts,
732
  onSorts,
733
+ sortsLocked = false,
734
+ onCopyToChange,
735
  groupBy,
736
  onGroupBy,
737
  statusValues,
 
761
  onRelationalWindow,
762
  sourceLabel,
763
  onViewActions,
764
+ fullscreen = false,
765
+ onFullscreen,
766
  }: ToolbarProps) {
767
  const shownCount = fields.filter((f) => visible.has(f.key)).length;
768
+ const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen";
769
 
770
  const fieldByKey = useMemo(() => {
771
  const m = new Map<string, Field>();
 
856
  return;
857
  }
858
  const f = filterSeed.key ? fieldByKey.get(filterSeed.key) : undefined;
859
+ if (!f || !isOfferableField(f) || f.filterable === false) return;
860
  onFilters([...filters, { colId: f.key, op: opsForType(f.type)[0], value: "" }]);
861
  }, [filterSeed, fieldByKey, measureByKey, filters, onFilters]);
862
 
 
872
  : n.rhs != null && n.rhs.kind !== "stat"));
873
  return walk(filters);
874
  }, [filters]);
875
+ const filterLabel = `${conditionCount ? `Filter · ${conditionCount}` : "Filter"}${
876
+ filtersLocked ? " · Locked" : ""
877
+ }`;
878
+ const sortLabel = `${sorts.length ? `Sort · ${sorts.length}` : "Sort"}${
879
+ sortsLocked ? " · Locked" : ""
880
+ }`;
881
  const groupLabel = groupBy
882
  ? `Group: ${fieldByKey.get(groupBy)?.label ?? "?"}`
883
  : "Group";
 
889
  : "Color";
890
  // W41-T42 — the same idiom `colorLabel` and `groupLabel` already use: a control that HAS a
891
  // current answer names it on the trigger, so the reader does not have to open it to find out.
892
+ const relationalLabel = relational ? `Related: ${relational.label}` : "Related";
893
 
894
  /**
895
  * R11's greying, as one attribute. `inert` is not in React 18's JSX typings (it landed with
 
932
  deletableKeys={deletableKeys}
933
  onDeleteField={onDeleteField}
934
  onEditField={onEditField}
935
+ viewer={viewer}
936
+ {...(manager
937
+ ? {
938
+ manager: true as const,
939
+ onSetFieldsHidden: onSetFieldsHidden ?? null,
940
+ onShareFields: onShareFields ?? null,
941
+ onReassignFields: onReassignFields ?? null,
942
+ onDeleteFields: onDeleteFields ?? null,
943
+ onRemoveField: onRemoveField ?? null,
944
+ }
945
+ : { manager: false as const })}
946
  />
947
  )}
948
  </Popover>
 
963
  pairWide={hasComparand}
964
  forceOpenSignal={filterSeed?.n}
965
  >
966
+ {(close) => filtersLocked ? (
967
+ <ImmutableViewConfigNotice subject="filters" onCopyToChange={onCopyToChange} />
968
+ ) : (
969
  <FilterBuilderPanel
970
  // The COMPLETE list: the kit narrows the picker to the filterable ones itself and
971
  // keeps the full map for resolving a condition saved against a column that has
 
995
  {/* Sort — multi-level. Deliberately over ALL fields: "rank by estimated missed dollars"
996
  is exactly what a score is FOR, even though a condition on it is not. */}
997
  <Popover label={sortLabel} icon={<IconSort />} active={sorts.length > 0} tone="sort" wide>
998
+ {() => sortsLocked ? (
999
+ <ImmutableViewConfigNotice subject="sorts" onCopyToChange={onCopyToChange} />
1000
+ ) : (
1001
  <SortBuilder
1002
  fields={fields}
1003
  fieldByKey={fieldByKey}
 
1147
 
1148
  ⚠ RADIO ROWS, the same markup "Group by" and "Color by" use for the same
1149
  "which one?" question. DESIGN §4: new nav joins the existing rhythm. */}
1150
+ <div className="cg-tb-related">
1151
  <Popover
1152
  label={relationalLabel}
1153
  icon={<IconRelational />}
 
1211
  </div>
1212
  )}
1213
  </Popover>
1214
+ </div>
1215
 
1216
  {onViewActions && (
1217
  <button
1218
  type="button"
1219
  className="cg-tb-btn cg-view-actions"
1220
+ aria-label="Edit view"
1221
+ title="Edit view"
1222
  onClick={(event) => onViewActions(event.currentTarget)}
1223
  >
1224
+ <IconEdit />
1225
+ <span className="cg-tb-label">Edit</span>
1226
+ </button>
1227
+ )}
1228
+
1229
+ {onFullscreen && (
1230
+ <button
1231
+ type="button"
1232
+ className={"cg-tb-btn cg-fullscreen-toggle" + (fullscreen ? " is-active" : "")}
1233
+ aria-pressed={fullscreen}
1234
+ aria-label={fullscreenLabel}
1235
+ title={fullscreenLabel}
1236
+ onClick={onFullscreen}
1237
+ >
1238
+ <IconFullScreen />
1239
+ <span className="cg-tb-label">{fullscreenLabel}</span>
1240
  </button>
1241
  )}
1242
 
web/src/customer-grid/ViewSidebar.tsx CHANGED
@@ -1,4 +1,4 @@
1
- import { useEffect, useMemo, useState } from "react";
2
  import type { ReactNode } from "react";
3
  import type { KeyboardEvent as ReactKeyboardEvent } from "react";
4
  import { AnchoredOverlay } from "./OverlaySurface";
@@ -44,6 +44,14 @@ 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
  // ⭐ 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
@@ -56,7 +64,6 @@ import { BellIcon, StarIcon } from "../ui/icons";
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,
@@ -222,6 +229,16 @@ export function viewShareMark(
222
  }
223
 
224
  interface ViewSidebarProps {
 
 
 
 
 
 
 
 
 
 
225
  views: SavedView[];
226
  activeViewId: string;
227
  saveState: "saved" | "saving";
@@ -287,6 +304,12 @@ interface ViewSidebarProps {
287
  * client does not hold the rows (server-windowed), so the entry never lies.
288
  */
289
  onExport?: (viewId: string, format: ExportFormat) => void;
 
 
 
 
 
 
290
  /**
291
  * Wave-8 I11c (contract C4) — folders. All of it is OPTIONAL: a caller that
292
  * passes no `folders` and no handlers renders exactly the pre-wave-8 flat rail,
@@ -444,6 +467,437 @@ interface ViewSidebarProps {
444
  onToggleChat?: () => void;
445
  }
446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
447
  /**
448
  * ⭐ WAVE 41 · T35 (owner instruction 11) — THE FOLDER ICON PICKER: ONE COPY, TWO DOORS.
449
  *
@@ -547,7 +1001,35 @@ function FolderIconPicker({
547
  );
548
  }
549
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550
  export default function ViewSidebar({
 
 
 
 
 
 
 
 
 
551
  agentPanel = null,
552
  agentOpen = false,
553
  onToggleAgent,
@@ -570,7 +1052,9 @@ export default function ViewSidebar({
570
  onCohortLock,
571
  today,
572
  onExport,
573
- folders,
 
 
574
  folderIdOf,
575
  onFolderCreate,
576
  onFolderRename,
@@ -590,6 +1074,15 @@ export default function ViewSidebar({
590
  actionAnchor,
591
  onActionAnchorConsumed,
592
  }: ViewSidebarProps) {
 
 
 
 
 
 
 
 
 
593
  /**
594
  * I14 — creating a view now always knows WHICH KIND of view is being created, because the
595
  * flyout is the only door in. `null` = not creating; a mode = the name step for that mode.
@@ -623,9 +1116,17 @@ export default function ViewSidebar({
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(() => {
@@ -669,7 +1170,8 @@ export default function ViewSidebar({
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,6 +1362,12 @@ export default function ViewSidebar({
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.
@@ -990,16 +1498,82 @@ export default function ViewSidebar({
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
@@ -1036,20 +1610,6 @@ export default function ViewSidebar({
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
@@ -1202,7 +1762,7 @@ export default function ViewSidebar({
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);
@@ -1289,7 +1849,7 @@ export default function ViewSidebar({
1289
  {agentPanel}
1290
  <aside
1291
  className={"cg-views" + (railShut ? " is-collapsed" : "")}
1292
- aria-label="Customer views"
1293
  >
1294
  {/* Owner item 11 — the rail's own minimize control: the same three-bars glyph as the
1295
  shell nav's, because the two rails are one idea ("a navigation bar folds"). */}
@@ -1384,6 +1944,17 @@ export default function ViewSidebar({
1384
  badge's ABSENCE from this row and its PRESENCE on the view rows, so re-adding one
1385
  reds it. */}
1386
  </div>
 
 
 
 
 
 
 
 
 
 
 
1387
  {/*
1388
  I13 — the "Views / All changes saved" header block is GONE and everything moved up.
1389
 
@@ -1656,16 +2227,63 @@ export default function ViewSidebar({
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.
@@ -1675,12 +2293,7 @@ export default function ViewSidebar({
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,7 +2329,13 @@ export default function ViewSidebar({
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
@@ -1735,13 +2354,12 @@ export default function ViewSidebar({
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,7 +2395,8 @@ export default function ViewSidebar({
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.
@@ -1786,16 +2405,19 @@ export default function ViewSidebar({
1786
  `item_move(id, ROOT_FOLDER_ID)` — a stored placement, which is the very thing that
1787
  takes a view OUT of this group. The drop would file the view and then move it
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 ─────────────────────
1795
  // Draggable only while it is renameable-idle: a `draggable` ancestor eats
1796
  // the text selection inside an input, so dragging would win over editing
1797
  // the name you just opened.
1798
- draggable={foldsReorderable && !isSynthetic && renamingFolder !== group.folder.id}
 
 
 
1799
  onDragStart={(e) => {
1800
  e.dataTransfer.setData(FOLD_DRAG_TYPE, group.folder!.id);
1801
  e.dataTransfer.effectAllowed = "move";
@@ -1817,7 +2439,6 @@ export default function ViewSidebar({
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`.
@@ -1830,18 +2451,9 @@ export default function ViewSidebar({
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". */}
@@ -1922,7 +2534,7 @@ export default function ViewSidebar({
1922
  group, for the reason the block above gives: a colleague's shared folder is no
1923
  more the reader's to rename, duplicate or delete than "Shared with me" is, and
1924
  every row of that menu would be refused by a server that has no such folder. */}
1925
- {isSynthetic ? null : (
1926
  <button
1927
  type="button"
1928
  className="cg-view-more"
@@ -1943,9 +2555,7 @@ export default function ViewSidebar({
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,7 +2860,8 @@ export default function ViewSidebar({
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>
@@ -2266,6 +2877,7 @@ export default function ViewSidebar({
2266
  free and this section has nothing left to render.
2267
  The lock MARK moved onto the ordinary view row, where `kind === "locked"` drives it. */}
2268
  </div>
 
2269
 
2270
  {/* I11c — the folder "…" menu. Rename · Add to cohort · Duplicate · Delete.
2271
  WAVE 20 item 22 — every row now carries the SAME icon vocabulary the view row's
@@ -2472,6 +3084,56 @@ export default function ViewSidebar({
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
@@ -2607,7 +3269,7 @@ export default function ViewSidebar({
2607
  dataKind="saved-view-menu"
2608
  >
2609
  {/* W2 (C2): Export sits ABOVE the rename/delete group, thin divider between. */}
2610
- {(onExport || onImport) && (
2611
  <>
2612
  {/* ⭐ WAVE-29 T32 (owner item 16 / R10) — the DATA group's header.
2613
  The owner's complaint was that Export "looks like an orphan": it is already the
@@ -2631,12 +3293,15 @@ export default function ViewSidebar({
2631
  >
2632
  Data
2633
  </div>
2634
- {onExport && (
2635
  <button
2636
  type="button"
2637
  role="menuitem"
2638
  onClick={() => {
2639
  setExportFor({ viewId: menuView.id, anchor: menu.anchor });
 
 
 
2640
  setMenu(null);
2641
  }}
2642
  >
@@ -2730,6 +3395,18 @@ export default function ViewSidebar({
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
@@ -2965,31 +3642,74 @@ export default function ViewSidebar({
2965
  {/* W2 (C2) — the format pane: CSV · Excel · PDF · JSON, keyboard-navigable like
2966
  the menu it came from. Rows/columns are the view's CURRENT matches and visible
2967
  fields; generation is client-side (the grid already holds the answer). */}
2968
- {exportFor && exportView && onExport && (
2969
  <AnchoredOverlay
2970
  anchor={exportFor.anchor}
2971
  className="cg-view-menu"
2972
  placement="bottom-end"
2973
- role="menu"
2974
  ariaLabel={`Export ${viewDisplayName(exportView)}`}
2975
  onDismiss={() => setExportFor(null)}
2976
  onKeyDown={onMenuKeyDown}
2977
  dataKind="view-export"
2978
  >
2979
  <div className="cg-pop-title cg-export-title">Export {viewDisplayName(exportView)}</div>
2980
- {EXPORT_FORMATS.map((format) => (
2981
- <button
2982
- key={format}
2983
- type="button"
2984
- role="menuitem"
2985
- onClick={() => {
2986
- onExport(exportView.id, format);
2987
- setExportFor(null);
2988
- }}
2989
- >
2990
- {EXPORT_LABELS[format]}
2991
- </button>
2992
- ))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2993
  </AnchoredOverlay>
2994
  )}
2995
 
 
1
+ import { useEffect, useMemo, useRef, useState } from "react";
2
  import type { ReactNode } from "react";
3
  import type { KeyboardEvent as ReactKeyboardEvent } from "react";
4
  import { AnchoredOverlay } from "./OverlaySurface";
 
44
  */
45
  import { WORKSPACE_STALE_EVENT, signal } from "../apiContract";
46
  import { ROOT_FOLDER_ID } from "./folders";
47
+ import {
48
+ folderPath,
49
+ groupDataDatabases,
50
+ levelAt,
51
+ pathStorageKey,
52
+ resolveStoredPath,
53
+ } from "./dataPath";
54
+ import type { DataDatabase, DataDatabaseFolder } from "./dataPath";
55
  // ⭐ W32-T23 (owner item 17) — THE BELL, from the shared layer rather than redrawn here.
56
  // The alert row wore `cohortAdd` (a LIST with a plus), which names "add to a cohort" on the
57
  // one row that creates an ALERT — a borrowed mark is a small lie a menu repeats every time
 
64
  // `isSyntheticFolderId`, and `noUnusedLocals` turns a leftover import into a build error rather
65
  // than into dead weight. The constant itself is still exported and still used by `folders.ts`.
66
  import {
 
67
  folderNesting,
68
  groupByFolder,
69
  isSyntheticFolderId,
 
229
  }
230
 
231
  interface ViewSidebarProps {
232
+ /** Granted databases live in this secondary navigator, never in the global shell rail. */
233
+ databases?: readonly DataDatabase[];
234
+ activeDatabaseKey?: string;
235
+ databaseFolders?: readonly DataDatabaseFolder[];
236
+ onSelectDatabase?: (key: string) => void;
237
+ onDatabaseMove?: (key: string, folderId: string | null) => void;
238
+ onDatabaseFolderRename?: (folderId: string, name: string) => void;
239
+ onDatabaseFolderDelete?: (folderId: string) => void;
240
+ renderDatabaseActions?: (database: DataDatabase) => ReactNode;
241
+ databaseCreateControl?: ReactNode;
242
  views: SavedView[];
243
  activeViewId: string;
244
  saveState: "saved" | "saving";
 
304
  * client does not hold the rows (server-windowed), so the entry never lies.
305
  */
306
  onExport?: (viewId: string, format: ExportFormat) => void;
307
+ /** C3 bulk-export path. The caller sends these visible View ids to the server, which evaluates
308
+ * every tab before the browser gives its result to the one XLSX writer. */
309
+ onExportXlsxViews?: (viewIds: string[]) => void;
310
+ /** The server-visible saved Views accepted by C3's export endpoint. Rail-only projections
311
+ * (for example an unsaved script result) remain out of the chooser. */
312
+ exportableViewIds?: readonly string[];
313
  /**
314
  * Wave-8 I11c (contract C4) — folders. All of it is OPTIONAL: a caller that
315
  * passes no `folders` and no handlers renders exactly the pre-wave-8 flat rail,
 
467
  onToggleChat?: () => void;
468
  }
469
 
470
+ interface DataDatabaseNavigatorProps {
471
+ databases: readonly DataDatabase[];
472
+ activeDatabaseKey: string;
473
+ folders: readonly DataDatabaseFolder[];
474
+ onSelect?: (key: string) => void;
475
+ onMove?: (key: string, folderId: string | null) => void;
476
+ onFolderRename?: (folderId: string, name: string) => void;
477
+ onFolderDelete?: (folderId: string) => void;
478
+ renderActions?: (database: DataDatabase) => ReactNode;
479
+ createControl?: ReactNode;
480
+ children: ReactNode;
481
+ }
482
+
483
+ type DataNavigatorLevel =
484
+ | { kind: "root" }
485
+ | { kind: "origin"; label: string }
486
+ | { kind: "folder"; id: string }
487
+ | { kind: "database"; key: string };
488
+
489
+ function dataNavigatorLevelKey(level: DataNavigatorLevel): string {
490
+ if (level.kind === "root") return "root";
491
+ if (level.kind === "origin") return `origin:${level.label}`;
492
+ if (level.kind === "folder") return `folder:${level.id}`;
493
+ return `database:${level.key}`;
494
+ }
495
+
496
+ /** Windows-style Data path rendered with the same segmented-path anatomy as the View path. */
497
+ function DataDatabaseNavigator({
498
+ databases,
499
+ activeDatabaseKey,
500
+ folders,
501
+ onSelect,
502
+ onMove,
503
+ onFolderRename,
504
+ onFolderDelete,
505
+ renderActions,
506
+ createControl,
507
+ children,
508
+ }: DataDatabaseNavigatorProps) {
509
+ const [draggedDatabase, setDraggedDatabase] = useState<string | null>(null);
510
+ const [folderMenu, setFolderMenu] = useState<{ folderId: string; anchor: HTMLElement } | null>(
511
+ null
512
+ );
513
+ const [renamingFolder, setRenamingFolder] = useState<string | null>(null);
514
+ const [folderName, setFolderName] = useState("");
515
+
516
+ const dropDatabase = (event: React.DragEvent<HTMLElement>, folderId: string | null) => {
517
+ if (!onMove) return;
518
+ const key = event.dataTransfer.getData("application/x-aios-database") || draggedDatabase;
519
+ if (!key) return;
520
+ event.preventDefault();
521
+ event.stopPropagation();
522
+ setDraggedDatabase(null);
523
+ onMove(key, folderId);
524
+ };
525
+ const dropProps = (folderId: string | null) =>
526
+ onMove
527
+ ? {
528
+ onDragOver: (event: React.DragEvent<HTMLElement>) => {
529
+ if (!event.dataTransfer.types.includes("application/x-aios-database")) return;
530
+ event.preventDefault();
531
+ event.stopPropagation();
532
+ event.dataTransfer.dropEffect = "move";
533
+ },
534
+ onDrop: (event: React.DragEvent<HTMLElement>) => dropDatabase(event, folderId),
535
+ }
536
+ : {};
537
+
538
+ const sourceGroups = useMemo(
539
+ () => groupDataDatabases(databases.filter((database) => !database.folderId)),
540
+ [databases]
541
+ );
542
+ const parentOfDatabase = (database: DataDatabase): DataNavigatorLevel =>
543
+ database.folderId
544
+ ? { kind: "folder", id: database.folderId }
545
+ : { kind: "origin", label: groupDataDatabases([database])[0]?.label ?? "Loopable" };
546
+ const levelsForDatabase = (database: DataDatabase): DataNavigatorLevel[] => [
547
+ { kind: "root" },
548
+ parentOfDatabase(database),
549
+ { kind: "database", key: database.key },
550
+ ];
551
+ const [dataPathState, setDataPathState] = useState<{
552
+ levels: DataNavigatorLevel[];
553
+ at: number;
554
+ }>(() => {
555
+ const database = databases.find((candidate) => candidate.key === activeDatabaseKey);
556
+ const levels = database ? levelsForDatabase(database) : [{ kind: "root" } as const];
557
+ return { levels, at: levels.length - 1 };
558
+ });
559
+ const activeDataKey = useRef(activeDatabaseKey);
560
+ const dataLevel = dataPathState.levels[dataPathState.at] ?? { kind: "root" as const };
561
+ const canDataBack = dataPathState.at > 0;
562
+ const canDataForward = dataPathState.at < dataPathState.levels.length - 1;
563
+ const pushDataLevel = (level: DataNavigatorLevel) => {
564
+ setDataPathState((current) => ({
565
+ levels: [...current.levels.slice(0, current.at + 1), level],
566
+ at: current.at + 1,
567
+ }));
568
+ };
569
+ const stepDataLevel = (delta: number) => {
570
+ setDataPathState((current) => {
571
+ const at = current.at + delta;
572
+ return at < 0 || at >= current.levels.length ? current : { ...current, at };
573
+ });
574
+ };
575
+ useEffect(() => {
576
+ if (activeDataKey.current === activeDatabaseKey) return;
577
+ activeDataKey.current = activeDatabaseKey;
578
+ setDataPathState((current) => {
579
+ const here = current.levels[current.at];
580
+ if (here?.kind === "database" && here.key === activeDatabaseKey) return current;
581
+ const database = databases.find((candidate) => candidate.key === activeDatabaseKey);
582
+ const levels = database ? levelsForDatabase(database) : [{ kind: "root" } as const];
583
+ return { levels, at: levels.length - 1 };
584
+ });
585
+ }, [activeDatabaseKey, databases]);
586
+ const pathDatabase =
587
+ dataLevel.kind === "database"
588
+ ? databases.find((database) => database.key === dataLevel.key)
589
+ : undefined;
590
+ const pathFolder =
591
+ dataLevel.kind === "folder" ? folders.find((folder) => folder.id === dataLevel.id) : undefined;
592
+ // Wave 44 QA / owner ruling: an address is a sequence of exact destinations. A joined label
593
+ // wired only to Back looks like a path but cannot do what a Windows path does.
594
+ const dataPathSegments: { level: DataNavigatorLevel; label: string }[] = [
595
+ { level: { kind: "root" }, label: "Data" },
596
+ ];
597
+ if (dataLevel.kind === "origin") {
598
+ dataPathSegments.push({ level: dataLevel, label: dataLevel.label });
599
+ } else if (dataLevel.kind === "folder") {
600
+ dataPathSegments.push({ level: dataLevel, label: pathFolder?.name ?? "Folder" });
601
+ } else if (dataLevel.kind === "database" && pathDatabase) {
602
+ const parent = parentOfDatabase(pathDatabase);
603
+ dataPathSegments.push({
604
+ level: parent,
605
+ label:
606
+ parent.kind === "folder"
607
+ ? folders.find((folder) => folder.id === parent.id)?.name ?? "Folder"
608
+ : parent.kind === "origin"
609
+ ? parent.label
610
+ : "Data",
611
+ });
612
+ dataPathSegments.push({ level: dataLevel, label: pathDatabase.label });
613
+ }
614
+ const visitDataLevel = (level: DataNavigatorLevel) => {
615
+ if (dataNavigatorLevelKey(level) === dataNavigatorLevelKey(dataLevel)) return;
616
+ pushDataLevel(level);
617
+ };
618
+ const openDatabase = (database: DataDatabase) => {
619
+ if (database.externalHref) return;
620
+ visitDataLevel({ kind: "database", key: database.key });
621
+ onSelect?.(database.key);
622
+ };
623
+ const pathDatabaseRow = (database: DataDatabase) => {
624
+ const active = database.key === activeDatabaseKey;
625
+ const draggable = !!onMove && !database.protected && database.managedBy !== "loopable";
626
+ const content = (
627
+ <>
628
+ <FolderMark icon={database.icon} size={16} />
629
+ <span className="cg-fold-name">{database.label}</span>
630
+ {database.locked ? (
631
+ <span
632
+ className="cg-data-database-lock"
633
+ role="img"
634
+ aria-label={`${database.label}, locked database`}
635
+ title="Locked database. Records are managed by its source; fields remain editable."
636
+ >
637
+ <LockMark size={12} />
638
+ </span>
639
+ ) : null}
640
+ </>
641
+ );
642
+ return (
643
+ <div
644
+ key={database.key}
645
+ className={
646
+ "cg-fold cg-data-database" +
647
+ (active ? " is-active" : "") +
648
+ (draggedDatabase === database.key ? " is-dragging" : "")
649
+ }
650
+ draggable={draggable}
651
+ onDragStart={(event) => {
652
+ event.dataTransfer.setData("application/x-aios-database", database.key);
653
+ event.dataTransfer.effectAllowed = "move";
654
+ setDraggedDatabase(database.key);
655
+ }}
656
+ onDragEnd={() => setDraggedDatabase(null)}
657
+ >
658
+ <div className="cg-fold-head">
659
+ {database.externalHref ? (
660
+ <a
661
+ className="cg-fold-toggle"
662
+ href={database.externalHref}
663
+ target="_blank"
664
+ rel="noreferrer"
665
+ aria-label={`Open ${database.label}`}
666
+ >
667
+ {content}
668
+ </a>
669
+ ) : (
670
+ <button
671
+ type="button"
672
+ className="cg-fold-toggle"
673
+ aria-current={active ? "page" : undefined}
674
+ aria-label={`Open database ${database.label}`}
675
+ onClick={() => openDatabase(database)}
676
+ >
677
+ {content}
678
+ </button>
679
+ )}
680
+ {renderActions?.(database)}
681
+ </div>
682
+ </div>
683
+ );
684
+ };
685
+
686
+ // CustomerGrid also renders this sidebar in embedded/query surfaces. Keep those surfaces'
687
+ // existing View-only navigator when the shell has not supplied a database contract.
688
+ if (databases.length === 0 || !activeDatabaseKey || !onSelect) return <>{children}</>;
689
+
690
+ const levelDatabases =
691
+ dataLevel.kind === "origin"
692
+ ? sourceGroups.find((group) => group.label === dataLevel.label)?.databases ?? []
693
+ : dataLevel.kind === "folder"
694
+ ? databases.filter((database) => database.folderId === dataLevel.id)
695
+ : [];
696
+
697
+ return (
698
+ <div className="cg-data-tree" data-data-path-tree>
699
+ <nav
700
+ className="cg-fold-head cg-data-path cg-segmented-path"
701
+ data-data-path-history
702
+ aria-label="Data location"
703
+ >
704
+ <button
705
+ type="button"
706
+ className="cg-path-history-button"
707
+ aria-label="Back"
708
+ title="Back"
709
+ disabled={!canDataBack}
710
+ onClick={() => stepDataLevel(-1)}
711
+ >
712
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
713
+ <path
714
+ d="M9.8 3.6 5.4 8l4.4 4.4"
715
+ stroke="currentColor"
716
+ strokeWidth="1.35"
717
+ strokeLinecap="round"
718
+ strokeLinejoin="round"
719
+ />
720
+ </svg>
721
+ </button>
722
+ <span className="cg-path-segments">
723
+ {dataPathSegments.map((segment, index) => {
724
+ const current = dataNavigatorLevelKey(segment.level) === dataNavigatorLevelKey(dataLevel);
725
+ return (
726
+ <span className="cg-path-segment-wrap" key={dataNavigatorLevelKey(segment.level)}>
727
+ {index > 0 ? <span className="cg-path-separator" aria-hidden="true">›</span> : null}
728
+ <button
729
+ type="button"
730
+ className="cg-path-segment"
731
+ data-data-path-segment={dataNavigatorLevelKey(segment.level)}
732
+ aria-current={current ? "page" : undefined}
733
+ disabled={current}
734
+ title={segment.label}
735
+ onClick={() => visitDataLevel(segment.level)}
736
+ >
737
+ {segment.label}
738
+ </button>
739
+ </span>
740
+ );
741
+ })}
742
+ </span>
743
+ {canDataForward ? (
744
+ <button
745
+ type="button"
746
+ className="cg-path-history-button"
747
+ aria-label="Forward"
748
+ title="Forward"
749
+ onClick={() => stepDataLevel(1)}
750
+ >
751
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
752
+ <path
753
+ d="M6.2 3.6 10.6 8l-4.4 4.4"
754
+ stroke="currentColor"
755
+ strokeWidth="1.35"
756
+ strokeLinecap="round"
757
+ strokeLinejoin="round"
758
+ />
759
+ </svg>
760
+ </button>
761
+ ) : null}
762
+ </nav>
763
+
764
+ {dataLevel.kind === "root" ? (
765
+ <div className="cg-data-path-level" data-data-level="root">
766
+ {sourceGroups.map((group) => (
767
+ <div key={group.label} className="cg-fold cg-data-origin" {...dropProps(null)}>
768
+ <div className="cg-fold-head">
769
+ <button
770
+ type="button"
771
+ className="cg-fold-toggle"
772
+ aria-label={`Open folder ${group.label}`}
773
+ onClick={() => pushDataLevel({ kind: "origin", label: group.label })}
774
+ >
775
+ <FolderMark size={16} />
776
+ <span className="cg-fold-name">{group.label}</span>
777
+ <span className="cg-fold-count">{group.databases.length}</span>
778
+ </button>
779
+ </div>
780
+ </div>
781
+ ))}
782
+ {folders.map((folder) => {
783
+ const members = databases.filter((database) => database.folderId === folder.id);
784
+ return (
785
+ <div
786
+ key={folder.id}
787
+ className="cg-fold cg-data-user-folder"
788
+ {...dropProps(folder.id)}
789
+ >
790
+ <div className="cg-fold-head">
791
+ <button
792
+ type="button"
793
+ className="cg-fold-toggle"
794
+ aria-label={`Open folder ${folder.name}`}
795
+ onClick={() => pushDataLevel({ kind: "folder", id: folder.id })}
796
+ >
797
+ <FolderMark size={16} />
798
+ <span className="cg-fold-name">{folder.name}</span>
799
+ <span className="cg-fold-count">{members.length}</span>
800
+ </button>
801
+ {onFolderRename || onFolderDelete ? (
802
+ <button
803
+ type="button"
804
+ className="cg-view-more"
805
+ aria-label={`Actions for ${folder.name}`}
806
+ aria-haspopup="menu"
807
+ onClick={(event) => {
808
+ setFolderMenu({ folderId: folder.id, anchor: event.currentTarget });
809
+ setRenamingFolder(null);
810
+ setFolderName(folder.name);
811
+ }}
812
+ >
813
+ ···
814
+ </button>
815
+ ) : null}
816
+ </div>
817
+ </div>
818
+ );
819
+ })}
820
+ </div>
821
+ ) : dataLevel.kind === "database" ? (
822
+ <div className="cg-data-database-views" data-data-level="database">
823
+ {children}
824
+ </div>
825
+ ) : (
826
+ <div className="cg-data-path-level" data-data-level={dataLevel.kind} {...dropProps(null)}>
827
+ {levelDatabases.map(pathDatabaseRow)}
828
+ {levelDatabases.length === 0 ? (
829
+ <div className="cg-fold-empty">No databases in this folder.</div>
830
+ ) : null}
831
+ </div>
832
+ )}
833
+
834
+ {dataLevel.kind === "root" && createControl ? (
835
+ <div className="cg-data-create">{createControl}</div>
836
+ ) : null}
837
+ {folderMenu ? (
838
+ <AnchoredOverlay
839
+ anchor={folderMenu.anchor}
840
+ className="cg-view-menu"
841
+ role="menu"
842
+ ariaLabel="Database folder actions"
843
+ onDismiss={() => setFolderMenu(null)}
844
+ placement="right-start"
845
+ >
846
+ {renamingFolder === folderMenu.folderId ? (
847
+ <form
848
+ className="cg-data-folder-rename"
849
+ onSubmit={(event) => {
850
+ event.preventDefault();
851
+ const clean = folderName.trim().replace(/\s+/g, " ");
852
+ if (clean) onFolderRename?.(folderMenu.folderId, clean);
853
+ setFolderMenu(null);
854
+ }}
855
+ >
856
+ <input
857
+ className="cg-input"
858
+ autoFocus
859
+ value={folderName}
860
+ maxLength={40}
861
+ aria-label="Database folder name"
862
+ onChange={(event) => setFolderName(event.target.value)}
863
+ />
864
+ <button type="submit" className="cg-btn cg-btn--primary" disabled={!folderName.trim()}>
865
+ Save
866
+ </button>
867
+ </form>
868
+ ) : (
869
+ <>
870
+ {onFolderRename ? (
871
+ <button
872
+ type="button"
873
+ role="menuitem"
874
+ onClick={() => setRenamingFolder(folderMenu.folderId)}
875
+ >
876
+ Rename
877
+ </button>
878
+ ) : null}
879
+ {onFolderDelete ? (
880
+ <button
881
+ type="button"
882
+ role="menuitem"
883
+ className="is-danger"
884
+ onClick={() => {
885
+ onFolderDelete(folderMenu.folderId);
886
+ setFolderMenu(null);
887
+ }}
888
+ >
889
+ Delete folder
890
+ </button>
891
+ ) : null}
892
+ </>
893
+ )}
894
+ </AnchoredOverlay>
895
+ ) : null}
896
+ </div>
897
+ );
898
+
899
+ }
900
+
901
  /**
902
  * ⭐ WAVE 41 · T35 (owner instruction 11) — THE FOLDER ICON PICKER: ONE COPY, TWO DOORS.
903
  *
 
1001
  );
1002
  }
1003
 
1004
+ function readRailPath(databaseKey: string): string | null {
1005
+ try {
1006
+ const stored = localStorage.getItem(pathStorageKey(databaseKey));
1007
+ return typeof stored === "string" && stored !== "" ? stored : null;
1008
+ } catch {
1009
+ return null;
1010
+ }
1011
+ }
1012
+
1013
+ function writeRailPath(databaseKey: string, folderId: string | null): void {
1014
+ try {
1015
+ const key = pathStorageKey(databaseKey);
1016
+ if (folderId) localStorage.setItem(key, folderId);
1017
+ else localStorage.removeItem(key);
1018
+ } catch {
1019
+ // Storage is optional; losing this convenience must never take down the navigation.
1020
+ }
1021
+ }
1022
+
1023
  export default function ViewSidebar({
1024
+ databases = [],
1025
+ activeDatabaseKey = "",
1026
+ databaseFolders = [],
1027
+ onSelectDatabase,
1028
+ onDatabaseMove,
1029
+ onDatabaseFolderRename,
1030
+ onDatabaseFolderDelete,
1031
+ renderDatabaseActions,
1032
+ databaseCreateControl,
1033
  agentPanel = null,
1034
  agentOpen = false,
1035
  onToggleAgent,
 
1052
  onCohortLock,
1053
  today,
1054
  onExport,
1055
+ onExportXlsxViews,
1056
+ exportableViewIds,
1057
+ folders: suppliedFolders,
1058
  folderIdOf,
1059
  onFolderCreate,
1060
  onFolderRename,
 
1074
  actionAnchor,
1075
  onActionAnchorConsumed,
1076
  }: ViewSidebarProps) {
1077
+ // The old managed "Loopable" View folder put an origin label inside every database. Origin now
1078
+ // belongs one level up in the Data tree, so its views fall back into the database's root group.
1079
+ const folders = useMemo(
1080
+ () =>
1081
+ suppliedFolders?.filter(
1082
+ (folder) => (folder as GridFolder & { managedBy?: "loopable" }).managedBy !== "loopable"
1083
+ ),
1084
+ [suppliedFolders]
1085
+ );
1086
  /**
1087
  * I14 — creating a view now always knows WHICH KIND of view is being created, because the
1088
  * flyout is the only door in. `null` = not creating; a mode = the name step for that mode.
 
1116
  viewId: string;
1117
  anchor: HTMLElement;
1118
  } | null>(null);
1119
+ /** C3 begins with the View whose menu opened this pane; later picks are explicit. */
1120
+ const [exportViewIds, setExportViewIds] = useState<string[]>([]);
1121
+ const xlsxExportViews = useMemo(() => {
1122
+ const allowed = new Set(exportableViewIds ?? []);
1123
+ return views.filter((view) => allowed.has(view.id));
1124
+ }, [views, exportableViewIds]);
1125
  const exportView = exportFor
1126
  ? views.find((view) => view.id === exportFor.viewId)
1127
  : undefined;
1128
+ const [moveFor, setMoveFor] = useState<{ viewId: string; anchor: HTMLElement } | null>(null);
1129
+ const moveView = moveFor ? views.find((view) => view.id === moveFor.viewId) : undefined;
1130
  const addView = addFor ? views.find((view) => view.id === addFor.viewId) : undefined;
1131
  const menuView = menu ? views.find((view) => view.id === menu.viewId) : undefined;
1132
  useEffect(() => {
 
1170
  * server preference, and adding one would defeat instruction 13's own first clause: a
1171
  * preference that survives a reload is a folder that is open when the user next logs in.
1172
  */
1173
+ // Recovered from 7f6a1c0 (W42-T43): one location replaces the old expand/collapse tree.
1174
+ const [at, setAt] = useState<string | null>(() => readRailPath(activeDatabaseKey));
1175
  const [folderMenu, setFolderMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null);
1176
  /**
1177
  * ⭐ W41-T35 (instruction 11) — WHICH FOLDER'S MARK IS BEING CHANGED, and off which button.
 
1362
  () => folderNesting(foldersOn ? (folders as GridFolder[]) : []),
1363
  [foldersOn, folders]
1364
  );
1365
+ const canFileMenuView =
1366
+ foldersOn && !!menuView && mayFileView(menuView, canEditMenuView);
1367
+ const moveFolders = useMemo(
1368
+ () => nesting.ordered.filter((folder) => !isSyntheticFolderId(folder.id)),
1369
+ [nesting]
1370
+ );
1371
  /**
1372
  * ⭐⭐ WAVE 41 · T37 (owner instruction 14) — THE GROUPING RUNS ONCE PER INPUT CHANGE, NOT
1373
  * ONCE PER RENDER.
 
1498
  * it never touches `opened`, so clearing the search returns each folder to exactly the state
1499
  * the user left it in.
1500
  */
1501
+ const standableIds = useMemo(
1502
+ () => groups.flatMap((group) => (group.folder ? [group.folder.id] : [])),
1503
+ [groups]
1504
+ );
1505
+ const atId = useMemo(() => {
1506
+ if (at === null) return null;
1507
+ if (viewNeedle) return at;
1508
+ return resolveStoredPath(at, standableIds);
1509
+ }, [at, standableIds, viewNeedle]);
1510
+ useEffect(() => {
1511
+ if (activeDatabaseKey) writeRailPath(activeDatabaseKey, at);
1512
+ }, [activeDatabaseKey, at]);
1513
+ const level = useMemo(
1514
+ () =>
1515
+ levelAt(
1516
+ atId,
1517
+ foldersOn ? (folders as GridFolder[]) : [],
1518
+ shownViews,
1519
+ (view) => (folderIdOf ? folderIdOf(view.id) : null)
1520
+ ),
1521
+ [atId, foldersOn, folders, shownViews, folderIdOf]
1522
+ );
1523
+ const crumbs = useMemo(
1524
+ () => folderPath(atId, foldersOn ? (folders as GridFolder[]) : []),
1525
+ [atId, foldersOn, folders]
1526
+ );
1527
+ const atLabel = useMemo(
1528
+ () =>
1529
+ atId === null
1530
+ ? null
1531
+ : groups.find((group) => group.folder?.id === atId)?.folder?.name ?? null,
1532
+ [atId, groups]
1533
+ );
1534
+ // The folder id travels with every visible crumb. This is what makes a depth-three click jump
1535
+ // straight to depth one instead of quietly behaving like the adjacent Back button again.
1536
+ const viewPathSegments: { id: string | null; label: string }[] = [
1537
+ { id: null, label: "All views" },
1538
+ ...(crumbs.length > 0
1539
+ ? crumbs.map((folder) => ({ id: folder.id, label: folder.name }))
1540
+ : atId !== null
1541
+ ? [{ id: atId, label: atLabel ?? "Folder" }]
1542
+ : []),
1543
+ ];
1544
+ const levelGroups = useMemo(() => {
1545
+ const pin: typeof groups = [];
1546
+ const heads: typeof groups = [];
1547
+ const leaves: typeof groups = [];
1548
+ const childIds = new Set(
1549
+ atId !== null && isSyntheticFolderId(atId) ? [] : level.folders.map((folder) => folder.id)
1550
+ );
1551
+ for (const group of groups) {
1552
+ const groupId = group.folder?.id ?? null;
1553
+ if (viewNeedle) {
1554
+ if (group.items.length > 0) leaves.push(group);
1555
+ continue;
1556
+ }
1557
+ if (group.pinned === true) {
1558
+ if (atId === null) pin.push(group);
1559
+ continue;
1560
  }
1561
+ if (groupId === null) {
1562
+ if (atId === null) leaves.push(group);
1563
+ continue;
1564
+ }
1565
+ if (groupId === atId) {
1566
+ leaves.push(group);
1567
+ continue;
1568
+ }
1569
+ if (isSyntheticFolderId(groupId)) {
1570
+ if (atId === null) heads.push(group);
1571
+ continue;
1572
+ }
1573
+ if (childIds.has(groupId)) heads.push(group);
1574
  }
1575
+ return { heads, rows: [...pin, ...heads, ...leaves] };
1576
+ }, [groups, level, atId, viewNeedle]);
1577
  const folderMenuF = folderMenu ? folders?.find((f) => f.id === folderMenu.id) : undefined;
1578
  /**
1579
  * ⭐⭐ W41-T35 — THE FOLDER WHOSE MARK IS BEING CHANGED, AND THE SECOND REFUSAL OF A SYNTHETIC
 
1610
  * ⚠ BUILT ONLY WHILE A SEARCH IS LIVE. With no needle the set is never walked and the rule it
1611
  * serves never fires, so the idle rail pays nothing for it.
1612
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1613
  const addPreview = addTarget && folderAddPreview ? folderAddPreview(addTarget) : null;
1614
  /**
1615
  * ONE pair of drop handlers per group, serving TWO drags — a view being filed into this
 
1762
  * ⚠ IT CAN ONLY ADD. Nothing here removes an id, so this cannot close a folder the user
1763
  * opened, and the same-set short-circuit keeps a repeat create from re-rendering the rail.
1764
  */
1765
+ if (into) setAt(into);
1766
  // cleanFolderIcon returns undefined for the all-defaults pair, so a folder the user
1767
  // never restyled stays byte-identical to a pre-wave-9 one (the no-churn rule).
1768
  onFolderCreate?.(value, cleanFolderIcon(folderIcon), into);
 
1849
  {agentPanel}
1850
  <aside
1851
  className={"cg-views" + (railShut ? " is-collapsed" : "")}
1852
+ aria-label={databases.length ? "Data and View navigation" : "Views"}
1853
  >
1854
  {/* Owner item 11 — the rail's own minimize control: the same three-bars glyph as the
1855
  shell nav's, because the two rails are one idea ("a navigation bar folds"). */}
 
1944
  badge's ABSENCE from this row and its PRESENCE on the view rows, so re-adding one
1945
  reds it. */}
1946
  </div>
1947
+ <DataDatabaseNavigator
1948
+ databases={databases}
1949
+ activeDatabaseKey={activeDatabaseKey}
1950
+ folders={databaseFolders}
1951
+ onSelect={onSelectDatabase}
1952
+ onMove={onDatabaseMove}
1953
+ onFolderRename={onDatabaseFolderRename}
1954
+ onFolderDelete={onDatabaseFolderDelete}
1955
+ renderActions={renderDatabaseActions}
1956
+ createControl={databaseCreateControl}
1957
+ >
1958
  {/*
1959
  I13 — the "Views / All changes saved" header block is GONE and everything moved up.
1960
 
 
2227
  </AnchoredOverlay>
2228
  )}
2229
 
2230
+ {viewNeedle ? (
2231
+ <div className="cg-fold-empty" data-view-folder-path>
2232
+ Showing matches in every folder
2233
+ </div>
2234
+ ) : (
2235
+ <nav
2236
+ className="cg-fold-head cg-view-path cg-segmented-path"
2237
+ data-view-folder-path
2238
+ aria-label="View folder location"
2239
+ >
2240
+ <button
2241
+ type="button"
2242
+ className="cg-path-history-button"
2243
+ aria-label="Back to parent folder"
2244
+ title="Back to parent folder"
2245
+ disabled={atId === null}
2246
+ onClick={() => setAt(level.parent)}
2247
+ >
2248
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
2249
+ <path
2250
+ d="M9.8 3.6 5.4 8l4.4 4.4"
2251
+ stroke="currentColor"
2252
+ strokeWidth="1.35"
2253
+ strokeLinecap="round"
2254
+ strokeLinejoin="round"
2255
+ />
2256
+ </svg>
2257
+ </button>
2258
+ <span className="cg-path-segments">
2259
+ {viewPathSegments.map((segment, index) => {
2260
+ const current = segment.id === atId;
2261
+ return (
2262
+ <span className="cg-path-segment-wrap" key={segment.id ?? "root"}>
2263
+ {index > 0 ? (
2264
+ <span className="cg-path-separator" aria-hidden="true">›</span>
2265
+ ) : null}
2266
+ <button
2267
+ type="button"
2268
+ className="cg-path-segment"
2269
+ data-view-path-segment={segment.id ?? "root"}
2270
+ aria-current={current ? "page" : undefined}
2271
+ disabled={current}
2272
+ title={segment.label}
2273
+ onClick={() => setAt(segment.id)}
2274
+ >
2275
+ {segment.label}
2276
+ </button>
2277
+ </span>
2278
+ );
2279
+ })}
2280
+ </span>
2281
+ </nav>
2282
+ )}
2283
+
2284
  <div className="cg-view-list cg-views-scroll">
2285
+ {levelGroups.rows.map((group) => {
2286
  const gid = group.folder?.id ?? null;
 
 
 
 
 
 
 
2287
  /**
2288
  * ⭐⭐ WAVE 41 · T33 (instruction 12, R1) — HOW DEEP THIS FOLDER SITS, AND WHETHER IT
2289
  * SHOWS AT ALL.
 
2293
  * fall to level 1 and to "not hidden" — which is exactly where they rendered before this
2294
  * ticket. The same is true of both `folder: null` groups.
2295
  */
2296
+ const asLeaves = !group.folder || gid === atId || !!viewNeedle;
 
 
 
 
 
2297
  /**
2298
  * ⭐⭐ WAVE 40 · T28 (owner instruction 30) — THE PIN GROUP: the unfiled default views,
2299
  * rendered above every folder.
 
2329
  // "Shared with me" while offering them on a colleague's folder would emit `item_move` /
2330
  // `folder_rename` / `folder_delete` against an id that exists in nobody's store.
2331
  const isSynthetic = isSyntheticFolderId(gid);
2332
+ // C1 injects this system-owned folder into the ordinary folder list. It remains
2333
+ // readable and expandable, but no generic rename, move, delete, or menu control is
2334
+ // offered for it. Keep the additive wire fact local until its broader type owner lands.
2335
+ const isManaged =
2336
+ (group.folder as (GridFolder & { managedBy?: "loopable" }) | undefined)?.managedBy ===
2337
+ "loopable";
2338
+ const isLevelFolder = asLeaves && gid !== null && !isSynthetic && !viewNeedle;
2339
  return (
2340
  <div
2341
  /* ⭐ W40-T28 — a key of its own. Both this group and the ungrouped section have a null
 
2354
  * stylesheet would need one rule per level to a cap the model owns, and the two
2355
  * numbers would then have to be kept equal by hand.
2356
  */
 
2357
  className={
2358
  /* ⭐ W40-T28 — `gid === null`, not `isRoot`: the pin group wears the SAME class as
2359
  the ungrouped section (no head, the rail's measured root indent) because it is the
2360
  same shape of thing rendered in a different place. DESIGN.md §4 — this is an
2361
  existing element joining the existing rhythm, not a new control shape. */
2362
+ (asLeaves ? "cg-fold-root" : "cg-fold") +
2363
  (!isPinnedGroup && dropTarget === (gid ?? "__root__") ? " is-drop" : "") +
2364
  // Item 19 — the insertion rule reads "the folder you are dragging lands HERE":
2365
  // above this folder, or above the ungrouped section, which is after them all.
 
2395
  // at `null` beside a `gid` that is `null` for this very section — that is the
2396
  // `foldDrag === gid` trap two lines up, which faded the whole ungrouped section
2397
  // permanently once already. `isRoot` is a separate boolean, so the two cannot collide.
2398
+ (isRoot && viewDrag !== null ? " is-viewdrop" : "") +
2399
+ (isLevelFolder && viewDrag !== null ? " is-viewdrop" : "")
2400
  }
2401
  {/* No drop handlers on the synthetic group — see `isSynthetic`. Spreading `{}`
2402
  rather than branching the element keeps ONE render path for every group.
 
2405
  `item_move(id, ROOT_FOLDER_ID)` — a stored placement, which is the very thing that
2406
  takes a view OUT of this group. The drop would file the view and then move it
2407
  somewhere else on screen. The ungrouped section below is the one root target. */
2408
+ ...(isSynthetic || isManaged || isPinnedGroup ? {} : dropHandlers(gid))}
2409
  >
2410
+ {group.folder && !asLeaves && (
2411
  <div
2412
  className="cg-fold-head"
2413
  // ── Item 19 — the folder itself is the drag handle ─────────────────────
2414
  // Draggable only while it is renameable-idle: a `draggable` ancestor eats
2415
  // the text selection inside an input, so dragging would win over editing
2416
  // the name you just opened.
2417
+ draggable={
2418
+ foldsReorderable && !isSynthetic && !isManaged &&
2419
+ renamingFolder !== group.folder.id
2420
+ }
2421
  onDragStart={(e) => {
2422
  e.dataTransfer.setData(FOLD_DRAG_TYPE, group.folder!.id);
2423
  e.dataTransfer.effectAllowed = "move";
 
2439
  <button
2440
  type="button"
2441
  className="cg-fold-toggle"
 
2442
  /**
2443
  * ⚠ W41-T34 — THE CLICK IS READ OFF `shut`, THE STATE THE CHEVRON IS DRAWING,
2444
  * not off membership of `opened`.
 
2451
  * open once the search cleared. The user pressed "close" and got "open", one
2452
  * gesture later. Reading the drawn state makes the click mean what it looks like.
2453
  */
2454
+ aria-label={`Open folder ${group.folder.name}`}
2455
+ onClick={() => setAt(group.folder!.id)}
 
 
 
 
 
 
2456
  >
 
 
 
2457
  {/* I14/I15 — the folder wears its chosen mark; a folder that never chose one
2458
  (every pre-wave-9 folder) renders the default grey folder shape, which is
2459
  precisely "existing folders get the folder icon". */}
 
2534
  group, for the reason the block above gives: a colleague's shared folder is no
2535
  more the reader's to rename, duplicate or delete than "Shared with me" is, and
2536
  every row of that menu would be refused by a server that has no such folder. */}
2537
+ {isSynthetic || isManaged ? null : (
2538
  <button
2539
  type="button"
2540
  className="cg-view-more"
 
2555
  )}
2556
  </div>
2557
  )}
2558
+ {asLeaves &&
 
 
2559
  group.items.map((view) => {
2560
  const active = view.id === activeViewId;
2561
  const renaming = renamingId === view.id;
 
2860
  </div>
2861
  );
2862
  })}
2863
+ {group.folder && asLeaves && group.items.length === 0
2864
+ && levelGroups.heads.length === 0 && (
2865
  <div className="cg-fold-empty">Empty. Drag a view here.</div>
2866
  )}
2867
  </div>
 
2877
  free and this section has nothing left to render.
2878
  The lock MARK moved onto the ordinary view row, where `kind === "locked"` drives it. */}
2879
  </div>
2880
+ </DataDatabaseNavigator>
2881
 
2882
  {/* I11c — the folder "…" menu. Rename · Add to cohort · Duplicate · Delete.
2883
  WAVE 20 item 22 — every row now carries the SAME icon vocabulary the view row's
 
3084
  </AnchoredOverlay>
3085
  )}
3086
 
3087
+ {moveFor && moveView && (() => {
3088
+ const currentId = folderIdOf ? folderIdOf(moveFor.viewId) : null;
3089
+ const fileInto = (folderId: string | null) => {
3090
+ onItemMove?.(moveFor.viewId, folderId ?? ROOT_FOLDER_ID);
3091
+ setMoveFor(null);
3092
+ };
3093
+ return (
3094
+ <AnchoredOverlay
3095
+ anchor={moveFor.anchor}
3096
+ className="cg-pop"
3097
+ placement="bottom-end"
3098
+ role="dialog"
3099
+ ariaLabel={`Move ${viewDisplayName(moveView)} to a folder`}
3100
+ onDismiss={() => setMoveFor(null)}
3101
+ dataKind="view-move-to"
3102
+ >
3103
+ <div className="cg-pop-title">Move to</div>
3104
+ <div className="cg-pop-list" data-full-folder-path-picker>
3105
+ <button
3106
+ type="button"
3107
+ className={
3108
+ "cg-pick-row" +
3109
+ (currentId === null || currentId === ROOT_FOLDER_ID ? " is-on" : "")
3110
+ }
3111
+ onClick={() => fileInto(null)}
3112
+ >
3113
+ <FolderMark size={16} />
3114
+ Top level
3115
+ </button>
3116
+ {moveFolders.map((folder) => (
3117
+ <button
3118
+ type="button"
3119
+ key={folder.id}
3120
+ className={"cg-pick-row" + (folder.id === currentId ? " is-on" : "")}
3121
+ style={{ paddingLeft: 6 + (nesting.depth[folder.id] ?? 0) * 12 }}
3122
+ title={folderPath(folder.id, moveFolders).map((part) => part.name).join(" / ")}
3123
+ onClick={() => fileInto(folder.id)}
3124
+ >
3125
+ <FolderMark icon={folder.icon} size={16} />
3126
+ {folder.name}
3127
+ </button>
3128
+ ))}
3129
+ {moveFolders.length === 0 ? (
3130
+ <div className="cg-pop-note">There are no folders in this database yet.</div>
3131
+ ) : null}
3132
+ </div>
3133
+ </AnchoredOverlay>
3134
+ );
3135
+ })()}
3136
+
3137
  {/* Item 12 (C-LOCK) — the lock picker. Lists the cohorts this reader can see, marks the
3138
  current one, and offers Unlock when there is one: a lock removable only from
3139
  somewhere other than where it was applied is a trap, and the owner asked for a
 
3269
  dataKind="saved-view-menu"
3270
  >
3271
  {/* W2 (C2): Export sits ABOVE the rename/delete group, thin divider between. */}
3272
+ {(onExport || onExportXlsxViews || onImport) && (
3273
  <>
3274
  {/* ⭐ WAVE-29 T32 (owner item 16 / R10) — the DATA group's header.
3275
  The owner's complaint was that Export "looks like an orphan": it is already the
 
3293
  >
3294
  Data
3295
  </div>
3296
+ {(onExport || onExportXlsxViews) && (
3297
  <button
3298
  type="button"
3299
  role="menuitem"
3300
  onClick={() => {
3301
  setExportFor({ viewId: menuView.id, anchor: menu.anchor });
3302
+ setExportViewIds(
3303
+ exportableViewIds?.includes(menuView.id) ? [menuView.id] : []
3304
+ );
3305
  setMenu(null);
3306
  }}
3307
  >
 
3395
  >
3396
  <MenuLabel icon="duplicate" text="Duplicate" />
3397
  </button>
3398
+ {canFileMenuView && (
3399
+ <button
3400
+ type="button"
3401
+ role="menuitem"
3402
+ onClick={() => {
3403
+ setMoveFor({ viewId: menuView.id, anchor: menu.anchor });
3404
+ setMenu(null);
3405
+ }}
3406
+ >
3407
+ <MenuLabel icon={<FolderMark size={16} />} text="Move to" />
3408
+ </button>
3409
+ )}
3410
  {/* WAVE 20 items 23/26 (R10) — "who else can reach this view", the same
3411
  editor a folder and a database open. Deliberately NOT gated on
3412
  `canEditMenuView`: the server decides who may administer (owner or
 
3642
  {/* W2 (C2) — the format pane: CSV · Excel · PDF · JSON, keyboard-navigable like
3643
  the menu it came from. Rows/columns are the view's CURRENT matches and visible
3644
  fields; generation is client-side (the grid already holds the answer). */}
3645
+ {exportFor && exportView && (onExport || onExportXlsxViews) && (
3646
  <AnchoredOverlay
3647
  anchor={exportFor.anchor}
3648
  className="cg-view-menu"
3649
  placement="bottom-end"
3650
+ role="dialog"
3651
  ariaLabel={`Export ${viewDisplayName(exportView)}`}
3652
  onDismiss={() => setExportFor(null)}
3653
  onKeyDown={onMenuKeyDown}
3654
  dataKind="view-export"
3655
  >
3656
  <div className="cg-pop-title cg-export-title">Export {viewDisplayName(exportView)}</div>
3657
+ {onExportXlsxViews && (
3658
+ <div className="cg-pop-body">
3659
+ <div className="cg-pop-note">Each selected View becomes its own Excel tab.</div>
3660
+ {xlsxExportViews.map((view) => {
3661
+ const selected = exportViewIds.includes(view.id);
3662
+ return (
3663
+ <label key={view.id} className="cg-radio-row">
3664
+ <input
3665
+ type="checkbox"
3666
+ checked={selected}
3667
+ disabled={(selected && exportViewIds.length === 1) ||
3668
+ (!selected && exportViewIds.length >= 20)}
3669
+ onChange={() =>
3670
+ setExportViewIds((current) => selected
3671
+ ? current.filter((id) => id !== view.id)
3672
+ : [...current, view.id])
3673
+ }
3674
+ />
3675
+ <span>{viewDisplayName(view)}</span>
3676
+ </label>
3677
+ );
3678
+ })}
3679
+ </div>
3680
+ )}
3681
+ {EXPORT_FORMATS.map((format) => {
3682
+ if (format === "xlsx" && onExportXlsxViews) {
3683
+ return (
3684
+ <button
3685
+ key={format}
3686
+ type="button"
3687
+ role="menuitem"
3688
+ disabled={exportViewIds.length === 0}
3689
+ onClick={() => {
3690
+ onExportXlsxViews(exportViewIds);
3691
+ setExportFor(null);
3692
+ }}
3693
+ >
3694
+ Export Excel
3695
+ </button>
3696
+ );
3697
+ }
3698
+ if (!onExport) return null;
3699
+ return (
3700
+ <button
3701
+ key={format}
3702
+ type="button"
3703
+ role="menuitem"
3704
+ onClick={() => {
3705
+ onExport(exportView.id, format);
3706
+ setExportFor(null);
3707
+ }}
3708
+ >
3709
+ {EXPORT_LABELS[format]}
3710
+ </button>
3711
+ );
3712
+ })}
3713
  </AnchoredOverlay>
3714
  )}
3715
 
web/src/customer-grid/apiBridge.ts CHANGED
@@ -949,6 +949,47 @@ export interface RollupSourceTopic {
949
  measures: { key: string; label: string; format: string; description: string }[];
950
  }
951
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
952
  export async function patchTableField(
953
  tableKey: string,
954
  fieldKey: string,
@@ -1098,6 +1139,105 @@ export async function deleteTableField(
1098
  }
1099
  }
1100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1101
  /**
1102
  * ⭐⭐ 2026-08-09 — THE DEFINITION SHAPE, NOT A THREE-KEY SUMMARY.
1103
  *
 
949
  measures: { key: string; label: string; format: string; description: string }[];
950
  }
951
 
952
+ /**
953
+ * W42-T08/T37: the semantic one-hop authoring offer is deliberately fetched from its own
954
+ * endpoint. It is not a projection of RollupSourceOffer: hop dimensions carry their real
955
+ * date/number/text types, which choose the filter operators rendered by FilterBuilderPanel.
956
+ */
957
+ export interface HopTopic {
958
+ key: string;
959
+ label: string;
960
+ dims: Field[];
961
+ measures: { key: string; label: string }[];
962
+ }
963
+
964
+ export interface HopTopicOffer {
965
+ topics: HopTopic[];
966
+ windows: { key: string; label: string }[];
967
+ omissions: { topic: string; label: string; reasons: string[] }[];
968
+ }
969
+
970
+ /** Preserve the server's typed dimensions; malformed envelopes fail closed to an empty offer. */
971
+ export function hopTopicOfferFromBody(body: unknown): HopTopicOffer {
972
+ const raw = body && typeof body === "object" && !Array.isArray(body)
973
+ ? body as Partial<HopTopicOffer>
974
+ : null;
975
+ return {
976
+ topics: Array.isArray(raw?.topics) ? raw.topics : [],
977
+ windows: Array.isArray(raw?.windows) ? raw.windows : [],
978
+ omissions: Array.isArray(raw?.omissions) ? raw.omissions : [],
979
+ };
980
+ }
981
+
982
+ export async function fetchHopTopics(): Promise<HopTopicOffer> {
983
+ const empty: HopTopicOffer = { topics: [], windows: [], omissions: [] };
984
+ try {
985
+ const res = await fetch(`${API_V1}/grid/hop-topics`, { credentials: CREDENTIALS });
986
+ if (handledSession(res) || !res.ok) return empty;
987
+ return hopTopicOfferFromBody(await readJson(res));
988
+ } catch {
989
+ return empty;
990
+ }
991
+ }
992
+
993
  export async function patchTableField(
994
  tableKey: string,
995
  fieldKey: string,
 
1139
  }
1140
  }
1141
 
1142
+ /** Per-column verdict returned by the plural schema delete door. */
1143
+ export interface FieldDeleteResult {
1144
+ key: string;
1145
+ status: "deleted" | "refused";
1146
+ code?: string;
1147
+ reason?: string;
1148
+ contract?: unknown;
1149
+ removed?: unknown;
1150
+ }
1151
+
1152
+ export interface FieldDeleteOutcome {
1153
+ deleted: string[];
1154
+ refused: string[];
1155
+ results: FieldDeleteResult[];
1156
+ /** The server accepted the request but did not name any affected key. */
1157
+ unreadable: boolean;
1158
+ }
1159
+
1160
+ const DELETE_ANSWER_NAMED_NO_COLUMN =
1161
+ "The server accepted that delete without saying which columns went, so the table is being read " +
1162
+ "again rather than guessed at.";
1163
+
1164
+ function refusedWholesale(
1165
+ fieldKeys: readonly string[],
1166
+ reason: string | undefined,
1167
+ code: string,
1168
+ unreadable = false,
1169
+ ): FieldDeleteOutcome {
1170
+ return {
1171
+ deleted: [],
1172
+ refused: [...fieldKeys],
1173
+ results: fieldKeys.map((key) => ({ key, status: "refused" as const, code, reason })),
1174
+ unreadable,
1175
+ };
1176
+ }
1177
+
1178
+ /**
1179
+ * Delete every selected definition through one request, including a one-item selection. The
1180
+ * caller reconciles only the keys the server explicitly reports as deleted.
1181
+ */
1182
+ export async function deleteTableFields(
1183
+ tableKey: string,
1184
+ fieldKeys: readonly string[],
1185
+ ): Promise<FieldDeleteOutcome> {
1186
+ if (fieldKeys.length === 0) {
1187
+ return { deleted: [], refused: [], results: [], unreadable: false };
1188
+ }
1189
+ let res: Response;
1190
+ try {
1191
+ res = await fetch(`${API_V1}/tables/${encodeURIComponent(tableKey)}/fields/delete`, {
1192
+ method: "POST",
1193
+ credentials: CREDENTIALS,
1194
+ headers: JSON_HEADERS,
1195
+ body: JSON.stringify({ keys: [...fieldKeys] }),
1196
+ });
1197
+ } catch {
1198
+ return refusedWholesale(fieldKeys, "That delete did not reach the server.", "unreachable");
1199
+ }
1200
+ if (handledSession(res)) return refusedWholesale(fieldKeys, undefined, "session_ended");
1201
+ const body = (await readJson(res)) as {
1202
+ results?: unknown;
1203
+ deleted?: unknown;
1204
+ refused?: unknown;
1205
+ error?: { message?: string; code?: string };
1206
+ } | null;
1207
+ if (!res.ok) {
1208
+ const code = typeof body?.error?.code === "string" ? body.error.code : "refused";
1209
+ return refusedWholesale(fieldKeys, refusalMessage(body, res.status), code);
1210
+ }
1211
+ const results: FieldDeleteResult[] = [];
1212
+ if (Array.isArray(body?.results)) {
1213
+ for (const entry of body.results) {
1214
+ const raw = entry as Record<string, unknown> | null;
1215
+ if (!raw || typeof raw.key !== "string") continue;
1216
+ results.push({
1217
+ key: raw.key,
1218
+ status: raw.status === "deleted" ? "deleted" : "refused",
1219
+ code: typeof raw.code === "string" ? raw.code : undefined,
1220
+ reason: typeof raw.reason === "string" ? raw.reason : undefined,
1221
+ contract: raw.contract,
1222
+ removed: raw.removed,
1223
+ });
1224
+ }
1225
+ } else {
1226
+ const named = (value: unknown): string[] =>
1227
+ Array.isArray(value) ? value.filter((key): key is string => typeof key === "string") : [];
1228
+ for (const key of named(body?.deleted)) results.push({ key, status: "deleted" });
1229
+ for (const key of named(body?.refused)) results.push({ key, status: "refused" });
1230
+ }
1231
+ if (results.length === 0) {
1232
+ dropTableRowsCache(tableKey);
1233
+ return refusedWholesale(fieldKeys, DELETE_ANSWER_NAMED_NO_COLUMN, "unreadable_answer", true);
1234
+ }
1235
+ const deleted = results.filter((item) => item.status === "deleted").map((item) => item.key);
1236
+ const refused = results.filter((item) => item.status === "refused").map((item) => item.key);
1237
+ if (deleted.length > 0) dropTableRowsCache(tableKey);
1238
+ return { deleted, refused, results, unreadable: false };
1239
+ }
1240
+
1241
  /**
1242
  * ⭐⭐ 2026-08-09 — THE DEFINITION SHAPE, NOT A THREE-KEY SUMMARY.
1243
  *
web/src/customer-grid/dataPath.ts ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { FolderIcon } from "./types";
2
+ import { folderNesting, ROOT_FOLDER_ID } from "./folders";
3
+
4
+ // Canonical, shareable Data addressing. The shell keeps the global main navigation;
5
+ // this describes only the Data workspace's secondary location.
6
+ export interface DataPath {
7
+ database: string;
8
+ view?: string;
9
+ field?: string;
10
+ }
11
+
12
+ /** A granted database as rendered by the Data workspace's secondary navigator. */
13
+ export interface DataDatabase {
14
+ key: string;
15
+ label: string;
16
+ source?: string;
17
+ managedBy?: "loopable";
18
+ protected?: boolean;
19
+ locked?: boolean;
20
+ icon?: FolderIcon;
21
+ folderId?: string;
22
+ externalHref?: string;
23
+ }
24
+
25
+ export interface DataDatabaseFolder {
26
+ id: string;
27
+ name: string;
28
+ }
29
+
30
+ export interface DataDatabaseGroup {
31
+ label: string;
32
+ databases: DataDatabase[];
33
+ }
34
+
35
+ /** The structural folder contract shared by database folders and View folders (W42-T41). */
36
+ export interface PathFolder {
37
+ id: string;
38
+ name: string;
39
+ parent?: string | null;
40
+ }
41
+
42
+ export interface FolderLevel<F, T> {
43
+ folder: F | null;
44
+ folders: F[];
45
+ leaves: T[];
46
+ parent: string | null;
47
+ depth: number;
48
+ }
49
+
50
+ function levelIdOf(raw: string | null | undefined, known: ReadonlySet<string>): string | null {
51
+ if (raw == null || raw === ROOT_FOLDER_ID) return null;
52
+ return known.has(raw) ? raw : null;
53
+ }
54
+
55
+ /**
56
+ * W42-T41's one level resolver. It keeps folders and leaves separate so every renderer lists
57
+ * folders first, and it takes the parent answer from the existing cycle-safe nesting model.
58
+ */
59
+ export function levelAt<F extends PathFolder, T>(
60
+ at: string | null | undefined,
61
+ folders: readonly F[],
62
+ items: readonly T[],
63
+ folderIdOf: (item: T) => string | null | undefined
64
+ ): FolderLevel<F, T> {
65
+ const list = [...folders];
66
+ const byId = new Map<string, F>(list.map((folder) => [folder.id, folder]));
67
+ const known = new Set(byId.keys());
68
+ const nesting = folderNesting(list);
69
+ const hereId = levelIdOf(at, known);
70
+ const here = hereId == null ? null : (byId.get(hereId) ?? null);
71
+ const parent = here ? (nesting.parent[here.id] ?? null) : null;
72
+ const subfolders: F[] = [];
73
+ for (const folder of nesting.ordered) {
74
+ const own = byId.get(folder.id);
75
+ if (!own) continue;
76
+ if ((nesting.parent[folder.id] ?? null) === (here?.id ?? null)) subfolders.push(own);
77
+ }
78
+ const leaves = items.filter(
79
+ (item) => levelIdOf(folderIdOf(item), known) === (here?.id ?? null)
80
+ );
81
+ return {
82
+ folder: here,
83
+ folders: subfolders,
84
+ leaves,
85
+ parent,
86
+ depth: here ? (nesting.depth[here.id] ?? 1) : 0,
87
+ };
88
+ }
89
+
90
+ /** Outermost-first breadcrumb over the same cycle-safe parent map as {@link levelAt}. */
91
+ export function folderPath<F extends PathFolder>(
92
+ at: string | null | undefined,
93
+ folders: readonly F[]
94
+ ): F[] {
95
+ const list = [...folders];
96
+ const byId = new Map<string, F>(list.map((folder) => [folder.id, folder]));
97
+ const nesting = folderNesting(list);
98
+ let cursor = levelIdOf(at, new Set(byId.keys()));
99
+ const path: F[] = [];
100
+ const walked = new Set<string>();
101
+ while (cursor) {
102
+ if (walked.has(cursor)) break;
103
+ walked.add(cursor);
104
+ const folder = byId.get(cursor);
105
+ if (!folder) break;
106
+ path.unshift(folder);
107
+ cursor = nesting.parent[cursor] ?? null;
108
+ }
109
+ return path;
110
+ }
111
+
112
+ const VIEW_PATH_KEY_PREFIX = "aios-views-at";
113
+
114
+ /** W42-T45: stable per-database browser slot for the open View folder. */
115
+ export function pathStorageKey(databaseKey: string): string {
116
+ return `${VIEW_PATH_KEY_PREFIX}-${typeof databaseKey === "string" ? databaseKey : ""}`;
117
+ }
118
+
119
+ /** Refuse a stale stored folder id instead of restoring an empty, unreachable level. */
120
+ export function resolveStoredPath(
121
+ stored: string | null | undefined,
122
+ validIds: Iterable<string> | null | undefined
123
+ ): string | null {
124
+ if (typeof stored !== "string" || stored === "") return null;
125
+ if (!validIds || typeof validIds[Symbol.iterator] !== "function") return null;
126
+ for (const id of validIds) if (id === stored) return stored;
127
+ return null;
128
+ }
129
+
130
+ /**
131
+ * The database tree is grouped by the provenance the server supplied, never by a tenant label.
132
+ * Blank and automation-created tables are Loopable-generated; managed system tables carry the
133
+ * stronger `managedBy` signal. Connected sources keep their own server-provided name.
134
+ */
135
+ export function dataDatabaseOrigin(database: DataDatabase): string {
136
+ const source = database.source?.trim() ?? "";
137
+ const normalized = source.toLowerCase();
138
+ if (
139
+ database.managedBy === "loopable" ||
140
+ normalized === "loopable" ||
141
+ normalized === "blank" ||
142
+ normalized === "automation" ||
143
+ !normalized
144
+ ) {
145
+ return "Loopable";
146
+ }
147
+ return source;
148
+ }
149
+
150
+ /** Preserve the granted order inside each origin and the first-seen order of origin folders. */
151
+ export function groupDataDatabases(databases: readonly DataDatabase[]): DataDatabaseGroup[] {
152
+ const groups = new Map<string, DataDatabase[]>();
153
+ for (const database of databases) {
154
+ const label = dataDatabaseOrigin(database);
155
+ const current = groups.get(label);
156
+ if (current) current.push(database);
157
+ else groups.set(label, [database]);
158
+ }
159
+ return [...groups].map(([label, grouped]) => ({ label, databases: grouped }));
160
+ }
161
+
162
+ export function dataPathHash(path: DataPath): string {
163
+ const query = new URLSearchParams({ database: path.database });
164
+ if (path.view) query.set("view", path.view);
165
+ if (path.field) query.set("field", path.field);
166
+ return `#/data?${query.toString()}`;
167
+ }
168
+
169
+ export function readDataPath(hash?: string): DataPath | null {
170
+ const source = hash ?? (typeof window === "undefined" ? "" : window.location.hash);
171
+ if (!source.startsWith("#/data?")) return null;
172
+ const query = new URLSearchParams(source.slice("#/data?".length));
173
+ const database = query.get("database");
174
+ if (!database) return null;
175
+ return {
176
+ database,
177
+ ...(query.get("view") ? { view: query.get("view")! } : {}),
178
+ ...(query.get("field") ? { field: query.get("field")! } : {}),
179
+ };
180
+ }
181
+
182
+ export function dataPathLabel(database: string, view?: string): string {
183
+ return ["Data", database, view].filter((part): part is string => !!part).join(" > ");
184
+ }
web/src/customer-grid/export.ts CHANGED
@@ -575,6 +575,53 @@ export function buildXlsx(
575
  );
576
  }
577
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
578
  // ----------------------------------------------------------------------- PDF
579
 
580
  // Landscape Letter, brand navy header (contract): repeated header row + page
 
575
  );
576
  }
577
 
578
+ /** A workbook tab is evaluated by its own saved View before it reaches this writer.
579
+ * This deliberately accepts rows rather than browser-visible rows: callers must run the View
580
+ * pipeline (including its Cohort set) separately for every tab. */
581
+ export interface XlsxWorkbookSheet {
582
+ name: string;
583
+ fields: Field[];
584
+ rows: Row[];
585
+ }
586
+
587
+ /**
588
+ * Multi-View XLSX writer. `buildXlsx` remains the compatibility one-tab path; this builder
589
+ * shares the package helpers and emits one worksheet relationship per evaluated View.
590
+ */
591
+ export function buildXlsxWorkbook(sheets: XlsxWorkbookSheet[], today?: string): Uint8Array {
592
+ if (!sheets.length) throw new Error("An XLSX workbook needs at least one View");
593
+ const enc = new TextEncoder();
594
+ const cell = (value: string) =>
595
+ `<c t="inlineStr"><is><t xml:space="preserve">${xmlEscape(value)}</t></is></c>`;
596
+ const rowXml = (cells: string[]) => `<row>${cells.join("")}</row>`;
597
+ const worksheet = (sheet: XlsxWorkbookSheet) => {
598
+ const body = [rowXml(sheet.fields.map((field) => cell(field.label)))];
599
+ for (const row of sheet.rows)
600
+ body.push(rowXml(sheet.fields.map((field) => cell(formatDisplay(field, row[field.key])))));
601
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
602
+ `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>` +
603
+ `${body.join("")}</sheetData></worksheet>`;
604
+ };
605
+ const workbookSheets = sheets.map((sheet, index) =>
606
+ `<sheet name="${xmlEscape(sheetName(sheet.name))}" sheetId="${index + 1}" r:id="rId${index + 1}"/>`
607
+ ).join("");
608
+ const workbook = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
609
+ `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>${workbookSheets}</sheets></workbook>`;
610
+ const types = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
611
+ `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>` +
612
+ sheets.map((_, index) => `<Override PartName="/xl/worksheets/sheet${index + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`).join("") + `</Types>`;
613
+ const rootRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`;
614
+ const workbookRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
615
+ sheets.map((_, index) => `<Relationship Id="rId${index + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${index + 1}.xml"/>`).join("") + `</Relationships>`;
616
+ return buildZip([
617
+ { name: "[Content_Types].xml", data: enc.encode(types) },
618
+ { name: "_rels/.rels", data: enc.encode(rootRels) },
619
+ { name: "xl/workbook.xml", data: enc.encode(workbook) },
620
+ { name: "xl/_rels/workbook.xml.rels", data: enc.encode(workbookRels) },
621
+ ...sheets.map((sheet, index) => ({ name: `xl/worksheets/sheet${index + 1}.xml`, data: enc.encode(worksheet(sheet)) })),
622
+ ], today);
623
+ }
624
+
625
  // ----------------------------------------------------------------------- PDF
626
 
627
  // Landscape Letter, brand navy header (contract): repeated header row + page
web/src/customer-grid/formulaEngine.ts CHANGED
@@ -6,7 +6,11 @@
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,7 +25,29 @@
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,10 +93,12 @@ export type FormulaAst =
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,6 +125,9 @@ const FN_ARITY: Record<FormulaFn, [number, number]> = {
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,11 +139,23 @@ const FN_ARITY: Record<FormulaFn, [number, number]> = {
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,15 +196,20 @@ function tokenize(src: string): Token[] | string {
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,7 +402,9 @@ export function parseFormula(src: string): ParseResult {
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,6 +551,187 @@ function dateSerial(p: { y: number; m: number; d: number }): number {
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,6 +940,18 @@ function evalNode(n: FormulaAst, get: (key: string) => unknown, env: FormulaEnv)
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,6 +993,75 @@ function evalNode(n: FormulaAst, get: (key: string) => unknown, env: FormulaEnv)
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,6 +1078,46 @@ function evalNode(n: FormulaAst, get: (key: string) => unknown, env: FormulaEnv)
766
  if (!end || !start) return null;
767
  return Math.round(dateSerial(end) - dateSerial(start));
768
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
769
  }
770
  return null;
771
  }
@@ -774,6 +1126,25 @@ function evalNode(n: FormulaAst, get: (key: string) => unknown, env: FormulaEnv)
774
  }
775
  }
776
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
777
  function cmpNums(op: "<" | "<=" | ">" | ">=" | "=" | "!=", l: number, r: number): boolean {
778
  switch (op) {
779
  case "<": return l < r;
@@ -855,6 +1226,58 @@ export function orderFormulas(sources: ReadonlyMap<string, string>): {
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,6 +1286,8 @@ export function validateFormula(
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 };
 
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
  // 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
  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
  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
  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
  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
  }
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
  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
  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
  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
  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
  }
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
  * 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
  ): { 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 };
web/src/customer-grid/map.css CHANGED
@@ -236,43 +236,90 @@
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-chooser {
259
- position: relative;
260
- }
261
-
262
  .cg-map-zone-choices {
263
- position: absolute;
264
- z-index: 4;
265
- top: calc(100% + 4px);
266
- left: 0;
267
  display: grid;
268
- width: min(280px, calc(100vw - 32px));
269
  max-height: 248px;
270
  overflow-y: auto;
271
  padding: 5px;
272
  border: 1px solid var(--lp-line);
273
- border-radius: 6px;
274
- background: var(--lp-panel, #fff);
275
- box-shadow: 0 8px 20px rgba(24, 39, 55, 0.14);
 
 
 
 
 
 
276
  }
277
 
278
  .cg-map-zone-choice {
@@ -288,9 +335,23 @@
288
  font: 500 var(--lp-fs-2xs)/1.35 Inter, system-ui, sans-serif;
289
  }
290
 
291
- .cg-map-zone-choice:hover { background: var(--lp-hover, #f3f6f9); }
292
 
293
  .cg-map-zone-choice input { margin: 0; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
 
295
  .cg-map-zone-swatch {
296
  width: 9px;
@@ -305,6 +366,8 @@
305
  font: 400 var(--lp-fs-2xs)/1.35 Inter, system-ui, sans-serif;
306
  }
307
 
 
 
308
  /* --- the address lookup (T37) ---------------------------------------------
309
  *
310
  * ⛔ THE PROGRESS LINE IS A REQUIREMENT, NOT A COURTESY. The free geocoder allows about one
 
236
 
237
  .cg-map-zone:hover { fill-opacity: 0.28; }
238
 
239
+ .cg-map-water { fill: var(--lp-purple-tint, var(--lp-primary-tint)); }
240
+ .cg-w44-route-nav { display: grid; gap: 6px; padding: 8px; border: 1px solid var(--lp-line); border-radius: var(--lp-r-md); background: var(--cg-white); color: var(--cg-text); font: 400 var(--lp-fs-2xs)/1.4 Inter, system-ui, sans-serif; }
241
+ .cg-w44-route-title { font-weight: 600; }
242
+ .cg-w44-route-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
243
+ .cg-w44-route-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px; align-items: center; }
244
+ .cg-w44-route-row.is-outside { color: var(--lp-muted); }
245
+ .cg-w44-route-select, .cg-w44-route-detail, .cg-w44-route-back, .cg-w44-route-stops button { border: 0; background: transparent; font: inherit; color: inherit; cursor: pointer; text-align: left; }
246
+ .cg-w44-route-select { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
247
+ .cg-w44-route-select i, .cg-w44-route-title i { display: inline-block; width: 8px; height: 8px; margin-right: 6px; border-radius: 50%; }
248
+ .cg-w44-route-detail { color: var(--lp-blue-deep); }
249
+ .cg-w44-route-detail:disabled { color: var(--lp-muted); cursor: not-allowed; }
250
+ .cg-w44-route-select:focus-visible, .cg-w44-route-detail:focus-visible, .cg-w44-route-back:focus-visible, .cg-w44-route-stops button:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 2px; }
251
+ .cg-w44-route-empty { margin: 0; color: var(--lp-muted); }
252
+ .cg-w44-route-stops { display: grid; gap: 4px; margin: 0; padding-left: 20px; }
253
+ .cg-w44-route-stops li { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 4px 8px; }
254
+ .cg-w44-route-stop-open { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
255
+ .cg-w44-route-stop-actions { display: inline-flex; align-items: flex-end; gap: 4px; }
256
+ .cg-w44-route-outside { grid-column: 1 / -1; color: var(--lp-muted); font: 500 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif; }
257
+ .cg-w44-route-position { display: grid; gap: 2px; color: var(--lp-muted); font-size: var(--lp-fs-3xs); }
258
+ .cg-w44-route-order { box-sizing: border-box; width: 46px; height: 28px; padding: 3px 5px; border: 1px solid var(--lp-line); border-radius: var(--lp-r-sm); background: var(--cg-white); color: inherit; font: inherit; text-align: center; }
259
+ .cg-w44-route-order:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 1px; }
260
+ .cg-w44-route-order:disabled { opacity: 0.55; cursor: not-allowed; }
261
+ .cg-w44-route-step, .cg-w44-route-position-apply { min-height: 28px; border-radius: var(--lp-r-sm); }
262
+ .cg-w44-route-step { display: grid; width: 28px; padding: 5px; place-items: center; }
263
+ .cg-w44-route-step svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-linecap: round; stroke-linejoin: round; stroke-width: 1.6; }
264
+ .cg-w44-route-position-apply { padding: 4px 6px; }
265
+ .cg-w44-route-step:hover:not(:disabled), .cg-w44-route-position-apply:hover:not(:disabled) { background: var(--lp-blue-tint); }
266
+ .cg-w44-route-step:disabled, .cg-w44-route-position-apply:disabled { opacity: 0.55; cursor: not-allowed; }
267
+ .cg-w44-route-order-error { grid-column: 1 / -1; color: var(--lp-red-deep); font: 500 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif; }
268
+ .cg-w44-route-label, .cg-w44-route-sources { display: grid; gap: 4px; min-width: 0; color: var(--cg-text); font: 500 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif; }
269
+ .cg-w44-route-sources { margin: 0; padding: 6px; border: 1px solid var(--lp-line); border-radius: var(--lp-r-sm); }
270
+ .cg-w44-route-sources label { display: flex; gap: 5px; align-items: center; }
271
+ .cg-w44-route-stops button, .cg-w44-route-back, .cg-w44-route-maps { color: var(--lp-blue-deep); }
272
+ .cg-w44-route-warning { color: var(--lp-yellow-deep); font: 500 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif; }
273
+ .cg-w44-route-edit, .cg-w44-route-prompt { display: grid; gap: 7px; padding-top: 8px; border-top: 1px solid var(--lp-line); }
274
+ .cg-w44-route-prompt p { margin: 0; color: var(--cg-text); font: 500 var(--lp-fs-2xs)/1.4 Inter, system-ui, sans-serif; }
275
+
276
+ .cg-map-zone-trigger {
277
+ display: inline-flex;
278
+ align-items: center;
279
+ gap: 5px;
280
+ }
281
+
282
+ .cg-map-zone-trigger svg {
283
+ width: 12px;
284
+ height: 8px;
285
+ fill: none;
286
+ stroke: currentColor;
287
+ stroke-width: 1.5;
288
+ stroke-linecap: round;
289
+ stroke-linejoin: round;
290
+ }
291
+
292
  .cg-map-zones {
293
+ display: grid;
294
+ align-items: stretch;
295
+ gap: 8px;
 
296
  width: 100%;
297
+ padding-top: 8px;
 
298
  }
299
 
300
  .cg-map-zone-control {
301
+ display: grid;
 
 
302
  gap: 3px;
303
  color: var(--lp-muted);
304
  font: 500 var(--lp-fs-3xs)/1.35 Inter, system-ui, sans-serif;
305
  }
306
 
 
 
 
 
307
  .cg-map-zone-choices {
 
 
 
 
308
  display: grid;
309
+ width: 100%;
310
  max-height: 248px;
311
  overflow-y: auto;
312
  padding: 5px;
313
  border: 1px solid var(--lp-line);
314
+ border-radius: var(--lp-r-sm);
315
+ background: var(--lp-surface);
316
+ }
317
+
318
+ .cg-map-zone-option {
319
+ display: grid;
320
+ grid-template-columns: minmax(0, 1fr) auto;
321
+ align-items: center;
322
+ gap: 6px;
323
  }
324
 
325
  .cg-map-zone-choice {
 
335
  font: 500 var(--lp-fs-2xs)/1.35 Inter, system-ui, sans-serif;
336
  }
337
 
338
+ .cg-map-zone-choice:hover { background: var(--lp-surface-2); }
339
 
340
  .cg-map-zone-choice input { margin: 0; }
341
+ .cg-map-zone-choice input:disabled { cursor: not-allowed; opacity: 0.45; }
342
+
343
+ .cg-map-zone-edit {
344
+ border: 0;
345
+ background: transparent;
346
+ font: inherit;
347
+ color: var(--lp-blue-deep);
348
+ cursor: pointer;
349
+ padding: 4px 6px;
350
+ border-radius: var(--lp-r-sm);
351
+ }
352
+
353
+ .cg-map-zone-edit:hover { background: var(--lp-blue-tint); }
354
+ .cg-map-zone-edit:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 2px; }
355
 
356
  .cg-map-zone-swatch {
357
  width: 9px;
 
366
  font: 400 var(--lp-fs-2xs)/1.35 Inter, system-ui, sans-serif;
367
  }
368
 
369
+ .cg-map-zone-editor .cg-btn { justify-self: start; }
370
+
371
  /* --- the address lookup (T37) ---------------------------------------------
372
  *
373
  * ⛔ THE PROGRESS LINE IS A REQUIREMENT, NOT A COURTESY. The free geocoder allows about one
web/src/customer-grid/navFold.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { PointerEvent as ReactPointerEvent } from "react";
2
+
3
+ import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
4
+
5
+ type WorkSurfacePointer = Pick<
6
+ ReactPointerEvent<HTMLElement>,
7
+ "button" | "detail" | "isPrimary"
8
+ >;
9
+
10
+ /** Fold the global rail when the primary pointer enters a view's body. */
11
+ export function foldNavOnWorkSurface(event: WorkSurfacePointer): void {
12
+ if (event.button !== 0 || event.isPrimary === false || event.detail > 1) return;
13
+ signal(NAV_MINIMIZE_EVENT);
14
+ }
15
+
16
+ /** Grid uses a cell callback rather than a rendered host element. */
17
+ export function foldGridCell(): void {
18
+ signal(NAV_MINIMIZE_EVENT);
19
+ }