fsanyoto commited on
Commit
9b4b996
·
verified ·
1 Parent(s): 76fae61

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "v54 (6a8e99a)",
3
  "releases": [
4
  {
5
  "version": "v54",
 
1
  {
2
+ "current": "43fd8cf",
3
  "releases": [
4
  {
5
  "version": "v54",
VERSION CHANGED
@@ -1 +1 @@
1
- v54 (6a8e99a)
 
1
+ 43fd8cf
api/automation_engine.py CHANGED
@@ -1481,8 +1481,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)
@@ -9259,6 +9265,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 +9275,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 +9333,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 +9355,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 +9442,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 +10037,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 +11120,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
  #
 
1481
  """
1482
  description = " ".join(str(extra.pop(
1483
  "description", IG_FIELD_DESCRIPTIONS.get(text_key, "")) or "").split())
1484
+ # W44 C3: machine-spawned columns must declare the same full field contract emitted by the
1485
+ # user-table validator. A generic engine field is source-owned; the two derived kinds are
1486
+ # computed. Keeping this in the one constructor keeps every preset family exact under
1487
+ # `_clean_field` instead of letting a new contract key drift across hundreds of declarations.
1488
+ value_authority = "computed" if ftype in {"formula", "rollup"} else "source"
1489
+ out = {"key": text_key, "label": "Table" if ftype == "json" else label,
1490
+ "type": ftype, "source": "overlay", "kind": ftype, "origin": "automation",
1491
+ "valueAuthority": value_authority, "scope": "tenant", "editRole": "admins"}
1492
  if description:
1493
  out["description"] = description
1494
  out.update(extra)
 
9265
  #: run-time refusal rather than becoming a store read on the automations LIST path (W30-T12 took
9266
  #: that read off this route; putting it back to draw a label would undo the wave before this one).
9267
  ACTION_REQUIRED = dict(WEB_REQUIRED)
9268
+ ACTION_REQUIRED["voice_agent"] = (("a Voice agent", "voiceAgentId"),)
9269
  #: ⭐ W31-T38 (C5) — the web step's own clamps. `20000` matches the default E's seam documents;
9270
  #: the ceiling exists because this blocks the record walk (~9-32 s of cold start ALREADY), and an
9271
  #: automation that can be configured to wait ten minutes per record is a stalled run, not a slow one.
 
9275
  #: and never by a literal list of group names: a client-side ordering is a second copy of this
9276
  #: table, and the way it fails is that a group added here renders last, or not at all, with
9277
  #: nothing red anywhere.
9278
+ ACTION_GROUP_ORDER = {"Agent": 1, "Database": 2, "Connected": 3, "Advanced logic": 4}
9279
  ACTION_CATALOG = [
9280
  # ── 1. WEB ACTION (owner rulings R1-R5) — DECLARED HERE, NOT YET BUILT (DEBT D-51). ────────
9281
  # ⛔ NOT A TEASE. `clean_actions` refuses an unready kind with a sentence, so the faded row
 
9333
  # hidden row's label is still rendered on a STORED step's card, so leaving the six captions in
9334
  # place would have kept them on screen for exactly the people who already use them. They now
9335
  # name the mechanism instead, and no old caption survives as a substring in any case.
9336
+ {"kind": "ai_agent", "label": "Web agent", "group": "Agent", "ready": True,
9337
  "detail": "Describe a job on a website in words; the agent works out the steps, runs them in "
9338
  "a browser and reports what it actually did"},
9339
+ {"kind": "voice_agent", "label": "Voice agent", "group": "Agent", "ready": True,
9340
+ "detail": "Use a configured Loopable Voice agent. Production calls remain unavailable; "
9341
+ "the no-dial harness is the only executable Voice path"},
9342
+ {"kind": "web_goto", "label": "Web agent step (navigate)", "group": "Agent",
9343
  "ready": True, "menu": False,
9344
  "detail": "Opens a page in a browser job and reports the title it landed on"},
9345
+ {"kind": "web_fill", "label": "Web agent step (type)", "group": "Agent",
9346
  "ready": True, "menu": False,
9347
  "detail": "Types a value into a field. Mark it secret and the value is masked in the log"},
9348
+ {"kind": "web_click", "label": "Web agent step (click)", "group": "Agent",
9349
  "ready": True, "menu": False,
9350
  "detail": "Clicks the element a selector names, and reports where it landed"},
9351
  # ⚠ `"kind": "web_read"` AND `"ready": True` STAY ON ONE LINE. `verify_wiring`'s C5 row matches
 
9355
  # the client can add must be one the runner will execute); the layout is what it happens to
9356
  # depend on, so the layout is preserved here rather than the assertion weakened there.
9357
  {"kind": "web_read", "ready": True, "label": "Web agent step (extract)",
9358
+ "group": "Agent", "menu": False,
9359
  "detail": "Reads one value off a live page in a browser job. Expect ~10-30 s per step"},
9360
+ {"kind": "web_repair", "label": "Web agent step (relocate)", "group": "Agent",
9361
  "ready": True, "menu": False,
9362
  "detail": "Follows a label to its control when a selector has gone stale, and proposes one"},
9363
  # ── 2. DATABASE ──────────────────────────────────────────────────────────────────────────
 
9442
  "ready": True, "menu": False,
9443
  "detail": "Pull the connected Odoo databases on a schedule. Configured on the connector, not "
9444
  "here"},
9445
+ {"kind": "ai_enrich", "label": "AI field agent", "group": "Agent",
9446
  "ready": True, "menu": False,
9447
  "detail": "Fill an AI column for the records this flow walks. Configured on the column, not "
9448
  "here"},
 
10037
  if limit < 1 or limit > FIND_LIMIT_MAX:
10038
  return None, f"the find records limit is between 1 and {FIND_LIMIT_MAX}"
10039
  return {"table": table, "cond": cond, "limit": limit}, None
10040
+ if kind == "voice_agent":
10041
+ # Voice configuration lives in the dedicated, permissioned control plane. The action
10042
+ # stores one Loopable-local reference only: never a provider id, phone number, SIP route,
10043
+ # or credential. An empty draft is addable and is then named Unconfigured by
10044
+ # ACTION_REQUIRED; the runner arm below still refuses every ordinary dispatch.
10045
+ voice_id = _s(cfg.get("voiceAgentId"), 120).strip()
10046
+ if voice_id and not re.fullmatch(r"va_[A-Za-z0-9_\-]{4,110}", voice_id):
10047
+ return None, "select a Voice agent from Loopable rather than entering a provider id"
10048
+ return {"voiceAgentId": voice_id}, None
10049
  if kind == "ai_agent":
10050
  # ⭐⭐ W33-T56 — THE FUZZY STEP'S CONFIG. Same posture as the web arm below in every
10051
  # respect that matters: an ALLOWLIST, a shape test on the url, a clamped timeout, and an
 
11120
  "editor, not from this canvas. Nothing was done")
11121
  counts["webBlocked"] += 1
11122
  continue
11123
+ elif kind == "voice_agent":
11124
+ # Voice has a dedicated no-dial harness and no ordinary automation dispatcher.
11125
+ # Keeping the refusal in the walk is load-bearing: this dispatcher has no final
11126
+ # unknown-kind else, so a catalog row without an arm would otherwise report a
11127
+ # successful run that silently did nothing. A future activation must replace this
11128
+ # wall only after consent, capacity lease, callback route, webhook verification,
11129
+ # provider tests, and an explicit owner authorization all exist.
11130
+ if "voice_agent_not_activated" not in web_notes:
11131
+ web_notes.append("voice_agent_not_activated")
11132
+ log("[aios-auto] voice_agent: production Voice dispatch is not activated. "
11133
+ "Use the no-dial harness; no call was created")
11134
+ counts["webBlocked"] += 1
11135
+ continue
11136
  elif kind == "ai_agent":
11137
  # ⭐⭐ W33-T56 (owner item 7, ruling R3) — THE FUZZY STEP, AT RUN TIME.
11138
  #
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
@@ -334,6 +334,13 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
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,
@@ -474,14 +481,17 @@ 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 +511,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 +613,323 @@ 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 +940,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
@@ -768,6 +1096,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
@@ -991,8 +1325,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(
 
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
+ # Legacy `Destination N` definitions remain in the shared document for rollback/audit, but
338
+ # once the dedicated migration recorded its independent parity proof they are display-hidden.
339
+ # This is intentionally a projection only: no field or cell is deleted here.
340
+ from core import route_system
341
+ _legacy_migrations = route_system.read(rt).get("legacyMigrations") or {}
342
+ fields = [field for field in fields if not (
343
+ isinstance(field, dict) and (_legacy_migrations.get(str(field.get("key"))) or {}).get("verified"))]
344
  # ⭐⭐ W41-T01 / RULING R5 / CONTRACTS C1 + C8 — **THE THREE BADGES, STAMPED ONCE, HERE.**
345
  #
346
  # C1 makes `field_permissions.field_class` the ONE producer of `{origin, audience, sharedBy,
 
481
  on_error=_measure_err) if may_metrics else {}).items():
482
  derived.setdefault(pid, {}).update(cells)
483
 
484
+ # Route stops and Zone membership are normalized system relations. They project into two
485
+ # read-only customer fields; neither is a generic Link or an editable user-table cell.
486
+ normalized_routes = route_system.list_routes(rt)
487
+ normalized_zones = route_system.list_zones(rt, rows_src)
488
+ fields = [field for field in fields if field.get("key") not in {"routes", "zone"}]
489
+ fields.extend(route_system.customer_projection_fields(normalized_routes, normalized_zones))
490
+ fields = [route_system.field_axes(field) for field in fields]
491
  return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
492
  "fields": fields, "views": views, "lists": lists, "derived": derived,
493
  "measures": measures, "measure_sets": measure_sets, "today": today,
494
+ "team_id": team_id, "routes": normalized_routes, "zones": normalized_zones}
495
 
496
 
497
  def _payload(session: Session):
 
511
  g = grid_assembly(session)
512
  rows = aios_grid.rows_from_pool(
513
  g["rows_src"], g["fields"], g["ws"].get("overlays"), derived=g["derived"])
514
+ from core import route_system
515
+ rows = route_system.apply_customer_projections(rows, g["routes"], g["zones"])
 
516
  # ⭐ C4 / D-138 (W30-T37) — THE DOCUMENTS PRODUCER FOR THE CUSTOMER SCOPE. The write door
517
  # (`doc_add`/`doc_fetch`/`doc_delete`) never stopped working and every client half is
518
  # complete; what vanished with `app.py` at EXIT-6 was the only thing that ever set this key.
 
613
  return _payload(session)
614
 
615
 
616
+ # ── Wave 44: normalized, Loopable-owned Route/Zone APIs ─────────────────────
617
+ # These are deliberately ahead of `/customers/{pid}`. Route stops are a protected relation;
618
+ # no generic Link field, generic table writer, or legacy Destination column is a write door.
619
+ def _route_view_can_edit(session, view_id):
620
+ """Route mutations inherit the source View editor wall, never an invented role."""
621
+ if not view_id:
622
+ return bool(session.admin)
623
+ try:
624
+ import core.table_store as table_store
625
+ ws = _customer_table(session).workspace(session.uname, consume_corrections=False)
626
+ view = (ws.get("views") or {}).get(str(view_id))
627
+ return bool(view and table_store._may_edit(view, session.uname, session.admin))
628
+ except Exception: # unavailable store is fail-closed
629
+ return False
630
+
631
+
632
+ def _route_input_pids(raw):
633
+ offered = []
634
+ for stop in (raw or {}).get("stops") or ():
635
+ candidate = stop.get("customerPid") if isinstance(stop, dict) else stop
636
+ if isinstance(candidate, bool):
637
+ raise err(400, "invalid_route_stop", "a route stop needs a customer id")
638
+ try:
639
+ offered.append(int(candidate))
640
+ except (TypeError, ValueError):
641
+ raise err(400, "invalid_route_stop", "a route stop needs a customer id")
642
+ return offered
643
+
644
+
645
+ def _route_dto(route, allowed, active, session):
646
+ from core import route_system
647
+ allowed = {int(pid) for pid in allowed}
648
+ stops = [stop for stop in route_system.ordered_stops(route)
649
+ if int(stop.get("customerPid")) in allowed]
650
+ visible = [int(stop["customerPid"]) for stop in stops]
651
+ active = {int(pid) for pid in active if int(pid) in allowed}
652
+ dto = {"id": route["id"], "name": route["name"], "color": route["color"],
653
+ "number": route["number"], "visibleStopIds": visible,
654
+ "outsideFilter": bool(active) and not bool(active.intersection(visible)),
655
+ "permission": {"canEdit": _route_view_can_edit(session, route.get("sourceViewId")),
656
+ "sourceViewId": route.get("sourceViewId")},
657
+ "source": {"viewId": route.get("sourceViewId"),
658
+ "revision": route.get("sourceViewRevision")}}
659
+ if route.get("mapsUrl"):
660
+ dto["mapsUrl"] = route["mapsUrl"]
661
+ return dto
662
+
663
+
664
+ def _query_pids(raw):
665
+ values = []
666
+ for value in str(raw or "").split(","):
667
+ try:
668
+ values.append(int(value))
669
+ except (TypeError, ValueError):
670
+ continue
671
+ return values
672
+
673
+
674
+ def _route_or_404(session, route_id):
675
+ from core import route_system
676
+ route = next((item for item in route_system.list_routes(session.runtime)
677
+ if item.get("id") == str(route_id)), None)
678
+ if route is None:
679
+ raise err(404, "route_not_found", "that Route does not exist")
680
+ return route
681
+
682
+
683
+ def _route_mutation_allowed(session, route, requested_source=None):
684
+ source = requested_source if requested_source is not None else route.get("sourceViewId")
685
+ if not _route_view_can_edit(session, source):
686
+ raise err(403, "route_view_read_only", "only an editor of the Route source View can change it")
687
+
688
+
689
+ @router.get("/customers/routes")
690
+ def routes(visiblePids: str = "", currentPids: str = "",
691
+ session: Session = Depends(module_gate(MODULE))):
692
+ """Route picker DTO consumed by C1/C3; only permitted stops ever leave the server."""
693
+ from core import route_system
694
+ allowed = allowed_pids(session)
695
+ active = _query_pids(currentPids or visiblePids)
696
+ return {"routes": [_route_dto(route, allowed, active, session)
697
+ for route in route_system.list_routes(session.runtime)]}
698
+
699
+
700
+ @router.post("/customers/routes", status_code=201)
701
+ def create_route(body: dict = Body(default=None), session: Session = Depends(module_gate(MODULE))):
702
+ from core import route_system
703
+ raw = dict(body or {})
704
+ if not _route_view_can_edit(session, raw.get("sourceViewId")):
705
+ raise err(403, "route_view_read_only", "a Route requires an editable source View")
706
+ permitted = allowed_pids(session)
707
+ if any(pid not in permitted for pid in _route_input_pids(raw)):
708
+ raise err(403, "out_of_scope", "a Route stop must be in your customer book")
709
+ route = route_system.put_route(session.runtime, raw, tenant_id=session.tenant, created_by=session.uname)
710
+ if route is None:
711
+ raise err(400, "invalid_route", "a Route needs a name and an optional HTTPS Google Maps URL")
712
+ return {"route": _route_dto(route, permitted, (), session)}
713
+
714
+
715
+ @router.patch("/customers/routes/{route_id}")
716
+ def update_route(route_id: str, body: dict = Body(default=None),
717
+ session: Session = Depends(module_gate(MODULE))):
718
+ from core import route_system
719
+ prior = _route_or_404(session, route_id)
720
+ raw = dict(body or {})
721
+ _route_mutation_allowed(session, prior, raw.get("sourceViewId", prior.get("sourceViewId")))
722
+ raw["id"] = prior["id"]
723
+ if "stops" in raw and any(pid not in allowed_pids(session) for pid in _route_input_pids(raw)):
724
+ raise err(403, "out_of_scope", "a Route stop must be in your customer book")
725
+ route = route_system.put_route(session.runtime, raw, tenant_id=session.tenant, created_by=session.uname)
726
+ if route is None:
727
+ raise err(400, "invalid_route", "a Route needs a name and an optional HTTPS Google Maps URL")
728
+ return {"route": _route_dto(route, allowed_pids(session), (), session)}
729
+
730
+
731
+ @router.post("/customers/routes/{route_id}/stops/move")
732
+ def move_route_stop(route_id: str, body: dict = Body(default=None),
733
+ session: Session = Depends(module_gate(MODULE))):
734
+ from core import route_system
735
+ prior = _route_or_404(session, route_id)
736
+ _route_mutation_allowed(session, prior)
737
+ raw = dict(body or {})
738
+ try:
739
+ pid, order = int(raw.get("customerPid")), int(raw.get("order"))
740
+ except (TypeError, ValueError):
741
+ raise err(400, "invalid_route_stop", "customerPid and order are required")
742
+ if pid not in allowed_pids(session):
743
+ raise err(403, "out_of_scope", "that customer is not in your book")
744
+ route = route_system.move_stop(session.runtime, route_id, pid, order,
745
+ tenant_id=session.tenant, created_by=session.uname)
746
+ if route is None:
747
+ # A Route may intentionally have no stops. We never turn that harmless state into a
748
+ # synthetic generic Link row; the caller can render the honest no-stop state.
749
+ raise err(409, "no_route_stop", "that customer is not a stop on this Route")
750
+ return {"route": _route_dto(route, allowed_pids(session), (), session)}
751
+
752
+
753
+ @router.delete("/customers/routes/{route_id}")
754
+ def remove_route(route_id: str, session: Session = Depends(module_gate(MODULE))):
755
+ from core import route_system
756
+ route = _route_or_404(session, route_id)
757
+ _route_mutation_allowed(session, route)
758
+ route_system.delete_route(session.runtime, route_id)
759
+ return {"deleted": True}
760
+
761
+
762
+ @router.post("/customers/routes/selection")
763
+ def route_selection(body: dict = Body(default=None), session: Session = Depends(module_gate(MODULE))):
764
+ """Dedicated managed-OR mutation; user filter clauses are returned byte-for-byte intact."""
765
+ from core import route_system
766
+ raw = dict(body or {})
767
+ chosen = [str(item) for item in raw.get("routeIds") or ()]
768
+ known = {route["id"] for route in route_system.list_routes(session.runtime)}
769
+ if any(route_id not in known for route_id in chosen):
770
+ raise err(404, "route_not_found", "a selected Route does not exist")
771
+ state = route_system.apply_managed_route_selection(
772
+ raw.get("viewState"), chosen, route_system.list_routes(session.runtime))
773
+ return {"viewState": state, "managedBy": route_system.MANAGED_BY}
774
+
775
+
776
+ def _export_sort_value(row, field):
777
+ value = row.get(field.get("key"))
778
+ if field.get("type") in {"currency", "int", "pct", "rating", "formula"}:
779
+ try:
780
+ return (value is None or value == "", float(value))
781
+ except (TypeError, ValueError):
782
+ return (True, 0.0)
783
+ return (value is None or value == "", str(value or "").lower())
784
+
785
+
786
+ @router.post("/customers/view-export")
787
+ def selected_view_export(body: dict = Body(default=None),
788
+ session: Session = Depends(module_gate(MODULE))):
789
+ """Authoritative selected-View export data; the browser owns XLSX rendering, not selection.
790
+
791
+ The request names saved View ids only. Its field order/visibility, filter, sort and cohort
792
+ membership are resolved independently per tab, so the caller cannot accidentally duplicate
793
+ the active View's rows under several View names.
794
+ """
795
+ import aios_grid
796
+ from core import route_system
797
+ from harness import filter_eval
798
+
799
+ raw_ids = (body or {}).get("viewIds")
800
+ if not isinstance(raw_ids, list) or not raw_ids or len(raw_ids) > 20:
801
+ raise err(400, "invalid_view_ids", "viewIds must name between one and twenty visible Views")
802
+ ids = [str(value).strip()[:120] for value in raw_ids]
803
+ if any(not value for value in ids) or len(set(ids)) != len(ids):
804
+ raise err(400, "invalid_view_ids", "viewIds must be unique non-empty View ids")
805
+ g = grid_assembly(session)
806
+ views = {str(view.get("id")): view for view in g["views"] if isinstance(view, dict)}
807
+ if any(view_id not in views for view_id in ids):
808
+ raise err(404, "view_not_found", "an export View is not visible to this account")
809
+ rows = aios_grid.rows_from_pool(g["rows_src"], g["fields"], g["ws"].get("overlays"),
810
+ derived=g["derived"])
811
+ rows = route_system.apply_customer_projections(rows, g["routes"], g["zones"])
812
+ by_key = {field["key"]: field for field in g["fields"] if isinstance(field, dict) and field.get("key")}
813
+ cohort_sets = {str(item.get("id")): set(item.get("pids") or [])
814
+ for item in g["lists"] if isinstance(item, dict) and item.get("id")}
815
+ exports = []
816
+ for view_id in ids:
817
+ view, cfg = views[view_id], dict(views[view_id].get("config") or {})
818
+ context = filter_eval.EvalCtx(cohort_sets=cohort_sets, measure_sets=g["measure_sets"],
819
+ today=g["today"])
820
+ tree = {"nodes": cfg.get("filters") or [], "conj": cfg.get("filterConj") or "and"}
821
+ pids = set(filter_eval.visible_pids(tree, rows, g["fields"], context,
822
+ member_pids=cfg.get("memberPids") or [],
823
+ group_by=cfg.get("groupBy")))
824
+ selected = [dict(row) for row in rows if row.get("pid") in pids]
825
+ for sort in reversed(cfg.get("sorts") or []):
826
+ field = by_key.get(sort.get("colId")) if isinstance(sort, dict) else None
827
+ if field is not None:
828
+ selected.sort(key=lambda row, f=field: _export_sort_value(row, f),
829
+ reverse=sort.get("dir") == "desc")
830
+ ordered = [key for key in cfg.get("order") or [] if key in by_key]
831
+ ordered += [key for key in by_key if key not in ordered]
832
+ visible = set(cfg.get("visible") or ordered)
833
+ columns = [dict(by_key[key]) for key in ordered if key in visible]
834
+ exports.append({"viewId": view_id, "name": view.get("name") or view_id,
835
+ "columns": columns, "rows": selected,
836
+ "view": {"filters": cfg.get("filters") or [],
837
+ "filterConj": cfg.get("filterConj") or "and",
838
+ "sorts": cfg.get("sorts") or [],
839
+ "memberPids": cfg.get("memberPids") or []}})
840
+ return {"today": g["today"], "exports": exports}
841
+
842
+
843
+ @router.post("/customers/routes/migrate-legacy")
844
+ def migrate_legacy_destination_fields(session: Session = Depends(module_gate(MODULE))):
845
+ """Copy legacy Destination N ranks, prove parity, then hide the retained columns.
846
+
847
+ The explicit whole-book check is important: a partial manager scope may copy a useful subset,
848
+ but it can never prove a tenant-wide route complete and therefore may not hide anything.
849
+ """
850
+ if not session.admin:
851
+ raise err(403, "legacy_migration_admin_only", "only an administrator may migrate legacy Routes")
852
+ from core import route_system
853
+ raw_rows = _pool_rows(session)
854
+ whole_book = {int(row["pid"]) for row in raw_rows if row.get("pid") is not None}
855
+ if whole_book != set(allowed_pids(session)):
856
+ raise err(409, "legacy_migration_scope_limited",
857
+ "legacy Route migration needs an unrestricted customer scope to prove parity")
858
+ defs = shared_fields(st=session.runtime)
859
+ result = route_system.migrate_legacy_routes(
860
+ session.runtime, defs, shared_cells(whole_book, st=session.runtime),
861
+ tenant_id=session.tenant, created_by=session.uname,
862
+ zones=route_system.list_zones(session.runtime, raw_rows))
863
+ # `legacyMigrations` lives with the normalized system data. The source field definition and
864
+ # every scalar rank cell are retained byte-for-byte; the persisted proof is the read-side
865
+ # hide/read-only marker rather than a generic field rewrite or a delete.
866
+ return result
867
+
868
+
869
+ def _zone_can_edit(session, source_view_id):
870
+ return bool(session.admin) or _route_view_can_edit(session, source_view_id)
871
+
872
+
873
+ def _zone_dto(zone, allowed, session):
874
+ return {"id": zone["id"], "name": zone["name"], "color": zone["color"],
875
+ "geometryGeoJson": zone.get("geometryGeoJson"), "zipCodes": zone.get("zipCodes") or [],
876
+ "visibleMemberIds": [int(pid) for pid in zone.get("memberPids") or [] if int(pid) in allowed],
877
+ "membershipRevision": zone.get("membershipRevision", 0),
878
+ "visible": zone.get("visible", True),
879
+ "permission": {"canEdit": bool(session.admin)}}
880
+
881
+
882
+ @router.get("/customers/zones")
883
+ def zones(session: Session = Depends(module_gate(MODULE))):
884
+ from core import route_system
885
+ rows = _pool_rows(session)
886
+ allowed = allowed_pids(session)
887
+ return {"zones": [_zone_dto(zone, allowed, session)
888
+ for zone in route_system.list_zones(session.runtime, rows)]}
889
+
890
+
891
+ @router.post("/customers/zones", status_code=201)
892
+ def create_zone(body: dict = Body(default=None), session: Session = Depends(module_gate(MODULE))):
893
+ from core import route_system
894
+ raw = dict(body or {})
895
+ if not _zone_can_edit(session, raw.get("sourceViewId")):
896
+ raise err(403, "zone_view_read_only", "a Zone requires an editable source View")
897
+ zone = route_system.put_zone(session.runtime, raw, rows=_pool_rows(session),
898
+ tenant_id=session.tenant, created_by=session.uname)
899
+ if zone is None:
900
+ raise err(400, "invalid_zone", "a Zone needs a name and a polygon or ZIP code")
901
+ return {"zone": _zone_dto(zone, allowed_pids(session), session)}
902
+
903
+
904
+ @router.patch("/customers/zones/{zone_id}")
905
+ def update_zone(zone_id: str, body: dict = Body(default=None),
906
+ session: Session = Depends(module_gate(MODULE))):
907
+ from core import route_system
908
+ prior = next((zone for zone in route_system.list_zones(session.runtime)
909
+ if zone.get("id") == str(zone_id)), None)
910
+ if prior is None:
911
+ raise err(404, "zone_not_found", "that Zone does not exist")
912
+ raw = dict(body or {})
913
+ if not _zone_can_edit(session, raw.get("sourceViewId")):
914
+ raise err(403, "zone_view_read_only", "a Zone requires an editable source View")
915
+ raw["id"] = prior["id"]
916
+ zone = route_system.put_zone(session.runtime, raw, rows=_pool_rows(session),
917
+ tenant_id=session.tenant, created_by=session.uname)
918
+ if zone is None:
919
+ raise err(400, "invalid_zone", "a Zone needs a name and a polygon or ZIP code")
920
+ return {"zone": _zone_dto(zone, allowed_pids(session), session)}
921
+
922
+
923
+ @router.delete("/customers/zones/{zone_id}")
924
+ def remove_zone(zone_id: str, session: Session = Depends(module_gate(MODULE))):
925
+ from core import route_system
926
+ if not session.admin:
927
+ raise err(403, "zone_view_read_only", "only an administrator can delete a Zone")
928
+ if not route_system.delete_zone(session.runtime, zone_id):
929
+ raise err(404, "zone_not_found", "that Zone does not exist")
930
+ return {"deleted": True}
931
+
932
+
933
  def _split_route_updates(session, updates):
934
  """Split a cell PATCH into `(route order updates, everything else)`.
935
 
 
940
  route, rest = {}, {}
941
  for key, value in (updates or {}).items():
942
  defn = defs.get(key)
943
+ from core import route_system
944
+ migrated = bool((route_system.read(session.runtime).get("legacyMigrations") or {}).get(key, {}).get("verified"))
945
+ if isinstance(defn, dict) and defn.get("kind") == ROUTE_KIND and not migrated:
946
  route[key] = value
947
  else:
948
  rest[key] = value
 
1096
  updates = dict(body or {})
1097
  if not updates:
1098
  raise err(400, "empty_patch", "no fields to update")
1099
+ from core import route_system
1100
+ retired = {str(key) for key, proof in (route_system.read(session.runtime).get("legacyMigrations") or {}).items()
1101
+ if isinstance(proof, dict) and proof.get("verified")}
1102
+ if retired.intersection(updates):
1103
+ raise err(403, "legacy_route_hidden",
1104
+ "this legacy Destination field was migrated; edit the named Route instead")
1105
  pool = allowed_pids(session)
1106
  if pid not in pool:
1107
  # 403, not 404: the pid may well exist — it is simply not in this session's book, and
 
1325
  import core.perm_scope as perm_scope
1326
 
1327
  all_defs = shared_fields(st=session.runtime) or {}
1328
+ from core import route_system
1329
+ migrated = route_system.read(session.runtime).get("legacyMigrations") or {}
1330
  defs = {k: v for k, v in all_defs.items()
1331
+ if isinstance(v, dict) and v.get("kind") == ROUTE_KIND
1332
+ and not bool((migrated.get(k) or {}).get("verified"))}
1333
  if not defs:
1334
  return {}
1335
  hide = perm_scope.hidden_keys(
api/routes_grid.py CHANGED
@@ -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
 
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
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
 
@@ -1050,7 +1082,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
 
@@ -1097,6 +1129,11 @@ def _field_usage(session, table_key, fields, defn, ops, st=None):
1097
  if isinstance(f, dict) and f.get("key")}
1098
  if not keys:
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)
@@ -1110,7 +1147,8 @@ def _field_usage(session, table_key, fields, defn, ops, st=None):
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 +1292,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)
@@ -1306,7 +1345,8 @@ 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:
@@ -1688,6 +1728,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
 
@@ -1862,6 +1914,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 +1988,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 +2191,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 +2281,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 +2329,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 +2433,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)
@@ -2495,9 +2552,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 +2680,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",
@@ -2643,6 +2704,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 +2740,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
 
 
1082
  return rollup, automation
1083
 
1084
 
1085
+ def _field_usage(session, table_key, fields, defn, ops, st=None, workspace_document=None):
1086
  """`{field_key: {views, filters, rollups, automations, permRules}}` — C8's `usage`, computed
1087
  over the WHOLE workspace, or `{}` when it cannot be established.
1088
 
 
1129
  if isinstance(f, dict) and f.get("key")}
1130
  if not keys:
1131
  return {}
1132
+ # Usage is delete-safety data: without a verified caller identity we cannot decide which
1133
+ # tenant's permission records are relevant. Refuse before any workspace read rather than
1134
+ # returning a misleading zero or paying a partial read that cannot produce a safe answer.
1135
+ if not isinstance(getattr(session, "user", None), dict):
1136
+ return {}
1137
  lent = st if st is not None else session.runtime
1138
  memo_key = (str(getattr(session, "tenant", "") or ""), str(table_key))
1139
  token = _usage_token(lent, ops.table_key)
 
1147
  # suffix is a second thing to keep in step. A lend passes `<key>_table_workspace` straight
1148
  # through to the runtime (it serves only `user_tables` and `object_shares`), so this is
1149
  # the tenant's own document.
1150
+ ws_doc = (workspace_document if isinstance(workspace_document, dict)
1151
+ else (ops.st.get(ops.table_key) or {}))
1152
  except Exception: # noqa: BLE001
1153
  return {}
1154
  try:
 
1292
  st=session.runtime,
1293
  scope_key=table_key, table=ops)
1294
  ws = grid_events.table_workspace(ctx, allowed_pids=pids,
1295
+ consume_corrections=consume_corrections,
1296
+ capture_document=True)
1297
  workspace, fields, views, lists = aios_grid.workspace_wire(
1298
  ws, session.uname, set(pids), defs={}, scope_key=table_key,
1299
  storage_key=storage_key, fields_base=fields_base, st=session.runtime)
 
1345
  # ⚠ A COPY OF THE BAG, because `_field_usage` MEMOISES its answer: handing the memo's own dict
1346
  # out would let anything downstream write into the number the next request reads.
1347
  try:
1348
+ _usage = _field_usage(session, table_key, fields, defn, ops, st=st,
1349
+ workspace_document=getattr(ctx, "workspace_document", None))
1350
  except Exception: # noqa: BLE001
1351
  _usage = {}
1352
  if _usage:
 
1728
  # picker renders this order verbatim.
1729
  out.extend(_module_link_targets(session, meta, st=lent))
1730
  out.sort(key=lambda r: (r.get("label") or "").lower())
1731
+ else:
1732
+ # C1's Loopable folder has virtual descriptor rows even before the first Route/Zone
1733
+ # exists. They deliberately do NOT enter `brief=1`: stops are a protected relation,
1734
+ # never a generic Link target.
1735
+ try:
1736
+ session.require("customer_data")
1737
+ except Exception:
1738
+ pass
1739
+ else:
1740
+ from core import route_system
1741
+ out.extend(route_system.system_table_descriptors())
1742
+ out.sort(key=lambda r: (r.get("label") or "").lower())
1743
  return {"tables": out}
1744
 
1745
 
 
1914
  picker that is confidently wrong rather than obviously stale. Posted to the wave doc as an
1915
  amendment for whoever owns that door.
1916
  """
1917
+ _managed_or_refuse(session, table_key, mutation=True)
1918
  defn = _defn_or_refuse(session, table_key)
1919
  ut = _ut()
1920
  if not (session.admin or defn.get("createdBy") == session.uname):
 
1988
  DISABLES bound automations with a status note — never deletes them. The client's confirm
1989
  dialog disclosed `/footprint` first; the server cannot tell a click from a plan, so the
1990
  dialog is a product requirement, not a formality."""
1991
+ _managed_or_refuse(session, table_key, mutation=True)
1992
  defn = _defn_or_refuse(session, table_key)
1993
  if not (session.admin or defn.get("createdBy") == session.uname):
1994
  raise err(403, "forbidden", "only the database's creator or an admin can delete it")
 
2191
  _zones = [dict(zone, memberships=[pid for pid in zone.get("memberships", [])
2192
  if str(pid) in _zone_pids])
2193
  for zone in _ut().zones(table_key, st=_lent)]
2194
+ return {"fields": _field_axes(g["fields"]), "rows": rows, "today": g["today"],
2195
  "zones": _zones,
2196
  "docs": _ge.docs_for(g["pids"], scope_key=table_key, uname=session.uname,
2197
  admin=session.admin, st=session.runtime),
 
2281
  that requested `rid: 7` and got 12 because 7 had been re-used must find that out from the
2282
  response rather than assume; the client re-anchors on what came back.
2283
  """
2284
+ _managed_or_refuse(session, table_key, mutation=True)
2285
  _records_or_refuse(session, table_key)
2286
  ut = _ut()
2287
  values = (body or {}).get("values") or {}
 
2329
  profile cell validates, because a half-imported file is the worst outcome available: the user
2330
  cannot tell which rows landed without reconciling the spreadsheet by hand.
2331
  """
2332
+ _managed_or_refuse(session, table_key, mutation=True)
2333
  _records_or_refuse(session, table_key)
2334
  ut = _ut()
2335
  rows_in = (body or {}).get("rows")
 
2433
  @router.post("/tables/{table_key}/fields", status_code=201)
2434
  def add_field(table_key: str, body: dict = Body(default=None),
2435
  session: Session = Depends(require_session)):
2436
+ _managed_or_refuse(session, table_key, mutation=True)
2437
  _field_or_refuse(session, table_key)
2438
  ut = _ut()
2439
  field = ut.add_field(table_key, body or {}, st=session.runtime)
 
2552
  Blue to Navy" from "deleted Blue, added Navy" — and guessing wrong empties the column and
2553
  every saved view that filtered on it.
2554
  """
2555
+ _managed_or_refuse(session, table_key, mutation=True)
2556
  _field_or_refuse(session, table_key, fkey)
2557
  ut = _ut()
2558
  body = body or {}
2559
+ if 'deletionLocked' in body and not session.admin:
2560
+ raise err(403, "owner_required", "only an Owner can change a field deletion lock")
2561
  migrated = None
2562
  renames = body.get("renames")
2563
  if renames:
 
2680
 
2681
  @router.delete("/tables/{table_key}/fields/{fkey}")
2682
  def delete_field(table_key: str, fkey: str, session: Session = Depends(require_session)):
2683
+ _managed_or_refuse(session, table_key, mutation=True)
2684
  _field_or_refuse(session, table_key, fkey)
2685
  if not _ut().delete_field(table_key, fkey, st=session.runtime):
2686
  raise err(400, "refused",
 
2704
  # ⚠ `flush='sync'` IS DELIBERATELY UNTOUCHED (D-118): nobody spams a delete, and an eventually
2705
  # consistent delete is indistinguishable from one that did not work. This makes the guard
2706
  # cheap; it does not make the commit optimistic.
2707
+ _managed_or_refuse(session, table_key, mutation=True)
2708
  lent = _ut().lend(session.runtime)
2709
  _records_or_refuse(session, table_key, st=lent)
2710
  # ⭐⭐ W36-T21 — THE ROW SCOPE, ON THE DELETE DOOR. `patch_row` has asked this since it was
 
2740
  updates = dict(body or {})
2741
  if not updates:
2742
  raise err(400, "empty_patch", "no fields to update")
2743
+ _managed_or_refuse(session, table_key, mutation=True)
2744
  _records_or_refuse(session, table_key)
2745
  g = ut_assembly(session, table_key, consume_corrections=False)
2746
  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
@@ -1247,6 +1247,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 +1259,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 +2620,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 +2639,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 +2698,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
 
 
1247
  out = []
1248
  for r in pool_rows:
1249
  pid = r.get("pid")
1250
+ saved = overlays.get(str(pid), {}) or {}
1251
  # `_created` (wave-5 item 11) rides every row like `pid` does — the datum the
1252
  # `created_time` field type renders, regardless of that field's own key. Not a Field:
1253
  # it has no column of its own until a user creates one. `lat`/`lon` (wave-7 W11) ride
 
1259
  if field.get("derived"):
1260
  continue # not on the pool row — filled from `derived` below
1261
  v = r.get(k)
1262
+ if k == "maps_url" and saved.get(k):
1263
+ v = saved[k]
1264
  # D-153 — three roundings, not two: text/status/date pass through verbatim, currency
1265
  # and pct keep two decimals (`_round2`), everything else stays a whole number.
1266
  row[k] = v if field["type"] in {"text", "status", "date"} else (
1267
  _round2(v) if field["type"] in {"currency", "pct"} else _round(v))
 
1268
  for field in overlay_fields:
1269
  row[field["key"]] = saved.get(field["key"], "")
1270
  got = derived.get(pid) or {}
 
2620
  # is the same all-or-nothing the single-cohort leaf already had, extended to a set.
2621
  if op in COHORT_OPS and named and all(c in (cohort_ids or ()) for c in named):
2622
  budget[0] -= 1
2623
+ leaf = {'colId': COHORT_FIELD, 'op': op,
2624
+ 'value': ','.join(named), 'value2': ''}
2625
+ if node.get('locked') is True:
2626
+ leaf['locked'] = True
2627
+ out.append(leaf)
2628
  continue
2629
  if node.get('colId') == VIEW_FIELD: # C4: a view-membership leaf
2630
  # ⛔ THE SAME ALL-OR-NOTHING THE COHORT ARM ABOVE APPLIES, AND FOR THE SAME REASON.
 
2639
  v_id = str(node.get('value') or '').strip()[:MAX_VIEW_ID]
2640
  if v_op in VIEW_OPS and v_id and v_id in (visible_view_ids or ()):
2641
  budget[0] -= 1
2642
+ leaf = {'colId': VIEW_FIELD, 'op': v_op, 'value': v_id, 'value2': ''}
2643
+ if node.get('locked') is True:
2644
+ leaf['locked'] = True
2645
+ out.append(leaf)
2646
  continue
2647
  if node.get('colId') in valid_keys and node.get('op') in FILTER_OPS:
2648
  budget[0] -= 1
 
2698
  rhs = _clean_rhs(node.get('rhs'), valid_keys)
2699
  if rhs is not None:
2700
  leaf['rhs'] = rhs
2701
+ # C3: a record lock is explicit on the leaf, not a view-wide presentation flag.
2702
+ # Once stored, grid_events preserves the containing filter config unless it is copied
2703
+ # to a new View; a later caller cannot turn this `True` into an editable-looking false.
2704
+ if node.get('locked') is True:
2705
+ leaf['locked'] = True
2706
  out.append(leaf)
2707
  return out
2708
 
2709
 
2710
+ def preserve_locked_view_records(prior_config, filters, sorts):
2711
+ """Return authoritative filter/sort records when an in-place lock was touched.
2712
+
2713
+ A lock protects its semantic position as well as its leaf text: moving a locked condition
2714
+ between AND/OR groups changes the question even when the leaf itself is byte-identical. We
2715
+ therefore retain the full corresponding list on any attempted change. A new View has no
2716
+ prior config, so copying is the explicit alteration path.
2717
+ """
2718
+ prior = prior_config if isinstance(prior_config, dict) else {}
2719
+ old_filters = prior.get('filters') if isinstance(prior.get('filters'), list) else []
2720
+ old_sorts = prior.get('sorts') if isinstance(prior.get('sorts'), list) else []
2721
+
2722
+ def _has_locked_filter(nodes):
2723
+ for node in nodes or ():
2724
+ if not isinstance(node, dict):
2725
+ continue
2726
+ if node.get('locked') is True:
2727
+ return True
2728
+ if _has_locked_filter(node.get('children') if isinstance(node.get('children'), list) else []):
2729
+ return True
2730
+ return False
2731
+
2732
+ def _same(left, right):
2733
+ return json.dumps(left, sort_keys=True, separators=(',', ':')) == json.dumps(
2734
+ right, sort_keys=True, separators=(',', ':'))
2735
+
2736
+ if _has_locked_filter(old_filters) and not _same(old_filters, filters):
2737
+ filters = json.loads(json.dumps(old_filters))
2738
+ if any(isinstance(rule, dict) and rule.get('locked') is True for rule in old_sorts) \
2739
+ and not _same(old_sorts, sorts):
2740
+ sorts = json.loads(json.dumps(old_sorts))
2741
+ return filters, sorts
2742
+
2743
+
2744
  def _clean_rank_scope(raw, valid_keys):
2745
  """The persisted rank scope, or ``None`` when absent/malformed.
2746
 
platform/core/grid_events.py CHANGED
@@ -507,7 +507,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 +534,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:
@@ -1262,6 +1267,9 @@ def handle_one(event, ctx):
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 +1379,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 +1480,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
 
507
  return _has_grants
508
 
509
 
510
+ def table_workspace(ctx, allowed_pids=None, consume_corrections=True, capture_document=False):
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
  """
535
  uname = ctx.uname
536
  if _store_of(ctx).available():
537
+ read = _tops(ctx).workspace(
538
+ uname, consume_corrections=bool(consume_corrections),
539
+ include_document=bool(capture_document))
540
+ if capture_document:
541
+ ws, ctx.workspace_document = read
542
+ else:
543
+ ws = read
544
  try:
545
  shared = _tops(ctx).shared_views(uname, bool(ctx.admin))
546
  except Exception as _se:
 
1267
  pass
1268
  valid_keys = set(field_by_key)
1269
  overlay_keys = {f['key'] for f in fields if f.get('source') == 'overlay'}
1270
+ # D-477: maps_url is source-backed but admits the normal overlay value-write wall.
1271
+ if any(f.get('key') == 'maps_url' and f.get('source') == 'odoo' for f in fields):
1272
+ overlay_keys.add('maps_url')
1273
  # Event validation is not a render payload. It must not consume a one-shot label
1274
  # correction before the browser has had a chance to receive it.
1275
  ws = table_workspace(
 
1379
  for rule in list(cfg.get('sorts') or [])[:20]:
1380
  if (isinstance(rule, dict) and rule.get('colId') in valid_keys
1381
  and rule.get('dir') in ('asc', 'desc')):
1382
+ clean_sort = {'colId': rule['colId'], 'dir': rule['dir']}
1383
+ if rule.get('locked') is True:
1384
+ clean_sort['locked'] = True
1385
+ sorts.append(clean_sort)
1386
  order = list(dict.fromkeys(
1387
  key for key in list(cfg.get('order') or []) if key in valid_keys))
1388
  order += [field['key'] for field in fields if field['key'] not in order]
 
1480
  if _raw_shared is not None and not _tstore._may_edit(_raw_shared, uname, admin):
1481
  return False # visible but not editable by this caller
1482
  is_new = not prior
1483
+ if not is_new:
1484
+ # W44 C3: filters/sorts locked in an existing View are immutable records. This
1485
+ # runs after the visibility/edit wall has established `prior`, so a guessed foreign
1486
+ # view cannot be used as a source of lock state. A copied View has no prior and is
1487
+ # consequently the only alteration path.
1488
+ filters, sorts = _ag.preserve_locked_view_records(
1489
+ prior.get('config') or {}, filters, sorts)
1490
+ config['filters'], config['sorts'] = filters, sorts
1491
  # C4: the creator is HOST-STAMPED and never read from the browser — the same rule as
1492
  # the field-level createdBy. An existing view keeps whoever made it.
1493
  creator = prior.get('createdBy') or uname
platform/core/route_system.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 math
12
+ import re
13
+ import uuid
14
+
15
+ MANAGED_BY = "loopable"
16
+ LOOPABLE_FOLDER_ID = "loopable"
17
+ LOOPABLE_FOLDER = {"id": LOOPABLE_FOLDER_ID, "name": "Loopable", "managedBy": MANAGED_BY}
18
+ ROUTES_KEY, ZONES_KEY = "ut_odoo_customers_routes", "ut_odoo_customers_zones"
19
+ SYSTEM_TABLES = {ROUTES_KEY: "Odoo Customers - Routes", ZONES_KEY: "Odoo Customers - Zones"}
20
+
21
+ # TenantRuntime namespaces this bucket. User-table rows are scalar user data; route stops are a
22
+ # protected relation (route id + customer id + order), so they cannot be a generic Link field.
23
+ STORE_KEY = "loopable_route_system"
24
+ _ROUTE_COLORS = ("#6E4AC7", "#1F4E78", "#C85A54", "#2F8F83", "#B57716", "#A14B8B")
25
+ _COLOR_RE = re.compile(r"^#[0-9A-Fa-f]{6}$")
26
+ _ZIP_RE = re.compile(r"^[A-Za-z0-9 -]{1,20}$")
27
+ _GOOGLE_MAPS_URL_RE = re.compile(
28
+ r"^https://(?:(?:www\.)?google\.(?:com|co\.[a-z]{2}|[a-z]{2,3})|maps\.app\.goo\.gl|goo\.gl)/", re.I)
29
+
30
+
31
+ class InternalWriterCapability:
32
+ """Opaque capability intentionally constructible only by this module."""
33
+ __slots__ = ("_token",)
34
+
35
+ def __init__(self, token):
36
+ self._token = token
37
+
38
+
39
+ _TOKEN = object()
40
+
41
+
42
+ def internal_writer_capability():
43
+ return InternalWriterCapability(_TOKEN)
44
+
45
+
46
+ def is_internal_writer(capability):
47
+ return isinstance(capability, InternalWriterCapability) and capability._token is _TOKEN
48
+
49
+
50
+ def descriptor(key):
51
+ label = SYSTEM_TABLES.get(str(key))
52
+ if not label:
53
+ return None
54
+ return {"key": str(key), "label": label, "managedBy": MANAGED_BY,
55
+ "folderId": LOOPABLE_FOLDER_ID, "protected": True, "source": "Loopable",
56
+ "recordsMutable": False, "canDelete": False, "canMove": False}
57
+
58
+
59
+ def system_table_descriptors():
60
+ """Virtual Data-nav rows that exist before the first Route is created."""
61
+ return [dict(descriptor(key)) for key in (ROUTES_KEY, ZONES_KEY)]
62
+
63
+
64
+ def is_managed(definition_or_key):
65
+ if isinstance(definition_or_key, dict):
66
+ return definition_or_key.get("managedBy") == MANAGED_BY
67
+ return str(definition_or_key) in SYSTEM_TABLES
68
+
69
+
70
+ def may_generic_mutate(definition_or_key, capability=None):
71
+ return not is_managed(definition_or_key) or is_internal_writer(capability)
72
+
73
+
74
+ def field_axes(field):
75
+ """Return the closed C3 axes without accepting caller-invented vocabulary."""
76
+ field = dict(field or {})
77
+ ftype = str(field.get("type") or "text")
78
+ source = str(field.get("source") or "odoo")
79
+ origin = field.get("origin") or ({"odoo": "odoo", "overlay": "user"}.get(source, "system"))
80
+ if origin not in {"odoo", "loopable", "system", "user", "automation"}:
81
+ raise ValueError("unapproved field origin")
82
+ kind = field.get("kind") or ftype
83
+ authority = field.get("valueAuthority") or (
84
+ "derived" if source == "odoo" or field.get("derived") else "user-entered")
85
+ scope = field.get("scope") or ("source" if source == "odoo" else "tenant")
86
+ if authority not in {"source", "derived", "user-entered", "computed"} or scope not in {"source", "tenant", "view", "record"}:
87
+ raise ValueError("unapproved field axis")
88
+ field.update({"kind": kind, "origin": origin, "valueAuthority": authority, "scope": scope})
89
+ if ftype in {"select", "multiselect", "user"}:
90
+ # This declaration is the only option cap; a client that cannot see it must refuse.
91
+ limits = dict(field.get("limits") or {})
92
+ limits.setdefault("maxOptions", 50)
93
+ field["limits"] = limits
94
+ if ftype == "json":
95
+ field["label"] = "Table"
96
+ return field
97
+
98
+
99
+ def inject_loopable_folder(workspace):
100
+ """Server projection: personal preferences cannot remove or relocate this folder."""
101
+ out = copy.deepcopy(workspace or {})
102
+ folders = out.setdefault("folders", [])
103
+ existing = next((row for row in folders if isinstance(row, dict)
104
+ and row.get("id") == LOOPABLE_FOLDER_ID), None)
105
+ if existing is None:
106
+ folders.append(dict(LOOPABLE_FOLDER))
107
+ else:
108
+ existing.update(LOOPABLE_FOLDER)
109
+ return out
110
+
111
+
112
+ def _now():
113
+ return _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0).isoformat()
114
+
115
+
116
+ def _store(st):
117
+ try:
118
+ return dict(st.get(STORE_KEY) or {})
119
+ except Exception:
120
+ return {}
121
+
122
+
123
+ def _pid(raw):
124
+ if isinstance(raw, bool):
125
+ return None
126
+ try:
127
+ value = int(raw)
128
+ except (TypeError, ValueError):
129
+ return None
130
+ return value if value >= 0 else None
131
+
132
+
133
+ def _color(raw, ordinal=0):
134
+ value = str(raw or "").upper()
135
+ return value if _COLOR_RE.fullmatch(value) else _ROUTE_COLORS[ordinal % len(_ROUTE_COLORS)]
136
+
137
+
138
+ def _name(raw):
139
+ return " ".join(str(raw or "").split())[:120]
140
+
141
+
142
+ def _stops(raw):
143
+ """Canonical dense stop relation. One customer can occur once in a Route."""
144
+ offered, seen = [], set()
145
+ for item in raw or ():
146
+ candidate = item.get("customerPid") if isinstance(item, dict) else item
147
+ pid = _pid(candidate)
148
+ if pid is not None and pid not in seen:
149
+ seen.add(pid)
150
+ offered.append(pid)
151
+ return [{"customerPid": pid, "position": index + 1}
152
+ for index, pid in enumerate(offered)]
153
+
154
+
155
+ def ordered_stops(route):
156
+ return [dict(stop) for stop in sorted(route.get("stops") or [],
157
+ key=lambda stop: int(stop.get("position") or 0))]
158
+
159
+
160
+ def _route(raw, *, ordinal=0, created_by="", tenant_id="", prior=None):
161
+ raw = raw if isinstance(raw, dict) else {}
162
+ prior = prior if isinstance(prior, dict) else {}
163
+ name = _name(raw.get("name", prior.get("name")))
164
+ if not name:
165
+ return None
166
+ rid = str(raw.get("id") or prior.get("id") or "route_" + uuid.uuid4().hex)[:96]
167
+ source_view = raw.get("sourceViewId", raw.get("source_view_id", prior.get("sourceViewId")))
168
+ source_view = str(source_view or "").strip()[:120] or None
169
+ revision = raw.get("sourceViewRevision", prior.get("sourceViewRevision"))
170
+ revision = str(revision or "").strip()[:128] or None
171
+ stops_raw = raw.get("stops") if "stops" in raw else prior.get("stops")
172
+ maps_url = str(raw.get("mapsUrl", prior.get("mapsUrl")) or "").strip()[:2048]
173
+ if maps_url and not _GOOGLE_MAPS_URL_RE.match(maps_url):
174
+ return None
175
+ stamp = _now()
176
+ out = {"id": rid, "tenantId": str(tenant_id or prior.get("tenantId") or ""), "name": name,
177
+ "color": _color(raw.get("color", prior.get("color")), ordinal),
178
+ "number": int(prior.get("number") or ordinal + 1), "sourceViewId": source_view,
179
+ "sourceViewRevision": revision, "stops": _stops(stops_raw), "managedBy": MANAGED_BY,
180
+ "createdBy": str(prior.get("createdBy") or created_by or "")[:120],
181
+ "createdAt": prior.get("createdAt") or stamp, "updatedAt": stamp}
182
+ if maps_url:
183
+ out["mapsUrl"] = maps_url
184
+ migration = raw.get("migration", prior.get("migration"))
185
+ if isinstance(migration, dict):
186
+ out["migration"] = {"legacyField": str(migration.get("legacyField") or "")[:80],
187
+ "verified": migration.get("verified") is True}
188
+ return out
189
+
190
+
191
+ def _point_in_ring(lon, lat, ring):
192
+ inside = False
193
+ if len(ring) < 4:
194
+ return False
195
+ for index, point in enumerate(ring):
196
+ previous = ring[index - 1]
197
+ try:
198
+ x1, y1, x2, y2 = float(previous[0]), float(previous[1]), float(point[0]), float(point[1])
199
+ except (TypeError, ValueError, IndexError):
200
+ return False
201
+ intersects = (y1 > lat) != (y2 > lat)
202
+ if intersects and lon < (x2 - x1) * (lat - y1) / ((y2 - y1) or 1e-15) + x1:
203
+ inside = not inside
204
+ return inside
205
+
206
+
207
+ def _polygon_contains(geometry, lon, lat):
208
+ if not isinstance(geometry, dict):
209
+ return False
210
+ kind, coords = geometry.get("type"), geometry.get("coordinates")
211
+ polygons = [coords] if kind == "Polygon" else coords if kind == "MultiPolygon" else []
212
+ for polygon in polygons or ():
213
+ if not isinstance(polygon, list) or not polygon:
214
+ continue
215
+ if _point_in_ring(lon, lat, polygon[0]) and not any(
216
+ _point_in_ring(lon, lat, ring) for ring in polygon[1:]):
217
+ return True
218
+ return False
219
+
220
+
221
+ def _zone(raw, *, ordinal=0, created_by="", tenant_id="", prior=None):
222
+ raw = raw if isinstance(raw, dict) else {}
223
+ prior = prior if isinstance(prior, dict) else {}
224
+ name = _name(raw.get("name", prior.get("name")))
225
+ geometry = raw.get("geometryGeoJson", prior.get("geometryGeoJson"))
226
+ zips_raw = raw.get("zipCodes", prior.get("zipCodes", ()))
227
+ zips, seen = [], set()
228
+ for value in zips_raw or ():
229
+ text = " ".join(str(value or "").upper().split())[:20]
230
+ if text and text not in seen and _ZIP_RE.fullmatch(text):
231
+ seen.add(text)
232
+ zips.append(text)
233
+ if not name or (geometry is not None and not isinstance(geometry, dict)) or (geometry is None and not zips):
234
+ return None
235
+ zid = str(raw.get("id") or prior.get("id") or "zone_" + uuid.uuid4().hex)[:96]
236
+ stamp = _now()
237
+ return {"id": zid, "tenantId": str(tenant_id or prior.get("tenantId") or ""), "name": name,
238
+ "color": _color(raw.get("color", prior.get("color")), ordinal),
239
+ "geometryGeoJson": copy.deepcopy(geometry) if isinstance(geometry, dict) else None,
240
+ "zipCodes": zips, "visible": raw.get("visible", prior.get("visible", True)) is not False,
241
+ "membershipRevision": int(prior.get("membershipRevision") or 0),
242
+ "memberPids": [int(pid) for pid in prior.get("memberPids") or [] if _pid(pid) is not None],
243
+ "managedBy": MANAGED_BY, "createdBy": str(prior.get("createdBy") or created_by or "")[:120],
244
+ "createdAt": prior.get("createdAt") or stamp, "updatedAt": stamp}
245
+
246
+
247
+ def _customer_zip(row):
248
+ for key in ("zip", "zip_code", "postal_code", "postalCode"):
249
+ value = row.get(key) if isinstance(row, dict) else None
250
+ text = " ".join(str(value or "").upper().split())[:20]
251
+ if text:
252
+ return text
253
+ return ""
254
+
255
+
256
+ def zone_members(zone, rows):
257
+ """Polygon-or-ZIP UNION, recalculated from the current customer address projection."""
258
+ zips = set(zone.get("zipCodes") or ())
259
+ out = []
260
+ for row in rows or ():
261
+ pid = _pid((row or {}).get("pid"))
262
+ if pid is None:
263
+ continue
264
+ zip_match = _customer_zip(row) in zips
265
+ try:
266
+ lon, lat = float(row.get("lon")), float(row.get("lat"))
267
+ polygon_match = math.isfinite(lon) and math.isfinite(lat) and _polygon_contains(
268
+ zone.get("geometryGeoJson"), lon, lat)
269
+ except (TypeError, ValueError):
270
+ polygon_match = False
271
+ if zip_match or polygon_match:
272
+ out.append(pid)
273
+ return out
274
+
275
+
276
+ def refresh_zone_memberships(state, rows):
277
+ """Pure state projection used by dedicated Zone writers and reads."""
278
+ out = copy.deepcopy(state if isinstance(state, dict) else {})
279
+ next_zones = []
280
+ for zone in out.get("zones") or []:
281
+ if not isinstance(zone, dict):
282
+ continue
283
+ members = zone_members(zone, rows)
284
+ previous = [int(pid) for pid in zone.get("memberPids") or [] if _pid(pid) is not None]
285
+ if members != previous:
286
+ zone["memberPids"] = members
287
+ zone["membershipRevision"] = int(zone.get("membershipRevision") or 0) + 1
288
+ zone["updatedAt"] = _now()
289
+ next_zones.append(zone)
290
+ out["zones"] = next_zones
291
+ return out
292
+
293
+
294
+ def _persist(st, mutate):
295
+ result = {}
296
+
297
+ def apply(current):
298
+ state = copy.deepcopy(current) if isinstance(current, dict) else {}
299
+ state.setdefault("routes", [])
300
+ state.setdefault("zones", [])
301
+ state.setdefault("legacyMigrations", {})
302
+ next_state, value = mutate(state)
303
+ result["value"] = copy.deepcopy(value)
304
+ return next_state
305
+
306
+ st.update(STORE_KEY, apply, flush="sync")
307
+ return result.get("value")
308
+
309
+
310
+ def read(st, rows=None):
311
+ state = _store(st)
312
+ state.setdefault("routes", [])
313
+ state.setdefault("zones", [])
314
+ state.setdefault("legacyMigrations", {})
315
+ return refresh_zone_memberships(state, rows or ()) if rows is not None else state
316
+
317
+
318
+ def list_routes(st):
319
+ return [copy.deepcopy(route) for route in read(st).get("routes") or [] if isinstance(route, dict)]
320
+
321
+
322
+ def list_zones(st, rows=None):
323
+ return [copy.deepcopy(zone) for zone in read(st, rows).get("zones") or [] if isinstance(zone, dict)]
324
+
325
+
326
+ def put_route(st, raw, *, tenant_id, created_by):
327
+ """Dedicated normalized Route writer. Generic table endpoints cannot call this."""
328
+ wanted = str((raw or {}).get("id") or "").strip()
329
+
330
+ def mutate(state):
331
+ routes = list(state.get("routes") or [])
332
+ prior_index = next((index for index, item in enumerate(routes)
333
+ if isinstance(item, dict) and item.get("id") == wanted), None)
334
+ prior = routes[prior_index] if prior_index is not None else None
335
+ clean = _route(raw, ordinal=prior_index if prior_index is not None else len(routes),
336
+ created_by=created_by, tenant_id=tenant_id, prior=prior)
337
+ if clean is None:
338
+ return state, None
339
+ if prior_index is None:
340
+ routes.append(clean)
341
+ else:
342
+ routes[prior_index] = clean
343
+ state["routes"] = routes
344
+ return state, clean
345
+
346
+ return _persist(st, mutate)
347
+
348
+
349
+ def move_stop(st, route_id, customer_pid, order, *, tenant_id, created_by):
350
+ """Move one protected stop. Empty routes are valid and never manufacture a stop."""
351
+ pid = _pid(customer_pid)
352
+ try:
353
+ target = max(1, int(order))
354
+ except (TypeError, ValueError):
355
+ return None
356
+ if pid is None:
357
+ return None
358
+ route = next((item for item in list_routes(st) if item.get("id") == str(route_id)), None)
359
+ if route is None:
360
+ return None
361
+ ids = [stop.get("customerPid") for stop in ordered_stops(route)]
362
+ if pid not in ids:
363
+ return None
364
+ ids.remove(pid)
365
+ ids.insert(min(target - 1, len(ids)), pid)
366
+ return put_route(st, {**route, "stops": ids}, tenant_id=tenant_id, created_by=created_by)
367
+
368
+
369
+ def delete_route(st, route_id):
370
+ route_id = str(route_id or "").strip()
371
+
372
+ def mutate(state):
373
+ prior = list(state.get("routes") or [])
374
+ state["routes"] = [item for item in prior if not (isinstance(item, dict) and item.get("id") == route_id)]
375
+ return state, len(prior) != len(state["routes"])
376
+
377
+ return bool(_persist(st, mutate))
378
+
379
+
380
+ def put_zone(st, raw, *, rows, tenant_id, created_by):
381
+ wanted = str((raw or {}).get("id") or "").strip()
382
+
383
+ def mutate(state):
384
+ zones = list(state.get("zones") or [])
385
+ prior_index = next((index for index, item in enumerate(zones)
386
+ if isinstance(item, dict) and item.get("id") == wanted), None)
387
+ prior = zones[prior_index] if prior_index is not None else None
388
+ clean = _zone(raw, ordinal=prior_index if prior_index is not None else len(zones),
389
+ created_by=created_by, tenant_id=tenant_id, prior=prior)
390
+ if clean is None:
391
+ return state, None
392
+ clean["memberPids"] = zone_members(clean, rows)
393
+ old_members = prior.get("memberPids") if isinstance(prior, dict) else None
394
+ clean["membershipRevision"] = int((prior or {}).get("membershipRevision") or 0) + (
395
+ 1 if old_members != clean["memberPids"] else 0)
396
+ if prior_index is None:
397
+ zones.append(clean)
398
+ else:
399
+ zones[prior_index] = clean
400
+ state["zones"] = zones
401
+ return state, clean
402
+
403
+ return _persist(st, mutate)
404
+
405
+
406
+ def delete_zone(st, zone_id):
407
+ zone_id = str(zone_id or "").strip()
408
+
409
+ def mutate(state):
410
+ prior = list(state.get("zones") or [])
411
+ state["zones"] = [item for item in prior if not (isinstance(item, dict) and item.get("id") == zone_id)]
412
+ return state, len(prior) != len(state["zones"])
413
+
414
+ return bool(_persist(st, mutate))
415
+
416
+
417
+ def customer_projections(routes, zones):
418
+ """Derived read-only customer multi-select values; stops are never generic Link cells."""
419
+ projections = {}
420
+ for route in routes or []:
421
+ for stop in ordered_stops(route):
422
+ projections.setdefault(stop.get("customerPid"), {"Routes": [], "Zone": []})["Routes"].append(route.get("name"))
423
+ for zone in zones or []:
424
+ for pid in zone.get("memberPids", zone.get("member_pids", ())) or ():
425
+ projections.setdefault(pid, {"Routes": [], "Zone": []})["Zone"].append(zone.get("name"))
426
+ return projections
427
+
428
+
429
+ def customer_projection_fields(routes, zones):
430
+ """The two read-only customer projection fields, never generic Link definitions."""
431
+ route_names = [str(route.get("name") or "") for route in routes or []
432
+ if str(route.get("name") or "")]
433
+ zone_names = [str(zone.get("name") or "") for zone in zones or []
434
+ if str(zone.get("name") or "")]
435
+ return [field_axes({"key": "routes", "label": "Routes", "type": "multiselect",
436
+ "source": "odoo", "derived": True, "readOnly": True,
437
+ "options": route_names}),
438
+ field_axes({"key": "zone", "label": "Zone", "type": "multiselect",
439
+ "source": "odoo", "derived": True, "readOnly": True,
440
+ "options": zone_names})]
441
+
442
+
443
+ def apply_customer_projections(rows, routes, zones):
444
+ """Layer normalized Route/Zone projections onto already scoped customer rows."""
445
+ projection = customer_projections(routes, zones)
446
+ out = []
447
+ for row in rows or []:
448
+ item = dict(row)
449
+ values = projection.get(item.get("pid"), projection.get(str(item.get("pid")), {})) or {}
450
+ item["routes"] = ", ".join(str(name) for name in values.get("Routes", ()) if name)
451
+ item["zone"] = ", ".join(str(name) for name in values.get("Zone", ()) if name)
452
+ out.append(item)
453
+ return out
454
+
455
+
456
+ def apply_managed_route_selection(view_state, route_ids, routes):
457
+ """Replace only Loopable's managed OR clause in an otherwise caller-owned View state.
458
+
459
+ The generic View writer remains the persistence authority. This narrow helper makes a
460
+ Route selection safe to compose: it neither reads nor rewrites the user's ordinary filter
461
+ tree and an empty selection removes only the managed clause it previously produced.
462
+ """
463
+ out = copy.deepcopy(view_state if isinstance(view_state, dict) else {})
464
+ out.pop("managedRouteClause", None)
465
+ wanted = {str(value) for value in route_ids or () if str(value)}
466
+ if not wanted:
467
+ return out
468
+ pids, known = [], set()
469
+ for route in routes or ():
470
+ if str(route.get("id")) not in wanted:
471
+ continue
472
+ for stop in ordered_stops(route):
473
+ pid = _pid(stop.get("customerPid"))
474
+ if pid is not None and pid not in known:
475
+ known.add(pid)
476
+ pids.append(pid)
477
+ out["managedRouteClause"] = {"managedBy": MANAGED_BY, "kind": "route-membership",
478
+ "operator": "or", "routeIds": sorted(wanted), "pids": pids}
479
+ return out
480
+
481
+
482
+ def legacy_route_plan(fields, cells, *, tenant_id, created_by):
483
+ """Copy/verify candidates for the dedicated migration endpoint; no store write occurs here."""
484
+ plans = []
485
+ for key, definition in (fields or {}).items():
486
+ if not isinstance(definition, dict) or definition.get("kind") != "route_order":
487
+ continue
488
+ migration_mark = definition.get("legacyRouteMigration")
489
+ if isinstance(migration_mark, dict) and migration_mark.get("verified"):
490
+ continue
491
+ ranks = []
492
+ for raw_pid, values in (cells or {}).items():
493
+ try:
494
+ rank = int(str((values or {}).get(key) or "").strip())
495
+ except (TypeError, ValueError):
496
+ continue
497
+ pid = _pid(raw_pid)
498
+ if pid is not None and rank > 0:
499
+ ranks.append((rank, pid))
500
+ ranks.sort()
501
+ if len({rank for rank, _pid_value in ranks}) != len(ranks):
502
+ continue
503
+ plan = _route({"id": "legacy_" + str(key)[:72], "name": definition.get("label") or key,
504
+ "color": definition.get("color"),
505
+ "sourceViewId": (definition.get("route") or {}).get("sourceViewId"),
506
+ "sourceViewRevision": (definition.get("route") or {}).get("inputsHash"),
507
+ "stops": [pid for _rank, pid in ranks],
508
+ "migration": {"legacyField": key, "verified": True}},
509
+ ordinal=len(plans), tenant_id=tenant_id, created_by=created_by)
510
+ if plan is not None:
511
+ plans.append({"field": key, "route": plan,
512
+ "expected": {pid: rank for rank, pid in ranks}})
513
+ return plans
514
+
515
+
516
+ def migrate_legacy_routes(st, fields, cells, *, tenant_id, created_by, zones=()):
517
+ """Persist copied Routes and prove count/member/order/projection parity before hiding fields."""
518
+ plans = legacy_route_plan(fields, cells, tenant_id=tenant_id, created_by=created_by)
519
+ if not plans:
520
+ return {"migrated": [], "verified": {}, "hide": []}
521
+
522
+ def mutate(state):
523
+ routes = list(state.get("routes") or [])
524
+ migrations = dict(state.get("legacyMigrations") or {})
525
+ migrated, verified, hide = [], {}, []
526
+ for plan in plans:
527
+ field, route = plan["field"], plan["route"]
528
+ existing_index = next((index for index, item in enumerate(routes)
529
+ if isinstance(item, dict) and item.get("id") == route["id"]), None)
530
+ if existing_index is None:
531
+ routes.append(route)
532
+ candidate = route
533
+ else:
534
+ candidate = routes[existing_index]
535
+ expected = plan["expected"]
536
+ observed = {stop["customerPid"]: stop["position"] for stop in ordered_stops(candidate)}
537
+ projections = customer_projections(routes, zones)
538
+ projection_ok = all(candidate.get("name") in (projections.get(pid) or {}).get("Routes", [])
539
+ for pid in expected)
540
+ parity = {"routeCount": len(expected) == len(observed),
541
+ "memberCount": set(expected) == set(observed), "order": expected == observed,
542
+ "projections": projection_ok}
543
+ verified[field] = parity
544
+ if all(parity.values()):
545
+ migrations[field] = {"routeId": candidate["id"], "verified": True, "at": _now()}
546
+ migrated.append(candidate["id"])
547
+ hide.append(field)
548
+ state["routes"], state["legacyMigrations"] = routes, migrations
549
+ return state, {"migrated": migrated, "verified": verified, "hide": hide}
550
+
551
+ return _persist(st, mutate)
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):
 
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):
platform/core/user_tables.py CHANGED
@@ -491,6 +491,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
@@ -947,7 +950,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.
@@ -1371,12 +1384,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 +1427,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 +1456,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 +1802,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
@@ -1946,6 +2011,12 @@ def _clean_link(raw):
1946
  out['reciprocal'] = reciprocal
1947
  if raw.get('single') is True:
1948
  out['single'] = True
 
 
 
 
 
 
1949
  return out
1950
 
1951
 
@@ -2425,7 +2496,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
@@ -3191,6 +3272,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 +3370,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 +3575,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 +3647,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'):
 
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
+ FIELD_ORIGINS = {'odoo', 'loopable', 'system', 'user', 'automation'}
495
+ FIELD_AUTHORITIES = {'source', 'derived', 'user-entered', 'computed'}
496
+ FIELD_SCOPES = {'source', 'tenant', 'view', 'record'}
497
  #: A cell is still a scalar on the wire (`Row` values are strings/numbers) — what this bounds is
498
  #: the DOCUMENT inside it. Source data is one already-paid provider response; keep it whole so a
499
  #: provider field is never silently discarded merely because the response is rich. 32 MiB matches
 
950
  if not key or key in seen or ftype not in UT_FIELD_TYPES or not label:
951
  continue
952
  seen.add(key)
953
+ origin = str(f.get('origin') or 'user')
954
+ authority = str(f.get('valueAuthority') or 'user-entered')
955
+ scope = str(f.get('scope') or 'tenant')
956
+ # C3: these are closed product vocabularies. Do not silently persist a word no
957
+ # renderer/permission door understands.
958
+ if origin not in FIELD_ORIGINS or authority not in FIELD_AUTHORITIES or scope not in FIELD_SCOPES:
959
+ continue
960
+ entry = {'key': key, 'label': label, 'type': ftype, 'source': 'overlay',
961
+ 'kind': ftype, 'origin': origin, 'valueAuthority': authority, 'scope': scope}
962
+ if ftype == 'json' and not f.get('label'):
963
+ entry['label'] = 'Table'
964
  # ⭐ 2026-08-10 — the DISPLAY format, carried through the CREATE door. See `_clean_format`:
965
  # this is the fifth time an entry built key-by-key has silently dropped a bag the editor
966
  # sends, and the fourth of those was `agg` on this very line one wave ago.
 
1384
  return str(table_key or '').startswith(KEY_PREFIX) and get(table_key, st) is not None
1385
 
1386
 
1387
+ def is_managed_system_table(table_key, st=None, definition=None):
1388
+ """C1 policy predicate, intentionally separate from ordinary record mutability."""
1389
+ from core import route_system
1390
+ return route_system.is_managed(definition if definition is not None else (get(table_key, st) or table_key))
1391
+
1392
+
1393
+ def create(label, username, fields=None, source=None, st=None, *, managed_by=None, capability=None):
1394
  """Create a blank table. Returns its key, or None if refused.
1395
 
1396
  Refuses rather than raises on the ordinary conditions (no name, duplicate, cap reached) —
1397
  the caller is a UI form and a refusal is a message, not an exception.
1398
  """
1399
+ if managed_by is not None:
1400
+ from core import route_system
1401
+ if managed_by != route_system.MANAGED_BY or not route_system.is_internal_writer(capability):
1402
+ return None
1403
  label = str(label or '').strip()[:MAX_LABEL]
1404
  if not label:
1405
  return None
 
1427
  'source': 'overlay', 'default': True}],
1428
  'rows': {},
1429
  }
1430
+ if managed_by:
1431
+ from core import route_system
1432
+ defn.update({'managedBy': route_system.MANAGED_BY, 'folderId': route_system.LOOPABLE_FOLDER_ID,
1433
+ 'protected': True})
1434
 
1435
  def _add(cur):
1436
  cur[key] = defn
 
1456
  Every family after the definition is best-effort: a store blip mid-sweep must not resurrect
1457
  the table, and an orphaned empty bucket is residue, not a leak."""
1458
  key = str(table_key)
1459
+ if is_managed_system_table(key, st=st):
1460
+ return False
1461
  s = _st(st)
1462
 
1463
  def _drop(cur):
 
1802
  #: ~3 KB — comfortably inside a text cell, and `MAX_ROWS` bounds the absolute worst case anyway.
1803
  LINK_MAX_IDS = 500
1804
 
1805
+ # Link picker filters are schema, not a View selection: the leaf below constrains candidate rows
1806
+ # in the linked table. `sourceField` is explicitly a field on the current record; absence means
1807
+ # this is the static/literal form. Keeping the two shapes disjoint prevents a dynamic picker
1808
+ # value being mistaken for a saved View lock or a stale literal.
1809
+ LINK_FILTER_OPS = ('eq', 'neq', 'contains', 'not_contains', 'is_empty', 'is_not_empty')
1810
+
1811
+
1812
+ def _clean_link_filter(raw):
1813
+ if not isinstance(raw, dict):
1814
+ return None
1815
+ field = _field_key(raw.get('field', raw.get('colId')))
1816
+ op = str(raw.get('op') or '').strip()
1817
+ if not field or op not in LINK_FILTER_OPS:
1818
+ return None
1819
+ source = _field_key(raw.get('sourceField', raw.get('currentRecordField')))
1820
+ if source:
1821
+ # A dynamic leaf has no literal fallback. Retaining one would let an old/current record
1822
+ # value silently answer when the source field goes blank, a different filter under one UI.
1823
+ return {'field': field, 'op': op, 'sourceField': source}
1824
+ if op in ('is_empty', 'is_not_empty'):
1825
+ return {'field': field, 'op': op}
1826
+ if 'value' not in raw or isinstance(raw.get('value'), (dict, list, tuple, set)):
1827
+ return None
1828
+ return {'field': field, 'op': op, 'value': str(raw.get('value'))[:500]}
1829
+
1830
+
1831
+ def dynamic_link_filter_valid(field, fields):
1832
+ """Does every dynamic Link-filter source name another field on this current record?"""
1833
+ bag = field.get('link') if isinstance(field, dict) else None
1834
+ leaf = bag.get('filter') if isinstance(bag, dict) else None
1835
+ source = leaf.get('sourceField') if isinstance(leaf, dict) else None
1836
+ if not source:
1837
+ return True
1838
+ names = {str(item.get('key') or '') for item in fields or () if isinstance(item, dict)}
1839
+ return source in names and source != str(field.get('key') or '')
1840
+
1841
  #: Airtable's 17 aggregations, minus the two that are meaningless over scalar cells.
1842
  #: ⛔ `arrayflatten` and `arrayslice` are NOT here: both operate on NESTED arrays, and a cell in
1843
  #: this product is a scalar — they could only ever return their own input, so offering them would
 
2011
  out['reciprocal'] = reciprocal
2012
  if raw.get('single') is True:
2013
  out['single'] = True
2014
+ supplied_filter = raw.get('filter', raw.get('where'))
2015
+ if supplied_filter is not None:
2016
+ leaf = _clean_link_filter(supplied_filter)
2017
+ if leaf is None:
2018
+ return None
2019
+ out['filter'] = leaf
2020
  return out
2021
 
2022
 
 
2496
  ftype = str(raw.get('type') or prev.get('type') or 'text').strip().lower()
2497
  if not key or not label or ftype not in UT_FIELD_TYPES:
2498
  return None
2499
+ origin = str(raw.get('origin') if 'origin' in raw else prev.get('origin') or 'user')
2500
+ authority = str(raw.get('valueAuthority') if 'valueAuthority' in raw else prev.get('valueAuthority') or 'user-entered')
2501
+ scope = str(raw.get('scope') if 'scope' in raw else prev.get('scope') or 'tenant')
2502
+ if origin not in FIELD_ORIGINS or authority not in FIELD_AUTHORITIES or scope not in FIELD_SCOPES:
2503
+ return None
2504
+ out = {'key': key, 'label': label, 'type': ftype, 'source': 'overlay', 'kind': ftype,
2505
+ 'origin': origin, 'valueAuthority': authority, 'scope': scope}
2506
+ if ftype == 'json':
2507
+ out['label'] = 'Table'
2508
+ if bool(raw.get('deletionLocked') if 'deletionLocked' in raw else prev.get('deletionLocked')):
2509
+ out['deletionLocked'] = True
2510
  # ⭐ 2026-08-10 — the DISPLAY format, on the add/patch door too. ⚠ `'format' in raw` rather than
2511
  # `raw.get('format')`, exactly like `description` below: an explicit `{}`/None CLEARS the
2512
  # format, while omitting the key keeps what is stored. A PATCH that sends only a label must not
 
3272
  grant_topic=grant_topic)
3273
  if bag is None:
3274
  return FIELD_NOT_FOUND
3275
+ if bool((field or {}).get('deletionLocked')):
3276
+ return 'field_deletion_locked'
3277
  # ⛔ ABOVE THE ADMIN BRANCH. Moving this below it is the mutation W41-T02's proof breaks on
3278
  # purpose, and R6a is the sentence it would violate.
3279
  if bag.get('origin') == 'preset':
 
3370
  field = _clean_field(raw)
3371
  if not field or any(f.get('key') == field['key'] for f in have):
3372
  return None
3373
+ if not dynamic_link_filter_valid(field, have):
3374
+ return None
3375
  if not flow_bound(field.get('automation'), st):
3376
  return None # C8: no field without a flow (400 at the route)
3377
  # C3 (wave 25, R7's first mitigation): AT MOST ONE profile field per table. Without it the
 
3575
  field = _clean_field(merged, fields[idx])
3576
  if not field:
3577
  return None
3578
+ if not dynamic_link_filter_valid(field, fields):
3579
+ return None
3580
  if 'automation' in merged and not flow_bound(field.get('automation'), st):
3581
  return None # C8: a patch cannot un-bind a column either
3582
  # C3: the one-per-table law on the PATCH door too — flagging a second column is the same act
 
3647
  if len(fields) <= 1 or not any(f.get('key') == str(fkey) for f in fields):
3648
  return False
3649
  doomed = next((f for f in fields if f.get('key') == str(fkey)), {})
3650
+ if doomed.get('deletionLocked') is True:
3651
+ return False
3652
  doomed_link = doomed.get('link') if isinstance(doomed.get('link'), dict) else {}
3653
  inverse_source = None
3654
  if doomed_link.get('inverse'):
web/src/automation/AutomationBuilder.tsx CHANGED
@@ -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".
@@ -102,6 +103,7 @@ interface Props {
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;
@@ -438,6 +440,7 @@ export default function AutomationBuilder({
438
  catalog,
439
  vocab,
440
  tables,
 
441
  oauth,
442
  busy,
443
  onPatch,
@@ -686,6 +689,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.
@@ -1534,6 +1539,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 +1706,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 +2924,7 @@ export function ActionProps({
2917
  agentMark,
2918
  catalog,
2919
  tables,
 
2920
  onTablesChanged,
2921
  walkFields,
2922
  walkTable,
@@ -2951,6 +2959,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 +3085,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 —
 
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".
 
103
  catalog: ActionCatalogRow[];
104
  vocab?: FlowVocab;
105
  tables: UserTable[];
106
+ voiceAgents?: VoiceAgent[];
107
  oauth: OAuthStatus | null;
108
  /** True while a write is in flight — drives the "All changes saved" stamp and disables edits. */
109
  busy: boolean;
 
440
  catalog,
441
  vocab,
442
  tables,
443
+ voiceAgents,
444
  oauth,
445
  busy,
446
  onPatch,
 
689
  : null;
690
  if (kind === "find_records")
691
  return firstTable ? { table: firstTable.key, cond: null, limit: 25 } : null;
692
+ if (kind === "voice_agent")
693
+ return { voiceAgentId: "" };
694
  /*
695
  ⭐⭐ WAVE 31 · T38 (contract C5, owner ruling R10) — THE WEB READ, and this branch is here
696
  because a gate demanded it rather than because anybody remembered.
 
1539
  picked={picked}
1540
  table={table}
1541
  tables={tables}
1542
+ voiceAgents={voiceAgents}
1543
  ops={ops}
1544
  nullaryOps={nullaryOps}
1545
  vocab={vocab}
 
1706
  picked: TriggerOption | null;
1707
  table: UserTable | null;
1708
  tables: UserTable[];
1709
+ voiceAgents?: VoiceAgent[];
1710
  ops: string[];
1711
  nullaryOps: string[];
1712
  vocab?: FlowVocab;
 
2924
  agentMark,
2925
  catalog,
2926
  tables,
2927
+ voiceAgents,
2928
  onTablesChanged,
2929
  walkFields,
2930
  walkTable,
 
2959
  agentMark?: { agent: string; agentName?: string; created?: string; by?: string } | null;
2960
  catalog: ActionCatalogRow[];
2961
  tables: UserTable[];
2962
+ voiceAgents?: VoiceAgent[];
2963
  /** ITEM 9 / R11 — re-read the list after this panel's picker creates one. REQUIRED; see Props. */
2964
  onTablesChanged: () => Promise<void> | void;
2965
  /**
 
3085
  />
3086
  ) : null}
3087
 
3088
+ {readOnly ? null : action.kind === "voice_agent" ? (
3089
+ <label className="auto-field">
3090
+ Voice agent
3091
+ <select value={String((cfg as { voiceAgentId?: string }).voiceAgentId || "")} onChange={(event) => setCfg({ voiceAgentId: event.target.value })}>
3092
+ <option value="">Choose a Voice agent</option>
3093
+ {(voiceAgents || []).map((agent) => <option key={agent.automationId} value={agent.automationId}>{agent.displayName}</option>)}
3094
+ </select>
3095
+ </label>
3096
+ ) : action.kind === "group" ? (
3097
  <>
3098
  {/*
3099
  ⭐ 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,7 @@ 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 +198,7 @@ export default function AutomationDetail({
196
  discover,
197
  triggers,
198
  catalog,
 
199
  vocab,
200
  tick,
201
  liveStep,
@@ -462,7 +465,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"
@@ -1759,6 +1762,7 @@ export default function AutomationDetail({
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
+ voiceAgents?: VoiceAgent[];
106
  vocab?: FlowVocab;
107
  /**
108
  * Can a schedule fire here? `null` = the server did not say (C6 amendment #1 is not live
 
198
  discover,
199
  triggers,
200
  catalog,
201
+ voiceAgents,
202
  vocab,
203
  tick,
204
  liveStep,
 
465
  );
466
  const viewTabs = (
467
  <div className="autox-views" role="radiogroup" aria-label="Editor view">
468
+ {([["chat", "Chat"], ["canvas", "Canvas"]] as const).map(([k, label]) => (
469
  <button
470
  key={k}
471
  type="button"
 
1762
  dirty={touched}
1763
  {...(triggers ? { triggers } : {})}
1764
  catalog={catalog || []}
1765
+ voiceAgents={voiceAgents}
1766
  {...(vocab ? { vocab } : {})}
1767
  tables={tables}
1768
  /* ⭐ 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,14 @@ 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 +63,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 +143,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 +233,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 +269,13 @@ export default function AutomationSurface() {
253
  const select = useCallback((id: string, _stage = "") => {
254
  wantedId.current = id;
255
  setActiveId(id);
 
 
 
 
 
 
 
256
  }, []);
257
 
258
  /**
@@ -335,6 +358,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
  *
@@ -481,6 +522,7 @@ export default function AutomationSurface() {
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 +682,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 +748,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 +776,11 @@ 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 +801,7 @@ 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
  } from "./automationApi";
40
+ import type { VoiceAgent } from "./voiceAgentTypes";
41
+ import "../styles/wave44/voice-agent.css";
42
 
43
  /**
44
  * ⭐⭐ WAVE 30 · T21 (owner items 4 + 5) — THE EDITOR STOPS SHIPPING INSIDE THE LIST.
 
63
  */
64
  const AutomationDetail = lazy(() => import("./AutomationDetail"));
65
 
66
+ // Voice properties are selected-detail work, never rail work. Keep their harness and form code
67
+ // behind the same local boundary so the first Agents paint remains within the rail chunk budget.
68
+ const VoiceAgentProperties = lazy(() => import("./VoiceAgentProperties"));
69
+
70
  /**
71
  * The run poll's cadence (item 6). Named constants because they are a MEASURED trade-off, not a
72
  * taste: `POLL_MAX_MS` is the longest a finished run can still look live, and it is the only
 
143
  return "Manual only";
144
  }
145
 
146
+ function voiceStatusLabel(value: string): string {
147
+ return String(value || "not reported")
148
+ .replace(/[_-]+/g, " ")
149
+ .replace(/\b\w/g, (letter) => letter.toUpperCase());
150
+ }
151
+
152
  /*
153
  * ⛔ W23-W5's LISTENER IS AT MODULE SCOPE, AND THAT IS THE POINT — not a stylistic choice.
154
  *
 
233
  every render instead, which is the same value at needless cost. A cold start still returns
234
  null and still gets the skeleton: it is made rare, not removed (see `automationApi.ts`). */
235
  const [data, setData] = useState<AutomationList | null>(() => cachedAutomations());
236
+ const [voiceAgents, setVoiceAgents] = useState<VoiceAgent[]>([]);
237
+ const [voiceLoadError, setVoiceLoadError] = useState("");
238
  const [error, setError] = useState("");
239
  const [activeId, setActiveId] = useState<string>("");
240
+ const [activeVoiceId, setActiveVoiceId] = useState<string>("");
241
  const [railShut, setRailShut] = useState(false);
242
  const [busy, setBusy] = useState("");
243
  /**
 
269
  const select = useCallback((id: string, _stage = "") => {
270
  wantedId.current = id;
271
  setActiveId(id);
272
+ setActiveVoiceId("");
273
+ }, []);
274
+
275
+ const selectVoice = useCallback((id: string) => {
276
+ wantedId.current = "";
277
+ setActiveId("");
278
+ setActiveVoiceId(id);
279
  }, []);
280
 
281
  /**
 
358
  return () => ac.abort();
359
  }, [load]);
360
 
361
+ useEffect(() => {
362
+ const ac = new AbortController();
363
+ void listVoiceAgents(ac.signal)
364
+ .then((next) => {
365
+ setVoiceAgents(next?.voiceAgents || []);
366
+ setVoiceLoadError("");
367
+ })
368
+ .catch((reason) => {
369
+ if ((reason as Error)?.name === "AbortError") return;
370
+ setVoiceLoadError(
371
+ reason instanceof AutomationError
372
+ ? reason.message
373
+ : "Voice configuration could not be loaded."
374
+ );
375
+ });
376
+ return () => ac.abort();
377
+ }, []);
378
+
379
  /**
380
  * ⭐⭐ WAVE 24 / C-CREATE (a) — CREATE AND OPEN. This REPLACED the three-step wizard.
381
  *
 
522
 
523
  const items = data?.automations || [];
524
  const active = items.find((a) => a.id === activeId) || null;
525
+ const activeVoice = voiceAgents.find((agent) => agent.automationId === activeVoiceId) || null;
526
 
527
  /**
528
  * ⭐⭐ WAVE 32 · T43 (owner item 2) — TURNING AN AUTOMATION ON OR OFF STOPS TAKING FOREVER.
 
682
  </div>
683
  );
684
  })}
685
+ {voiceAgents.map((agent) => {
686
+ const isActive = agent.activationState === "active";
687
+ return (
688
+ <div
689
+ key={agent.automationId}
690
+ className={"auto-row" + (agent.automationId === activeVoiceId ? " is-active" : "")}
691
+ >
692
+ <button
693
+ type="button"
694
+ className="auto-row-main"
695
+ onClick={() => selectVoice(agent.automationId)}
696
+ >
697
+ <span className="auto-loopmark">
698
+ <Mark size={15} />
699
+ </span>
700
+ <span className="auto-row-text">
701
+ <span className="auto-row-name">{agent.displayName}</span>
702
+ <span className="auto-row-desc">
703
+ Voice · {voiceStatusLabel(agent.connectionStatus)}
704
+ </span>
705
+ </span>
706
+ </button>
707
+ <button
708
+ type="button"
709
+ className={"auto-row-switch voice-agent-row-toggle" + (isActive ? " is-on" : "")}
710
+ disabled
711
+ aria-pressed={isActive}
712
+ aria-label={`${agent.displayName}: ${voiceStatusLabel(agent.activationState)}. Server controlled.`}
713
+ title="Voice activation is controlled on the server."
714
+ >
715
+ <span className="auto-row-switch-knob" />
716
+ </button>
717
+ </div>
718
+ );
719
+ })}
720
  {/* ONE LINE (R13). It used to describe the kinds — "one reads a public web page…
721
  the other fills an automation column…" — which was two sentences, wrong by the
722
  time a third kind shipped, and printed inside a `--lp-rail-w` column. What the
 
748
  {error}
749
  </div>
750
  ) : null}
751
+ {voiceLoadError ? (
752
+ <div className="auto-banner is-warn" role="status">
753
+ {voiceLoadError}
754
+ </div>
755
+ ) : null}
756
  {data && !data.storeAvailable ? (
757
  <div className="auto-banner is-warn" role="status">
758
  The tenant store is unavailable, so nothing can be saved right now.
 
776
  */}
777
  {/* T21: the editor's own Suspense boundary — see the `lazy()` above for why it cannot be
778
  `Shell.tsx`'s. `fallback={null}`, matching `Lazily`. */}
779
+ {activeVoice ? (
780
+ <Suspense fallback={null}>
781
+ <VoiceAgentProperties key={activeVoice.automationId} agent={activeVoice} />
782
+ </Suspense>
783
+ ) : active ? (
784
  <Suspense fallback={null}>
785
  <AutomationDetail
786
  key={active.id}
 
801
  // `triggers` is: absent must stay absent, so the builder can tell "the server
802
  // offered nothing" from "the server offered an empty list".
803
  catalog={data?.actionsCatalog}
804
+ voiceAgents={voiceAgents}
805
  vocab={data?.flow}
806
  // `?? null` and never `|| {enabled:false}`: an absent tick bit is "the server did
807
  // not say", which Step 1 prints as its own sentence. Defaulting it here would
web/src/automation/VoiceAgentProperties.tsx ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from "react";
2
+
3
+ import { AutomationError, dryRunVoiceAgent } from "./automationApi";
4
+ import type { VoiceAgent, VoiceHarnessInput, VoiceHarnessResult } from "./voiceAgentTypes";
5
+
6
+ interface Props {
7
+ agent: VoiceAgent;
8
+ }
9
+
10
+ const CONFIGURATION_LABELS: Record<string, string> = {
11
+ responseEngineRef: "Response engine",
12
+ voiceRef: "Voice",
13
+ purpose: "Purpose",
14
+ callbackOnly: "Callback-only behaviour",
15
+ };
16
+
17
+ function statusLabel(value: string): string {
18
+ return String(value || "not reported")
19
+ .replace(/[_-]+/g, " ")
20
+ .replace(/\b\w/g, (letter) => letter.toUpperCase());
21
+ }
22
+
23
+ function configurationLabel(key: string): string {
24
+ return CONFIGURATION_LABELS[key] || "Additional configuration";
25
+ }
26
+
27
+ export default function VoiceAgentProperties({ agent }: Props) {
28
+ const [input, setInput] = useState<VoiceHarnessInput>({
29
+ table: "",
30
+ viewId: "",
31
+ phoneField: "",
32
+ });
33
+ const [result, setResult] = useState<VoiceHarnessResult | null>(null);
34
+ const [error, setError] = useState("");
35
+ const [checking, setChecking] = useState(false);
36
+ const canCheck = !!input.table.trim() && !!input.viewId.trim() && !!input.phoneField.trim();
37
+ const configuration = Object.keys(agent.supportedConfiguration || {});
38
+ const tables = agent.audienceOptions?.tables || [];
39
+ const selectedTable = tables.find((table) => table.key === input.table);
40
+ const views = selectedTable?.views || [];
41
+ const selectedView = views.find((view) => view.id === input.viewId);
42
+ const phoneFields = selectedView ? (selectedTable?.phoneFields || []) : [];
43
+
44
+ const updateInput = (key: keyof VoiceHarnessInput, value: string) => {
45
+ setInput((current) => ({ ...current, [key]: value }));
46
+ setError("");
47
+ setResult(null);
48
+ };
49
+
50
+ const checkHarness = async () => {
51
+ if (!canCheck || checking) return;
52
+ setChecking(true);
53
+ setError("");
54
+ setResult(null);
55
+ try {
56
+ const next = await dryRunVoiceAgent(agent.automationId, {
57
+ table: input.table.trim(),
58
+ viewId: input.viewId.trim(),
59
+ phoneField: input.phoneField.trim(),
60
+ });
61
+ setResult(next);
62
+ } catch (reason) {
63
+ setError(
64
+ reason instanceof AutomationError
65
+ ? reason.message
66
+ : "The Voice harness could not validate this selection."
67
+ );
68
+ } finally {
69
+ setChecking(false);
70
+ }
71
+ };
72
+
73
+ return (
74
+ <section className="voice-agent-properties" aria-label={`${agent.displayName} properties`}>
75
+ <header className="voice-agent-heading">
76
+ <div>
77
+ <p className="voice-agent-eyebrow">Agent</p>
78
+ <h1>{agent.displayName}</h1>
79
+ </div>
80
+ <span className="voice-agent-status" title="Connection status">
81
+ {statusLabel(agent.connectionStatus)}
82
+ </span>
83
+ </header>
84
+
85
+ <div className="voice-agent-grid">
86
+ <section className="voice-agent-section" aria-labelledby="voice-properties-heading">
87
+ <h2 id="voice-properties-heading">Properties</h2>
88
+ <dl className="voice-agent-details">
89
+ <div>
90
+ <dt>Purpose</dt>
91
+ <dd>{agent.purpose || "Not set"}</dd>
92
+ </div>
93
+ <div>
94
+ <dt>Callback only</dt>
95
+ <dd>{agent.callbackOnly ? "Yes" : "No"}</dd>
96
+ </div>
97
+ <div>
98
+ <dt>Activation</dt>
99
+ <dd>{statusLabel(agent.activationState)}</dd>
100
+ </div>
101
+ </dl>
102
+ <button type="button" className="voice-agent-disabled-control" disabled>
103
+ Voice runs unavailable
104
+ </button>
105
+ <p className="voice-agent-note">
106
+ The server keeps Voice inactive until configuration is complete and Loopable explicitly
107
+ activates it.
108
+ </p>
109
+ </section>
110
+
111
+ <section className="voice-agent-section" aria-labelledby="voice-config-heading">
112
+ <h2 id="voice-config-heading">Configuration</h2>
113
+ {configuration.length ? (
114
+ <ul className="voice-agent-config-list">
115
+ {configuration.map((key) => (
116
+ <li key={key}>
117
+ <span>{configurationLabel(key)}</span>
118
+ <span>Supported</span>
119
+ </li>
120
+ ))}
121
+ </ul>
122
+ ) : (
123
+ <p className="voice-agent-note">No supported configuration was reported.</p>
124
+ )}
125
+ {agent.capabilities.numberProvisioning === "contact_loopable" ? (
126
+ <p className="voice-agent-contact">
127
+ Number and SIP provisioning: <strong>Contact Loopable</strong>
128
+ </p>
129
+ ) : null}
130
+ </section>
131
+ </div>
132
+
133
+ <section className="voice-agent-section" aria-labelledby="voice-bindings-heading">
134
+ <h2 id="voice-bindings-heading">Phone bindings</h2>
135
+ {agent.phoneBindings.length ? (
136
+ <ul className="voice-agent-bindings">
137
+ {agent.phoneBindings.map((binding) => (
138
+ <li key={binding.opaqueId}>
139
+ <span className="voice-agent-number">{binding.maskedNumber}</span>
140
+ <span className={binding.active ? "is-active" : ""}>
141
+ {binding.active ? "Active inbound" : "Inactive"}
142
+ </span>
143
+ </li>
144
+ ))}
145
+ </ul>
146
+ ) : (
147
+ <p className="voice-agent-note">No phone bindings are available.</p>
148
+ )}
149
+ </section>
150
+
151
+ <section className="voice-agent-section" aria-labelledby="voice-harness-heading">
152
+ <div className="voice-agent-section-head">
153
+ <div>
154
+ <h2 id="voice-harness-heading">Test harness</h2>
155
+ <p className="voice-agent-note">
156
+ Validate a saved View and phone-type field without external dispatch.
157
+ </p>
158
+ </div>
159
+ <span className="voice-agent-harness-state">No external dispatch</span>
160
+ </div>
161
+ <div className="voice-agent-harness-fields">
162
+ <label>
163
+ Database
164
+ <select
165
+ value={input.table}
166
+ onChange={(event) => {
167
+ setInput((current) => ({ ...current, table: event.target.value, viewId: "", phoneField: "" }));
168
+ setError(""); setResult(null);
169
+ }}
170
+ aria-label="Voice audience database"
171
+ >
172
+ <option value="">Choose a database</option>
173
+ {tables.map((table) => <option key={table.key} value={table.key}>{table.label}</option>)}
174
+ </select>
175
+ </label>
176
+ <label>
177
+ Saved View
178
+ <select
179
+ value={input.viewId}
180
+ onChange={(event) => {
181
+ setInput((current) => ({ ...current, viewId: event.target.value, phoneField: "" }));
182
+ setError(""); setResult(null);
183
+ }}
184
+ aria-label="Voice audience saved View"
185
+ disabled={!selectedTable}
186
+ >
187
+ <option value="">Choose a View</option>
188
+ {views.map((view) => <option key={view.id} value={view.id}>{view.label}</option>)}
189
+ </select>
190
+ </label>
191
+ <label>
192
+ Phone field
193
+ <select
194
+ value={input.phoneField}
195
+ onChange={(event) => updateInput("phoneField", event.target.value)}
196
+ aria-label="Voice audience phone field"
197
+ disabled={!selectedView}
198
+ >
199
+ <option value="">Choose a phone field</option>
200
+ {phoneFields.map((field) => <option key={field.key} value={field.key}>{field.label}</option>)}
201
+ </select>
202
+ </label>
203
+ </div>
204
+ <button
205
+ type="button"
206
+ className="voice-agent-harness-submit"
207
+ disabled={!canCheck || checking || !agent.capabilities.dryRun}
208
+ onClick={() => void checkHarness()}
209
+ >
210
+ {checking ? "Checking…" : "Validate dry run"}
211
+ </button>
212
+ {error ? <p className="voice-agent-result is-error" role="alert">{error}</p> : null}
213
+ {result ? (
214
+ <p className="voice-agent-result" role="status">
215
+ {result.noExternalDispatch
216
+ ? "Dry run complete. No external dispatch occurred."
217
+ : "The server did not confirm the no-external-dispatch safety check."}
218
+ </p>
219
+ ) : null}
220
+ </section>
221
+ </section>
222
+ );
223
+ }
web/src/automation/automationApi.ts CHANGED
@@ -22,6 +22,11 @@ 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 +1016,28 @@ 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
+ VoiceAgentList,
27
+ VoiceHarnessInput,
28
+ VoiceHarnessResult,
29
+ } from "./voiceAgentTypes";
30
 
31
  /**
32
  * ⭐ WAVE 24 / R6 — `plain` IS A REAL KIND, and it is the default for every new automation.
 
1016
  });
1017
  }
1018
 
1019
+ /**
1020
+ * The Voice control plane has its own narrow browser contract. It is deliberately not folded
1021
+ * into `/automations`: ordinary Agents and Voice Agent configuration have different safety doors.
1022
+ */
1023
+ export function listVoiceAgents(abort?: AbortSignal): Promise<VoiceAgentList> {
1024
+ return send<VoiceAgentList>("/voice-agents", { signal: abort });
1025
+ }
1026
+
1027
+ /**
1028
+ * Validates only the server-authorized saved View and phone-type field. This is the sole Voice
1029
+ * mutation-shaped request available to the browser, and the server proves no external dispatch.
1030
+ */
1031
+ export function dryRunVoiceAgent(
1032
+ voiceId: string,
1033
+ input: VoiceHarnessInput
1034
+ ): Promise<VoiceHarnessResult> {
1035
+ return send<VoiceHarnessResult>(
1036
+ `/voice-agents/${encodeURIComponent(voiceId)}/harness/dry-run`,
1037
+ { method: "POST", body: JSON.stringify(input) }
1038
+ );
1039
+ }
1040
+
1041
  /**
1042
  * ⭐⭐ WAVE 31 · T31 — fold ONE freshly-written automation into the memo, and hand back the list.
1043
  *
web/src/automation/voiceAgentTypes.ts ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Browser-safe Voice control-plane shapes. Provider, credential, SIP, routing and raw-number
2
+ // data intentionally have no representation in this client module.
3
+
4
+ export interface VoicePhoneBinding {
5
+ opaqueId: string;
6
+ maskedNumber: string;
7
+ active: boolean;
8
+ }
9
+
10
+ export type VoiceSupportedConfiguration = Partial<
11
+ Record<"responseEngineRef" | "voiceRef" | "purpose" | "callbackOnly", string>
12
+ >;
13
+
14
+ export interface VoiceCapabilities {
15
+ dryRun: boolean;
16
+ numberProvisioning: "contact_loopable";
17
+ activation: boolean;
18
+ }
19
+
20
+ export interface VoiceAudienceOption {
21
+ key: string;
22
+ label: string;
23
+ views?: { id: string; label: string; revision?: string }[];
24
+ phoneFields?: { key: string; label: string }[];
25
+ }
26
+
27
+ export interface VoiceAgent {
28
+ automationId: string;
29
+ displayName: string;
30
+ agentType: "voice";
31
+ connectionStatus: string;
32
+ supportedConfiguration: VoiceSupportedConfiguration;
33
+ purpose: string;
34
+ callbackOnly: boolean;
35
+ activationState: string;
36
+ phoneBindings: VoicePhoneBinding[];
37
+ capabilities: VoiceCapabilities;
38
+ /** Server-composed choices; the browser never invents table/View/field IDs. */
39
+ audienceOptions?: { tables: VoiceAudienceOption[] };
40
+ }
41
+
42
+ export interface VoiceAgentList {
43
+ voiceAgents: VoiceAgent[];
44
+ }
45
+
46
+ export interface VoiceHarnessInput {
47
+ table: string;
48
+ viewId: string;
49
+ phoneField: string;
50
+ }
51
+
52
+ export interface VoiceHarnessResult {
53
+ noExternalDispatch: boolean;
54
+ preview?: {
55
+ displayName?: string;
56
+ maskedBindingCount?: number;
57
+ };
58
+ }
web/src/customer-grid/ColumnMenu.tsx CHANGED
@@ -53,6 +53,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;
@@ -294,6 +295,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
@@ -321,10 +326,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,
@@ -2138,6 +2143,8 @@ export default function ColumnMenu({
2138
  onUnpin,
2139
  onPeriod,
2140
  onDelete,
 
 
2141
  onRemoveFromMine,
2142
  onEnrich,
2143
  onDuplicate,
@@ -4174,11 +4181,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 +4201,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 +4258,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 +4375,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 +4403,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 +4540,11 @@ export default function ColumnMenu({
4514
  {presetRefusal}
4515
  </p>
4516
  )}
 
 
 
 
 
4517
  {!schemaLocked && offer.remove && onDelete && c1AllowsDelete && (
4518
  <button
4519
  type="button"
 
53
  import { validateFormula } from "./formulaEngine";
54
  import { BRAND_SWATCHES, defaultOptionColor, nearestSwatch, normalizeOptionColor,
55
  OPTION_PALETTE } from "./choiceColors";
56
+ import { FieldProperties, fieldDeletionLocked } from "./FieldProperties";
57
 
58
  export interface ColumnMenuState {
59
  fieldKey: string;
 
295
  * the control is not rendered at all, so a base field cannot even be offered the action.
296
  */
297
  onDelete?: () => void;
298
+ /** Owner-only change to C3's server-owned deletion lock. */
299
+ onSetDeletionLock?: (locked: boolean) => void;
300
+ /** Copies a canonical Data path that opens this field's properties. */
301
+ onCopyFieldLink?: () => void;
302
  /**
303
  * ⭐⭐ W41-T29 (R6(b)) — DROP A COLUMN SOMEBODY ELSE SHARED WITH ME, off my own list. A
304
  * DIFFERENT ACT from `onDelete`, and therefore a different door: it destroys no definition and
 
326
  onAggregate?: (agg: AggName | undefined) => void;
327
  /** Wave-5 item 1 — Sort by this field (replaces the view's sort), and the conditional
328
  * clears (item 3). All of these mutate the EXISTING view config — no new host surface. */
329
+ onSort?: (dir: "asc" | "desc") => void;
330
+ onClearSort?: () => void;
331
+ onFilterBy?: () => void;
332
+ onClearFilter?: () => void;
333
  onGroupByField: () => void;
334
  onClearGroup: () => void;
335
  /** Assignable people, from the host's real user list. Empty = the host did not supply one,
 
2143
  onUnpin,
2144
  onPeriod,
2145
  onDelete,
2146
+ onSetDeletionLock,
2147
+ onCopyFieldLink,
2148
  onRemoveFromMine,
2149
  onEnrich,
2150
  onDuplicate,
 
4181
  * `preset`, its Delete goes — which is R6(a) working, and worth a look before the wave closes.
4182
  */
4183
  const fieldC1 = fieldClassOf(field);
4184
+ const deletionLocked = fieldDeletionLocked(field);
4185
  const presetRefusal = deleteRefusalReason(fieldC1, viewer);
4186
  const canRemoveFromMine = mayRemoveField(fieldC1, viewer);
4187
  const rightsKnown = fieldC1 !== null && !!viewer;
4188
  const c1AllowsDelete =
4189
+ !deletionLocked && !presetRefusal && !canRemoveFromMine &&
4190
+ (!rightsKnown || mayDeleteFieldRight(fieldC1, viewer));
4191
  const deleteImpact = deleteImpactTitle(fieldC1, fieldUsageOf(field));
4192
 
4193
  return (
 
4201
  dataKind="column-menu"
4202
  >
4203
  <PaneHead title={field.label} sub={typeLine} onClose={onClose} />
4204
+ <FieldProperties field={field} />
4205
 
4206
  {/* Item 8c — any measure-carrying column exposes its PERIOD, the property that defines
4207
  it. Item 21 (2026-08-02) moved the EDITOR into the Edit-field pane; what stays here
 
4258
  row would leave a collaborator guessing why the column they can see is not theirs to
4259
  pass on. The one thing that DOES withdraw it is a missing server table key, because
4260
  without one the id cannot be built. */}
4261
+ {onSetDeletionLock && (
4262
+ <button type="button" onClick={() => onSetDeletionLock(!deletionLocked)}>
4263
+ <MenuLabel
4264
+ icon={deletionLocked ? "unlock" : "permissions"}
4265
+ text={deletionLocked ? "Clear deletion lock" : "Lock deletion"}
4266
+ />
4267
+ </button>
4268
+ )}
4269
+ {onCopyFieldLink && (
4270
+ <button type="button" onClick={onCopyFieldLink}>
4271
+ <MenuLabel icon="duplicate" text="Copy link to field" />
4272
+ </button>
4273
+ )}
4274
+
4275
  {shareOid && (
4276
  <button
4277
  type="button"
 
4375
  <div className="cg-menu-sep" role="separator" aria-hidden />
4376
 
4377
  {/* Group 3 — sort. Direction wording stays the shipped per-type directionLabel. */}
4378
+ {onSort && <>
4379
+ <button type="button" onClick={() => { onSort("asc"); onClose(); }}>
4380
+ <MenuLabel
4381
+ icon="sortAsc"
4382
+ text={`Sort ${directionLabel(field.type, "asc")}`}
4383
+ />
4384
+ </button>
4385
+ <button type="button" onClick={() => { onSort("desc"); onClose(); }}>
4386
+ <MenuLabel
4387
+ icon="sortDesc"
4388
+ text={`Sort ${directionLabel(field.type, "desc")}`}
4389
+ />
4390
+ </button>
4391
+ </>}
4392
+ {onClearSort && sortedDir != null && (
4393
  <button type="button" onClick={() => { onClearSort(); onClose(); }}>
4394
  <MenuLabel icon="off" text="Don't sort by this field" />
4395
  </button>
 
4403
  column itself (offered only while the host serves measures, the same
4404
  availability rule as measure conditions). Everything else keeps the plain
4405
  filterable check. */}
4406
+ {onFilterBy && (field.filterable !== false ||
4407
  (field.measure != null && measures.length > 0)) && (
4408
  <button type="button" onClick={() => { onFilterBy(); onClose(); }}>
4409
  <MenuLabel icon="filter" text="Filter by this field" />
4410
  </button>
4411
  )}
4412
+ {onClearFilter && isFiltered && (
4413
  <button type="button" onClick={() => { onClearFilter(); onClose(); }}>
4414
  <MenuLabel icon="off" text="Don't filter by this field" />
4415
  </button>
 
4540
  {presetRefusal}
4541
  </p>
4542
  )}
4543
+ {deletionLocked && !schemaLocked && offer.remove && onDelete && (
4544
+ <p className="cg-field-hint" style={{ padding: "2px 8px 4px" }}>
4545
+ Deletion is locked. An Owner must clear the deletion lock before this field can be deleted.
4546
+ </p>
4547
+ )}
4548
  {!schemaLocked && offer.remove && onDelete && c1AllowsDelete && (
4549
  <button
4550
  type="button"
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -104,8 +104,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";
@@ -196,6 +199,7 @@ import type {
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 +447,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
  *
@@ -926,6 +985,9 @@ 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
@@ -1072,6 +1134,8 @@ function CustomerGrid(props: CustomerGridProps = {}) {
1072
 
1073
  function CustomerGridSurface({
1074
  scope = "customer",
 
 
1075
  queryBinding,
1076
  embedded = false,
1077
  embeddedRecordIds,
@@ -1264,6 +1328,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 +1899,20 @@ function CustomerGridSurface({
1832
  },
1833
  [config.groupBy, isQueryPreview, queryBinding]
1834
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1835
  useEffect(() => {
1836
  if (!config.fullscreen) return;
1837
  const onKey = (event: KeyboardEvent) => {
@@ -2449,6 +2530,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 +2589,12 @@ function CustomerGridSurface({
2504
  : computedRows,
2505
  [cohortMode, computedRows, cohortMemberSet]
2506
  );
 
 
 
 
 
 
2507
 
2508
  const { visibleRows, pidToIndex } = useVisibleRows(
2509
  scopedRows,
@@ -2514,7 +2605,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,
@@ -4763,6 +4854,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 +4868,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 +4897,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 +5188,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 +5855,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 +6303,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
@@ -7183,6 +7399,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,9 +7435,11 @@ 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.
@@ -7247,7 +7481,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;
@@ -7696,6 +7934,10 @@ function CustomerGridSurface({
7696
  onAddToList={serverWindowed ? undefined : addToList}
7697
  today={today}
7698
  onExport={serverWindowed ? undefined : exportViewData}
 
 
 
 
7699
  folders={folders}
7700
  folderIdOf={folderIdOf}
7701
  /**
@@ -7977,6 +8219,18 @@ function CustomerGridSurface({
7977
  ) : null
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
@@ -8045,9 +8299,24 @@ 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 +8363,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
@@ -8837,6 +9100,7 @@ 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
@@ -9266,6 +9530,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
  //
@@ -9454,16 +9724,20 @@ 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 +9757,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 })}
 
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 { buildXlsxWorkbook, exportFilename, groupingApplies, runExport, toExportGroups, triggerDownload } from "./export";
108
  import type { ExportFormat, ExportGrouping } from "./export";
109
+ import { dataPathHash } from "./dataPath";
110
+ import type { DataPath } from "./dataPath";
111
+ import "../styles/wave44/data-workspace.css";
112
  // owner item 3 (2026-08-03) — a time-series view exports its SHEET, not the rows under it.
113
  import { buildTsCsv, tsSheetToTable } from "./timeSeriesData";
114
  import type { TsSheet } from "./timeSeriesData";
 
199
  Row,
200
  RowHeightMode,
201
  SavedView,
202
+ SortRule,
203
  ViewConfig,
204
  } from "./types";
205
  // Item 7 (C-TS). Default-exported because it is a leaf VIEW like MapView, and because RECORD
 
447
  return JSON.stringify(a) === JSON.stringify(b);
448
  }
449
 
450
+ /** C3 locks are present on the server projection, while the long-lived shared type remains
451
+ * deliberately backward-compatible. Keep that wire detail additive here rather than widening a
452
+ * cross-lane contract just to paint one property. */
453
+ type LockedFilterRule = FilterRule & { locked?: boolean };
454
+ type LockedSortRule = SortRule & { locked?: boolean };
455
+ type ManagedRouteClause = {
456
+ managedBy: "loopable";
457
+ kind: "route-membership";
458
+ operator: "or";
459
+ pids: number[];
460
+ };
461
+
462
+ function hasLockedFilter(nodes: FilterNode[]): boolean {
463
+ return nodes.some((node) =>
464
+ isFilterGroup(node)
465
+ ? hasLockedFilter(node.children)
466
+ : (node as LockedFilterRule).locked === true
467
+ );
468
+ }
469
+
470
+ function hasLockedSort(sorts: SortRule[]): boolean {
471
+ return sorts.some((sort) => (sort as LockedSortRule).locked === true);
472
+ }
473
+
474
+ /** A duplicate has a new View id, the one C3 alteration path. Preserve the actual rules but
475
+ * remove the immutable-record mark, so the new View does not inherit a false in-place refusal. */
476
+ function unlockedFilterCopy(nodes: FilterNode[]): FilterNode[] {
477
+ return nodes.map((node) => {
478
+ if (isFilterGroup(node)) return { ...node, children: unlockedFilterCopy(node.children) };
479
+ const { locked: _locked, ...rule } = node as LockedFilterRule;
480
+ return rule;
481
+ });
482
+ }
483
+
484
+ function unlockedViewConfigCopy(config: ViewConfig): ViewConfig {
485
+ return {
486
+ ...config,
487
+ filters: unlockedFilterCopy(config.filters),
488
+ sorts: config.sorts.map((sort) => {
489
+ const { locked: _locked, ...rule } = sort as LockedSortRule;
490
+ return rule;
491
+ }),
492
+ };
493
+ }
494
+
495
+ /** C2's server-issued clause is an OR inclusion. This reader validates only its declared shape;
496
+ * it never derives route membership from Map rows or ids. */
497
+ function managedRoutePids(value: unknown): number[] {
498
+ if (!value || typeof value !== "object") return [];
499
+ const clause = value as Partial<ManagedRouteClause>;
500
+ if (clause.managedBy !== "loopable" || clause.kind !== "route-membership" ||
501
+ clause.operator !== "or" || !Array.isArray(clause.pids)) return [];
502
+ return [...new Set(clause.pids.filter((pid): pid is number => Number.isInteger(pid)))];
503
+ }
504
+
505
  /**
506
  * ⭐ W41-T42 — the pivot's four states, and the fourth one is the point.
507
  *
 
985
  * re-renders for its own state (edits, resize) and remounts on route change via `key`. */
986
  interface CustomerGridProps {
987
  scope?: SurfaceScope;
988
+ /** Shell-owned Data workspace location; grid resolves its view/field, never the global rail. */
989
+ dataPath?: DataPath;
990
+ dataLabel?: string;
991
  /** A Query-owned immutable artefact. `scope` remains the renderer's mapped data scope. */
992
  queryBinding?: QueryVirtualBinding;
993
  /** Read-only Grid view embedded in a linked-record modal. It keeps the standard
 
1134
 
1135
  function CustomerGridSurface({
1136
  scope = "customer",
1137
+ dataPath,
1138
+ dataLabel,
1139
  queryBinding,
1140
  embedded = false,
1141
  embeddedRecordIds,
 
1328
  const [views, setViews] = useState<SavedView[]>([]);
1329
  const [activeViewId, setActiveViewId] = useState(ALL_VIEW_ID);
1330
  const [config, setConfig] = useState<ViewConfig>(() => defaultViewConfig([]));
1331
+ /** C2 membership is a server-approved, active-View-only inclusion. It deliberately does not
1332
+ * live in `config`: that object has a generic autosave effect for authored View changes. */
1333
+ const [managedRouteClause, setManagedRouteClause] = useState<unknown>(undefined);
1334
  /** W36-T02 — the live `config`, readable from an effect that must not DEPEND on it. The
1335
  * after-mount reconcile needs to know whether an edit is unsaved before it re-seeds the open
1336
  * view; taking `config` as a dependency would re-run that whole pass on every drag and
 
1899
  },
1900
  [config.groupBy, isQueryPreview, queryBinding]
1901
  );
1902
+ /** C2 returns the entire state so it can prove it did not rewrite user clauses. B consumes
1903
+ * exactly its managed addition/removal; filters, conjunction, user membership and every other
1904
+ * authored View key remain untouched. */
1905
+ const applyManagedRouteViewState = useCallback(
1906
+ (viewState: Record<string, unknown>) => {
1907
+ if (Object.prototype.hasOwnProperty.call(viewState, "managedRouteClause"))
1908
+ setManagedRouteClause(viewState.managedRouteClause);
1909
+ else
1910
+ setManagedRouteClause(undefined);
1911
+ },
1912
+ []
1913
+ );
1914
+ // A managed selection belongs to precisely one active View; opening another cannot carry it.
1915
+ useEffect(() => setManagedRouteClause(undefined), [activeViewId]);
1916
  useEffect(() => {
1917
  if (!config.fullscreen) return;
1918
  const onKey = (event: KeyboardEvent) => {
 
2530
  */
2531
  const applyFilters = useCallback(
2532
  (filters: FilterNode[]) => {
2533
+ if (hasLockedFilter(config.filters)) {
2534
+ signal(TOAST_EVENT, "These filters are locked. Copy this View to change them.");
2535
+ return;
2536
+ }
2537
  const id = activeViewId;
2538
  if (id) {
2539
  const cycle = viewFilterCycle(id, filters, (other) =>
 
2589
  : computedRows,
2590
  [cohortMode, computedRows, cohortMemberSet]
2591
  );
2592
+ // C2's server-minted membership is an OR inclusion, like the pipeline's view-pinned members,
2593
+ // but never becomes a user-authored `memberPids` edit.
2594
+ const effectiveMemberPids = useMemo(
2595
+ () => [...new Set([...(config.memberPids ?? []), ...managedRoutePids(managedRouteClause)])],
2596
+ [config.memberPids, managedRouteClause]
2597
+ );
2598
 
2599
  const { visibleRows, pidToIndex } = useVisibleRows(
2600
  scopedRows,
 
2605
  // grouping a WINDOW would headline a page's count/subtotals as the group's
2606
  serverWindowed ? null : config.groupBy,
2607
  collapsed,
2608
+ effectiveMemberPids,
2609
  config.filterConj,
2610
  serverWindowed,
2611
  measureSets,
 
4854
  setSearch("");
4855
  setDetailPid(null);
4856
  setDisplayCap(DISPLAY_PAGE);
4857
+ // A Data path is the shell's shareable location, not a second routing model. Keep it
4858
+ // canonical when a person switches views, while ordinary grid mounts remain hash-neutral.
4859
+ if (dataPath && typeof window !== "undefined") {
4860
+ const nextHash = dataPathHash({ ...dataPath, view: id });
4861
+ if (window.location.hash !== nextHash) window.location.hash = nextHash;
4862
+ }
4863
  // Owner item 3 (2026-07-31): tell the host WHERE THE USER IS, so a fresh browser (no
4864
  // localStorage copy) resumes on this view instead of the system default. Presentation
4865
  // state — the host stores the id and the read side re-validates it.
 
4868
  signal(NAV_MINIMIZE_EVENT);
4869
  },
4870
  [views, activeViewId, config, persistView, fields, isQueryPreview, recordStars.stars.view,
4871
+ scriptProjections, dataPath]
4872
  );
4873
 
4874
+ useEffect(() => {
4875
+ const viewId = dataPath?.view;
4876
+ if (!viewId || viewId === activeViewId) return;
4877
+ if (!views.some((view) => view.id === viewId)) return;
4878
+ selectView(viewId);
4879
+ }, [dataPath?.view, activeViewId, views, selectView]);
4880
+
4881
  /**
4882
  * A-S4-3 (item 25) — a notification's click-through. The SHELL routes to the table and fires
4883
  * this; the GRID owns view selection, so neither learns the other's state.
 
4897
  window.addEventListener(VIEW_OPEN_EVENT, onOpen);
4898
  return () => window.removeEventListener(VIEW_OPEN_EVENT, onOpen);
4899
  }, [scope, views, selectView]);
4900
+
4901
+ const addressedFieldRef = useRef<string | null>(null);
4902
+ useEffect(() => {
4903
+ const fieldKey = dataPath?.field;
4904
+ const address = fieldKey ? `${dataPath.database}:${fieldKey}` : null;
4905
+ if (!fieldKey || !address) {
4906
+ addressedFieldRef.current = null;
4907
+ return;
4908
+ }
4909
+ if (addressedFieldRef.current === address) return;
4910
+ if (!fields.some((field) => field.key === fieldKey)) return;
4911
+ const rect = gridBoxRef.current?.getBoundingClientRect();
4912
+ if (!rect) return;
4913
+ addressedFieldRef.current = address;
4914
+ setColumnMenu({
4915
+ fieldKey,
4916
+ anchor: {
4917
+ left: rect.left,
4918
+ top: rect.top,
4919
+ right: rect.right,
4920
+ bottom: rect.bottom,
4921
+ width: rect.width,
4922
+ height: rect.height,
4923
+ },
4924
+ });
4925
+ }, [dataPath?.database, dataPath?.field, fields]);
4926
  const createView = useCallback(
4927
  (name: string, mode: DisplayMode, permissions: ViewPermissions) => {
4928
  if (queryBinding) {
 
5188
  // Never echo the SOURCE's creator: the host stamps and ignores what the browser
5189
  // sends, but sending someone else's name is a laundering attempt on its face.
5190
  createdBy: undefined,
5191
+ config: unlockedViewConfigCopy(source.config),
5192
  };
5193
  persistView(copy);
5194
  setActiveViewId(copy.id);
 
5855
  [views, fields, computedRows, exportRows, activeViewId, today]
5856
  );
5857
 
5858
+ /** C3's selected-View export is evaluated server-side. The browser receives one already
5859
+ * evaluated fields/rows pair per requested View and gives those pairs, unchanged, to the sole
5860
+ * XLSX assembly writer. It never reuses the active View's loaded rows for another tab. */
5861
+ const exportSelectedViews = useCallback(
5862
+ async (viewIds: string[]) => {
5863
+ const ids = [...new Set(viewIds)];
5864
+ const visibleIds = new Set(views.map((view) => view.id));
5865
+ if (scope !== "customer" || embedded || isQueryPreview || ids.length < 1 || ids.length > 20 ||
5866
+ ids.some((id) => !visibleIds.has(id))) {
5867
+ signal(TOAST_EVENT, "Choose between one and twenty visible Views to export.");
5868
+ return;
5869
+ }
5870
+ try {
5871
+ const response = await fetch(`${API_V1}/customers/view-export`, {
5872
+ method: "POST",
5873
+ credentials: CREDENTIALS,
5874
+ headers: { "Content-Type": "application/json" },
5875
+ body: JSON.stringify({ viewIds: ids }),
5876
+ });
5877
+ const payload = await response.json().catch(() => null) as {
5878
+ today?: unknown;
5879
+ exports?: unknown;
5880
+ error?: { message?: unknown };
5881
+ } | null;
5882
+ if (!response.ok) {
5883
+ const message = typeof payload?.error?.message === "string"
5884
+ ? payload.error.message
5885
+ : "Selected Views could not be exported.";
5886
+ signal(TOAST_EVENT, message);
5887
+ return;
5888
+ }
5889
+ if (!Array.isArray(payload?.exports)) throw new Error("missing evaluated Views");
5890
+ const received = new Map<string, { name: string; fields: Field[]; rows: Row[] }>();
5891
+ for (const item of payload.exports) {
5892
+ if (!item || typeof item !== "object") throw new Error("invalid evaluated View");
5893
+ const candidate = item as {
5894
+ viewId?: unknown;
5895
+ name?: unknown;
5896
+ columns?: unknown;
5897
+ rows?: unknown;
5898
+ view?: unknown;
5899
+ };
5900
+ if (typeof candidate.viewId !== "string" || typeof candidate.name !== "string" ||
5901
+ !Array.isArray(candidate.columns) || !Array.isArray(candidate.rows) ||
5902
+ !candidate.view || typeof candidate.view !== "object" || received.has(candidate.viewId))
5903
+ throw new Error("invalid evaluated View");
5904
+ received.set(candidate.viewId, {
5905
+ name: candidate.name,
5906
+ fields: candidate.columns as Field[],
5907
+ rows: candidate.rows as Row[],
5908
+ });
5909
+ }
5910
+ if (received.size !== ids.length || ids.some((id) => !received.has(id)))
5911
+ throw new Error("incomplete evaluated Views");
5912
+ const sheets = ids.map((id) => received.get(id)!);
5913
+ const exportToday = typeof payload?.today === "string" ? payload.today : undefined;
5914
+ const bytes = buildXlsxWorkbook(sheets, exportToday);
5915
+ const blobBytes = new Uint8Array(bytes.byteLength);
5916
+ blobBytes.set(bytes);
5917
+ triggerDownload(
5918
+ exportFilename("Selected Views", exportToday, "xlsx"),
5919
+ new Blob([blobBytes.buffer], {
5920
+ type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
5921
+ })
5922
+ );
5923
+ } catch {
5924
+ signal(TOAST_EVENT, "Selected Views could not be exported.");
5925
+ }
5926
+ },
5927
+ [views, scope, embedded, isQueryPreview]
5928
+ );
5929
+
5930
  /**
5931
  * The selection bar's "Add to locked view": exactly the CHECKED customers, not a view's
5932
  * matches.
 
6303
  [isUserTable, scope]
6304
  );
6305
 
6306
+ // C3 owns both the state and the wall. `session.admin` is its current Owner mapping;
6307
+ // this client gate only avoids advertising a PATCH the server will refuse.
6308
+ const setDeletionLock = useCallback(
6309
+ (key: string, deletionLocked: boolean) => {
6310
+ if (!isUserTable || !viewer?.isAdmin) return;
6311
+ void patchTableField(scope, key, { deletionLocked }).then((made) => {
6312
+ if (!made) return;
6313
+ setFields((current) => current.map((f) => (f.key === made.key ? made : f)));
6314
+ signal(WORKSPACE_STALE_EVENT);
6315
+ });
6316
+ },
6317
+ [isUserTable, scope, viewer?.isAdmin]
6318
+ );
6319
+
6320
  /**
6321
  * Owner item 9 — "Change field": the clicked column starts showing another field, in place.
6322
  * The new field takes the old one's slot in `order`; the old field is HIDDEN, not lost — it
 
7399
  };
7400
  }, [pivotRequestBody]);
7401
 
7402
+ const copyFieldDataLink = useCallback(
7403
+ (fieldKey: string) => {
7404
+ if (typeof window === "undefined" || !navigator.clipboard) {
7405
+ signal(TOAST_EVENT, "Copying a field link is unavailable in this browser.");
7406
+ return;
7407
+ }
7408
+ const hash = dataPathHash({ database: topic.key, view: activeViewId, field: fieldKey });
7409
+ const url = new URL(hash, window.location.href).toString();
7410
+ void navigator.clipboard.writeText(url).then(
7411
+ () => signal(TOAST_EVENT, "Copied link to field."),
7412
+ () => signal(TOAST_EVENT, "Could not copy the field link.")
7413
+ );
7414
+ },
7415
+ [topic.key, activeViewId]
7416
+ );
7417
+
7418
  if (loading || !workspaceReady) {
7419
  /* wave17 GRID — item 3 / owner R6: one small bare rotating icon, NO WORDS. `aria-label`
7420
  is not a word on screen and stays: `.lp-spin` is an empty span, so without it the wait
 
7435
  name: viewDisplayName(activeView),
7436
  // The API compares this complete saved config to its visible View and mints the durable
7437
  // revision itself. A browser may carry provenance, never choose it.
7438
+ config,
7439
  }
7440
  : null;
7441
+ const activeFiltersLocked = hasLockedFilter(config.filters);
7442
+ const activeSortsLocked = hasLockedSort(config.sorts);
7443
  // Cohort mode's toolbar control (rendered by Toolbar via the `cohortAction` slot; the popover
7444
  // it opens is with the other overlays at the bottom). Disabled without an active cohort —
7445
  // zero cohorts is the host page's near-empty state, not this button's error to explain.
 
7481
  */
7482
  const deletableKeys = new Set(
7483
  fields
7484
+ .filter(
7485
+ (f) =>
7486
+ !((f as Field & { deletionLocked?: boolean }).deletionLocked) &&
7487
+ (f.custom || (f.shared && f.kind === "route_order")) && f.key !== lockedKey
7488
+ )
7489
  .map((f) => f.key)
7490
  );
7491
  const menuField = columnMenu ? fieldByKey.get(columnMenu.fieldKey) : undefined;
 
7934
  onAddToList={serverWindowed ? undefined : addToList}
7935
  today={today}
7936
  onExport={serverWindowed ? undefined : exportViewData}
7937
+ onExportXlsxViews={
7938
+ scope === "customer" && !embedded && !isQueryPreview ? exportSelectedViews : undefined
7939
+ }
7940
+ exportableViewIds={views.map((view) => view.id)}
7941
  folders={folders}
7942
  folderIdOf={folderIdOf}
7943
  /**
 
8219
  ) : null
8220
  )}
8221
  <main className="cg-main">
8222
+ {dataPath && (
8223
+ <nav className="cg-data-path" aria-label="Data path">
8224
+ <span>Data</span>
8225
+ <span aria-hidden>›</span>
8226
+ <span>{dataLabel ?? topic.key}</span>
8227
+ <span aria-hidden>›</span>
8228
+ <span>{viewDisplayName(views.find((view) => view.id === activeViewId) ?? {
8229
+ id: activeViewId,
8230
+ name: activeViewId,
8231
+ })}</span>
8232
+ </nav>
8233
+ )}
8234
  <Toolbar
8235
  nouns={topic.nouns}
8236
  // Item 12 (C-LOCK) — the banner's copy. ⚠ BOTH fields are omitted when this reader
 
8299
  filters={config.filters}
8300
  onFilters={applyFilters}
8301
  filterConj={config.filterConj ?? "and"}
8302
+ onFilterConj={(filterConj) => {
8303
+ if (activeFiltersLocked) {
8304
+ signal(TOAST_EVENT, "These filters are locked. Copy this View to change them.");
8305
+ return;
8306
+ }
8307
+ updateConfig({ ...config, filterConj });
8308
+ }}
8309
+ filtersLocked={activeFiltersLocked}
8310
  sorts={config.sorts}
8311
+ onSorts={(sorts) => {
8312
+ if (activeSortsLocked) {
8313
+ signal(TOAST_EVENT, "These sorts are locked. Copy this View to change them.");
8314
+ return;
8315
+ }
8316
+ updateConfig({ ...config, sorts });
8317
+ }}
8318
+ sortsLocked={activeSortsLocked}
8319
+ onCopyToChange={() => duplicateView(activeViewId)}
8320
  // the toolbar must not advertise a grouping the pipeline is not applying
8321
  groupBy={serverWindowed ? null : config.groupBy}
8322
  onGroupBy={(groupBy) => updateConfig({ ...config, groupBy })}
 
8363
  onRelationalWindow={setPivotWindow}
8364
  sourceLabel={topic.nouns}
8365
  onViewActions={setViewActionsAnchor}
8366
+ fullscreen={!!config.fullscreen}
8367
+ onFullscreen={() => updateConfig({ ...config, fullscreen: !config.fullscreen })}
8368
  />
 
 
 
 
 
 
 
 
8369
  {/* ⭐ R11's SECOND ROW — live, on the pivoted database. It renders only once the pivot has
8370
  actually been SERVED, which is the house posture for a control whose other half may
8371
  not be wired yet: absent beats present-and-inert. A control row over a database whose
 
9100
  routePanelOpen={routePanelOpen}
9101
  activeView={routeSourceView}
9102
  tableKey={topic.key}
9103
+ onManagedRouteViewState={applyManagedRouteViewState}
9104
  /* ⭐ OWNER ITEM 9 — the route's "Add a record" search reaches PAST the view's own
9105
  filter, so it is handed `scopedRows`: the book after the row wall (`allowed_pids`
9106
  plus the business-unit scope) and before `useVisibleRows` applies filters, search
 
9530
  }
9531
  onProfileFlag={isUserTable ? setProfileFlag : undefined}
9532
  onFieldConfig={isUserTable ? (patch) => setFieldConfig(menuField.key, patch) : undefined}
9533
+ onSetDeletionLock={
9534
+ isUserTable && viewer?.isAdmin
9535
+ ? (deletionLocked) => setDeletionLock(menuField.key, deletionLocked)
9536
+ : undefined
9537
+ }
9538
+ onCopyFieldLink={() => copyFieldDataLink(menuField.key)}
9539
  onRetype={
9540
  // Item 2 — a CREATED field retypes IN PLACE from the pane.
9541
  //
 
9724
  ? setFieldConfig(menuField.key, { agg: agg ?? "" })
9725
  : saveField({ ...menuField, agg })
9726
  }
9727
+ onSort={
9728
+ activeSortsLocked
9729
+ ? undefined
9730
+ : (dir) => updateConfig({ ...config, sorts: [{ colId: menuField.key, dir }] })
9731
  }
9732
+ onClearSort={
9733
+ activeSortsLocked
9734
+ ? undefined
9735
+ : () => updateConfig({
9736
+ ...config,
9737
+ sorts: config.sorts.filter((s) => s.colId !== menuField.key),
9738
+ })
9739
  }
9740
+ onFilterBy={activeFiltersLocked ? undefined : () =>
9741
  // Item 6c — a MEASURE-carrying column seeds the equivalent MEASURE condition
9742
  // (same measure key + window, value empty); every other filterable column seeds
9743
  // an ordinary column condition. Same signal, one consumer (the Toolbar).
 
9757
  }
9758
  onUnpin={frozenN > 1 ? unpinFields : undefined}
9759
  scopeChoice={scopeChoice}
9760
+ onClearFilter={
9761
+ activeFiltersLocked
9762
+ ? undefined
9763
+ : () => updateConfig({
9764
+ ...config,
9765
+ filters: dropFieldFromTree(config.filters, menuField.key, measureCols),
9766
+ })
9767
  }
9768
  onGroupByField={() => updateConfig({ ...config, groupBy: menuField.key })}
9769
  onClearGroup={() => updateConfig({ ...config, groupBy: null })}
web/src/customer-grid/FieldProperties.tsx ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Field } from "./types";
2
+
3
+ /** C3's server-owned field facts are intentionally read, never inferred client-side. */
4
+ type ContractField = Field & {
5
+ origin?: string;
6
+ valueAuthority?: string;
7
+ scope?: string;
8
+ deletionLocked?: boolean;
9
+ limits?: { maxOptions?: number };
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
+ {typeof contract.limits?.maxOptions === "number" && (
37
+ <div>
38
+ <dt>Maximum options</dt>
39
+ <dd>{contract.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/MapView.tsx CHANGED
@@ -92,7 +92,10 @@ import {
92
  zoomLimits,
93
  } from "./mapProjection";
94
  import type { GeoStop, Pt, RouteStamp, View } from "./mapProjection";
95
- import { LP_INK, LP_MAP_SELECTED } from "./theme";
 
 
 
96
  import "./map.css";
97
 
98
  /**
@@ -293,14 +296,15 @@ interface RouteDepot {
293
  }
294
 
295
  /**
296
- * The pin palette: C1's cycle (blue -> green -> yellow -> red) then its
 
297
  * 20%-darkened variants, exactly as the contract specifies for series colour.
298
  * `fill` is the pastel; `line` is a darker companion, because a C1 pastel
299
  * measures 1.4-1.9:1 on white and a fill alone would be a smudge (the same
300
  * measurement that drove the I7c amendment).
301
  */
302
  const SERIES: { fill: string; line: string }[] = [
303
- { fill: "#9DBFF2", line: "#5F7FB0" },
304
  { fill: "#A5D8B4", line: "#5E9C74" },
305
  { fill: "#F5D989", line: "#B39A46" },
306
  { fill: "#F0A8A0", line: "#B76D65" },
@@ -312,9 +316,9 @@ const SERIES: { fill: string; line: string }[] = [
312
  /** Anything past the palette, plus the blank bucket. Neutral ON PURPOSE: a
313
  * ninth colour that repeats the first would make two meanings look identical. */
314
  const OVERFLOW = { fill: "#D7DBE3", line: "#8A909C" };
315
- const DEFAULT_PIN = { fill: "#9DBFF2", line: "#4F6079" };
316
  const ZONE_COLOR_CHOICES = [
317
- { value: "#9DBFF2", label: "Blue" },
318
  { value: "#A5D8B4", label: "Green" },
319
  { value: "#F5D989", label: "Yellow" },
320
  { value: "#F0A8A0", label: "Red" },
@@ -352,6 +356,8 @@ interface MapZone {
352
  visible: boolean;
353
  geographicField: string;
354
  memberships: number[];
 
 
355
  createdBy?: string;
356
  createdAt?: string;
357
  }
@@ -431,6 +437,7 @@ export function MapView({
431
  allRows,
432
  activeView,
433
  tableKey,
 
434
  }: {
435
  /** DISTINCT data rows from the full pipeline, overlay edits layered — the
436
  * calendar/kanban contract, verbatim. */
@@ -472,6 +479,8 @@ export function MapView({
472
  activeView: RouteSourceView | null;
473
  /** Canonical database identity for durable, table-scoped Zones. */
474
  tableKey: string;
 
 
475
  /**
476
  * ⭐⭐ OWNER ITEM 9 — THE WHOLE BOOK, so a stop can be added that the VIEW filtered out.
477
  *
@@ -489,7 +498,6 @@ export function MapView({
489
  const [routeOn, setRouteOn] = useState(false);
490
  /** Route navigation is an index first; planning begins only after the explicit Create route
491
  * action or an existing saved route has been opened. */
492
- const [routeCreateOpen, setRouteCreateOpen] = useState(false);
493
  const [roundTrip, setRoundTrip] = useState(false);
494
  const [routeStartPid, setRouteStartPid] = useState<number | null>(null);
495
  const askRoadRef = useRef(false);
@@ -533,18 +541,29 @@ export function MapView({
533
  /** C3 Zone chooser/editor state. `null` means the tenant read has not answered; an empty
534
  * array is an honest, editable no-Zones state. */
535
  const [zones, setZones] = useState<MapZone[] | null>(null);
 
 
 
 
 
536
  const [activeZoneIds, setActiveZoneIds] = useState<ReadonlySet<string>>(new Set());
537
  const [zoneChooserOpen, setZoneChooserOpen] = useState(false);
 
538
  const [zoneEditorId, setZoneEditorId] = useState("");
539
  const [zoneName, setZoneName] = useState("");
540
  const [zoneColor, setZoneColor] = useState(ZONE_COLOR_CHOICES[0].value);
541
  const [zoneGeographicField, setZoneGeographicField] = useState("");
542
  const [zoneGeographicValue, setZoneGeographicValue] = useState("");
 
543
  const [drawnZoneGeometry, setDrawnZoneGeometry] = useState<ZoneGeometry | null>(null);
544
  const [zoneMove, setZoneMove] = useState<ZoneMove | null>(null);
545
  const [zoneGeometryDraft, setZoneGeometryDraft] = useState<{ id: string; geometry: ZoneGeometry } | null>(null);
546
  const [zoneBusy, setZoneBusy] = useState(false);
547
  const [zoneErr, setZoneErr] = useState<string | null>(null);
 
 
 
 
548
  /**
549
  * W37-T36 — the ROAD answer, which is the half arithmetic cannot produce.
550
  *
@@ -836,6 +855,99 @@ export function MapView({
836
  }
837
  }, [tableKey]);
838
  useEffect(() => { void loadZones(); }, [loadZones]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
839
 
840
  const activeZones = useMemo(
841
  () => (zones || []).filter((zone) => zone.visible && activeZoneIds.has(zone.id)),
@@ -846,6 +958,24 @@ export function MapView({
846
  for (const zone of activeZones) for (const pid of zone.memberships || []) pids.add(pid);
847
  return pids;
848
  }, [activeZones]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
849
  const zoneEditor = useMemo(
850
  () => (zones || []).find((zone) => zone.id === zoneEditorId) || null,
851
  [zones, zoneEditorId]
@@ -874,6 +1004,7 @@ export function MapView({
874
  setZoneName(zone.name);
875
  setZoneColor(zone.color);
876
  setZoneGeographicField(zone.geographicField || "");
 
877
  }
878
  }, [activeZoneIds, zones, selectedPids, onSelectPids]);
879
  const zonePolygons = useMemo(() => activeZones.flatMap((zone) => {
@@ -932,6 +1063,7 @@ export function MapView({
932
  geometryGeoJson,
933
  visible: existing?.visible ?? true,
934
  geographicField: zoneGeographicField,
 
935
  memberships: [...selectedPids],
936
  }),
937
  });
@@ -955,7 +1087,7 @@ export function MapView({
955
  } finally {
956
  setZoneBusy(false);
957
  }
958
- }, [selectionZoneGeometry, zoneName, zoneColor, zoneGeographicField, selectedPids, tableKey]);
959
 
960
  const setZoneVisible = useCallback(async (zone: MapZone, visible: boolean) => {
961
  setZoneBusy(true);
@@ -1913,6 +2045,18 @@ export function MapView({
1913
  [plan]
1914
  );
1915
 
 
 
 
 
 
 
 
 
 
 
 
 
1916
  const paint = useCallback(
1917
  (p: MapPoint) => {
1918
  if (!colorBuckets) return DEFAULT_PIN;
@@ -2399,6 +2543,11 @@ export function MapView({
2399
  </a>
2400
  </span>
2401
  )}
 
 
 
 
 
2402
  {/* ═══════════════════════════════════════════════════════════════════════════════════
2403
  THE ROUTE PANEL — rebuilt for owner items 2, 4, 6, 8 and 9.
2404
 
@@ -2415,759 +2564,30 @@ export function MapView({
2415
  body was behind the two-selected wall this item removes; `plan.ordered[0]` with nothing
2416
  selected is a crash, not a blank.
2417
  ═══════════════════════════════════════════════════════════════════════════════════ */}
2418
- {routePanelOpen && !routeCreateOpen && (
2419
  <aside id="cg-route-popover" className="cg-route-popover cg-route-nav-panel cg-route-index" aria-label="Routes">
2420
- <div className="cg-route-popover-head">
2421
- <span className="cg-views-title">Routes</span>
2422
- <button
2423
- type="button"
2424
- className="cg-route-index-create"
2425
- onClick={() => {
2426
- setOpenedRoute("");
2427
- setSaveTarget("");
2428
- setRouteOn(false);
2429
- setRouteOrder(null);
2430
- setRouteCreateOpen(true);
2431
- }}
2432
- >
2433
- Create route
2434
- </button>
2435
- </div>
2436
- {routeCols === null ? (
2437
- <span className="cg-route-index-empty">Loading routes.</span>
2438
- ) : routeCols.length === 0 ? (
2439
- <span className="cg-route-index-empty">No routes yet. Create one from selected map records.</span>
2440
- ) : (
2441
- <div className="cg-route-index-list">
2442
- {routeCols.map((route) => (
2443
- <div className="cg-route-index-row" key={route.key}>
2444
- <button
2445
- type="button"
2446
- className="cg-route-index-name"
2447
- onClick={() => {
2448
- setRouteCreateOpen(true);
2449
- openSavedRoute(route.key);
2450
- }}
2451
- title={`Open ${route.label}`}
2452
- >
2453
- {route.label}
2454
- </button>
2455
- {route.mine && (
2456
- <button
2457
- type="button"
2458
- className="cg-route-index-gear"
2459
- aria-label={`Edit ${route.label}`}
2460
- title={`Edit ${route.label}`}
2461
- onClick={() => {
2462
- setRouteEditErr(null);
2463
- setRouteEditKey(route.key);
2464
- setRouteEditName(route.label);
2465
- setRouteEditNote(route.note || "");
2466
- }}
2467
- >
2468
- <svg viewBox="0 0 16 16" aria-hidden="true">
2469
- <path d="M6.5 2.2h3l.5 1.6 1.5.9 1.6-.4 1.5 2.6-1.2 1.1v1.8l1.2 1.1-1.5 2.6-1.6-.4-1.5.9-.5 1.6h-3L6 14l-1.5-.9-1.6.4-1.5-2.6 1.2-1.1V7.9L2.4 6.8l1.5-2.6 1.6.4L6 3.8z" />
2470
- <circle cx="8" cy="8.8" r="2.1" />
2471
- </svg>
2472
- </button>
2473
- )}
2474
- <span className="cg-route-index-detail">
2475
- {typeof route.stops === "number" ? `${route.stops.toLocaleString()} stops` : "Route"}
2476
- {route.solvedBy ? ` · ${route.solvedBy}` : ""}
2477
- {route.solvedAt ? ` · ${route.solvedAt.slice(0, 10)}` : ""}
2478
- </span>
2479
- {route.note && <span className="cg-route-index-detail">{route.note}</span>}
2480
- {routeEditKey === route.key && (
2481
- <div className="cg-route-index-edit" role="group" aria-label={`Edit ${route.label}`}>
2482
- <input
2483
- className="cg-input"
2484
- value={routeEditName}
2485
- aria-label="Route name"
2486
- maxLength={120}
2487
- onChange={(event) => setRouteEditName(event.target.value)}
2488
- />
2489
- <input
2490
- className="cg-input"
2491
- value={routeEditNote}
2492
- aria-label="Route details"
2493
- placeholder="Details"
2494
- maxLength={240}
2495
- onChange={(event) => setRouteEditNote(event.target.value)}
2496
- />
2497
- <span className="cg-route-index-actions">
2498
- <button type="button" className="cg-btn cg-btn--primary" disabled={routeEditBusy || !routeEditName.trim()} onClick={() => void updateRouteDetails()}>
2499
- {routeEditBusy ? "Saving" : "Save"}
2500
- </button>
2501
- <button type="button" className="cg-btn" onClick={() => setRouteEditKey("")}>Cancel</button>
2502
- </span>
2503
- {routeEditErr && <span className="cg-cal-nodate">{routeEditErr}</span>}
2504
- </div>
2505
- )}
2506
- </div>
2507
- ))}
2508
- </div>
2509
- )}
2510
- {routeDeliveries && routeDeliveries.length > 0 && (
2511
- <div className="cg-route-index-schedules" aria-label="Scheduled routes">
2512
- <span className="cg-route-index-label">Scheduled</span>
2513
- {routeDeliveries.map((delivery) => (
2514
- <span className="cg-route-index-detail" key={delivery.id}>
2515
- {delivery.name} · {delivery.recipient} · {delivery.snapshot.orderedStopIds.length.toLocaleString()} stops
2516
- </span>
2517
- ))}
2518
- </div>
2519
  )}
2520
  </aside>
2521
  )}
2522
- {routePanelOpen && routeCreateOpen && (
2523
- <aside id="cg-route-popover" className="cg-route-popover cg-route-nav-panel" aria-label="Route navigation">
2524
- <div className="cg-route-popover-head">
2525
- <button
2526
- type="button"
2527
- className="cg-route-index-back"
2528
- onClick={() => setRouteCreateOpen(false)}
2529
- title="Back to routes"
2530
- >
2531
- Routes
2532
- </button>
2533
- <span className="cg-route-popover-count">
2534
- {selectedPids.size > 0
2535
- ? `${selectedPids.size.toLocaleString()} selected`
2536
- : "Nothing selected"}
2537
- </span>
2538
- </div>
2539
- <div className="cg-map-route">
2540
- {/* ══ OWNER, 2026-08-23 — CHOOSE WHICH SAVED ROUTE TO LOOK AT ══════════════════
2541
- Owner: *"when I click the Route navigation button. I should be able to choose any
2542
- Route field I want to see the Routes."*
2543
- ⛔ FIRST IN THE PANEL, AND OUTSIDE `plan &&`. Opening somebody's saved plan is
2544
- how this surface starts for a rep driving a day that was planned for them; it
2545
- cannot sit behind having already solved a route of your own.
2546
- ⛔ EVERY route this account may see, `mine` or not — `GET /customers/route-order`
2547
- has already applied the per-field wall, so what is listed here is exactly what
2548
- the grid would show. Whether you may RE-SOLVE one is a different question, and
2549
- it is answered by the saved route's own edit flow, never by a second selector. */}
2550
- {(routeCols || []).length > 0 && (
2551
- <>
2552
- <label className="cg-map-route-opt cg-route-field">
2553
- Saved route
2554
- <select
2555
- className="cg-route-select"
2556
- value={openedRoute}
2557
- aria-label="Which saved route to show on the map"
2558
- onChange={(e) => openSavedRoute(e.target.value)}
2559
- >
2560
- <option value="">Choose a route to show</option>
2561
- {(routeCols || []).map((f) => (
2562
- <option key={f.key} value={f.key}>
2563
- {f.label}
2564
- </option>
2565
- ))}
2566
- </select>
2567
- </label>
2568
- {openErr && <span className="cg-cal-nodate">{openErr}</span>}
2569
- {/* ⛔⛔ SAID OUT LOUD, BECAUSE THE FOOT BUTTON DOES SOMETHING ELSE THAN IT
2570
- LOOKS LIKE HERE. Opening a route this account cannot re-solve leaves
2571
- `saveTarget` empty, so the primary button at the foot reads "Save route"
2572
- and mints a NEW column rather than touching the one on screen. That is a
2573
- real and useful act — take a colleague's Monday, reorder it, keep your own
2574
- copy — and it is the only one the server will allow (`route_order_write`
2575
- is creator-or-admin for a re-solve). What would be wrong is doing it
2576
- SILENTLY under a button whose position implies it acts on what is open.
2577
- ⚠ Gated on a route being open AND not mine, so the sentence appears only
2578
- in the situation it describes. */}
2579
- {openedRoute &&
2580
- (routeCols || []).some((f) => f.key === openedRoute && !f.mine) && (
2581
- <span className="cg-map-route-note">
2582
- You can open this route but not re-solve it, so Save route below will
2583
- create a new route of your own rather than change this one.
2584
- </span>
2585
- )}
2586
- </>
2587
- )}
2588
-
2589
- {/* ── the answer, or what is still missing ───────────────────────────────────── */}
2590
- {plan ? (
2591
- <span className="cg-map-route-sum">
2592
- <strong>{plan.customerStops.toLocaleString()}</strong> visits
2593
- {plan.depot ? " + depot" : ""} ·{" "}
2594
- {/* ⭐ W37-T36 — THE ROAD ANSWER REPLACES THE STRAIGHT LINE WHEN WE HOLD ONE,
2595
- and the caveat goes with it: which claim is on screen depends on which
2596
- answer we have, so the number and its qualifier move together.
2597
- ⭐ ITEM 7 — and the qualifier now names the MODE the server actually
2598
- answered in (`road.mode`), never the toggle's current position. */}
2599
- {road && !roadStale ? (
2600
- <>
2601
- {road.km.toLocaleString()} km · {formatDuration(road.minutes)}
2602
- <span className="cg-map-route-note">
2603
- {road.mode === "walking" ? " on foot" : " by road"}
2604
- </span>
2605
- </>
2606
- ) : (
2607
- <>
2608
- {Math.round(plan.km).toLocaleString()} km
2609
- <span className="cg-map-route-note">
2610
- {roadBusy
2611
- ? " working out the travelling route"
2612
- : roadStale
2613
- ? " straight line. The stops or the travel mode moved, so the route below is out of date."
2614
- : " straight line, not travelling distance"}
2615
- </span>
2616
- </>
2617
- )}
2618
- </span>
2619
- ) : (
2620
- <span className="cg-route-empty">
2621
- {/* ⚠ THREE STATES, NOT TWO, AND THE MIDDLE ONE IS THE X BUTTON'S LANDING SPOT.
2622
- Removing stops until one is left drops `customerRoutable` below two, and the
2623
- teardown effect then clears `routeOn` and the hand-picked order: correct,
2624
- because one stop is not a route. But "No stops yet" over a selection of one
2625
- is simply false, and it is exactly what a person sees right after using the
2626
- new X control. Each state says what is actually true. */}
2627
- {selectedPids.size === 0
2628
- ? "No stops yet. Search for a record below, or shift-click pins on the map."
2629
- : customerRoutable.length < 2
2630
- ? "A route needs at least two stops with a location. Add another record below."
2631
- : "Ready to plan."}
2632
- </span>
2633
- )}
2634
-
2635
- {/* ── ITEM 7: driving or walking ─────────────────────────────────────────────────
2636
- ⛔ THE MODES COME FROM THE SERVER. A deployment with no walking router must not
2637
- be offered a Walking button that spends a click to earn an error, so an
2638
- unavailable mode renders DISABLED with the reason on it rather than vanishing:
2639
- a control that disappears reads as a feature we do not have, and this one we do.
2640
- ⚠ Flipping the mode does NOT re-ask on its own (R3: a request is spent by a
2641
- click, never by a state change). It stales the drawn road, and the re-ask button
2642
- below appears. */}
2643
- <div className="cg-route-modes" role="group" aria-label="Travel mode">
2644
- {travelModes.map((m) => (
2645
- <button
2646
- key={m.key}
2647
- type="button"
2648
- className={"cg-route-mode" + (travelMode === m.key ? " is-on" : "")}
2649
- aria-pressed={travelMode === m.key}
2650
- disabled={!m.available}
2651
- title={
2652
- m.available
2653
- ? m.key === "walking"
2654
- ? "Work the route out at walking pace, on paths a car cannot take"
2655
- : "Work the route out by road, at driving pace"
2656
- : `This deployment has no ${m.label.toLowerCase()} routing service configured.`
2657
- }
2658
- onClick={() => setTravelMode(m.key)}
2659
- >
2660
- {m.label}
2661
- </button>
2662
- ))}
2663
- </div>
2664
-
2665
- {/* ── plan it ───────────────────────────────────────────────────────────────────
2666
- ⭐ WAVE 41 / R13 — ONCE THE PLANNER IS ON, THIS SLOT IS EMPTY AND THAT IS THE
2667
- POINT. It used to be a ternary: unrouted it offered `Plan route`, and routed it
2668
- offered a second, loose, full-width button that re-asked the routing service for
2669
- road geometry without touching the stop order. R13 folded that half into
2670
- `Update calculation` in the foot row, where the other committing controls live,
2671
- so a person is never choosing between two buttons whose difference the panel
2672
- could not explain. */}
2673
- {!routeOn && (
2674
- <button
2675
- type="button"
2676
- className="cg-btn cg-btn--primary cg-route-cta"
2677
- // ⭐ ONE CLICK IS THE WHOLE ASK (R3). It turns the planner on AND fetches the
2678
- // road answer, because "plan this and show me the distance" is one action to a
2679
- // person and should not be two buttons.
2680
- onClick={() => {
2681
- setRouteOn(true);
2682
- setRouteOrder(null);
2683
- askRoadRef.current = true;
2684
- }}
2685
- disabled={customerRoutable.length < 2}
2686
- title={
2687
- customerRoutable.length < 2
2688
- ? "At least two records with a location are needed to plan a route"
2689
- : "Order these stops into a route"
2690
- }
2691
- >
2692
- {customerRoutable.length < 2
2693
- ? "Plan route"
2694
- : `Plan route (${customerRoutable.length.toLocaleString()} stops)`}
2695
- </button>
2696
- )}
2697
- {roadErr && <span className="cg-cal-nodate">{roadErr}</span>}
2698
-
2699
- {/* ⛔⛔ STANDING RULE 1's SECOND SENTENCE, WHICH IS THE HALF THAT GETS DROPPED: a
2700
- limit that cannot be removed is REPORTED, with its cause and what to do about
2701
- it, never silently enforced. Two different sentences because they are two
2702
- different situations and only one of them is the user's doing.
2703
- ⚠ NOT a `cg-cal-nodate` (the red one). Neither of these is an error: the first
2704
- says what the panel took on the user's behalf, the second warns about a click
2705
- that has not been spent yet. */}
2706
- {customerRoutable.length > ROUTE_STOP_CAP && (
2707
- <span className="cg-map-route-note">
2708
- {customerRoutable.length.toLocaleString()} stops selected. The routing service
2709
- takes {ROUTE_STOP_CAP.toLocaleString()} in one request, so it will refuse the
2710
- road answer for this many. The sequence and the straight line estimate below
2711
- still hold.
2712
- </span>
2713
- )}
2714
-
2715
- {/* ══ OWNER ITEM 3b (2026-08-23) — THE TWO CONTROLS THAT SET UP A ROUTE COME FIRST ══
2716
- Owner: *"add a record AND visit order function should be moved to the top, above
2717
- the Start section of the Route navigation."* They used to sit BELOW the stop list,
2718
- which put the two things you reach for while building a route (bring another
2719
- customer in; choose the column the numbers land in) behind a list that is 66 rows
2720
- long on a real day.
2721
- ⚠ THE SAVE BUTTON AND THE GOOGLE LINKS TRAVEL WITH THE SELECT, not with the old
2722
- position. Their note below says position is part of the instruction: the links sit
2723
- BETWEEN the select and its Save button so the block reads as one committing step.
2724
- Splitting them here to leave Save at the bottom would break the older instruction
2725
- while honouring the newer one. ══ */}
2726
- {/* ── ITEM 9: add a record the view is not showing ────────────────────────────── */}
2727
- <button
2728
- type="button"
2729
- className="cg-btn"
2730
- disabled={rows.length === 0}
2731
- onClick={selectFilteredRouteRecords}
2732
- title="Select every record currently matched by this View and plan the route"
2733
- >
2734
- Select all {rows.length.toLocaleString()} filtered records
2735
- </button>
2736
- {allRows && allRows.length > 0 && (
2737
- <RecordPicker
2738
- label="Add a record"
2739
- placeholder="Search the database"
2740
- emptyNote="Every record in your book is already on this route."
2741
- options={addableRecords}
2742
- onPick={addRecord}
2743
- />
2744
- )}
2745
-
2746
- {/* ── ITEM 8: the visit order field, and its committing button ──────────────────
2747
- ⭐⭐ W38-T20 — THE ORDER BECOMES A COLUMN EVERY PERMITTED COLLEAGUE READS.
2748
- The number written per record is the INVERSE of the planner's permutation (see
2749
- `saveRouteOrder`), the field is tenant-wide and grant-governed, and the
2750
- fingerprint it was solved from rides it so a later reader is TOLD it is out of
2751
- date rather than shown yesterday's numbers as today's.
2752
- ⭐ ITEM 8 — "New column" reads "New field": `ColumnMenu` calls these fields
2753
- everywhere else, and one surface calling them columns is the kind of split
2754
- vocabulary a person has to translate. The SERVER key is untouched. */}
2755
- {plan && (
2756
- <>
2757
- <span className="cg-map-route-note">
2758
- {saveTarget
2759
- ? `Updating ${(routeCols || []).find((route) => route.key === saveTarget)?.label || "this route"}.`
2760
- : "Save this plan as a new route."}
2761
- </span>
2762
- {/* ⚠ THIS NOTE STAYS WITH THE SELECT, while items 8 and 9 send the Save
2763
- button and the Google links to the foot. It is a statement about what
2764
- the LIST ABOVE does not contain ("not listed above"), so it is the one
2765
- line in the old block that would become false the moment it travelled. */}
2766
- {/* ⚠ THE OLD SENTENCE READ *"Shared orders you can read but not re-solve are
2767
- not listed above"*, and the Saved route picker at the top of this panel made
2768
- it false on the day it shipped: those routes ARE listed now, one control up.
2769
- What is still true, and what a person needs told here, is why choosing one
2770
- up there did not arm this Save. */}
2771
- {(routeCols || []).some((f) => !f.mine) && (
2772
- <span className="cg-map-route-note">
2773
- A route somebody else planned can be opened under Saved route above. Only
2774
- the person who planned it can re-solve it, so it is not offered here.
2775
- </span>
2776
- )}
2777
- </>
2778
- )}
2779
-
2780
- {/* ── ITEM 9: where the day starts, and it SEARCHES ──────────────────────────────
2781
- ⛔ ITEM 6 removed the "Optional route start" address box above this, so the
2782
- start is the record dropdown and nothing else. The `!plan.depot` guard the old
2783
- select carried is gone with the control that could set one. */}
2784
- {plan && (
2785
- <>
2786
- <RecordPicker
2787
- label="Start"
2788
- placeholder="Choose the first stop"
2789
- emptyNote="No stops on this route yet."
2790
- options={routable
2791
- .filter((pt) => pt.pid !== DEPOT_PID)
2792
- .map((pt) => ({ pid: pt.pid, title: pt.title || `#${pt.pid}` }))}
2793
- currentPid={plan.ordered[0]?.pid ?? null}
2794
- onPick={(pid) => setRouteStartPid(pid)}
2795
- />
2796
- <label className="cg-map-route-opt cg-route-check">
2797
- <input
2798
- type="checkbox"
2799
- checked={roundTrip}
2800
- onChange={(e) => setRoundTrip(e.target.checked)}
2801
- />
2802
- Return to start
2803
- </label>
2804
- </>
2805
- )}
2806
-
2807
- {/* ── the stops ────────────────────────────────────────────────────────────────
2808
- ⭐ W37-T36 — THE ORDER IS CHANGEABLE, and it has to be more than the Start
2809
- picker: the planner optimises for distance, and a person routing a day is
2810
- working around an appointment at eleven that no solver knows about.
2811
- ⭐ ITEM 9 — the controls are UP and DOWN, not left and right. The list runs
2812
- vertically, so a chevron pointing sideways described the wrong axis; and each
2813
- row now carries an X, because "not this customer today" was previously only
2814
- expressible by leaving the panel and changing the selection on the map. */}
2815
- {plan && plan.ordered.length > 0 && (
2816
- <div className="cg-map-stoplist">
2817
- {plan.ordered.map((pt, i) => (
2818
- <span className="cg-map-stopitem" key={pt.pid}>
2819
- <span className="cg-map-stopn">
2820
- {pt.pid === DEPOT_PID ? "" : i + 1 - (plan.depot ? 1 : 0)}
2821
- </span>
2822
- {pt.pid === DEPOT_PID ? (
2823
- <span className="cg-map-stopname">{pt.title || "Depot"}</span>
2824
- ) : (
2825
- <button
2826
- type="button"
2827
- className="cg-map-stopname cg-map-stopopen"
2828
- title={`Open ${pt.title || `record #${pt.pid}`} details`}
2829
- onClick={() => onOpen(pt.pid)}
2830
- >
2831
- {pt.title || `#${pt.pid}`}
2832
- </button>
2833
- )}
2834
- {pt.pid !== DEPOT_PID && (
2835
- <>
2836
- <button
2837
- type="button"
2838
- className="cg-map-stopmove"
2839
- disabled={i === (plan.depot ? 1 : 0)}
2840
- aria-label={`Move ${pt.title || `#${pt.pid}`} earlier`}
2841
- title="Visit this stop earlier"
2842
- onClick={() => moveStop(pt.pid, -1)}
2843
- >
2844
- <svg viewBox="0 0 16 16" aria-hidden="true">
2845
- <path d="M8 12.5v-9M4 7.5 8 3.5l4 4" />
2846
- </svg>
2847
- </button>
2848
- <button
2849
- type="button"
2850
- className="cg-map-stopmove"
2851
- disabled={i === plan.ordered.length - 1}
2852
- aria-label={`Move ${pt.title || `#${pt.pid}`} later`}
2853
- title="Visit this stop later"
2854
- onClick={() => moveStop(pt.pid, 1)}
2855
- >
2856
- <svg viewBox="0 0 16 16" aria-hidden="true">
2857
- <path d="M8 3.5v9M4 8.5l4 4 4-4" />
2858
- </svg>
2859
- </button>
2860
- <button
2861
- type="button"
2862
- className="cg-map-stopmove cg-map-stopdrop"
2863
- aria-label={`Remove ${pt.title || `#${pt.pid}`} from the route`}
2864
- title="Take this stop off the route"
2865
- onClick={() => removeStop(pt.pid)}
2866
- >
2867
- <svg viewBox="0 0 16 16" aria-hidden="true">
2868
- <path d="m4.5 4.5 7 7m0-7-7 7" />
2869
- </svg>
2870
- </button>
2871
- </>
2872
- )}
2873
- </span>
2874
- ))}
2875
- </div>
2876
- )}
2877
-
2878
- {/* ⛔ WAVE 41 / R13 — THE DISCARD-MY-ORDER BUTTON STOOD HERE AND IS NOT REPLACED
2879
- IN PLACE. Discarding the hand-picked sequence is half of `Update calculation`
2880
- in the foot row now, so a control offering only that half would put the panel
2881
- back in the state R13 removed: two buttons, one flow, and no way to tell from
2882
- the labels which one leaves the drawn road answering a sequence nobody is
2883
- looking at any more. */}
2884
-
2885
- {/* ⛔ W37-T36 — NAMED, NOT COUNTED. "4 selected records have no location" tells you
2886
- something is missing and not WHICH visit you are about to fail to make, and the
2887
- whole point of the chip is that the exclusion is not silent. Three inline so a
2888
- big selection cannot swamp the panel, the rest on the tooltip. */}
2889
- {/* ⛔⛔ GATED ON `selectedPids.size >= 2`, AND THAT IS A REAL DEFECT THIS PANEL
2890
- REBUILD WOULD OTHERWISE HAVE SHIPPED. `customerRoutable` SHORT-CIRCUITS to `[]`
2891
- below two selected records, so `unroutable` (= selection size minus routable) is
2892
- 1 whenever exactly ONE record is selected -- and the chip would then name a
2893
- customer that has a perfectly good location and say it has none. It could not
2894
- happen before because the whole body sat behind the two-selected wall item 2
2895
- removes; taking that wall down without this gate turns an honest disclosure into
2896
- a false accusation about a named customer. */}
2897
- {selectedPids.size >= 2 && unroutable > 0 && (
2898
- <span
2899
- className="cg-cal-nodate"
2900
- title={`No location on file, so these cannot be routed: ${unroutableNames.join(", ")}`}
2901
- >
2902
- No location, so not routed: {unroutableNames.slice(0, 3).join(", ")}
2903
- {unroutableNames.length > 3 &&
2904
- ` and ${(unroutableNames.length - 3).toLocaleString()} more`}
2905
- </span>
2906
- )}
2907
-
2908
- {/* ══ OWNER ITEMS 8 AND 9 (2026-08-23) — THE COMMITTING CONTROLS LIVE AT THE FOOT ══
2909
- Owner: *"the 'Google Map Route 1' etc. should still be located at the bottom
2910
- just above clear route button. And the save route button should still be at
2911
- the bottom too beside clear route button."*
2912
- ⛔⛔ THIS OVERRULES THE OLDER "POSITION IS PART OF THE INSTRUCTION" NOTE, WHICH
2913
- IS KEPT NOWHERE ELSE, SO IT IS RESTATED HERE RATHER THAN DELETED. Item 4 of the
2914
- earlier pass put the Google links BETWEEN the visit-order select and its Save
2915
- button, so that "under the Visit order column" stayed true; item 3b then moved
2916
- that whole block above Start. The owner has now separated the two jobs: the
2917
- select is SETUP and belongs at the top with Add a record, while saving and
2918
- clearing are the two ways to FINISH and belong together at the bottom. The old
2919
- argument was about keeping the links adjacent to something; they are now
2920
- adjacent to the button that commits them, which serves it.
2921
- ⚠ The Save button and Clear route share one row (item 9's "beside"), so
2922
- `.cg-route-cta`'s full-width override is deliberately NOT applied to them —
2923
- two full-width buttons cannot sit beside each other. */}
2924
- {plan && (
2925
- <>
2926
- {/* ── ITEM 4: the hand-off links, ONE PER LINE ─────────────────────────
2927
- They were a `flex-wrap` cluster of chips, unreadable the moment a route
2928
- needs more than one Google leg. Stacked, each on its own row, the list
2929
- reads as what it is: leg 1, then leg 2. Owner item 8 moved the stack down
2930
- here, directly above the two buttons that finish the job. */}
2931
- {plan.links.length > 0 && (
2932
- <div className="cg-map-google-links" aria-label="Google Maps route links">
2933
- <label className="cg-map-route-opt cg-route-maps-cap">
2934
- Stops per Google Maps link
2935
- <select
2936
- className="cg-route-select"
2937
- value={mapsPerLink}
2938
- aria-label="Stops per Google Maps link"
2939
- onChange={(event) => setMapsPerLink(Math.max(2, Math.min(10, Number(event.target.value) || 10)))}
2940
- >
2941
- {Array.from({ length: 9 }, (_, index) => index + 2).map((count) => (
2942
- <option key={count} value={count}>{count}</option>
2943
- ))}
2944
- </select>
2945
- </label>
2946
- {plan.links.map((link) => (
2947
- <a
2948
- key={link.index}
2949
- href={link.url}
2950
- target="_blank"
2951
- rel="noopener noreferrer"
2952
- title={`Open Google Maps route ${link.index} in a new tab`}
2953
- >
2954
- Google Maps route {link.index}
2955
- </a>
2956
- ))}
2957
- <button type="button" className="cg-route-copy-links" onClick={() => void copyRouteLinks()}>
2958
- Copy links
2959
- </button>
2960
- {routeCopyMsg && <span className="cg-map-route-note">{routeCopyMsg}</span>}
2961
- </div>
2962
- )}
2963
- <div className="cg-route-schedule" role="group" aria-label="Schedule route delivery">
2964
- <label className="cg-map-route-opt">
2965
- Inbox recipient
2966
- <input
2967
- className="cg-input"
2968
- value={routeRecipient}
2969
- aria-label="Inbox recipient"
2970
- placeholder="Account username"
2971
- onChange={(event) => setRouteRecipient(event.target.value)}
2972
- />
2973
- </label>
2974
- <button
2975
- type="button"
2976
- className="cg-btn"
2977
- disabled={routeScheduleBusy || !routeRecipient.trim()}
2978
- onClick={() => void scheduleRouteDelivery()}
2979
- title="Send this frozen route to the selected account's Inbox every day at 08:00"
2980
- >
2981
- {routeScheduleBusy ? "Scheduling" : "Schedule daily"}
2982
- </button>
2983
- {routeScheduleMsg && <span className="cg-map-route-note">{routeScheduleMsg}</span>}
2984
- {routeScheduleErr && <span className="cg-cal-nodate">{routeScheduleErr}</span>}
2985
- </div>
2986
- {/* ── ITEMS 4 AND 5: "Save route", and it ASKS FOR THE NAME ─────────────────
2987
- ⭐ ITEM 4 — the button read "Save visit order". Owner: *"Change the button
2988
- called 'Save visit order' to 'Save route'."* The FIELD is still the visit
2989
- order (that is what the numbers in it are); the ACT is saving a route.
2990
- ⭐ ITEM 5 — a NEW field now opens a name box first, pre-filled with the
2991
- server's next free "Route N". Updating a field that already exists does not
2992
- prompt: it already has a name, and asking again would invite a rename
2993
- through a door that re-solves numbers rather than through Edit field.
2994
- ⛔ AN INLINE STEP, NOT A BROWSER `prompt()`. A modal dialog blocks the page
2995
- and cannot be styled, read by the design system, or dismissed with Escape
2996
- the way every other overlay here is. */}
2997
- {naming && !saveTarget && (
2998
- <div className="cg-route-name" role="group" aria-label="Name this route">
2999
- <input
3000
- className="cg-input"
3001
- autoFocus
3002
- value={nameDraft}
3003
- aria-label="Route name"
3004
- placeholder={nextLabel || "Name this route"}
3005
- maxLength={120}
3006
- onChange={(e) => setNameDraft(e.target.value)}
3007
- onKeyDown={(e) => {
3008
- if (e.key === "Enter") { e.preventDefault(); void saveRouteOrder(nameDraft); }
3009
- if (e.key === "Escape") { e.preventDefault(); setNaming(false); }
3010
- }}
3011
- />
3012
- <span className="cg-route-name-actions">
3013
- <button
3014
- type="button"
3015
- className="cg-btn cg-btn--primary"
3016
- disabled={saveBusy || !nameDraft.trim()}
3017
- onClick={() => void saveRouteOrder(nameDraft)}
3018
- title="Save these visit numbers into a new field with this name"
3019
- >
3020
- {saveBusy ? "Saving" : "Save route"}
3021
- </button>
3022
- <button
3023
- type="button"
3024
- className="cg-btn"
3025
- onClick={() => setNaming(false)}
3026
- title="Do not save this route yet"
3027
- >
3028
- Cancel
3029
- </button>
3030
- </span>
3031
- </div>
3032
- )}
3033
- {/* ⛔ DERIVED, NEVER STORED. The saved field carries the fingerprint of the
3034
- inputs it was solved from; this compares it against the cohort ON SCREEN
3035
- NOW, so the marker cannot itself go out of date. */}
3036
- {orderStale && (
3037
- <span className="cg-map-route-note">
3038
- Stale. The saved numbers were solved from different stops, so re-solving
3039
- would change them.
3040
- </span>
3041
- )}
3042
- {saveMsg && <span className="cg-map-route-note">{saveMsg}</span>}
3043
- {saveErr && <span className="cg-cal-nodate">{saveErr}</span>}
3044
- </>
3045
- )}
3046
-
3047
- <div className="cg-route-foot">
3048
- {/* ⚠ THE NAME BOX IS FULL WIDTH ABOVE THE ROW, NOT INSIDE IT. A text input, a
3049
- Save and a Cancel cannot share a 338px row with Clear route without every
3050
- one of them shrinking past reading width, so while it is open the row drops
3051
- its Save and the prompt owns the line above it. */}
3052
- {plan && !(naming && !saveTarget) && (
3053
- <button
3054
- type="button"
3055
- className="cg-btn cg-btn--primary cg-route-foot-btn"
3056
- disabled={saveBusy}
3057
- onClick={() => {
3058
- if (saveTarget) { void saveRouteOrder(); return; }
3059
- setNameDraft(nextLabel);
3060
- setSaveErr(null);
3061
- setSaveMsg(null);
3062
- setNaming(true);
3063
- }}
3064
- title={
3065
- saveTarget
3066
- ? "Write these visit numbers into the saved field, for everyone it is shared with"
3067
- : "Name this route and save these visit numbers as a new field"
3068
- }
3069
- >
3070
- {saveBusy ? "Saving" : saveTarget ? "Update route" : "Save route"}
3071
- </button>
3072
- )}
3073
- {/* ══ WAVE 41 ITEM 19 / R13 — ONE BUTTON, ONE FLOW ═══════════════════════════
3074
- Owner: *"the difference between update route and re-optimize is unclear and
3075
- should become one flow."* It was two controls in two different places, and
3076
- neither did the whole job: one discarded the hand-picked stop sequence and
3077
- left the drawn road still answering the sequence nobody was looking at, the
3078
- other re-asked the routing service and moved no stop. Pressing either alone
3079
- left the panel half updated, and the labels gave a person no way to know
3080
- which half they had just bought. Both effects are now one click.
3081
-
3082
- ⛔ THE REF, NOT A BARE `fetchRoad()` BESIDE THE `setRouteOrder`, AND THIS IS
3083
- THE WHOLE REASON THE MERGE IS NOT TWO LINES. `fetchRoad` closes over `plan`,
3084
- and `plan` is a memo over `routeOrder`: calling it in the same handler would
3085
- send the routing service the stops in the order being DISCARDED, then draw
3086
- that answer under the re-solved one. `askRoadRef` is the same one-shot
3087
- `Plan route` above uses, consumed by the effect on the render where the new
3088
- plan exists.
3089
-
3090
- ⚠ AND THE `else` IS NOT TIDINESS EITHER. With no hand order to discard,
3091
- `setRouteOrder(null)` is a no-op React bails out of: `plan` keeps its
3092
- identity, the effect never runs, and the ref would sit ARMED until the next
3093
- plan change spent a provider request on a mere selection change, which is
3094
- precisely what R3 forbids. That case has a current `plan` in scope already,
3095
- so it asks directly.
3096
-
3097
- ⚠ ALWAYS PRESENT, DISABLED RATHER THAN ABSENT. The old re-ask button existed
3098
- only while the road was stale or unfetched, so the row it should have lived
3099
- in changed shape under the user. `disabled` says the same thing without
3100
- moving its neighbours, and the title says why.
3101
-
3102
- ⚠ THE TRAVEL MODE MOVED TO THE TITLE, NOT AWAY. The old button spelled the
3103
- pending mode in its LABEL; the mode is set by the segmented control a few
3104
- rows above and reported on the answer by `road.mode`, so the label would be
3105
- a third statement of a fact two controls already make. The title keeps it
3106
- against the action about to be spent. */}
3107
- {plan && (
3108
- <button
3109
- type="button"
3110
- className="cg-btn cg-route-cta"
3111
- disabled={roadBusy || (!!road && !roadStale && !routeOrder)}
3112
- onClick={() => {
3113
- if (routeOrder) {
3114
- askRoadRef.current = true;
3115
- setRouteOrder(null);
3116
- return;
3117
- }
3118
- void fetchRoad();
3119
- }}
3120
- title={
3121
- roadBusy
3122
- ? "Working out the travelling route"
3123
- : !!road && !roadStale && !routeOrder
3124
- ? "The stops are already in the shortest order and the travelling route is current"
3125
- : `Put the stops in the shortest order and ask for the ${
3126
- travelMode === "walking" ? "walking" : "driving"
3127
- } route`
3128
- }
3129
- >
3130
- {roadBusy ? "Calculating" : "Update calculation"}
3131
- </button>
3132
- )}
3133
- {routeOn && (
3134
- <button
3135
- type="button"
3136
- className="cg-btn cg-btn--danger cg-route-cta"
3137
- onClick={() => {
3138
- setRouteOn(false);
3139
- setRouteStartPid(null);
3140
- setRouteOrder(null);
3141
- setRoad(null);
3142
- setRoadErr(null);
3143
- setDepot(null);
3144
- }}
3145
- /* ⚠ LOCAL ONLY, AND THE COPY NOW SAYS SO. Every call in the handler above is
3146
- `setState`: no door is opened and no saved route field is touched. The old
3147
- sentence opened "Drop this route", which reads as a deletion the moment a
3148
- colleague's saved route is the thing on screen, and the panel offers
3149
- exactly that. What is being cleared is the drawing, and the second clause
3150
- names both things that survive it. */
3151
- title="Take this route off the map. The records stay selected and nothing saved is deleted."
3152
- >
3153
- Clear route
3154
- </button>
3155
- )}
3156
- </div>
3157
- </div>
3158
  </aside>
3159
  )}
3160
- {/* ⭐⭐ W37-T37 (R4 / R3 / R14) — LOOK UP THE ADDRESSES OF THE RECORDS YOU CHOSE.
3161
- It lives HERE, on the map, because this is the surface where the absence is felt: you
3162
- are looking at a picture with a chip saying N records have no location, and the answer
3163
- is one control away instead of in a field editor two menus deep.
3164
- ⛔ THREE THINGS MAKE IT R3-SAFE AND NONE OF THEM IS A COMMENT. It renders only when a
3165
- geocode column EXISTS, only when records are SELECTED, and it walks `geocodable`, which
3166
- is built from the selection. There is no expression anywhere in this file that means
3167
- "every record without a pin", so a whole-table run is not a thing a user can reach or a
3168
- future edit can accidentally enable. */}
3169
  {geoControl}
3170
- {zones !== null && (
 
 
3171
  <div className="cg-map-zones" role="group" aria-label="Map Zones">
3172
  <div className="cg-map-zone-chooser">
3173
  <button
@@ -3209,19 +2629,6 @@ export function MapView({
3209
  >
3210
  New Zone
3211
  </button>
3212
- <button
3213
- type="button"
3214
- className="cg-btn"
3215
- disabled={activeZonePids.size < 2}
3216
- onClick={() => {
3217
- setRouteCreateOpen(true);
3218
- setRouteOn(false);
3219
- setRouteOrder(null);
3220
- }}
3221
- title="Use the selected visible Zones as this route's records"
3222
- >
3223
- Route Zones
3224
- </button>
3225
  {zoneEditor && (
3226
  <button
3227
  type="button"
@@ -3270,6 +2677,16 @@ export function MapView({
3270
  </select>
3271
  </label>
3272
  )}
 
 
 
 
 
 
 
 
 
 
3273
  <label className="cg-map-zone-control">
3274
  Zone name
3275
  <input
@@ -3307,6 +2724,7 @@ export function MapView({
3307
  </button>
3308
  {zoneErr && <span className="cg-cal-nodate">{zoneErr}</span>}
3309
  </div>
 
3310
  )}
3311
  {/* Every gesture the map has, named. `alt` (add to the selection rather
3312
  than replace it, onPointerUp) shipped in wave 8 and was disclosed
@@ -3324,6 +2742,7 @@ export function MapView({
3324
  role="group"
3325
  aria-label="Map canvas. Arrow keys pan, plus and minus zoom, square brackets rotate, zero fits to data and faces north."
3326
  onKeyDown={onFrameKeyDown}
 
3327
  >
3328
  <svg
3329
  ref={setSvgEl}
 
92
  zoomLimits,
93
  } from "./mapProjection";
94
  import type { GeoStop, Pt, RouteStamp, View } from "./mapProjection";
95
+ import { LP_INK, LP_MAP_SELECTED, LP_PURPLE, LP_PURPLE_DEEP } from "./theme";
96
+ import { RouteNav } from "./RouteNav";
97
+ import { mapNavigatorMode, normalizedZoneZipCodes, routeSourceStopIds, toggleRouteSelection } from "./routeZoneTypes";
98
+ import type { MapRouteDto, MapRouteSource, RouteSelectionRequest, RouteSelectionResponse } from "./routeZoneTypes";
99
  import "./map.css";
100
 
101
  /**
 
296
  }
297
 
298
  /**
299
+ * The Map starts in the Group-purple family. Colour-by retains its distinct
300
+ * series after that first default, while an unencoded point never regresses to blue.
301
  * 20%-darkened variants, exactly as the contract specifies for series colour.
302
  * `fill` is the pastel; `line` is a darker companion, because a C1 pastel
303
  * measures 1.4-1.9:1 on white and a fill alone would be a smudge (the same
304
  * measurement that drove the I7c amendment).
305
  */
306
  const SERIES: { fill: string; line: string }[] = [
307
+ { fill: LP_PURPLE, line: LP_PURPLE_DEEP },
308
  { fill: "#A5D8B4", line: "#5E9C74" },
309
  { fill: "#F5D989", line: "#B39A46" },
310
  { fill: "#F0A8A0", line: "#B76D65" },
 
316
  /** Anything past the palette, plus the blank bucket. Neutral ON PURPOSE: a
317
  * ninth colour that repeats the first would make two meanings look identical. */
318
  const OVERFLOW = { fill: "#D7DBE3", line: "#8A909C" };
319
+ const DEFAULT_PIN = { fill: LP_PURPLE, line: LP_PURPLE_DEEP };
320
  const ZONE_COLOR_CHOICES = [
321
+ { value: LP_PURPLE, label: "Purple" },
322
  { value: "#A5D8B4", label: "Green" },
323
  { value: "#F5D989", label: "Yellow" },
324
  { value: "#F0A8A0", label: "Red" },
 
356
  visible: boolean;
357
  geographicField: string;
358
  memberships: number[];
359
+ /** C1 Zone membership is polygon OR ZIP; the server recomputes the union. */
360
+ zipCodes?: string[];
361
  createdBy?: string;
362
  createdAt?: string;
363
  }
 
437
  allRows,
438
  activeView,
439
  tableKey,
440
+ onManagedRouteViewState,
441
  }: {
442
  /** DISTINCT data rows from the full pipeline, overlay edits layered — the
443
  * calendar/kanban contract, verbatim. */
 
479
  activeView: RouteSourceView | null;
480
  /** Canonical database identity for durable, table-scoped Zones. */
481
  tableKey: string;
482
+ /** C2 handoff: the server alone returns the managed route-membership clause. */
483
+ onManagedRouteViewState?: (viewState: Record<string, unknown>) => void;
484
  /**
485
  * ⭐⭐ OWNER ITEM 9 — THE WHOLE BOOK, so a stop can be added that the VIEW filtered out.
486
  *
 
498
  const [routeOn, setRouteOn] = useState(false);
499
  /** Route navigation is an index first; planning begins only after the explicit Create route
500
  * action or an existing saved route has been opened. */
 
501
  const [roundTrip, setRoundTrip] = useState(false);
502
  const [routeStartPid, setRouteStartPid] = useState<number | null>(null);
503
  const askRoadRef = useRef(false);
 
541
  /** C3 Zone chooser/editor state. `null` means the tenant read has not answered; an empty
542
  * array is an honest, editable no-Zones state. */
543
  const [zones, setZones] = useState<MapZone[] | null>(null);
544
+ /** C2 named-route read model. Legacy route-order columns remain compatibility only. */
545
+ const [namedRoutes, setNamedRoutes] = useState<MapRouteDto[]>([]);
546
+ const [selectedRouteIds, setSelectedRouteIds] = useState<ReadonlySet<string>>(new Set());
547
+ const [managedRouteViewState, setManagedRouteViewState] = useState<Record<string, unknown> | null>(null);
548
+ const [routeSelectionWarning, setRouteSelectionWarning] = useState<string | null>(null);
549
  const [activeZoneIds, setActiveZoneIds] = useState<ReadonlySet<string>>(new Set());
550
  const [zoneChooserOpen, setZoneChooserOpen] = useState(false);
551
+ const [zoneNavigatorOpen, setZoneNavigatorOpen] = useState(false);
552
  const [zoneEditorId, setZoneEditorId] = useState("");
553
  const [zoneName, setZoneName] = useState("");
554
  const [zoneColor, setZoneColor] = useState(ZONE_COLOR_CHOICES[0].value);
555
  const [zoneGeographicField, setZoneGeographicField] = useState("");
556
  const [zoneGeographicValue, setZoneGeographicValue] = useState("");
557
+ const [zoneZipCodes, setZoneZipCodes] = useState("");
558
  const [drawnZoneGeometry, setDrawnZoneGeometry] = useState<ZoneGeometry | null>(null);
559
  const [zoneMove, setZoneMove] = useState<ZoneMove | null>(null);
560
  const [zoneGeometryDraft, setZoneGeometryDraft] = useState<{ id: string; geometry: ZoneGeometry } | null>(null);
561
  const [zoneBusy, setZoneBusy] = useState(false);
562
  const [zoneErr, setZoneErr] = useState<string | null>(null);
563
+ const mapNavigator = mapNavigatorMode(routePanelOpen, zoneNavigatorOpen);
564
+ useEffect(() => {
565
+ if (routePanelOpen) setZoneNavigatorOpen(false);
566
+ }, [routePanelOpen]);
567
  /**
568
  * W37-T36 — the ROAD answer, which is the half arithmetic cannot produce.
569
  *
 
855
  }
856
  }, [tableKey]);
857
  useEffect(() => { void loadZones(); }, [loadZones]);
858
+ const visibleRoutePids = useMemo(
859
+ () => [...new Set(rows.map((row) => row.pid))].sort((a, b) => a - b).join(","),
860
+ [rows]
861
+ );
862
+ useEffect(() => {
863
+ let live = true;
864
+ fetch(`/api/v1/customers/routes?visiblePids=${encodeURIComponent(visibleRoutePids)}`, { credentials: "same-origin" })
865
+ .then((res) => res.ok ? res.json() : null)
866
+ .then((body) => { if (live && Array.isArray(body?.routes)) setNamedRoutes(body.routes); })
867
+ .catch(() => { /* Dedicated Route DTO is supplied by lane A. */ });
868
+ return () => { live = false; };
869
+ }, [visibleRoutePids]);
870
+ useEffect(() => {
871
+ // A managed clause belongs to one saved View. Never carry it into another View's authored state.
872
+ setManagedRouteViewState(null);
873
+ setSelectedRouteIds(new Set());
874
+ setRouteSelectionWarning(null);
875
+ }, [activeView?.id]);
876
+ const routeFilterSignature = useMemo(
877
+ () => JSON.stringify({ filters: activeView?.config?.filters || [], filterConj: activeView?.config?.filterConj || "and" }),
878
+ [activeView?.config?.filterConj, activeView?.config?.filters]
879
+ );
880
+ const routeFilterSignatureRef = useRef({ viewId: activeView?.id || "", signature: routeFilterSignature });
881
+ useEffect(() => {
882
+ const prior = routeFilterSignatureRef.current;
883
+ const viewId = activeView?.id || "";
884
+ const changed = prior.viewId === viewId && prior.signature !== routeFilterSignature;
885
+ routeFilterSignatureRef.current = { viewId, signature: routeFilterSignature };
886
+ if (!changed || !activeView || selectedRouteIds.size === 0) return;
887
+ void (async () => {
888
+ try {
889
+ const res = await fetch("/api/v1/customers/routes/selection", {
890
+ method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
891
+ body: JSON.stringify({ routeIds: [], viewState: activeView.config as unknown as Record<string, unknown> } satisfies RouteSelectionRequest),
892
+ });
893
+ const body = await res.json().catch(() => null) as RouteSelectionResponse | null;
894
+ if (!res.ok || body?.managedBy !== "loopable" || !body.viewState) throw new Error("managed selection refusal");
895
+ setSelectedRouteIds(new Set());
896
+ setManagedRouteViewState(body.viewState);
897
+ onManagedRouteViewState?.(body.viewState);
898
+ setRouteSelectionWarning("Route selection cleared because the View filter changed.");
899
+ } catch {
900
+ setRouteSelectionWarning("Route selection could not be cleared after the View filter changed.");
901
+ }
902
+ })();
903
+ }, [activeView, onManagedRouteViewState, routeFilterSignature, selectedRouteIds]);
904
+ const toggleNamedRoute = useCallback(async (route: MapRouteDto) => {
905
+ const isAdding = !selectedRouteIds.has(route.id);
906
+ if (isAdding) {
907
+ if (route.outsideFilter && !window.confirm(`${route.name} is outside this filter. Include only this route's managed membership group?`)) return;
908
+ }
909
+ const next = toggleRouteSelection(selectedRouteIds, route.id);
910
+ if (!activeView) {
911
+ setRouteSelectionWarning("Select a saved View before adding a route inclusion.");
912
+ return;
913
+ }
914
+ const routeIds = [...next];
915
+ try {
916
+ const request: RouteSelectionRequest = {
917
+ routeIds,
918
+ viewState: managedRouteViewState || (activeView.config as unknown as Record<string, unknown>),
919
+ };
920
+ const res = await fetch("/api/v1/customers/routes/selection", {
921
+ method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
922
+ body: JSON.stringify(request),
923
+ });
924
+ const body = await res.json().catch(() => null) as RouteSelectionResponse | null;
925
+ if (!res.ok || body?.managedBy !== "loopable" || !body.viewState) {
926
+ setRouteSelectionWarning(body && "error" in body ? String((body as { error?: { message?: string } }).error?.message || "Route inclusion could not be changed.") : "Route inclusion could not be changed.");
927
+ return;
928
+ }
929
+ setSelectedRouteIds(next);
930
+ setManagedRouteViewState(body.viewState);
931
+ onManagedRouteViewState?.(body.viewState);
932
+ setRouteSelectionWarning(route.outsideFilter && next.has(route.id) ? `${route.name} is included through its managed route group.` : null);
933
+ const pids = namedRoutes.filter((item) => next.has(item.id)).flatMap((item) => item.visibleStopIds);
934
+ onSelectPids([...new Set(pids)], "add");
935
+ } catch { setRouteSelectionWarning("Route inclusion could not be changed."); }
936
+ }, [activeView, managedRouteViewState, namedRoutes, onManagedRouteViewState, onSelectPids, selectedRouteIds]);
937
+ const moveNamedRouteStop = useCallback(async (route: MapRouteDto, customerPid: number, order: number): Promise<string | null> => {
938
+ try {
939
+ const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/stops/move`, {
940
+ method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
941
+ body: JSON.stringify({ customerPid, order }),
942
+ });
943
+ const body = await res.json().catch(() => null);
944
+ if (res.status === 409 && body?.error?.code === "no_route_stop") return "This route has no matching stop to move.";
945
+ if (!res.ok) return body?.error?.message || "The stop order could not be changed.";
946
+ const routeUpdate = body?.route as MapRouteDto | undefined;
947
+ if (routeUpdate) setNamedRoutes((current) => current.map((item) => item.id === routeUpdate.id ? routeUpdate : item));
948
+ return null;
949
+ } catch { return "The stop order could not be changed."; }
950
+ }, []);
951
 
952
  const activeZones = useMemo(
953
  () => (zones || []).filter((zone) => zone.visible && activeZoneIds.has(zone.id)),
 
958
  for (const zone of activeZones) for (const pid of zone.memberships || []) pids.add(pid);
959
  return pids;
960
  }, [activeZones]);
961
+ const routeSources = useMemo<MapRouteSource[]>(() => [
962
+ { id: "selection", label: "Current selection", pids: routeSourceStopIds(selectedPids) },
963
+ { id: "zones", label: "Selected Zones", pids: routeSourceStopIds(activeZonePids) },
964
+ ], [activeZonePids, selectedPids]);
965
+ const createNamedRoute = useCallback(async (name: string, source: MapRouteSource): Promise<string | null> => {
966
+ if (!activeView) return "Select a saved View before creating a Route.";
967
+ if (!source.pids.length) return "Choose a Route source with at least one customer.";
968
+ try {
969
+ const res = await fetch("/api/v1/customers/routes", {
970
+ method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
971
+ body: JSON.stringify({ name, stops: source.pids, sourceViewId: activeView.id }),
972
+ });
973
+ const body = await res.json().catch(() => null);
974
+ if (!res.ok) return body?.error?.message || "The Route could not be created.";
975
+ if (body?.route) setNamedRoutes((current) => [...current, body.route].sort((a, b) => a.number - b.number));
976
+ return null;
977
+ } catch { return "The Route could not be created."; }
978
+ }, [activeView]);
979
  const zoneEditor = useMemo(
980
  () => (zones || []).find((zone) => zone.id === zoneEditorId) || null,
981
  [zones, zoneEditorId]
 
1004
  setZoneName(zone.name);
1005
  setZoneColor(zone.color);
1006
  setZoneGeographicField(zone.geographicField || "");
1007
+ setZoneZipCodes((zone.zipCodes || []).join(", "));
1008
  }
1009
  }, [activeZoneIds, zones, selectedPids, onSelectPids]);
1010
  const zonePolygons = useMemo(() => activeZones.flatMap((zone) => {
 
1063
  geometryGeoJson,
1064
  visible: existing?.visible ?? true,
1065
  geographicField: zoneGeographicField,
1066
+ zipCodes: normalizedZoneZipCodes(zoneZipCodes),
1067
  memberships: [...selectedPids],
1068
  }),
1069
  });
 
1087
  } finally {
1088
  setZoneBusy(false);
1089
  }
1090
+ }, [selectionZoneGeometry, zoneName, zoneColor, zoneGeographicField, zoneZipCodes, selectedPids, tableKey]);
1091
 
1092
  const setZoneVisible = useCallback(async (zone: MapZone, visible: boolean) => {
1093
  setZoneBusy(true);
 
2045
  [plan]
2046
  );
2047
 
2048
+ // The legacy route-order calculation remains available to the existing map drawing and data
2049
+ // migration code, but its second navigator is deliberately gone. Keep these compatibility
2050
+ // hooks live until route-order columns are retired server-side; none renders a second Route UI.
2051
+ void [
2052
+ formatDuration, ROUTE_STOP_CAP, RecordPicker, setRoundTrip, setDepot, setTravelMode, travelModes,
2053
+ roadBusy, roadErr, routeEditBusy, routeEditErr, setMapsPerLink, routeCopyMsg, setRouteRecipient,
2054
+ routeScheduleBusy, routeScheduleMsg, routeScheduleErr, openErr, naming, nameDraft, setNameDraft,
2055
+ saveBusy, saveMsg, saveErr, selectFilteredRouteRecords, unroutable, unroutableNames,
2056
+ updateRouteDetails, copyRouteLinks, scheduleRouteDelivery, openSavedRoute, saveRouteOrder,
2057
+ orderStale, removeStop, addRecord, addableRecords, moveStop,
2058
+ ];
2059
+
2060
  const paint = useCallback(
2061
  (p: MapPoint) => {
2062
  if (!colorBuckets) return DEFAULT_PIN;
 
2543
  </a>
2544
  </span>
2545
  )}
2546
+ {zones !== null && (
2547
+ <button type="button" className="cg-btn" disabled={mapNavigator === "routes"} aria-expanded={mapNavigator === "zones"} onClick={() => setZoneNavigatorOpen((open) => !open)} title={mapNavigator === "routes" ? "Close Routes before opening Zones" : "Open Zone navigation"}>
2548
+ Zones{activeZoneIds.size ? ` (${activeZoneIds.size.toLocaleString()})` : ""}
2549
+ </button>
2550
+ )}
2551
  {/* ═══════════════════════════════════════════════════════════════════════════════════
2552
  THE ROUTE PANEL — rebuilt for owner items 2, 4, 6, 8 and 9.
2553
 
 
2564
  body was behind the two-selected wall this item removes; `plan.ordered[0]` with nothing
2565
  selected is a crash, not a blank.
2566
  ═══════════════════════════════════════════════════════════════════════════════════ */}
2567
+ {mapNavigator === "routes" && (
2568
  <aside id="cg-route-popover" className="cg-route-popover cg-route-nav-panel cg-route-index" aria-label="Routes">
2569
+ <RouteNav
2570
+ routes={namedRoutes}
2571
+ selectedIds={selectedRouteIds}
2572
+ sources={routeSources}
2573
+ onToggle={(route) => void toggleNamedRoute(route)}
2574
+ onCreate={createNamedRoute}
2575
+ onMoveToOrder={moveNamedRouteStop}
2576
+ />
2577
+ {routeSelectionWarning && (
2578
+ <span className="cg-w44-route-warning" role="status">{routeSelectionWarning}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2579
  )}
2580
  </aside>
2581
  )}
2582
+ {routeSelectionWarning && !routePanelOpen && (
2583
+ <aside className="cg-route-popover" aria-label="Route selection notice">
2584
+ <span className="cg-w44-route-warning" role="status">{routeSelectionWarning}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2585
  </aside>
2586
  )}
 
 
 
 
 
 
 
 
 
2587
  {geoControl}
2588
+ {zones !== null && mapNavigator === "zones" && (
2589
+ <aside className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label="Zone navigation">
2590
+ <div className="cg-route-popover-head"><button type="button" className="cg-route-index-back" onClick={() => setZoneNavigatorOpen(false)}>Back</button><span className="cg-views-title">Zones</span></div>
2591
  <div className="cg-map-zones" role="group" aria-label="Map Zones">
2592
  <div className="cg-map-zone-chooser">
2593
  <button
 
2629
  >
2630
  New Zone
2631
  </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
2632
  {zoneEditor && (
2633
  <button
2634
  type="button"
 
2677
  </select>
2678
  </label>
2679
  )}
2680
+ <label className="cg-map-zone-control">
2681
+ ZIP codes
2682
+ <input
2683
+ className="cg-input"
2684
+ value={zoneZipCodes}
2685
+ aria-label="Zone ZIP codes"
2686
+ placeholder="75201, 75202"
2687
+ onChange={(event) => setZoneZipCodes(event.target.value)}
2688
+ />
2689
+ </label>
2690
  <label className="cg-map-zone-control">
2691
  Zone name
2692
  <input
 
2724
  </button>
2725
  {zoneErr && <span className="cg-cal-nodate">{zoneErr}</span>}
2726
  </div>
2727
+ </aside>
2728
  )}
2729
  {/* Every gesture the map has, named. `alt` (add to the selection rather
2730
  than replace it, onPointerUp) shipped in wave 8 and was disclosed
 
2742
  role="group"
2743
  aria-label="Map canvas. Arrow keys pan, plus and minus zoom, square brackets rotate, zero fits to data and faces north."
2744
  onKeyDown={onFrameKeyDown}
2745
+ onPointerDown={() => signal(NAV_MINIMIZE_EVENT)}
2746
  >
2747
  <svg
2748
  ref={setSvgEl}
web/src/customer-grid/RouteNav.tsx ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from "react";
2
+ import { boundedGoogleMapsUrl } from "./routeZoneTypes";
3
+ import type { MapRouteDto, MapRouteSource } from "./routeZoneTypes";
4
+
5
+ export function RouteNav({ routes, selectedIds, sources, onToggle, onCreate, onMoveToOrder }: {
6
+ routes: MapRouteDto[];
7
+ selectedIds: ReadonlySet<string>;
8
+ sources: MapRouteSource[];
9
+ onToggle: (route: MapRouteDto) => void;
10
+ onCreate: (name: string, source: MapRouteSource) => Promise<string | null>;
11
+ onMoveToOrder: (route: MapRouteDto, customerPid: number, order: number) => Promise<string | null>;
12
+ }) {
13
+ const [detail, setDetail] = useState<string | null>(null);
14
+ const [creating, setCreating] = useState(false);
15
+ const [name, setName] = useState("");
16
+ const [sourceId, setSourceId] = useState<MapRouteSource["id"]>("selection");
17
+ const [error, setError] = useState<string | null>(null);
18
+ const [orders, setOrders] = useState<Record<number, number>>({});
19
+ const route = detail ? routes.find((item) => item.id === detail) : null;
20
+ const source = sources.find((item) => item.id === sourceId) || sources[0];
21
+ const mapsUrl = boundedGoogleMapsUrl(route?.mapsUrl);
22
+
23
+ if (route) return <section className="cg-w44-route-nav" aria-label={`${route.name} route`}>
24
+ <button type="button" className="cg-w44-route-back" onClick={() => { setError(null); setDetail(null); }}>Back to routes</button>
25
+ <div className="cg-w44-route-title"><i style={{ backgroundColor: route.color }} aria-hidden="true" />{route.number}. {route.name}</div>
26
+ {route.visibleStopIds.length ? <ol className="cg-w44-route-stops">{route.visibleStopIds.map((pid, index) => <li key={pid}>Stop {index + 1}<label>Order <input className="cg-w44-route-order" type="number" min={1} max={route.visibleStopIds.length} value={orders[pid] ?? index + 1} onChange={(event) => setOrders((current) => ({ ...current, [pid]: Number(event.target.value) }))} /></label><button type="button" onClick={() => void onMoveToOrder(route, pid, orders[pid] ?? index + 1).then(setError)}>Move to order</button></li>)}</ol> : <p className="cg-w44-route-empty">No stops yet. Add customers from a route source.</p>}
27
+ {error && <span className="cg-w44-route-empty" role="status">{error}</span>}
28
+ {mapsUrl && <a className="cg-w44-route-maps" href={mapsUrl} target="_blank" rel="noopener noreferrer">Open Maps</a>}
29
+ {route.mapsUrl && !mapsUrl && <span className="cg-w44-route-empty">Maps link is unavailable.</span>}
30
+ </section>;
31
+
32
+ if (creating) return <section className="cg-w44-route-nav" aria-label="Create route">
33
+ <button type="button" className="cg-w44-route-back" onClick={() => { setError(null); setCreating(false); }}>Back to routes</button>
34
+ <label className="cg-w44-route-label">Route name<input className="cg-input" value={name} maxLength={120} onChange={(event) => setName(event.target.value)} /></label>
35
+ <fieldset className="cg-w44-route-sources"><legend>Route source</legend>{sources.map((item) => <label key={item.id}><input type="radio" name="route-source" checked={sourceId === item.id} onChange={() => setSourceId(item.id)} />{item.label} ({item.pids.length.toLocaleString()})</label>)}</fieldset>
36
+ <button type="button" className="cg-btn cg-btn--primary" disabled={!name.trim() || !source || source.pids.length === 0} onClick={() => { if (source) void onCreate(name.trim(), source).then((message) => { setError(message); if (!message) { setName(""); setCreating(false); } }); }}>Create route</button>
37
+ {error && <span className="cg-w44-route-empty" role="status">{error}</span>}
38
+ </section>;
39
+
40
+ return <section className="cg-w44-route-nav" aria-label="Named routes">
41
+ <div className="cg-w44-route-head"><div className="cg-w44-route-title">Routes</div><button type="button" className="cg-w44-route-detail" onClick={() => { setError(null); setCreating(true); }}>Create route</button></div>
42
+ {routes.length === 0 ? <p className="cg-w44-route-empty">No routes yet. Create one from selected Zones or records.</p> : routes.map((item) => <div key={item.id} className={`cg-w44-route-row${item.outsideFilter ? " is-outside" : ""}`}><button type="button" className="cg-w44-route-select" aria-pressed={selectedIds.has(item.id)} onClick={() => onToggle(item)} title={item.outsideFilter ? "Select and include this route" : "Select route"}><i style={{ backgroundColor: item.color }} aria-hidden="true" />{item.number}. {item.name}</button><button type="button" className="cg-w44-route-detail" disabled={item.outsideFilter} onClick={() => { setError(null); setDetail(item.id); }}>Details</button>{item.outsideFilter && <span>Outside filter</span>}</div>)}
43
+ </section>;
44
+ }
web/src/customer-grid/SwipeView.tsx CHANGED
@@ -1,586 +1,586 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / SwipeView.tsx
3
- // ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) — the SWIPE deck.
4
- //
5
- // One record at a time, decided left or right into two options of ONE
6
- // single-select. R2 fixes the shape and it is narrow on purpose:
7
- // · SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
8
- // · the deck holds only the records whose bound field is EMPTY — a record
9
- // that already has a value has been decided, and re-asking is not triage.
10
- // · a swipe writes through the NORMAL cell door (`onSwipe`, which the host
11
- // maps to the same `patchAndRecord` a kanban card move uses), so undo,
12
- // echo-suppression and the permission wall all hold without being
13
- // re-implemented here.
14
- //
15
- // Honesty rules carried from the other modes:
16
- // · nothing is silently hidden — the deck states what is left, and the
17
- // empty state names the bound field rather than saying "all done".
18
- // · a lost binding is SHOWN, never repaired by guessing. `_clean_display`
19
- // validates that `fieldKey` names a field the table HAS and stops there;
20
- // it cannot know the field is still a select, or that the two options are
21
- // still in its vocabulary (its docstring draws that line explicitly). So
22
- // those three losses land here, and each one says what happened and
23
- // re-opens the picker — the `viewModes.tsx:190-194` rule, which exists
24
- // because the wave-7 trap was a picker silently falling back to its first
25
- // option.
26
- // ---------------------------------------------------------------------------
27
-
28
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
- // ⭐⭐ W41-T48 (owner instruction 22) — opening a record from the swipe deck folds the shell's
30
- // navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`.
31
- import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
32
- import { choiceOptions } from "./types";
33
- import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
34
- // ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is
35
- // loaded here) — the same import `RecordComments` takes for the same prop.
36
- import type { SurfaceScope } from "./apiBridge";
37
- import RecordComments from "./RecordComments";
38
- import { Documents } from "./Documents";
39
- import { formatDisplay } from "./cells";
40
- import { actionHref } from "./display";
41
- import { optionTint } from "./choiceColors";
42
- import { ModeIcon } from "./icons";
43
- // ⭐ W29-T73 — the line its three siblings all have, and the one this file shipped without.
44
- // `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
45
- // unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right —
46
- // a partially-styled surface reads as a design choice, which is why nobody reported it and no
47
- // gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
48
- import "./SwipeView.css";
49
-
50
- export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
51
-
52
- /** The three ways a stored binding can rot that the host cannot see (see the header note). */
53
- type BindingFault =
54
- | { kind: "unbound" }
55
- | { kind: "field-gone"; fieldKey: string }
56
- | { kind: "not-select"; field: Field }
57
- | { kind: "option-gone"; field: Field; missing: string[] };
58
-
59
- function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):
60
- { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
61
- if (!spec) return { ok: false, fault: { kind: "unbound" } };
62
- const field = fieldByKey.get(spec.fieldKey);
63
- if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
64
- // R2 — SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
65
- // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
66
- // adds and sometimes overwrites is two gestures wearing one button.
67
- if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
68
- const options = choiceOptions(field);
69
- const has = new Set(options.map((o) => o.toLowerCase()));
70
- const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
71
- if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
72
- return { ok: true, field, spec };
73
- }
74
-
75
- /** The bound cell is EMPTY — the one predicate that decides deck membership (R2). */
76
- const isUndecided = (row: Row, key: string): boolean =>
77
- String(row[key] ?? "").trim() === "";
78
-
79
- export function SwipeView({
80
- rows,
81
- fields,
82
- fieldByKey,
83
- spec,
84
- cardKeys,
85
- detailKeys,
86
- scope,
87
- viewer,
88
- docs,
89
- docPayload,
90
- onDocAdd,
91
- onDocFetch,
92
- onDocDelete,
93
- titleKey,
94
- canWrite,
95
- readOnlyReason,
96
- canBind,
97
- onSpec,
98
- onSwipe,
99
- onOpen,
100
- }: {
101
- /** DISTINCT data rows from the full pipeline, overlay edits layered — the kanban's contract.
102
- * The deck re-derives from these, so a written record leaves it as soon as the optimistic
103
- * patch lands; there is no local cursor to drift out of step with the data. */
104
- rows: Row[];
105
- /** Every field, for the picker's field list. */
106
- fields: Field[];
107
- fieldByKey: Map<string, Field>;
108
- /** The stored binding, or undefined for a deck nobody has configured yet. */
109
- spec: SwipeSpec | undefined;
110
- /** The handful of visible fields the card lists under its title. */
111
- cardKeys: string[];
112
- titleKey: string;
113
- /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
114
- canWrite: boolean;
115
- /** Stated when the deck cannot be decided — permissions, or a computed column. */
116
- readOnlyReason: string | null;
117
- /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
118
- * view-editing permission and NOT `canWrite` — conflating the two is
119
- * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
120
- * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
121
- canBind: boolean;
122
- /** `undefined` DELETES the binding — absent is the honest unconfigured state, and storing a
123
- * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
124
- onSpec: (next: SwipeSpec | undefined) => void;
125
- onSwipe: (pid: number, value: string) => void;
126
- onOpen: (pid: number) => void;
127
- /**
128
- * ⭐⭐ WAVE-29 T26 (owner R9) — WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.
129
- *
130
- * R9: *"the swipe CARD itself renders the record detail inline — fields, comments and
131
- * attachments — so a reviewer decides without leaving the deck."* Everything below is that,
132
- * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply
133
- * different amounts. A card must render with none of them rather than throw — the standalone
134
- * embed has no `scope`, and a deployment with no document storage serves no handlers.
135
- */
136
- /** Every field the VIEW shows, in its order — not the three-key card summary. */
137
- detailKeys?: string[];
138
- /** The surface these records live on. Comments are keyed by it; absent ⇒ no comments section,
139
- * which is the pre-existing precondition `RecordDetail` already carries. */
140
- scope?: SurfaceScope;
141
- viewer?: Viewer;
142
- /** This record's attachments, and the plumbing. Handlers absent ⇒ the section is not rendered
143
- * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app
144
- * cannot keep). */
145
- /** Keyed by pid, because a deck shows many records — `RecordDetail` takes ONE record's list
146
- * and that shape cannot serve a deck. */
147
- docs?: Record<string, CustomerDoc[]>;
148
- docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };
149
- /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE
150
- * open record. A deck paints many records at once, so a handler bound to a single pid would
151
- * attach every reviewer's upload to whichever card happened to be open. */
152
- onDocAdd?: (
153
- pid: number,
154
- file: { name: string; mime: string; size: number; data_b64: string }
155
- ) => void;
156
- onDocFetch?: (pid: number, docId: string) => void;
157
- onDocDelete?: (pid: number, docId: string) => void;
158
- }) {
159
- // "Later" — session-only, never stored. A deck with no way past a record you cannot decide
160
- // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
161
- // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
162
- // state rather than quietly shrinking the deck (rule 8b).
163
- const [later, setLater] = useState<Set<number>>(new Set());
164
- const deckRef = useRef<HTMLDivElement>(null);
165
-
166
- const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
167
- const boundKey = binding.ok ? binding.field.key : null;
168
-
169
- const undecided = useMemo(
170
- () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
171
- [rows, boundKey]
172
- );
173
- const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
174
- const card = deck[0];
175
-
176
- // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever —
177
- // otherwise the disclosed skip count drifts away from what is actually on the deck.
178
- useEffect(() => {
179
- setLater((prev) => {
180
- if (prev.size === 0) return prev;
181
- const live = new Set(undecided.map((r) => r.pid));
182
- const next = new Set([...prev].filter((pid) => live.has(pid)));
183
- return next.size === prev.size ? prev : next;
184
- });
185
- }, [undecided]);
186
-
187
- const decide = useCallback(
188
- (value: string) => {
189
- if (!card || !canWrite) return;
190
- onSwipe(card.pid, value);
191
- },
192
- [card, canWrite, onSwipe]
193
- );
194
-
195
- // �� / → decide, and they are the SAME two actions the buttons are rather than a second code
196
- // path: the whole point of the mode is that one hand can clear a queue.
197
- useEffect(() => {
198
- if (!binding.ok || !canWrite || !card) return;
199
- const onKey = (e: KeyboardEvent) => {
200
- if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
201
- const el = document.activeElement as HTMLElement | null;
202
- // Never steal an arrow key from a text field or a native control the user is inside.
203
- if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
204
- return;
205
- if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
206
- e.preventDefault();
207
- decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
208
- };
209
- window.addEventListener("keydown", onKey);
210
- return () => window.removeEventListener("keydown", onKey);
211
- }, [binding, canWrite, card, decide]);
212
-
213
- if (!binding.ok) {
214
- return (
215
- <div className="cg-swipe" ref={deckRef}>
216
- <SwipeBinder
217
- fault={binding.fault}
218
- fields={fields}
219
- fieldByKey={fieldByKey}
220
- spec={spec}
221
- canBind={canBind}
222
- onSpec={onSpec}
223
- />
224
- </div>
225
- );
226
- }
227
-
228
- const { field } = binding;
229
- const leftTint = optionTint(field, binding.spec.leftOption);
230
- const rightTint = optionTint(field, binding.spec.rightOption);
231
-
232
- return (
233
- <div className="cg-swipe" ref={deckRef} tabIndex={-1}>
234
- <div className="cg-swipe-bar">
235
- <span className="cg-swipe-bound">
236
- <ModeIcon mode="swipe" />
237
- Sorting into <strong>{field.label}</strong>
238
- </span>
239
- <span className="cg-swipe-left">
240
- {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
241
- </span>
242
- {canBind && (
243
- <button
244
- type="button"
245
- className="cg-link-btn"
246
- onClick={() => onSpec(undefined)}
247
- title="Choose a different field or different options for this deck"
248
- >
249
- Change
250
- </button>
251
- )}
252
- </div>
253
- {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
254
- {card ? (
255
- <div className="cg-swipe-deck">
256
- <button
257
- type="button"
258
- className="cg-swipe-side cg-swipe-side--left"
259
- disabled={!canWrite}
260
- style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}
261
- onClick={() => decide(binding.spec.leftOption)}
262
- title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
263
- >
264
- <span aria-hidden className="cg-swipe-arrow">
265
- <svg width="16" height="16" viewBox="0 0 16 16">
266
- <path
267
- d="M11 3.2 6.2 8l4.8 4.8"
268
- fill="none"
269
- stroke="currentColor"
270
- strokeWidth="1.6"
271
- strokeLinecap="round"
272
- strokeLinejoin="round"
273
- />
274
- </svg>
275
- </span>
276
- {binding.spec.leftOption}
277
- </button>
278
- <article
279
- className="cg-swipe-card"
280
- role="button"
281
- tabIndex={0}
282
- onClick={(e) => {
283
- // ⭐ W41-T48 — the card IS the deck's record open, so it folds the rail.
284
- // ⚠ Nothing that is NOT an open can reach this line: every control inside the
285
- // card (a url cell, the comments box, the document tray) already stops its own
286
- // click, and the left/right decision buttons are siblings of the card, not
287
- // children of it. The deck also has no pointer drag to disambiguate — its swipe
288
- // is the two buttons and the arrow keys, neither of which opens anything.
289
- // ⚠ `<article role="button">`, not a native button, so a keyboard activation
290
- // never arrives here as a synthetic click; the keydown path below is the whole
291
- // keyboard story and the two cannot both fire for one gesture.
292
- if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT);
293
- onOpen(card.pid);
294
- }}
295
- onKeyDown={(e) => {
296
- if (e.key !== "Enter" && e.key !== " ") return;
297
- e.preventDefault();
298
- // W41-T48 — `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space
299
- // auto-repeats keydown, and every one of those repeats is the SAME gesture.
300
- if (!e.repeat) signal(NAV_MINIMIZE_EVENT);
301
- onOpen(card.pid);
302
- }}
303
- >
304
- <h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3>
305
- <div className="cg-swipe-cells">
306
- {/* ⭐ WAVE-29 T26 (R9) — the RECORD's visible fields, not the three-key summary the
307
- kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not
308
- been widened yet renders exactly what it rendered before. */}
309
- {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {
310
- const f = fieldByKey.get(k);
311
- if (!f) return null;
312
- const text = formatDisplay(f, card[k]);
313
- if (!text) return null;
314
- // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
315
- // scheme guard — and every gesture that reaches it must be stopped from also
316
- // reaching the card, which is a button (the kanban card's note, same trap).
317
- const href = actionHref(f, card[k]);
318
- return (
319
- <div key={k} className="cg-swipe-cell">
320
- <span className="cg-lv-k">{f.label}</span>
321
- {href ? (
322
- <a
323
- className="cg-lv-v"
324
- href={href}
325
- target="_blank"
326
- rel="noopener noreferrer"
327
- title={text}
328
- onClick={(e) => e.stopPropagation()}
329
- onKeyDown={(e) => e.stopPropagation()}
330
- >
331
- {text}
332
- </a>
333
- ) : (
334
- <span className="cg-lv-v">{text}</span>
335
- )}
336
- </div>
337
- );
338
- })}
339
- </div>
340
- {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"`
341
- that opens the record, and a click on a comment box or an upload control must not
342
- also open the modal it exists to make unnecessary (the kanban card's link trap,
343
- one surface over). */}
344
- {onDocAdd && onDocFetch && onDocDelete && (
345
- <div
346
- className="cg-swipe-docs"
347
- onClick={(e) => e.stopPropagation()}
348
- onKeyDown={(e) => e.stopPropagation()}
349
- role="presentation"
350
- >
351
- <Documents
352
- pid={Number(card.pid)}
353
- docs={docs?.[String(card.pid)] ?? []}
354
- docPayload={docPayload}
355
- onAdd={(file) => onDocAdd(card.pid, file)}
356
- onFetch={(docId) => onDocFetch(card.pid, docId)}
357
- onDelete={(docId) => onDocDelete(card.pid, docId)}
358
- />
359
- </div>
360
- )}
361
- {scope != null && (
362
- <div
363
- className="cg-swipe-comments"
364
- onClick={(e) => e.stopPropagation()}
365
- onKeyDown={(e) => e.stopPropagation()}
366
- role="presentation"
367
- >
368
- {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React
369
- reuses the mounted instance across a card change and paints one record's
370
- comments under another's name until the fetch returns. */}
371
- <RecordComments
372
- key={`${scope}:${Number(card.pid)}`}
373
- scope={scope}
374
- pid={Number(card.pid)}
375
- viewer={viewer}
376
- />
377
- </div>
378
- )}
379
- {canWrite && (
380
- <button
381
- type="button"
382
- className="cg-link-btn cg-swipe-later"
383
- onClick={(e) => {
384
- e.stopPropagation();
385
- setLater((prev) => new Set(prev).add(card.pid));
386
- }}
387
- >
388
- Decide later
389
- </button>
390
- )}
391
- </article>
392
- <button
393
- type="button"
394
- className="cg-swipe-side cg-swipe-side--right"
395
- disabled={!canWrite}
396
- style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}
397
- onClick={() => decide(binding.spec.rightOption)}
398
- title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
399
- >
400
- {binding.spec.rightOption}
401
- <span aria-hidden className="cg-swipe-arrow">
402
- <svg width="16" height="16" viewBox="0 0 16 16">
403
- <path
404
- d="M5 3.2 9.8 8 5 12.8"
405
- fill="none"
406
- stroke="currentColor"
407
- strokeWidth="1.6"
408
- strokeLinecap="round"
409
- strokeLinejoin="round"
410
- />
411
- </svg>
412
- </span>
413
- </button>
414
- </div>
415
- ) : (
416
- // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
417
- // between "the deck is finished" and "the filter hid everything", and the two want
418
- // different next actions. `later` is disclosed rather than quietly subtracted.
419
- <div className="cg-mode-empty cg-swipe-empty">
420
- {later.size > 0 ? (
421
- <>
422
- <p>
423
- {later.size.toLocaleString()}{" "}
424
- {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
425
- in this view is missing a <strong>{field.label}</strong>.
426
- </p>
427
- <button type="button" className="cg-btn" onClick={() => setLater(new Set())}>
428
- Bring them back
429
- </button>
430
- </>
431
- ) : (
432
- <p>
433
- Every record in this view already has a <strong>{field.label}</strong>. Widen the
434
- view's filters to sort more.
435
- </p>
436
- )}
437
- </div>
438
- )}
439
- </div>
440
- );
441
- }
442
-
443
- /**
444
- * The binding picker: field + two options. It is also the surface every LOST binding lands on,
445
- * with the loss stated above it — one place that answers "what is this deck for", rather than an
446
- * error screen beside a separate setup screen.
447
- */
448
- function SwipeBinder({
449
- fault,
450
- fields,
451
- fieldByKey,
452
- spec,
453
- canBind,
454
- onSpec,
455
- }: {
456
- fault: BindingFault;
457
- fields: Field[];
458
- fieldByKey: Map<string, Field>;
459
- spec: SwipeSpec | undefined;
460
- canBind: boolean;
461
- onSpec: (next: SwipeSpec | undefined) => void;
462
- }) {
463
- const selects = useMemo(
464
- () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
465
- [fields]
466
- );
467
- const [fieldKey, setFieldKey] = useState<string>(() => {
468
- if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
469
- return selects[0]?.key ?? "";
470
- });
471
- const chosen = fieldByKey.get(fieldKey);
472
- const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
473
- const [left, setLeft] = useState<string>("");
474
- const [right, setRight] = useState<string>("");
475
-
476
- // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
477
- // pick survives re-renders, and reset whenever the field changes — carrying an option from the
478
- // previous field would offer a value the new field cannot hold.
479
- useEffect(() => {
480
- setLeft(options[0] ?? "");
481
- setRight(options.find((o) => o !== options[0]) ?? "");
482
- }, [options]);
483
-
484
- const message = ((): string => {
485
- switch (fault.kind) {
486
- case "field-gone":
487
- return "The field this deck sorted into has been deleted. Pick another one.";
488
- case "not-select":
489
- return `“${fault.field.label}” is no longer a single-select, so it has no options to`
490
- + " sort into. Pick another field.";
491
- case "option-gone":
492
- return `${fault.missing.map((m) => `“${m}”`).join(" and ")} ${
493
- fault.missing.length === 1 ? "is" : "are"
494
- } no longer ${fault.missing.length === 1 ? "an option" : "options"} on “${
495
- fault.field.label
496
- }”. Pick the sides again.`;
497
- default:
498
- return "Sort records one at a time into two options of a single-select field.";
499
- }
500
- })();
501
-
502
- if (!canBind) {
503
- return (
504
- <div className="cg-mode-empty">
505
- <p>{message}</p>
506
- <p>Its creator or an admin can set this view up.</p>
507
- </div>
508
- );
509
- }
510
- if (selects.length === 0) {
511
- // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
512
- // requirement is what turns a dead end into a next action.
513
- return (
514
- <div className="cg-mode-empty">
515
- <p>
516
- A swipe deck sorts into a single-select field with at least two options. This database
517
- does not have one yet — add a single-select column, then come back.
518
- </p>
519
- </div>
520
- );
521
- }
522
- const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
523
- return (
524
- <div className="cg-swipe-setup">
525
- <p className="cg-swipe-setup-note">{message}</p>
526
- <label className="cg-swipe-setup-row">
527
- <span>Sort into</span>
528
- <select
529
- className="cg-select"
530
- value={fieldKey}
531
- onChange={(e) => setFieldKey(e.target.value)}
532
- >
533
- {/* Every option carries an explicit `value`: a <select> whose value names nothing
534
- renders its FIRST option and reports a choice the user never made
535
- ([[cg-condition-builder-items]]). */}
536
- {selects.map((f) => (
537
- <option key={f.key} value={f.key}>
538
- {f.label}
539
- </option>
540
- ))}
541
- </select>
542
- </label>
543
- <div className="cg-swipe-setup-sides">
544
- <label className="cg-swipe-setup-row">
545
- <span>Swipe left</span>
546
- <select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>
547
- {options.map((o) => (
548
- <option key={o} value={o}>
549
- {o}
550
- </option>
551
- ))}
552
- </select>
553
- </label>
554
- <label className="cg-swipe-setup-row">
555
- <span>Swipe right</span>
556
- <select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>
557
- {options.map((o) => (
558
- <option key={o} value={o}>
559
- {o}
560
- </option>
561
- ))}
562
- </select>
563
- </label>
564
- </div>
565
- {!ready && left && right && (
566
- // Stated, not silently refused: both engines DROP a binding whose sides are the same
567
- // option, so a Save that looked like it worked would simply not persist.
568
- <p className="cg-swipe-setup-warn">
569
- The two sides must be different options — otherwise both gestures do the same thing.
570
- </p>
571
- )}
572
- <button
573
- type="button"
574
- className="cg-btn cg-btn--primary"
575
- disabled={!ready}
576
- onClick={() =>
577
- chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
578
- }
579
- >
580
- Start sorting
581
- </button>
582
- </div>
583
- );
584
- }
585
-
586
- export default SwipeView;
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / SwipeView.tsx
3
+ // ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) — the SWIPE deck.
4
+ //
5
+ // One record at a time, decided left or right into two options of ONE
6
+ // single-select. R2 fixes the shape and it is narrow on purpose:
7
+ // · SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
8
+ // · the deck holds only the records whose bound field is EMPTY — a record
9
+ // that already has a value has been decided, and re-asking is not triage.
10
+ // · a swipe writes through the NORMAL cell door (`onSwipe`, which the host
11
+ // maps to the same `patchAndRecord` a kanban card move uses), so undo,
12
+ // echo-suppression and the permission wall all hold without being
13
+ // re-implemented here.
14
+ //
15
+ // Honesty rules carried from the other modes:
16
+ // · nothing is silently hidden — the deck states what is left, and the
17
+ // empty state names the bound field rather than saying "all done".
18
+ // · a lost binding is SHOWN, never repaired by guessing. `_clean_display`
19
+ // validates that `fieldKey` names a field the table HAS and stops there;
20
+ // it cannot know the field is still a select, or that the two options are
21
+ // still in its vocabulary (its docstring draws that line explicitly). So
22
+ // those three losses land here, and each one says what happened and
23
+ // re-opens the picker — the `viewModes.tsx:190-194` rule, which exists
24
+ // because the wave-7 trap was a picker silently falling back to its first
25
+ // option.
26
+ // ---------------------------------------------------------------------------
27
+
28
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
+ // ⭐⭐ W41-T48 (owner instruction 22) — opening a record from the swipe deck folds the shell's
30
+ // navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`.
31
+ import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
32
+ import { choiceOptions } from "./types";
33
+ import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
34
+ // ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is
35
+ // loaded here) — the same import `RecordComments` takes for the same prop.
36
+ import type { SurfaceScope } from "./apiBridge";
37
+ import RecordComments from "./RecordComments";
38
+ import { Documents } from "./Documents";
39
+ import { formatDisplay } from "./cells";
40
+ import { actionHref } from "./display";
41
+ import { optionTint } from "./choiceColors";
42
+ import { ModeIcon } from "./icons";
43
+ // ⭐ W29-T73 — the line its three siblings all have, and the one this file shipped without.
44
+ // `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
45
+ // unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right —
46
+ // a partially-styled surface reads as a design choice, which is why nobody reported it and no
47
+ // gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
48
+ import "./SwipeView.css";
49
+
50
+ export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
51
+
52
+ /** The three ways a stored binding can rot that the host cannot see (see the header note). */
53
+ type BindingFault =
54
+ | { kind: "unbound" }
55
+ | { kind: "field-gone"; fieldKey: string }
56
+ | { kind: "not-select"; field: Field }
57
+ | { kind: "option-gone"; field: Field; missing: string[] };
58
+
59
+ function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):
60
+ { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
61
+ if (!spec) return { ok: false, fault: { kind: "unbound" } };
62
+ const field = fieldByKey.get(spec.fieldKey);
63
+ if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
64
+ // R2 — SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
65
+ // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
66
+ // adds and sometimes overwrites is two gestures wearing one button.
67
+ if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
68
+ const options = choiceOptions(field);
69
+ const has = new Set(options.map((o) => o.toLowerCase()));
70
+ const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
71
+ if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
72
+ return { ok: true, field, spec };
73
+ }
74
+
75
+ /** The bound cell is EMPTY — the one predicate that decides deck membership (R2). */
76
+ const isUndecided = (row: Row, key: string): boolean =>
77
+ String(row[key] ?? "").trim() === "";
78
+
79
+ export function SwipeView({
80
+ rows,
81
+ fields,
82
+ fieldByKey,
83
+ spec,
84
+ cardKeys,
85
+ detailKeys,
86
+ scope,
87
+ viewer,
88
+ docs,
89
+ docPayload,
90
+ onDocAdd,
91
+ onDocFetch,
92
+ onDocDelete,
93
+ titleKey,
94
+ canWrite,
95
+ readOnlyReason,
96
+ canBind,
97
+ onSpec,
98
+ onSwipe,
99
+ onOpen,
100
+ }: {
101
+ /** DISTINCT data rows from the full pipeline, overlay edits layered — the kanban's contract.
102
+ * The deck re-derives from these, so a written record leaves it as soon as the optimistic
103
+ * patch lands; there is no local cursor to drift out of step with the data. */
104
+ rows: Row[];
105
+ /** Every field, for the picker's field list. */
106
+ fields: Field[];
107
+ fieldByKey: Map<string, Field>;
108
+ /** The stored binding, or undefined for a deck nobody has configured yet. */
109
+ spec: SwipeSpec | undefined;
110
+ /** The handful of visible fields the card lists under its title. */
111
+ cardKeys: string[];
112
+ titleKey: string;
113
+ /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
114
+ canWrite: boolean;
115
+ /** Stated when the deck cannot be decided — permissions, or a computed column. */
116
+ readOnlyReason: string | null;
117
+ /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
118
+ * view-editing permission and NOT `canWrite` — conflating the two is
119
+ * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
120
+ * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
121
+ canBind: boolean;
122
+ /** `undefined` DELETES the binding — absent is the honest unconfigured state, and storing a
123
+ * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
124
+ onSpec: (next: SwipeSpec | undefined) => void;
125
+ onSwipe: (pid: number, value: string) => void;
126
+ onOpen: (pid: number) => void;
127
+ /**
128
+ * ⭐⭐ WAVE-29 T26 (owner R9) — WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.
129
+ *
130
+ * R9: *"the swipe CARD itself renders the record detail inline — fields, comments and
131
+ * attachments — so a reviewer decides without leaving the deck."* Everything below is that,
132
+ * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply
133
+ * different amounts. A card must render with none of them rather than throw — the standalone
134
+ * embed has no `scope`, and a deployment with no document storage serves no handlers.
135
+ */
136
+ /** Every field the VIEW shows, in its order — not the three-key card summary. */
137
+ detailKeys?: string[];
138
+ /** The surface these records live on. Comments are keyed by it; absent ⇒ no comments section,
139
+ * which is the pre-existing precondition `RecordDetail` already carries. */
140
+ scope?: SurfaceScope;
141
+ viewer?: Viewer;
142
+ /** This record's attachments, and the plumbing. Handlers absent ⇒ the section is not rendered
143
+ * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app
144
+ * cannot keep). */
145
+ /** Keyed by pid, because a deck shows many records — `RecordDetail` takes ONE record's list
146
+ * and that shape cannot serve a deck. */
147
+ docs?: Record<string, CustomerDoc[]>;
148
+ docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };
149
+ /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE
150
+ * open record. A deck paints many records at once, so a handler bound to a single pid would
151
+ * attach every reviewer's upload to whichever card happened to be open. */
152
+ onDocAdd?: (
153
+ pid: number,
154
+ file: { name: string; mime: string; size: number; data_b64: string }
155
+ ) => void;
156
+ onDocFetch?: (pid: number, docId: string) => void;
157
+ onDocDelete?: (pid: number, docId: string) => void;
158
+ }) {
159
+ // "Later" — session-only, never stored. A deck with no way past a record you cannot decide
160
+ // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
161
+ // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
162
+ // state rather than quietly shrinking the deck (rule 8b).
163
+ const [later, setLater] = useState<Set<number>>(new Set());
164
+ const deckRef = useRef<HTMLDivElement>(null);
165
+
166
+ const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
167
+ const boundKey = binding.ok ? binding.field.key : null;
168
+
169
+ const undecided = useMemo(
170
+ () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
171
+ [rows, boundKey]
172
+ );
173
+ const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
174
+ const card = deck[0];
175
+
176
+ // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever —
177
+ // otherwise the disclosed skip count drifts away from what is actually on the deck.
178
+ useEffect(() => {
179
+ setLater((prev) => {
180
+ if (prev.size === 0) return prev;
181
+ const live = new Set(undecided.map((r) => r.pid));
182
+ const next = new Set([...prev].filter((pid) => live.has(pid)));
183
+ return next.size === prev.size ? prev : next;
184
+ });
185
+ }, [undecided]);
186
+
187
+ const decide = useCallback(
188
+ (value: string) => {
189
+ if (!card || !canWrite) return;
190
+ onSwipe(card.pid, value);
191
+ },
192
+ [card, canWrite, onSwipe]
193
+ );
194
+
195
+ // ← / → decide, and they are the SAME two actions the buttons are rather than a second code
196
+ // path: the whole point of the mode is that one hand can clear a queue.
197
+ useEffect(() => {
198
+ if (!binding.ok || !canWrite || !card) return;
199
+ const onKey = (e: KeyboardEvent) => {
200
+ if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
201
+ const el = document.activeElement as HTMLElement | null;
202
+ // Never steal an arrow key from a text field or a native control the user is inside.
203
+ if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
204
+ return;
205
+ if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
206
+ e.preventDefault();
207
+ decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
208
+ };
209
+ window.addEventListener("keydown", onKey);
210
+ return () => window.removeEventListener("keydown", onKey);
211
+ }, [binding, canWrite, card, decide]);
212
+
213
+ if (!binding.ok) {
214
+ return (
215
+ <div className="cg-swipe" ref={deckRef}>
216
+ <SwipeBinder
217
+ fault={binding.fault}
218
+ fields={fields}
219
+ fieldByKey={fieldByKey}
220
+ spec={spec}
221
+ canBind={canBind}
222
+ onSpec={onSpec}
223
+ />
224
+ </div>
225
+ );
226
+ }
227
+
228
+ const { field } = binding;
229
+ const leftTint = optionTint(field, binding.spec.leftOption);
230
+ const rightTint = optionTint(field, binding.spec.rightOption);
231
+
232
+ return (
233
+ <div className="cg-swipe" ref={deckRef} tabIndex={-1}>
234
+ <div className="cg-swipe-bar">
235
+ <span className="cg-swipe-bound">
236
+ <ModeIcon mode="swipe" />
237
+ Sorting into <strong>{field.label}</strong>
238
+ </span>
239
+ <span className="cg-swipe-left">
240
+ {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
241
+ </span>
242
+ {canBind && (
243
+ <button
244
+ type="button"
245
+ className="cg-link-btn"
246
+ onClick={() => onSpec(undefined)}
247
+ title="Choose a different field or different options for this deck"
248
+ >
249
+ Change
250
+ </button>
251
+ )}
252
+ </div>
253
+ {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
254
+ {card ? (
255
+ <div className="cg-swipe-deck">
256
+ <button
257
+ type="button"
258
+ className="cg-swipe-side cg-swipe-side--left"
259
+ disabled={!canWrite}
260
+ style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}
261
+ onClick={() => decide(binding.spec.leftOption)}
262
+ title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
263
+ >
264
+ <span aria-hidden className="cg-swipe-arrow">
265
+ <svg width="16" height="16" viewBox="0 0 16 16">
266
+ <path
267
+ d="M11 3.2 6.2 8l4.8 4.8"
268
+ fill="none"
269
+ stroke="currentColor"
270
+ strokeWidth="1.6"
271
+ strokeLinecap="round"
272
+ strokeLinejoin="round"
273
+ />
274
+ </svg>
275
+ </span>
276
+ {binding.spec.leftOption}
277
+ </button>
278
+ <article
279
+ className="cg-swipe-card"
280
+ role="button"
281
+ tabIndex={0}
282
+ onClick={(e) => {
283
+ // ⭐ W41-T48 — the card IS the deck's record open, so it folds the rail.
284
+ // ⚠ Nothing that is NOT an open can reach this line: every control inside the
285
+ // card (a url cell, the comments box, the document tray) already stops its own
286
+ // click, and the left/right decision buttons are siblings of the card, not
287
+ // children of it. The deck also has no pointer drag to disambiguate — its swipe
288
+ // is the two buttons and the arrow keys, neither of which opens anything.
289
+ // ⚠ `<article role="button">`, not a native button, so a keyboard activation
290
+ // never arrives here as a synthetic click; the keydown path below is the whole
291
+ // keyboard story and the two cannot both fire for one gesture.
292
+ if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT);
293
+ onOpen(card.pid);
294
+ }}
295
+ onKeyDown={(e) => {
296
+ if (e.key !== "Enter" && e.key !== " ") return;
297
+ e.preventDefault();
298
+ // W41-T48 — `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space
299
+ // auto-repeats keydown, and every one of those repeats is the SAME gesture.
300
+ if (!e.repeat) signal(NAV_MINIMIZE_EVENT);
301
+ onOpen(card.pid);
302
+ }}
303
+ >
304
+ <h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3>
305
+ <div className="cg-swipe-cells">
306
+ {/* ⭐ WAVE-29 T26 (R9) — the RECORD's visible fields, not the three-key summary the
307
+ kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not
308
+ been widened yet renders exactly what it rendered before. */}
309
+ {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {
310
+ const f = fieldByKey.get(k);
311
+ if (!f) return null;
312
+ const text = formatDisplay(f, card[k]);
313
+ if (!text) return null;
314
+ // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
315
+ // scheme guard — and every gesture that reaches it must be stopped from also
316
+ // reaching the card, which is a button (the kanban card's note, same trap).
317
+ const href = actionHref(f, card[k]);
318
+ return (
319
+ <div key={k} className="cg-swipe-cell">
320
+ <span className="cg-lv-k">{f.label}</span>
321
+ {href ? (
322
+ <a
323
+ className="cg-lv-v"
324
+ href={href}
325
+ target="_blank"
326
+ rel="noopener noreferrer"
327
+ title={text}
328
+ onClick={(e) => e.stopPropagation()}
329
+ onKeyDown={(e) => e.stopPropagation()}
330
+ >
331
+ {text}
332
+ </a>
333
+ ) : (
334
+ <span className="cg-lv-v">{text}</span>
335
+ )}
336
+ </div>
337
+ );
338
+ })}
339
+ </div>
340
+ {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"`
341
+ that opens the record, and a click on a comment box or an upload control must not
342
+ also open the modal it exists to make unnecessary (the kanban card's link trap,
343
+ one surface over). */}
344
+ {onDocAdd && onDocFetch && onDocDelete && (
345
+ <div
346
+ className="cg-swipe-docs"
347
+ onClick={(e) => e.stopPropagation()}
348
+ onKeyDown={(e) => e.stopPropagation()}
349
+ role="presentation"
350
+ >
351
+ <Documents
352
+ pid={Number(card.pid)}
353
+ docs={docs?.[String(card.pid)] ?? []}
354
+ docPayload={docPayload}
355
+ onAdd={(file) => onDocAdd(card.pid, file)}
356
+ onFetch={(docId) => onDocFetch(card.pid, docId)}
357
+ onDelete={(docId) => onDocDelete(card.pid, docId)}
358
+ />
359
+ </div>
360
+ )}
361
+ {scope != null && (
362
+ <div
363
+ className="cg-swipe-comments"
364
+ onClick={(e) => e.stopPropagation()}
365
+ onKeyDown={(e) => e.stopPropagation()}
366
+ role="presentation"
367
+ >
368
+ {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React
369
+ reuses the mounted instance across a card change and paints one record's
370
+ comments under another's name until the fetch returns. */}
371
+ <RecordComments
372
+ key={`${scope}:${Number(card.pid)}`}
373
+ scope={scope}
374
+ pid={Number(card.pid)}
375
+ viewer={viewer}
376
+ />
377
+ </div>
378
+ )}
379
+ {canWrite && (
380
+ <button
381
+ type="button"
382
+ className="cg-link-btn cg-swipe-later"
383
+ onClick={(e) => {
384
+ e.stopPropagation();
385
+ setLater((prev) => new Set(prev).add(card.pid));
386
+ }}
387
+ >
388
+ Decide later
389
+ </button>
390
+ )}
391
+ </article>
392
+ <button
393
+ type="button"
394
+ className="cg-swipe-side cg-swipe-side--right"
395
+ disabled={!canWrite}
396
+ style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}
397
+ onClick={() => decide(binding.spec.rightOption)}
398
+ title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
399
+ >
400
+ {binding.spec.rightOption}
401
+ <span aria-hidden className="cg-swipe-arrow">
402
+ <svg width="16" height="16" viewBox="0 0 16 16">
403
+ <path
404
+ d="M5 3.2 9.8 8 5 12.8"
405
+ fill="none"
406
+ stroke="currentColor"
407
+ strokeWidth="1.6"
408
+ strokeLinecap="round"
409
+ strokeLinejoin="round"
410
+ />
411
+ </svg>
412
+ </span>
413
+ </button>
414
+ </div>
415
+ ) : (
416
+ // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
417
+ // between "the deck is finished" and "the filter hid everything", and the two want
418
+ // different next actions. `later` is disclosed rather than quietly subtracted.
419
+ <div className="cg-mode-empty cg-swipe-empty">
420
+ {later.size > 0 ? (
421
+ <>
422
+ <p>
423
+ {later.size.toLocaleString()}{" "}
424
+ {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
425
+ in this view is missing a <strong>{field.label}</strong>.
426
+ </p>
427
+ <button type="button" className="cg-btn" onClick={() => setLater(new Set())}>
428
+ Bring them back
429
+ </button>
430
+ </>
431
+ ) : (
432
+ <p>
433
+ Every record in this view already has a <strong>{field.label}</strong>. Widen the
434
+ view's filters to sort more.
435
+ </p>
436
+ )}
437
+ </div>
438
+ )}
439
+ </div>
440
+ );
441
+ }
442
+
443
+ /**
444
+ * The binding picker: field + two options. It is also the surface every LOST binding lands on,
445
+ * with the loss stated above it — one place that answers "what is this deck for", rather than an
446
+ * error screen beside a separate setup screen.
447
+ */
448
+ function SwipeBinder({
449
+ fault,
450
+ fields,
451
+ fieldByKey,
452
+ spec,
453
+ canBind,
454
+ onSpec,
455
+ }: {
456
+ fault: BindingFault;
457
+ fields: Field[];
458
+ fieldByKey: Map<string, Field>;
459
+ spec: SwipeSpec | undefined;
460
+ canBind: boolean;
461
+ onSpec: (next: SwipeSpec | undefined) => void;
462
+ }) {
463
+ const selects = useMemo(
464
+ () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
465
+ [fields]
466
+ );
467
+ const [fieldKey, setFieldKey] = useState<string>(() => {
468
+ if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
469
+ return selects[0]?.key ?? "";
470
+ });
471
+ const chosen = fieldByKey.get(fieldKey);
472
+ const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
473
+ const [left, setLeft] = useState<string>("");
474
+ const [right, setRight] = useState<string>("");
475
+
476
+ // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
477
+ // pick survives re-renders, and reset whenever the field changes — carrying an option from the
478
+ // previous field would offer a value the new field cannot hold.
479
+ useEffect(() => {
480
+ setLeft(options[0] ?? "");
481
+ setRight(options.find((o) => o !== options[0]) ?? "");
482
+ }, [options]);
483
+
484
+ const message = ((): string => {
485
+ switch (fault.kind) {
486
+ case "field-gone":
487
+ return "The field this deck sorted into has been deleted. Pick another one.";
488
+ case "not-select":
489
+ return `“${fault.field.label}” is no longer a single-select, so it has no options to`
490
+ + " sort into. Pick another field.";
491
+ case "option-gone":
492
+ return `${fault.missing.map((m) => `“${m}”`).join(" and ")} ${
493
+ fault.missing.length === 1 ? "is" : "are"
494
+ } no longer ${fault.missing.length === 1 ? "an option" : "options"} on “${
495
+ fault.field.label
496
+ }”. Pick the sides again.`;
497
+ default:
498
+ return "Sort records one at a time into two options of a single-select field.";
499
+ }
500
+ })();
501
+
502
+ if (!canBind) {
503
+ return (
504
+ <div className="cg-mode-empty">
505
+ <p>{message}</p>
506
+ <p>Its creator or an admin can set this view up.</p>
507
+ </div>
508
+ );
509
+ }
510
+ if (selects.length === 0) {
511
+ // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
512
+ // requirement is what turns a dead end into a next action.
513
+ return (
514
+ <div className="cg-mode-empty">
515
+ <p>
516
+ A swipe deck sorts into a single-select field with at least two options. This database
517
+ does not have one yet — add a single-select column, then come back.
518
+ </p>
519
+ </div>
520
+ );
521
+ }
522
+ const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
523
+ return (
524
+ <div className="cg-swipe-setup">
525
+ <p className="cg-swipe-setup-note">{message}</p>
526
+ <label className="cg-swipe-setup-row">
527
+ <span>Sort into</span>
528
+ <select
529
+ className="cg-select"
530
+ value={fieldKey}
531
+ onChange={(e) => setFieldKey(e.target.value)}
532
+ >
533
+ {/* Every option carries an explicit `value`: a <select> whose value names nothing
534
+ renders its FIRST option and reports a choice the user never made
535
+ ([[cg-condition-builder-items]]). */}
536
+ {selects.map((f) => (
537
+ <option key={f.key} value={f.key}>
538
+ {f.label}
539
+ </option>
540
+ ))}
541
+ </select>
542
+ </label>
543
+ <div className="cg-swipe-setup-sides">
544
+ <label className="cg-swipe-setup-row">
545
+ <span>Swipe left</span>
546
+ <select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>
547
+ {options.map((o) => (
548
+ <option key={o} value={o}>
549
+ {o}
550
+ </option>
551
+ ))}
552
+ </select>
553
+ </label>
554
+ <label className="cg-swipe-setup-row">
555
+ <span>Swipe right</span>
556
+ <select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>
557
+ {options.map((o) => (
558
+ <option key={o} value={o}>
559
+ {o}
560
+ </option>
561
+ ))}
562
+ </select>
563
+ </label>
564
+ </div>
565
+ {!ready && left && right && (
566
+ // Stated, not silently refused: both engines DROP a binding whose sides are the same
567
+ // option, so a Save that looked like it worked would simply not persist.
568
+ <p className="cg-swipe-setup-warn">
569
+ The two sides must be different options — otherwise both gestures do the same thing.
570
+ </p>
571
+ )}
572
+ <button
573
+ type="button"
574
+ className="cg-btn cg-btn--primary"
575
+ disabled={!ready}
576
+ onClick={() =>
577
+ chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
578
+ }
579
+ >
580
+ Start sorting
581
+ </button>
582
+ </div>
583
+ );
584
+ }
585
+
586
+ export default SwipeView;
web/src/customer-grid/Toolbar.tsx CHANGED
@@ -100,8 +100,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,6 +251,9 @@ 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) -----------------------
@@ -299,11 +309,11 @@ 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
  }
@@ -625,6 +635,30 @@ function SortBuilder({
625
  );
626
  }
627
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
628
  const ROW_OPTIONS: { mode: RowHeightMode; label: string }[] = [
629
  { mode: "short", label: "Short" },
630
  { mode: "medium", label: "Medium" },
@@ -652,8 +686,11 @@ export default function Toolbar({
652
  onFilters,
653
  filterConj,
654
  onFilterConj,
 
655
  sorts,
656
  onSorts,
 
 
657
  groupBy,
658
  onGroupBy,
659
  statusValues,
@@ -683,6 +720,8 @@ export default function Toolbar({
683
  onRelationalWindow,
684
  sourceLabel,
685
  onViewActions,
 
 
686
  }: ToolbarProps) {
687
  const shownCount = fields.filter((f) => visible.has(f.key)).length;
688
 
@@ -791,8 +830,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";
@@ -867,7 +910,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 +942,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 +1094,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 +1158,29 @@ 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
 
 
100
  /** conjunction joining the ROOT-level conditions */
101
  filterConj: Conjunction;
102
  onFilterConj: (c: Conjunction) => void;
103
+ /** A server-projected locked leaf freezes the whole tree: moving a group or changing the
104
+ * root conjunction rewrites that leaf's semantics too. */
105
+ filtersLocked?: boolean;
106
  sorts: SortSpec;
107
  onSorts: (s: SortSpec) => void;
108
+ /** A locked sort preserves the ordered sort list as one immutable record. */
109
+ sortsLocked?: boolean;
110
+ /** Duplicate the active View; the new id is C3's only alteration path. */
111
+ onCopyToChange?: () => void;
112
  // grouping — Batch 4: bucket rows by a text/status field (null = ungrouped)
113
  groupBy: string | null;
114
  onGroupBy: (key: string | null) => void;
 
251
  sourceLabel?: string;
252
  /** Opens the active view's existing ellipsis menu. */
253
  onViewActions?: (anchor: HTMLButtonElement) => void;
254
+ /** The active view's fullscreen door belongs beside Edit, not below the whole toolbar. */
255
+ fullscreen?: boolean;
256
+ onFullscreen?: () => void;
257
  }
258
 
259
  // --- tiny inline icons (14px, stroke = currentColor) -----------------------
 
309
  </svg>
310
  );
311
  }
312
+ function IconEdit() {
313
  return (
314
  <svg {...ic} aria-hidden>
315
+ <path d="m3 11.8.7-2.5L10.5 2.5l2.9 2.9-6.8 6.8L4 13Z" {...stroke} />
316
+ <path d="m9.5 3.5 2.9 2.9" {...stroke} />
317
  </svg>
318
  );
319
  }
 
635
  );
636
  }
637
 
638
+ function ImmutableViewConfigNotice({
639
+ subject,
640
+ onCopyToChange,
641
+ }: {
642
+ subject: "filters" | "sorts";
643
+ onCopyToChange?: () => void;
644
+ }) {
645
+ return (
646
+ <div className="cg-pop-body">
647
+ <div className="cg-pop-title">{subject === "filters" ? "Filters locked" : "Sorts locked"}</div>
648
+ <div className="cg-pop-note">
649
+ These {subject} are immutable on this View. Copy it to make changes.
650
+ </div>
651
+ {onCopyToChange && (
652
+ <div className="cg-pop-footer cg-builder-footer">
653
+ <button type="button" className="cg-btn" onClick={onCopyToChange}>
654
+ Copy to change
655
+ </button>
656
+ </div>
657
+ )}
658
+ </div>
659
+ );
660
+ }
661
+
662
  const ROW_OPTIONS: { mode: RowHeightMode; label: string }[] = [
663
  { mode: "short", label: "Short" },
664
  { mode: "medium", label: "Medium" },
 
686
  onFilters,
687
  filterConj,
688
  onFilterConj,
689
+ filtersLocked = false,
690
  sorts,
691
  onSorts,
692
+ sortsLocked = false,
693
+ onCopyToChange,
694
  groupBy,
695
  onGroupBy,
696
  statusValues,
 
720
  onRelationalWindow,
721
  sourceLabel,
722
  onViewActions,
723
+ fullscreen = false,
724
+ onFullscreen,
725
  }: ToolbarProps) {
726
  const shownCount = fields.filter((f) => visible.has(f.key)).length;
727
 
 
830
  : n.rhs != null && n.rhs.kind !== "stat"));
831
  return walk(filters);
832
  }, [filters]);
833
+ const filterLabel = `${conditionCount ? `Filter · ${conditionCount}` : "Filter"}${
834
+ filtersLocked ? " · Locked" : ""
835
+ }`;
836
+ const sortLabel = `${sorts.length ? `Sort · ${sorts.length}` : "Sort"}${
837
+ sortsLocked ? " · Locked" : ""
838
+ }`;
839
  const groupLabel = groupBy
840
  ? `Group: ${fieldByKey.get(groupBy)?.label ?? "?"}`
841
  : "Group";
 
910
  pairWide={hasComparand}
911
  forceOpenSignal={filterSeed?.n}
912
  >
913
+ {(close) => filtersLocked ? (
914
+ <ImmutableViewConfigNotice subject="filters" onCopyToChange={onCopyToChange} />
915
+ ) : (
916
  <FilterBuilderPanel
917
  // The COMPLETE list: the kit narrows the picker to the filterable ones itself and
918
  // keeps the full map for resolving a condition saved against a column that has
 
942
  {/* Sort — multi-level. Deliberately over ALL fields: "rank by estimated missed dollars"
943
  is exactly what a score is FOR, even though a condition on it is not. */}
944
  <Popover label={sortLabel} icon={<IconSort />} active={sorts.length > 0} tone="sort" wide>
945
+ {() => sortsLocked ? (
946
+ <ImmutableViewConfigNotice subject="sorts" onCopyToChange={onCopyToChange} />
947
+ ) : (
948
  <SortBuilder
949
  fields={fields}
950
  fieldByKey={fieldByKey}
 
1094
 
1095
  ⚠ RADIO ROWS, the same markup "Group by" and "Color by" use for the same
1096
  "which one?" question. DESIGN §4: new nav joins the existing rhythm. */}
1097
+ <div className="cg-tb-related">
1098
  <Popover
1099
  label={relationalLabel}
1100
  icon={<IconRelational />}
 
1158
  </div>
1159
  )}
1160
  </Popover>
1161
+ </div>
1162
 
1163
  {onViewActions && (
1164
  <button
1165
  type="button"
1166
  className="cg-tb-btn cg-view-actions"
1167
+ aria-label="Edit view"
1168
+ title="Edit view"
1169
  onClick={(event) => onViewActions(event.currentTarget)}
1170
  >
1171
+ <IconEdit />
1172
+ <span className="cg-tb-label">Edit</span>
1173
+ </button>
1174
+ )}
1175
+
1176
+ {onFullscreen && (
1177
+ <button
1178
+ type="button"
1179
+ className="cg-tb-btn cg-fullscreen-toggle"
1180
+ aria-pressed={fullscreen}
1181
+ onClick={onFullscreen}
1182
+ >
1183
+ {fullscreen ? "Exit fullscreen" : "Fullscreen"}
1184
  </button>
1185
  )}
1186
 
web/src/customer-grid/ViewSidebar.tsx CHANGED
@@ -287,6 +287,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,
@@ -570,6 +576,8 @@ export default function ViewSidebar({
570
  onCohortLock,
571
  today,
572
  onExport,
 
 
573
  folders,
574
  folderIdOf,
575
  onFolderCreate,
@@ -623,6 +631,12 @@ 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;
@@ -1716,6 +1730,12 @@ 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
@@ -1786,7 +1806,7 @@ 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
@@ -1795,7 +1815,10 @@ export default function ViewSidebar({
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";
@@ -1922,7 +1945,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"
@@ -2607,7 +2630,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 +2654,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
  >
@@ -2965,31 +2991,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
 
 
287
  * client does not hold the rows (server-windowed), so the entry never lies.
288
  */
289
  onExport?: (viewId: string, format: ExportFormat) => void;
290
+ /** C3 bulk-export path. The caller sends these visible View ids to the server, which evaluates
291
+ * every tab before the browser gives its result to the one XLSX writer. */
292
+ onExportXlsxViews?: (viewIds: string[]) => void;
293
+ /** The server-visible saved Views accepted by C3's export endpoint. Rail-only projections
294
+ * (for example an unsaved script result) remain out of the chooser. */
295
+ exportableViewIds?: readonly string[];
296
  /**
297
  * Wave-8 I11c (contract C4) — folders. All of it is OPTIONAL: a caller that
298
  * passes no `folders` and no handlers renders exactly the pre-wave-8 flat rail,
 
576
  onCohortLock,
577
  today,
578
  onExport,
579
+ onExportXlsxViews,
580
+ exportableViewIds,
581
  folders,
582
  folderIdOf,
583
  onFolderCreate,
 
631
  viewId: string;
632
  anchor: HTMLElement;
633
  } | null>(null);
634
+ /** C3 begins with the View whose menu opened this pane; later picks are explicit. */
635
+ const [exportViewIds, setExportViewIds] = useState<string[]>([]);
636
+ const xlsxExportViews = useMemo(() => {
637
+ const allowed = new Set(exportableViewIds ?? []);
638
+ return views.filter((view) => allowed.has(view.id));
639
+ }, [views, exportableViewIds]);
640
  const exportView = exportFor
641
  ? views.find((view) => view.id === exportFor.viewId)
642
  : undefined;
 
1730
  // "Shared with me" while offering them on a colleague's folder would emit `item_move` /
1731
  // `folder_rename` / `folder_delete` against an id that exists in nobody's store.
1732
  const isSynthetic = isSyntheticFolderId(gid);
1733
+ // C1 injects this system-owned folder into the ordinary folder list. It remains
1734
+ // readable and expandable, but no generic rename, move, delete, or menu control is
1735
+ // offered for it. Keep the additive wire fact local until its broader type owner lands.
1736
+ const isManaged =
1737
+ (group.folder as (GridFolder & { managedBy?: "loopable" }) | undefined)?.managedBy ===
1738
+ "loopable";
1739
  const shut = gid != null && collapsed.has(gid);
1740
  return (
1741
  <div
 
1806
  `item_move(id, ROOT_FOLDER_ID)` — a stored placement, which is the very thing that
1807
  takes a view OUT of this group. The drop would file the view and then move it
1808
  somewhere else on screen. The ungrouped section below is the one root target. */
1809
+ ...(isSynthetic || isManaged || isPinnedGroup ? {} : dropHandlers(gid))}
1810
  >
1811
  {group.folder && (
1812
  <div
 
1815
  // Draggable only while it is renameable-idle: a `draggable` ancestor eats
1816
  // the text selection inside an input, so dragging would win over editing
1817
  // the name you just opened.
1818
+ draggable={
1819
+ foldsReorderable && !isSynthetic && !isManaged &&
1820
+ renamingFolder !== group.folder.id
1821
+ }
1822
  onDragStart={(e) => {
1823
  e.dataTransfer.setData(FOLD_DRAG_TYPE, group.folder!.id);
1824
  e.dataTransfer.effectAllowed = "move";
 
1945
  group, for the reason the block above gives: a colleague's shared folder is no
1946
  more the reader's to rename, duplicate or delete than "Shared with me" is, and
1947
  every row of that menu would be refused by a server that has no such folder. */}
1948
+ {isSynthetic || isManaged ? null : (
1949
  <button
1950
  type="button"
1951
  className="cg-view-more"
 
2630
  dataKind="saved-view-menu"
2631
  >
2632
  {/* W2 (C2): Export sits ABOVE the rename/delete group, thin divider between. */}
2633
+ {(onExport || onExportXlsxViews || onImport) && (
2634
  <>
2635
  {/* ⭐ WAVE-29 T32 (owner item 16 / R10) — the DATA group's header.
2636
  The owner's complaint was that Export "looks like an orphan": it is already the
 
2654
  >
2655
  Data
2656
  </div>
2657
+ {(onExport || onExportXlsxViews) && (
2658
  <button
2659
  type="button"
2660
  role="menuitem"
2661
  onClick={() => {
2662
  setExportFor({ viewId: menuView.id, anchor: menu.anchor });
2663
+ setExportViewIds(
2664
+ exportableViewIds?.includes(menuView.id) ? [menuView.id] : []
2665
+ );
2666
  setMenu(null);
2667
  }}
2668
  >
 
2991
  {/* W2 (C2) — the format pane: CSV · Excel · PDF · JSON, keyboard-navigable like
2992
  the menu it came from. Rows/columns are the view's CURRENT matches and visible
2993
  fields; generation is client-side (the grid already holds the answer). */}
2994
+ {exportFor && exportView && (onExport || onExportXlsxViews) && (
2995
  <AnchoredOverlay
2996
  anchor={exportFor.anchor}
2997
  className="cg-view-menu"
2998
  placement="bottom-end"
2999
+ role="dialog"
3000
  ariaLabel={`Export ${viewDisplayName(exportView)}`}
3001
  onDismiss={() => setExportFor(null)}
3002
  onKeyDown={onMenuKeyDown}
3003
  dataKind="view-export"
3004
  >
3005
  <div className="cg-pop-title cg-export-title">Export {viewDisplayName(exportView)}</div>
3006
+ {onExportXlsxViews && (
3007
+ <div className="cg-pop-body">
3008
+ <div className="cg-pop-note">Each selected View becomes its own Excel tab.</div>
3009
+ {xlsxExportViews.map((view) => {
3010
+ const selected = exportViewIds.includes(view.id);
3011
+ return (
3012
+ <label key={view.id} className="cg-radio-row">
3013
+ <input
3014
+ type="checkbox"
3015
+ checked={selected}
3016
+ disabled={(selected && exportViewIds.length === 1) ||
3017
+ (!selected && exportViewIds.length >= 20)}
3018
+ onChange={() =>
3019
+ setExportViewIds((current) => selected
3020
+ ? current.filter((id) => id !== view.id)
3021
+ : [...current, view.id])
3022
+ }
3023
+ />
3024
+ <span>{viewDisplayName(view)}</span>
3025
+ </label>
3026
+ );
3027
+ })}
3028
+ </div>
3029
+ )}
3030
+ {EXPORT_FORMATS.map((format) => {
3031
+ if (format === "xlsx" && onExportXlsxViews) {
3032
+ return (
3033
+ <button
3034
+ key={format}
3035
+ type="button"
3036
+ role="menuitem"
3037
+ disabled={exportViewIds.length === 0}
3038
+ onClick={() => {
3039
+ onExportXlsxViews(exportViewIds);
3040
+ setExportFor(null);
3041
+ }}
3042
+ >
3043
+ Export Excel
3044
+ </button>
3045
+ );
3046
+ }
3047
+ if (!onExport) return null;
3048
+ return (
3049
+ <button
3050
+ key={format}
3051
+ type="button"
3052
+ role="menuitem"
3053
+ onClick={() => {
3054
+ onExport(exportView.id, format);
3055
+ setExportFor(null);
3056
+ }}
3057
+ >
3058
+ {EXPORT_LABELS[format]}
3059
+ </button>
3060
+ );
3061
+ })}
3062
  </AnchoredOverlay>
3063
  )}
3064
 
web/src/customer-grid/dataPath.ts ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Canonical, shareable Data addressing. The shell keeps the global main navigation;
2
+ // this describes only the Data workspace's secondary location.
3
+ export interface DataPath {
4
+ database: string;
5
+ view?: string;
6
+ field?: string;
7
+ }
8
+
9
+ export function dataPathHash(path: DataPath): string {
10
+ const query = new URLSearchParams({ database: path.database });
11
+ if (path.view) query.set("view", path.view);
12
+ if (path.field) query.set("field", path.field);
13
+ return `#/data?${query.toString()}`;
14
+ }
15
+
16
+ export function readDataPath(hash?: string): DataPath | null {
17
+ const source = hash ?? (typeof window === "undefined" ? "" : window.location.hash);
18
+ if (!source.startsWith("#/data?")) return null;
19
+ const query = new URLSearchParams(source.slice("#/data?".length));
20
+ const database = query.get("database");
21
+ if (!database) return null;
22
+ return {
23
+ database,
24
+ ...(query.get("view") ? { view: query.get("view")! } : {}),
25
+ ...(query.get("field") ? { field: query.get("field")! } : {}),
26
+ };
27
+ }
28
+
29
+ export function dataPathLabel(database: string, view?: string): string {
30
+ return ["Data", database, view].filter((part): part is string => !!part).join(" > ");
31
+ }
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/map.css CHANGED
@@ -236,6 +236,28 @@
236
 
237
  .cg-map-zone:hover { fill-opacity: 0.28; }
238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  .cg-map-zones {
240
  display: flex;
241
  align-items: end;
 
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: flex; justify-content: space-between; gap: 8px; }
254
+ .cg-w44-route-order { width: 42px; margin-left: 4px; border: 1px solid var(--lp-line); border-radius: var(--lp-r-sm); background: var(--cg-white); color: inherit; font: inherit; }
255
+ .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; }
256
+ .cg-w44-route-sources { margin: 0; padding: 6px; border: 1px solid var(--lp-line); border-radius: var(--lp-r-sm); }
257
+ .cg-w44-route-sources label { display: flex; gap: 5px; align-items: center; }
258
+ .cg-w44-route-stops button, .cg-w44-route-back, .cg-w44-route-maps { color: var(--lp-blue-deep); }
259
+ .cg-w44-route-warning { color: var(--lp-yellow-deep); font: 500 var(--lp-fs-3xs)/1.4 Inter, system-ui, sans-serif; }
260
+
261
  .cg-map-zones {
262
  display: flex;
263
  align-items: end;
web/src/customer-grid/routeZoneTypes.ts ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Wave 44 Route / Zone wire model. MapView never writes a legacy Destination N field.
2
+ export interface ZoneGeometry {
3
+ type: "Polygon" | "MultiPolygon";
4
+ coordinates: number[][][] | number[][][][];
5
+ }
6
+
7
+ export interface MapZoneDto {
8
+ id: string; name: string; color: string; geometryGeoJson: ZoneGeometry;
9
+ zipCodes: string[]; visible: boolean; memberships: number[];
10
+ permission?: { canEdit?: boolean };
11
+ }
12
+
13
+ export interface MapRouteDto {
14
+ id: string; name: string; color: string; number: number; visibleStopIds: number[];
15
+ outsideFilter: boolean;
16
+ permission: { canEdit: boolean; sourceViewId: string };
17
+ source: { viewId: string; revision: string };
18
+ mapsUrl?: string;
19
+ }
20
+
21
+ export interface RouteSelectionRequest { routeIds: string[]; viewState: Record<string, unknown>; }
22
+
23
+ export interface RouteSelectionResponse {
24
+ managedBy: "loopable";
25
+ viewState: Record<string, unknown>;
26
+ }
27
+
28
+ /** The two authored sources that can become a named Route. */
29
+ export type MapRouteSource = {
30
+ id: "selection" | "zones";
31
+ label: string;
32
+ pids: number[];
33
+ };
34
+
35
+ /** A map may show one navigator at a time. The Routes rail wins when its host toggle is open. */
36
+ export function mapNavigatorMode(routeOpen: boolean, zoneOpen: boolean): "routes" | "zones" | null {
37
+ if (routeOpen) return "routes";
38
+ return zoneOpen ? "zones" : null;
39
+ }
40
+
41
+ /** Toggle exactly one named Route while preserving the existing multi-selection. */
42
+ export function toggleRouteSelection(selected: ReadonlySet<string>, routeId: string): Set<string> {
43
+ const next = new Set(selected);
44
+ if (next.has(routeId)) next.delete(routeId);
45
+ else next.add(routeId);
46
+ return next;
47
+ }
48
+
49
+ /** Route creation never submits duplicate, empty, or non-customer IDs from either source. */
50
+ export function routeSourceStopIds(pids: Iterable<number>): number[] {
51
+ return [...new Set([...pids].filter((pid) => Number.isSafeInteger(pid) && pid > 0))];
52
+ }
53
+
54
+ /** ZIP boundaries are a union: whitespace and duplicate entries do not create duplicate members. */
55
+ export function normalizedZoneZipCodes(value: string): string[] {
56
+ return [...new Set(value.split(/[\s,]+/).filter((zip) => /^\d{5}(?:-\d{4})?$/.test(zip)))];
57
+ }
58
+
59
+ /** Only a bounded HTTPS Google Maps link may leave the in-app Route detail. */
60
+ export function boundedGoogleMapsUrl(value: string | undefined): string | null {
61
+ if (!value || value.length > 2_048) return null;
62
+ try {
63
+ const url = new URL(value);
64
+ return url.protocol === "https:" && /(^|\.)google\.[a-z.]+$/i.test(url.hostname) ? url.href : null;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
web/src/customer-grid/types.ts CHANGED
@@ -2113,6 +2113,12 @@ export interface Field {
2113
  labelCorrectionId?: string;
2114
  type: FieldType;
2115
  source: FieldSource;
 
 
 
 
 
 
2116
  /**
2117
  * Computed by the HOST per render rather than read off a source row — today the cohort
2118
  * column. It carries `source: "odoo"` because that is what makes a column read-only at both
 
2113
  labelCorrectionId?: string;
2114
  type: FieldType;
2115
  source: FieldSource;
2116
+ /** Owner-controlled lifecycle lock; it blocks deletion without blocking edits. */
2117
+ deletionLocked?: boolean;
2118
+ /** C3's declared field provenance; the client renders it rather than inferring it. */
2119
+ origin?: "odoo" | "loopable" | "system" | "user" | "automation";
2120
+ /** C3's declared owner of the cell value. */
2121
+ valueAuthority?: "source" | "derived" | "user-entered" | "computed";
2122
  /**
2123
  * Computed by the HOST per render rather than read off a source row — today the cohort
2124
  * column. It carries `source: "odoo"` because that is what makes a column read-only at both
web/src/shell/Shell.tsx CHANGED
@@ -66,6 +66,7 @@ const AutomationSurface = lazy(() => import("../automation/AutomationSurface"));
66
  const CustomerGrid = lazy(() => import("../customer-grid/CustomerGrid"));
67
  import { clearCustomersCache, currentSurfaceScope } from "../customer-grid/apiBridge";
68
  import { OverlayProvider } from "../customer-grid/OverlaySurface";
 
69
  // ROWS_STALE_EVENT left with `addRecord` (wave 20 item 4): the shell no longer writes rows,
70
  // so it no longer has to tell the grid that it did.
71
  import { AGENTS_CHANGED, API_V1, AUTOMATION_OPEN_EVENT, CREDENTIALS, DATA_ERROR_EVENT, NAV_MINIMIZE_EVENT, TOAST_EVENT, UNAUTHORIZED_EVENT, VIEW_OPEN_EVENT, signal } from "../apiContract";
@@ -1042,6 +1043,7 @@ function ShellFrame() {
1042
  * have TWO ladders racing, and the older one would yank them back to the previous view. */
1043
  const viewEmitCancel = useRef<null | (() => void)>(null);
1044
  const route = useHashRoute();
 
1045
  /**
1046
  * ⭐⭐ WAVE 35 · T06/T09 (asks B-2 and B-8) — OPEN A VIEW INSIDE ITS DATABASE. One handler,
1047
  * passed to BOTH `HomePage` and `StarredPage`, so a starred view opened from Home and the same
@@ -1075,7 +1077,7 @@ function ShellFrame() {
1075
  // invented a second vocabulary for the same thing. [[one-question-two-normalizers]]
1076
  // ⚠ The failure is silent by construction, which is why no gate saw it: a route that does not
1077
  // resolve is the SAME code path as "no route yet", and that path renders Home on purpose.
1078
- window.location.hash = `#/${database}`;
1079
  viewEmitCancel.current?.();
1080
  viewEmitCancel.current = retryEmit(
1081
  () => {
@@ -1776,7 +1778,9 @@ function ShellFrame() {
1776
  // Home mean "most recently opened".
1777
  useEffect(() => {
1778
  if (session.phase !== "authed") return;
1779
- const hit = resolveRoute(entries, route);
 
 
1780
  if (!hit || hit.kind !== "native") {
1781
  lastStamped.current = "";
1782
  return;
@@ -1785,7 +1789,7 @@ function ShellFrame() {
1785
  lastStamped.current = hit.key;
1786
  postOpened(hit.key);
1787
  setOpened((cur) => ({ ...cur, [hit.key]: Math.floor(Date.now() / 1000) }));
1788
- }, [session.phase, route, entries]);
1789
 
1790
  const signOut = useCallback(() => {
1791
  // The cached customer payload dies with the session: the next sign-in on
@@ -2021,7 +2025,9 @@ function ShellFrame() {
2021
  );
2022
  }
2023
 
2024
- const active = resolveRoute(entries, route);
 
 
2025
  const utility = nav.phase === "ready" ? nav.utility : NO_UTILITY;
2026
  const analyst = findAnalyst(utility);
2027
  // ── WAVE 19 R10 / C3: Automation LEAVES THE DATABASE LIST ────────────────────
@@ -2818,7 +2824,11 @@ function ShellFrame() {
2818
  // pointing at a database they never opened.
2819
  const link =
2820
  item.kind === "native" ? (
2821
- <a className={cls} href={item.href} onClick={() => pushDb(item.key)}>
 
 
 
 
2822
  {inner}
2823
  </a>
2824
  ) : (
@@ -2849,7 +2859,7 @@ function ShellFrame() {
2849
  // true. The folder-reorder drag and the row menu therefore keep working with
2850
  // the rail folded, which is the state a user who opened this panel is most
2851
  // likely to be in.
2852
- draggable={item.depth === 0}
2853
  onDragStart={(e) => {
2854
  e.dataTransfer.setData(NAV_DRAG_TYPE, item.key);
2855
  e.dataTransfer.effectAllowed = "move";
@@ -2861,7 +2871,7 @@ function ShellFrame() {
2861
  }}
2862
  >
2863
  {link}
2864
- {item.depth === 0 && (
2865
  <RowMenu
2866
  entryLabel={item.label}
2867
  canSchema
@@ -3199,7 +3209,12 @@ function ShellFrame() {
3199
  when they diverge — `CustomerGrid`'s VIEW_OPEN listener drops an event whose
3200
  `topic` is the other one. [[one-question-two-normalizers]] */}
3201
  <Lazily surface={active.label || "Database"}>
3202
- <CustomerGrid key={active.key} scope={gridScopeFor(active.key)} />
 
 
 
 
 
3203
  </Lazily>
3204
  </OverlayProvider>
3205
  </div>
 
66
  const CustomerGrid = lazy(() => import("../customer-grid/CustomerGrid"));
67
  import { clearCustomersCache, currentSurfaceScope } from "../customer-grid/apiBridge";
68
  import { OverlayProvider } from "../customer-grid/OverlaySurface";
69
+ import { dataPathHash, readDataPath } from "../customer-grid/dataPath";
70
  // ROWS_STALE_EVENT left with `addRecord` (wave 20 item 4): the shell no longer writes rows,
71
  // so it no longer has to tell the grid that it did.
72
  import { AGENTS_CHANGED, API_V1, AUTOMATION_OPEN_EVENT, CREDENTIALS, DATA_ERROR_EVENT, NAV_MINIMIZE_EVENT, TOAST_EVENT, UNAUTHORIZED_EVENT, VIEW_OPEN_EVENT, signal } from "../apiContract";
 
1043
  * have TWO ladders racing, and the older one would yank them back to the previous view. */
1044
  const viewEmitCancel = useRef<null | (() => void)>(null);
1045
  const route = useHashRoute();
1046
+ const dataPath = readDataPath();
1047
  /**
1048
  * ⭐⭐ WAVE 35 · T06/T09 (asks B-2 and B-8) — OPEN A VIEW INSIDE ITS DATABASE. One handler,
1049
  * passed to BOTH `HomePage` and `StarredPage`, so a starred view opened from Home and the same
 
1077
  // invented a second vocabulary for the same thing. [[one-question-two-normalizers]]
1078
  // ⚠ The failure is silent by construction, which is why no gate saw it: a route that does not
1079
  // resolve is the SAME code path as "no route yet", and that path renders Home on purpose.
1080
+ window.location.hash = dataPathHash({ database, view: viewId });
1081
  viewEmitCancel.current?.();
1082
  viewEmitCancel.current = retryEmit(
1083
  () => {
 
1778
  // Home mean "most recently opened".
1779
  useEffect(() => {
1780
  if (session.phase !== "authed") return;
1781
+ const hit =
1782
+ (dataPath ? entries.find((entry) => entry.key === dataPath.database) : undefined) ??
1783
+ resolveRoute(entries, route);
1784
  if (!hit || hit.kind !== "native") {
1785
  lastStamped.current = "";
1786
  return;
 
1789
  lastStamped.current = hit.key;
1790
  postOpened(hit.key);
1791
  setOpened((cur) => ({ ...cur, [hit.key]: Math.floor(Date.now() / 1000) }));
1792
+ }, [session.phase, route, entries, dataPath?.database]);
1793
 
1794
  const signOut = useCallback(() => {
1795
  // The cached customer payload dies with the session: the next sign-in on
 
2025
  );
2026
  }
2027
 
2028
+ const active =
2029
+ (dataPath ? entries.find((entry) => entry.key === dataPath.database) : undefined) ??
2030
+ resolveRoute(entries, route);
2031
  const utility = nav.phase === "ready" ? nav.utility : NO_UTILITY;
2032
  const analyst = findAnalyst(utility);
2033
  // ── WAVE 19 R10 / C3: Automation LEAVES THE DATABASE LIST ────────────────────
 
2824
  // pointing at a database they never opened.
2825
  const link =
2826
  item.kind === "native" ? (
2827
+ <a
2828
+ className={cls}
2829
+ href={dataPathHash({ database: item.key })}
2830
+ onClick={() => pushDb(item.key)}
2831
+ >
2832
  {inner}
2833
  </a>
2834
  ) : (
 
2859
  // true. The folder-reorder drag and the row menu therefore keep working with
2860
  // the rail folded, which is the state a user who opened this panel is most
2861
  // likely to be in.
2862
+ draggable={item.depth === 0 && !item.protected && item.managedBy !== "loopable"}
2863
  onDragStart={(e) => {
2864
  e.dataTransfer.setData(NAV_DRAG_TYPE, item.key);
2865
  e.dataTransfer.effectAllowed = "move";
 
2871
  }}
2872
  >
2873
  {link}
2874
+ {item.depth === 0 && !item.protected && item.managedBy !== "loopable" && (
2875
  <RowMenu
2876
  entryLabel={item.label}
2877
  canSchema
 
3209
  when they diverge — `CustomerGrid`'s VIEW_OPEN listener drops an event whose
3210
  `topic` is the other one. [[one-question-two-normalizers]] */}
3211
  <Lazily surface={active.label || "Database"}>
3212
+ <CustomerGrid
3213
+ key={active.key}
3214
+ scope={gridScopeFor(active.key)}
3215
+ dataPath={dataPath?.database === active.key ? dataPath : undefined}
3216
+ dataLabel={active.label}
3217
+ />
3218
  </Lazily>
3219
  </OverlayProvider>
3220
  </div>
web/src/shell/nav.ts CHANGED
@@ -36,6 +36,9 @@ import type { FolderIcon } from "../customer-grid/types";
36
  export interface NavPage {
37
  key: string;
38
  label: string;
 
 
 
39
  source?: string;
40
  parent?: string;
41
  /**
@@ -254,6 +257,8 @@ export function parsePages(body: unknown): NavPage[] {
254
  label,
255
  ...(typeof p.source === "string" && p.source ? { source: p.source } : {}),
256
  ...(typeof p.parent === "string" && p.parent ? { parent: p.parent } : {}),
 
 
257
  ...(p.group_only === true ? { group_only: true } : {}),
258
  ...(p.chrome === "main" || p.chrome === "utility" ? { chrome: p.chrome } : {}),
259
  ...(parseNavIcon(p.icon) ? { icon: parseNavIcon(p.icon)! } : {}),
@@ -839,6 +844,8 @@ export type NavKind = "native" | "handoff" | "group";
839
  export interface NavEntry {
840
  key: string;
841
  label: string;
 
 
842
  source?: string;
843
  kind: NavKind;
844
  /** 0 = top level, 1 = a sub-module rail entry (indented, like the app's rail). */
@@ -1011,6 +1018,8 @@ export function shapeNav(pages: NavPage[], appBase: string): NavEntry[] {
1011
  key: p.key,
1012
  label: p.label,
1013
  ...(p.source ? { source: p.source } : {}),
 
 
1014
  ...(p.icon ? { icon: p.icon } : {}),
1015
  ...(p.manage ? { manage: true } : {}),
1016
  // C3 (W-5) — carried through `shapeNav` beside `manage`. THE SECOND HALF
 
36
  export interface NavPage {
37
  key: string;
38
  label: string;
39
+ /** C1's injected system-table descriptor. The client displays it but never offers generic mutation. */
40
+ managedBy?: "loopable";
41
+ protected?: boolean;
42
  source?: string;
43
  parent?: string;
44
  /**
 
257
  label,
258
  ...(typeof p.source === "string" && p.source ? { source: p.source } : {}),
259
  ...(typeof p.parent === "string" && p.parent ? { parent: p.parent } : {}),
260
+ ...(p.managedBy === "loopable" ? { managedBy: "loopable" as const } : {}),
261
+ ...(p.protected === true ? { protected: true } : {}),
262
  ...(p.group_only === true ? { group_only: true } : {}),
263
  ...(p.chrome === "main" || p.chrome === "utility" ? { chrome: p.chrome } : {}),
264
  ...(parseNavIcon(p.icon) ? { icon: parseNavIcon(p.icon)! } : {}),
 
844
  export interface NavEntry {
845
  key: string;
846
  label: string;
847
+ managedBy?: "loopable";
848
+ protected?: boolean;
849
  source?: string;
850
  kind: NavKind;
851
  /** 0 = top level, 1 = a sub-module rail entry (indented, like the app's rail). */
 
1018
  key: p.key,
1019
  label: p.label,
1020
  ...(p.source ? { source: p.source } : {}),
1021
+ ...(p.managedBy === "loopable" ? { managedBy: "loopable" as const } : {}),
1022
+ ...(p.protected ? { protected: true } : {}),
1023
  ...(p.icon ? { icon: p.icon } : {}),
1024
  ...(p.manage ? { manage: true } : {}),
1025
  // C3 (W-5) — carried through `shapeNav` beside `manage`. THE SECOND HALF
web/src/styles/wave44/data-workspace.css ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Wave 44 Data workspace additions. Values use the shared token system exclusively. */
2
+ .cg-data-path {
3
+ color: var(--lp-ink-muted);
4
+ font-size: var(--lp-fs-2xs);
5
+ }
6
+
7
+ .cg-field-properties {
8
+ border-top: 1px solid var(--lp-line);
9
+ margin-top: 8px;
10
+ padding-top: 8px;
11
+ }
12
+
13
+ .cg-field-properties h3 {
14
+ color: var(--lp-ink);
15
+ font-size: var(--lp-fs-xs);
16
+ font-weight: 600;
17
+ margin: 0 0 8px;
18
+ }
19
+
20
+ .cg-field-properties dl { margin: 0; }
21
+ .cg-field-properties dl > div {
22
+ display: grid;
23
+ gap: 8px;
24
+ grid-template-columns: minmax(8rem, 1fr) minmax(0, 2fr);
25
+ padding: 4px 0;
26
+ }
27
+ .cg-field-properties dt { color: var(--lp-ink-muted); }
28
+ .cg-field-properties dd { color: var(--lp-ink); margin: 0; }
29
+ .cg-tb-related {
30
+ display: inline-flex;
31
+ order: 20;
32
+ }
33
+
34
+ /* Keep the requested Edit → Fullscreen → Rows → Related run together, before search/count. */
35
+ .cg-toolbar > .cg-tb-related ~ * { order: 21; }
36
+ .cg-toolbar > .cg-tb-related + .cg-pop-wrap { order: 19; }
37
+ .cg-toolbar > .cg-tb-related + .cg-view-actions { order: 17; }
38
+ .cg-toolbar > .cg-tb-related + .cg-view-actions + .cg-fullscreen-toggle { order: 18; }
39
+ .cg-toolbar > .cg-tb-related + .cg-view-actions + .cg-fullscreen-toggle + .cg-pop-wrap { order: 19; }
web/src/styles/wave44/voice-agent.css ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Wave 44 Voice properties: presentation only. The client has no provider or number mutation door. */
2
+
3
+ .voice-agent-properties {
4
+ min-width: 0;
5
+ overflow: auto;
6
+ padding: 24px;
7
+ color: var(--lp-ink);
8
+ }
9
+
10
+ .voice-agent-heading,
11
+ .voice-agent-section-head,
12
+ .voice-agent-bindings li,
13
+ .voice-agent-config-list li {
14
+ display: flex;
15
+ align-items: center;
16
+ justify-content: space-between;
17
+ gap: 16px;
18
+ }
19
+
20
+ .voice-agent-heading {
21
+ padding-bottom: 16px;
22
+ border-bottom: 1px solid var(--lp-line);
23
+ }
24
+
25
+ .voice-agent-eyebrow {
26
+ margin: 0 0 4px;
27
+ color: var(--lp-muted);
28
+ font-size: var(--lp-fs-2xs);
29
+ font-weight: 600;
30
+ }
31
+
32
+ .voice-agent-heading h1,
33
+ .voice-agent-section h2 {
34
+ margin: 0;
35
+ font-size: var(--lp-fs-md);
36
+ font-weight: 600;
37
+ }
38
+
39
+ .voice-agent-status,
40
+ .voice-agent-harness-state {
41
+ flex: 0 0 auto;
42
+ border-radius: var(--lp-r-pill);
43
+ padding: 4px 8px;
44
+ background: var(--lp-blue-tint);
45
+ color: var(--lp-blue-deep);
46
+ font-size: var(--lp-fs-2xs);
47
+ font-weight: 600;
48
+ }
49
+
50
+ .voice-agent-grid {
51
+ display: grid;
52
+ grid-template-columns: repeat(2, minmax(0, 1fr));
53
+ gap: 16px;
54
+ margin-top: 16px;
55
+ }
56
+
57
+ .voice-agent-section {
58
+ min-width: 0;
59
+ margin-top: 16px;
60
+ padding: 16px;
61
+ border: 1px solid var(--lp-line);
62
+ border-radius: var(--lp-r-md);
63
+ background: var(--lp-surface);
64
+ }
65
+
66
+ .voice-agent-grid .voice-agent-section { margin-top: 0; }
67
+
68
+ .voice-agent-details {
69
+ display: grid;
70
+ gap: 10px;
71
+ margin: 16px 0;
72
+ }
73
+
74
+ .voice-agent-details div {
75
+ display: flex;
76
+ align-items: baseline;
77
+ justify-content: space-between;
78
+ gap: 16px;
79
+ }
80
+
81
+ .voice-agent-details dt,
82
+ .voice-agent-note {
83
+ color: var(--lp-muted);
84
+ font-size: var(--lp-fs-xs);
85
+ }
86
+
87
+ .voice-agent-details dd { margin: 0; font-size: var(--lp-fs-sm); }
88
+
89
+ .voice-agent-disabled-control,
90
+ .voice-agent-harness-submit {
91
+ border: 0;
92
+ background: transparent;
93
+ font: inherit;
94
+ color: inherit;
95
+ border-radius: var(--lp-r-md);
96
+ font-size: var(--lp-fs-xs);
97
+ font-weight: 600;
98
+ }
99
+
100
+ .voice-agent-disabled-control {
101
+ background: transparent;
102
+ padding: 0;
103
+ color: var(--lp-muted);
104
+ cursor: not-allowed;
105
+ }
106
+
107
+ .voice-agent-note { margin: 8px 0 0; line-height: 1.5; }
108
+
109
+ .voice-agent-config-list,
110
+ .voice-agent-bindings {
111
+ display: grid;
112
+ gap: 8px;
113
+ margin: 16px 0 0;
114
+ padding: 0;
115
+ list-style: none;
116
+ }
117
+
118
+ .voice-agent-config-list li,
119
+ .voice-agent-bindings li {
120
+ min-height: 32px;
121
+ padding: 0 10px;
122
+ border-radius: var(--lp-r-sm);
123
+ background: var(--lp-surface-2);
124
+ font-size: var(--lp-fs-xs);
125
+ }
126
+
127
+ .voice-agent-config-list li span:last-child,
128
+ .voice-agent-bindings li span:last-child {
129
+ color: var(--lp-muted);
130
+ font-size: var(--lp-fs-2xs);
131
+ }
132
+
133
+ .voice-agent-bindings li span:last-child.is-active { color: var(--lp-green-deep); }
134
+ .voice-agent-number { font-variant-numeric: tabular-nums; }
135
+
136
+ .voice-agent-contact {
137
+ margin: 16px 0 0;
138
+ padding: 10px;
139
+ border-radius: var(--lp-r-sm);
140
+ background: var(--lp-yellow-tint);
141
+ color: var(--lp-yellow-deep);
142
+ font-size: var(--lp-fs-xs);
143
+ }
144
+
145
+ .voice-agent-harness-fields {
146
+ display: grid;
147
+ grid-template-columns: repeat(3, minmax(0, 1fr));
148
+ gap: 12px;
149
+ margin-top: 16px;
150
+ }
151
+
152
+ .voice-agent-harness-fields label {
153
+ display: grid;
154
+ gap: 6px;
155
+ color: var(--lp-muted);
156
+ font-size: var(--lp-fs-2xs);
157
+ font-weight: 600;
158
+ }
159
+
160
+ .voice-agent-harness-fields input,
161
+ .voice-agent-harness-fields select {
162
+ box-sizing: border-box;
163
+ min-width: 0;
164
+ height: 34px;
165
+ border: 1px solid var(--lp-line);
166
+ border-radius: var(--lp-r-sm);
167
+ outline: 0;
168
+ padding: 0 10px;
169
+ background: var(--lp-surface);
170
+ color: var(--lp-ink);
171
+ font: inherit;
172
+ font-size: var(--lp-fs-xs);
173
+ }
174
+
175
+ .voice-agent-harness-fields input:focus {
176
+ border-color: var(--lp-blue-deep);
177
+ outline: 2px solid var(--lp-blue-tint);
178
+ outline-offset: 1px;
179
+ }
180
+
181
+ .voice-agent-harness-fields select:focus {
182
+ border-color: var(--lp-blue-deep);
183
+ outline: 2px solid var(--lp-blue-tint);
184
+ outline-offset: 1px;
185
+ }
186
+
187
+ .voice-agent-harness-submit {
188
+ margin-top: 16px;
189
+ padding: 8px 12px;
190
+ background: var(--lp-primary);
191
+ color: var(--lp-surface);
192
+ cursor: pointer;
193
+ }
194
+
195
+ .voice-agent-harness-submit:disabled {
196
+ cursor: not-allowed;
197
+ opacity: 0.55;
198
+ }
199
+
200
+ .voice-agent-harness-submit:focus-visible,
201
+ .voice-agent-disabled-control:focus-visible {
202
+ outline: 2px solid var(--lp-blue-deep);
203
+ outline-offset: 2px;
204
+ }
205
+
206
+ .voice-agent-result {
207
+ margin: 12px 0 0;
208
+ color: var(--lp-green-deep);
209
+ font-size: var(--lp-fs-xs);
210
+ }
211
+
212
+ .voice-agent-result.is-error { color: var(--lp-red-deep); }
213
+
214
+ @media (max-width: 760px) {
215
+ .voice-agent-grid,
216
+ .voice-agent-harness-fields { grid-template-columns: 1fr; }
217
+ }
web/wiring_rows/wave44.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wave 44 cross-lane wiring rows.
2
+
3
+ The row package is the sanctioned extension of the frozen wiring gate: it proves mounts without
4
+ making the shared verifier a parallel-wave merge hub.
5
+ """
6
+
7
+ ROWS = [
8
+ ("W44-T05 field properties are mounted from the grid field action",
9
+ "customer-grid/FieldProperties.tsx", r"export function FieldProperties",
10
+ "customer-grid/ColumnMenu.tsx", r"<FieldProperties"),
11
+ ("W44-T08 named Route navigation is mounted inside the Map route overlay",
12
+ "customer-grid/RouteNav.tsx", r"export function RouteNav",
13
+ "customer-grid/MapView.tsx", r"<RouteNav"),
14
+ ]