fsanyoto commited on
Commit
3ae85d8
·
verified ·
1 Parent(s): cdee232

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. RELEASES.json +7 -1
  2. VERSION +1 -1
  3. api/application_registry.py +290 -0
  4. api/automation_engine.py +328 -2
  5. api/formula_runtime.py +750 -0
  6. api/main.py +18 -0
  7. api/odoo_relational.py +27 -0
  8. api/operator_control.py +206 -0
  9. api/routes_admin.py +21 -0
  10. api/routes_alerts.py +27 -4
  11. api/routes_assets.py +154 -5
  12. api/routes_automation.py +295 -1
  13. api/routes_connectors.py +86 -2
  14. api/routes_customers.py +122 -29
  15. api/routes_geo.py +35 -31
  16. api/routes_grid.py +288 -8
  17. api/routes_nav.py +10 -1
  18. api/routes_platform_admin.py +128 -1
  19. api/routes_products.py +67 -4
  20. api/routes_query.py +505 -5
  21. api/routes_starred.py +31 -2
  22. api/routes_tables.py +143 -6
  23. api/routes_templates.py +18 -1
  24. api/semantic_registry.py +287 -0
  25. api/voice_control_plane.py +248 -14
  26. api/voice_provider_adapters.py +77 -2
  27. platform/aios_grid.py +161 -30
  28. platform/core/assets.py +17 -0
  29. platform/core/grid_events.py +62 -4
  30. platform/core/route_system.py +233 -14
  31. platform/core/user_tables.py +304 -41
  32. platform/core/view_templates.py +27 -3
  33. platform/harness/semantic.py +38 -0
  34. platform/model/topics/odoo_customers.yml +20 -0
  35. platform/modules/product_data.py +9 -2
  36. platform/modules/products.py +3 -2
  37. web/src/assistant/AssistantPage.tsx +129 -8
  38. web/src/automation/AutomationBuilder.tsx +19 -0
  39. web/src/automation/AutomationChat.tsx +64 -13
  40. web/src/automation/AutomationDetail.tsx +127 -3
  41. web/src/automation/AutomationSurface.tsx +4 -1
  42. web/src/automation/VoiceAgentProperties.tsx +67 -2
  43. web/src/automation/automationApi.ts +234 -1
  44. web/src/automation/voiceAgentTypes.ts +35 -0
  45. web/src/connectors/ConnectorsPage.tsx +62 -0
  46. web/src/customer-grid/ColumnMenu.tsx +37 -34
  47. web/src/customer-grid/CustomerGrid.tsx +316 -100
  48. web/src/customer-grid/DatePicker.tsx +45 -4
  49. web/src/customer-grid/MapView.tsx +318 -168
  50. web/src/customer-grid/RouteNav.tsx +123 -6
RELEASES.json CHANGED
@@ -1,6 +1,12 @@
1
  {
2
- "current": "2970b72",
3
  "releases": [
 
 
 
 
 
 
4
  {
5
  "version": "v55",
6
  "sha": "b766b90",
 
1
  {
2
+ "current": "ba24d8b",
3
  "releases": [
4
+ {
5
+ "version": "v56",
6
+ "sha": "2970b72",
7
+ "date": "2026-08-28",
8
+ "subject": "release v56"
9
+ },
10
  {
11
  "version": "v55",
12
  "sha": "b766b90",
VERSION CHANGED
@@ -1 +1 @@
1
- 2970b72
 
1
+ ba24d8b
api/application_registry.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tenant-level reusable Application assets and deterministic default resolution."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ import datetime as dt
6
+ import uuid
7
+
8
+
9
+ APPLICATION_TYPES = ("chart", "route", "map", "timeseries")
10
+ _KEY = "applications_v1"
11
+ _MAX = 500
12
+
13
+
14
+ class ApplicationError(ValueError):
15
+ pass
16
+
17
+
18
+ def blank_doc():
19
+ return {"schema": 1, "applications": {}, "defaults": {}}
20
+
21
+
22
+ def _clean_doc(raw):
23
+ doc = blank_doc()
24
+ if isinstance(raw, dict):
25
+ if isinstance(raw.get("applications"), dict):
26
+ doc["applications"] = copy.deepcopy(raw["applications"])
27
+ if isinstance(raw.get("defaults"), dict):
28
+ doc["defaults"] = copy.deepcopy(raw["defaults"])
29
+ return doc
30
+
31
+
32
+ def load(runtime):
33
+ try: return _clean_doc(runtime.get(_KEY))
34
+ except Exception: return blank_doc()
35
+
36
+
37
+ def _users(raw):
38
+ out=[]
39
+ for item in raw if isinstance(raw, (list, tuple)) else ():
40
+ got=str(item or "").strip()[:120]
41
+ if got and got not in out: out.append(got)
42
+ return out
43
+
44
+
45
+ def may_read(app, user, is_admin=False):
46
+ if not isinstance(app, dict): return False
47
+ if is_admin or app.get("createdBy") == user: return True
48
+ share=app.get("share") if isinstance(app.get("share"), dict) else {}
49
+ return share.get("mode") == "tenant" or user in set(share.get("users") or ())
50
+
51
+
52
+ def may_edit(app, user, is_admin=False):
53
+ return bool(is_admin or (isinstance(app, dict) and app.get("createdBy") == user))
54
+
55
+
56
+ def _compat(raw):
57
+ values=[]
58
+ for item in raw if isinstance(raw, (list, tuple)) else ():
59
+ key=str(item or "").strip()[:120]
60
+ if key and key not in values: values.append(key)
61
+ if not values: raise ApplicationError("at least one compatible database is required")
62
+ return values
63
+
64
+
65
+ def _governed_bindings(raw, compatible, semantic_records):
66
+ """Normalize role -> database -> approved field, refusing optimistic bindings."""
67
+ if raw in (None, {}):
68
+ return {}
69
+ if not isinstance(raw, dict):
70
+ raise ApplicationError("semanticRoleBindings must be an object")
71
+ compatible = tuple(compatible or ())
72
+ out = {}
73
+ for raw_role, raw_binding in raw.items():
74
+ role = str(raw_role or "").strip()[:80]
75
+ if not role or not isinstance(raw_binding, dict):
76
+ raise ApplicationError("every semantic role needs a binding object")
77
+ # The first Wave shape was one flat binding. Admit it only for one compatible database,
78
+ # then store the canonical per-database shape.
79
+ if "field" in raw_binding:
80
+ database = str(raw_binding.get("database") or "").strip()
81
+ if not database and len(compatible) == 1:
82
+ database = compatible[0]
83
+ bindings = {database: raw_binding} if database else {}
84
+ else:
85
+ bindings = raw_binding
86
+ if set(bindings) != set(compatible):
87
+ raise ApplicationError(
88
+ f"semantic role {role!r} must be confirmed for every compatible database")
89
+ per_database = {}
90
+ for database in compatible:
91
+ binding = bindings.get(database)
92
+ if not isinstance(binding, dict) or binding.get("confirmed") is not True:
93
+ raise ApplicationError(f"semantic role {role!r} is not confirmed for {database}")
94
+ field = str(binding.get("field") or "").strip()[:120]
95
+ records = semantic_records.get(database) if isinstance(semantic_records, dict) else None
96
+ record = (records or {}).get(f"{database}::{field}") if field else None
97
+ if not isinstance(record, dict) or record.get("state") != "approved":
98
+ raise ApplicationError(
99
+ f"semantic role {role!r} needs an approved field in {database}")
100
+ per_database[database] = {"field": field, "confirmed": True}
101
+ out[role] = per_database
102
+ return out
103
+
104
+
105
+ _CONFIG_MODE = {"chart": "chart", "route": "map", "map": "map", "timeseries": "timeseries"}
106
+
107
+
108
+ def _typed_config(kind, raw):
109
+ if not isinstance(raw, dict):
110
+ raise ApplicationError("config must be an object")
111
+ if set(raw) - {"schemaVersion", "display"}:
112
+ raise ApplicationError("config contains fields outside the typed Application contract")
113
+ if raw.get("schemaVersion") != 1:
114
+ raise ApplicationError("config schemaVersion must be 1")
115
+ display = raw.get("display")
116
+ if not isinstance(display, dict):
117
+ raise ApplicationError("config.display must be an object")
118
+ if str(display.get("mode") or "") != _CONFIG_MODE[kind]:
119
+ raise ApplicationError(f"{kind} config has the wrong display mode")
120
+ return {"schemaVersion": 1, "display": copy.deepcopy(display)}
121
+
122
+
123
+ def _allowed(compatible, allowed_databases):
124
+ return (set(compatible or ()) if allowed_databases is None
125
+ else set(compatible or ()) & set(allowed_databases))
126
+
127
+
128
+ def _public(app, user, is_admin=False, *, allowed_databases=None, target_database=None,
129
+ is_default=False):
130
+ row=copy.deepcopy(app)
131
+ compatible = [database for database in row.get("compatibleDatabases") or ()
132
+ if database in _allowed(row.get("compatibleDatabases"), allowed_databases)]
133
+ row["compatibleDatabases"] = compatible
134
+ row["capabilities"]={"read":may_read(app,user,is_admin),"edit":may_edit(app,user,is_admin),
135
+ "share":may_edit(app,user,is_admin),"delete":may_edit(app,user,is_admin),
136
+ "duplicate":may_read(app,user,is_admin),"star":may_read(app,user,is_admin),
137
+ "default":bool(is_admin)}
138
+ row["starred"] = user in (app.get("starredBy") or ())
139
+ row["isDefault"] = bool(is_default)
140
+ target_database = target_database if target_database in compatible else (compatible[0] if compatible else None)
141
+ row["openTarget"]={"kind":"application","id":row["id"],"type":row["type"],
142
+ "database":target_database}
143
+ return row
144
+
145
+
146
+ def list_apps(runtime, user, is_admin=False, *, database=None, kind=None, starred=None,
147
+ allowed_databases=None):
148
+ doc = load(runtime)
149
+ rows=[]
150
+ for app in doc["applications"].values():
151
+ if not may_read(app,user,is_admin): continue
152
+ if database and database not in (app.get("compatibleDatabases") or ()): continue
153
+ if not _allowed(app.get("compatibleDatabases"), allowed_databases): continue
154
+ if kind and app.get("type") != kind: continue
155
+ if starred is not None and bool(user in (app.get("starredBy") or ())) != bool(starred): continue
156
+ default_key = f"{database}::{app.get('type')}" if database else ""
157
+ rows.append(_public(app,user,is_admin,allowed_databases=allowed_databases,
158
+ target_database=database,
159
+ is_default=bool(default_key and doc["defaults"].get(default_key)==app.get("id"))))
160
+ return sorted(rows,key=lambda x:(str(x.get("updatedAt") or ""),str(x.get("id"))),reverse=True)
161
+
162
+
163
+ def create(runtime, tenant, user, payload, *, semantic_records=None, allowed_databases=None):
164
+ payload=payload if isinstance(payload,dict) else {}
165
+ kind=str(payload.get("type") or "").lower()
166
+ if kind not in APPLICATION_TYPES: raise ApplicationError("application type is not recognized")
167
+ name=" ".join(str(payload.get("name") or "").split())[:120]
168
+ if not name: raise ApplicationError("application name is required")
169
+ app_id=f"app_{uuid.uuid4().hex[:16]}"; now=dt.datetime.now(dt.timezone.utc).isoformat()
170
+ compatible = _compat(payload.get("compatibleDatabases"))
171
+ if _allowed(compatible, allowed_databases) != set(compatible):
172
+ raise PermissionError("an Application cannot bind a database you cannot open")
173
+ app={"id":app_id,"tenant":str(tenant),"type":kind,"name":name,
174
+ "compatibleDatabases":compatible,
175
+ "semanticRoleBindings":_governed_bindings(
176
+ payload.get("semanticRoleBindings"), compatible, semantic_records or {}),
177
+ "config":_typed_config(kind, payload.get("config")),
178
+ "share":{"mode":"private","users":[]},"starredBy":[],"createdBy":user,
179
+ "createdAt":now,"updatedAt":now,"revision":1}
180
+ def apply(raw):
181
+ doc=_clean_doc(raw)
182
+ if len(doc["applications"])>=_MAX: raise ApplicationError("application limit reached")
183
+ doc["applications"][app_id]=app; return doc
184
+ runtime.update(_KEY,apply)
185
+ return _public(app,user,allowed_databases=allowed_databases)
186
+
187
+
188
+ def mutate(runtime, app_id, user, is_admin, patch, *, semantic_records=None,
189
+ allowed_databases=None, target_database=None):
190
+ patch=patch if isinstance(patch,dict) else {}; landed={}
191
+ def apply(raw):
192
+ doc=_clean_doc(raw); app=doc["applications"].get(app_id)
193
+ if not app: raise ApplicationError("application does not exist")
194
+ if not _allowed(app.get("compatibleDatabases"), allowed_databases):
195
+ raise ApplicationError("application does not exist")
196
+ star_only = set(patch) <= {"starred"}
197
+ if star_only:
198
+ if not may_read(app,user,is_admin): raise PermissionError("application is not available")
199
+ elif not may_edit(app,user,is_admin):
200
+ raise PermissionError("application belongs to another user")
201
+ if "name" in patch:
202
+ name=" ".join(str(patch["name"] or "").split())[:120]
203
+ if not name: raise ApplicationError("application name is required")
204
+ app["name"]=name
205
+ if "config" in patch:
206
+ app["config"]=_typed_config(app["type"],patch["config"])
207
+ compatible = (_compat(patch["compatibleDatabases"])
208
+ if "compatibleDatabases" in patch else app.get("compatibleDatabases") or [])
209
+ if _allowed(compatible, allowed_databases) != set(compatible):
210
+ raise PermissionError("an Application cannot bind a database you cannot open")
211
+ if "semanticRoleBindings" in patch or "compatibleDatabases" in patch:
212
+ bindings = patch.get("semanticRoleBindings", app.get("semanticRoleBindings"))
213
+ app["semanticRoleBindings"]=_governed_bindings(
214
+ bindings, compatible, semantic_records or {})
215
+ app["compatibleDatabases"] = list(compatible)
216
+ if "share" in patch:
217
+ share=patch["share"] if isinstance(patch["share"],dict) else {}
218
+ mode=str(share.get("mode") or "private")
219
+ if mode not in ("private","users","tenant"): raise ApplicationError("share mode is not recognized")
220
+ app["share"]={"mode":mode,"users":_users(share.get("users")) if mode=="users" else []}
221
+ if "starred" in patch:
222
+ stars=set(app.get("starredBy") or ())
223
+ (stars.add if patch["starred"] else stars.discard)(user); app["starredBy"]=sorted(stars)
224
+ app["revision"]=int(app.get("revision") or 0)+1
225
+ app["updatedAt"]=dt.datetime.now(dt.timezone.utc).isoformat(); landed.update(app)
226
+ return doc
227
+ runtime.update(_KEY,apply)
228
+ return _public(landed,user,is_admin,allowed_databases=allowed_databases,
229
+ target_database=target_database)
230
+
231
+
232
+ def duplicate(runtime, app_id, tenant, user, is_admin=False, *, semantic_records=None,
233
+ allowed_databases=None):
234
+ app=load(runtime)["applications"].get(app_id)
235
+ if not may_read(app,user,is_admin): raise ApplicationError("application does not exist")
236
+ if not _allowed(app.get("compatibleDatabases"), allowed_databases):
237
+ raise ApplicationError("application does not exist")
238
+ return create(runtime,tenant,user,{"type":app["type"],"name":f"{app['name']} copy",
239
+ "compatibleDatabases":app.get("compatibleDatabases"),
240
+ "semanticRoleBindings":app.get("semanticRoleBindings"),"config":app.get("config")},
241
+ semantic_records=semantic_records, allowed_databases=allowed_databases)
242
+
243
+
244
+ def delete(runtime, app_id, user, is_admin=False, *, allowed_databases=None):
245
+ def apply(raw):
246
+ doc=_clean_doc(raw); app=doc["applications"].get(app_id)
247
+ if not app: raise ApplicationError("application does not exist")
248
+ if not _allowed(app.get("compatibleDatabases"), allowed_databases):
249
+ raise ApplicationError("application does not exist")
250
+ if not may_edit(app,user,is_admin): raise PermissionError("application belongs to another user")
251
+ doc["applications"].pop(app_id)
252
+ for key in list(doc["defaults"]):
253
+ if doc["defaults"][key]==app_id: doc["defaults"].pop(key)
254
+ return doc
255
+ runtime.update(_KEY,apply); return {"deleted":app_id}
256
+
257
+
258
+ def set_default(runtime, database, kind, app_id, user, is_admin=False, *, allowed_databases=None):
259
+ if kind not in APPLICATION_TYPES: raise ApplicationError("application type is not recognized")
260
+ if not is_admin: raise PermissionError("only a tenant admin can change Application defaults")
261
+ if database not in set(allowed_databases or ()):
262
+ raise PermissionError("that database is not available")
263
+ key=f"{database}::{kind}"
264
+ def apply(raw):
265
+ doc=_clean_doc(raw); app=doc["applications"].get(app_id)
266
+ if (not isinstance(app, dict) or not may_edit(app,user,is_admin)
267
+ or database not in (app.get("compatibleDatabases") or ())
268
+ or app.get("type")!=kind):
269
+ raise ApplicationError("application is not compatible with this default")
270
+ doc["defaults"][key]=app_id; return doc
271
+ runtime.update(_KEY,apply); return resolve_default(
272
+ runtime,database,kind,user,is_admin,allowed_databases=allowed_databases)
273
+
274
+
275
+ def resolve_default(runtime, database, kind, user, is_admin=False, *, allowed_databases=None):
276
+ if kind not in APPLICATION_TYPES:
277
+ raise ApplicationError("application type is not recognized")
278
+ if database not in set(allowed_databases or ()):
279
+ raise PermissionError("that database is not available")
280
+ doc=load(runtime); explicit=doc["defaults"].get(f"{database}::{kind}")
281
+ app=doc["applications"].get(explicit)
282
+ if app and may_read(app,user,is_admin) and database in (app.get("compatibleDatabases") or ()) and app.get("type")==kind:
283
+ return {"resolution":"explicit","application":_public(
284
+ app,user,is_admin,allowed_databases=allowed_databases,target_database=database,
285
+ is_default=True)}
286
+ matches=[x for x in doc["applications"].values() if x.get("type")==kind and database in (x.get("compatibleDatabases") or ()) and may_read(x,user,is_admin)]
287
+ matches.sort(key=lambda x:(str(x.get("updatedAt") or ""),str(x.get("id"))),reverse=True)
288
+ return {"resolution":"latest" if matches else "blank",
289
+ "application":_public(matches[0],user,is_admin,allowed_databases=allowed_databases,
290
+ target_database=database) if matches else None}
api/automation_engine.py CHANGED
@@ -58,6 +58,9 @@ except Exception: # pragma: no cover — deploy lag; see m
58
 
59
  #: The per-tenant store key. Colocated with its reader, the `routes_nav._NAV_PREFS_KEY` pattern.
60
  STORE_KEY = "automations"
 
 
 
61
  #: The user-table bucket. ⚠ Read/written HERE through `TenantRuntime`, never through
62
  #: `core.user_tables` — that module writes the UNPREFIXED module-global key, which is correct for
63
  #: tenant #0 (empty prefix) and silently cross-tenant for every R2 tenant after it. Booked in the
@@ -2681,6 +2684,329 @@ def all_definitions(rt, cached=False):
2681
  return out
2682
 
2683
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2684
  def tick_definitions(rt):
2685
  """Definitions for the external scheduler, cached until `_store_update` changes them.
2686
 
@@ -11111,7 +11437,7 @@ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print
11111
  if "odoo_sync_not_run_here" not in web_notes:
11112
  web_notes.append("odoo_sync_not_run_here")
11113
  log("[aios-auto] odoo_sync: the Odoo pull runs on the connector's own "
11114
- "schedule, not from this canvas. Nothing was done")
11115
  counts["webBlocked"] += 1
11116
  continue
11117
  elif kind == "ai_enrich":
@@ -11128,7 +11454,7 @@ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print
11128
  if "ai_enrich_not_run_here" not in web_notes:
11129
  web_notes.append("ai_enrich_not_run_here")
11130
  log("[aios-auto] ai_enrich: an AI column is filled from the column's own "
11131
- "editor, not from this canvas. Nothing was done")
11132
  counts["webBlocked"] += 1
11133
  continue
11134
  elif kind == "voice_agent":
 
58
 
59
  #: The per-tenant store key. Colocated with its reader, the `routes_nav._NAV_PREFS_KEY` pattern.
60
  STORE_KEY = "automations"
61
+ AGENT_CONTRACT_KEY = "agent_contracts"
62
+ AGENT_EVENT_TYPES = ("transcript", "message", "gathered_data", "run", "consent")
63
+ AGENT_ACTIONS = ("read", "create", "update", "overwrite", "delete")
64
  #: The user-table bucket. ⚠ Read/written HERE through `TenantRuntime`, never through
65
  #: `core.user_tables` — that module writes the UNPREFIXED module-global key, which is correct for
66
  #: tenant #0 (empty prefix) and silently cross-tenant for every R2 tenant after it. Booked in the
 
2684
  return out
2685
 
2686
 
2687
+ def _agent_contracts(rt):
2688
+ """Private Agent metadata and events, stored outside normal database navigation."""
2689
+ try:
2690
+ raw = rt.get(AGENT_CONTRACT_KEY) or {}
2691
+ except Exception:
2692
+ return {}
2693
+ return copy.deepcopy(raw) if isinstance(raw, dict) else {}
2694
+
2695
+
2696
+ def _agent_event_schema():
2697
+ return {
2698
+ "transcript": {"required": ["text"], "optional": ["speaker", "channel"]},
2699
+ "message": {"required": ["text"], "optional": ["role", "channel"]},
2700
+ "gathered_data": {"required": ["data"], "optional": ["source", "citations"]},
2701
+ "run": {"required": ["state"], "optional": ["workflowId", "evidence"]},
2702
+ "consent": {"required": ["state"], "optional": ["subjectRef", "purpose"]},
2703
+ }
2704
+
2705
+
2706
+ def _new_agent_contract(agent_id, actor="", name=""):
2707
+ aid = str(agent_id or "").strip()
2708
+ stamp = int(time.time())
2709
+ workflow_id = "wf_main"
2710
+ return {
2711
+ "schemaVersion": 1,
2712
+ "agentId": aid,
2713
+ "eventStore": {
2714
+ "id": "aes_" + hashlib.sha256(aid.encode("utf-8")).hexdigest()[:18],
2715
+ "kind": "agent_event_store",
2716
+ "visibility": "private",
2717
+ "hiddenFromData": True,
2718
+ "eventSchemas": _agent_event_schema(),
2719
+ },
2720
+ "events": [],
2721
+ "workflows": [{"id": workflow_id, "name": "Main", "kind": "event_store_view",
2722
+ "eventStoreId": "aes_" + hashlib.sha256(aid.encode("utf-8")).hexdigest()[:18],
2723
+ "purpose": "", "createdAt": stamp, "updatedAt": stamp}],
2724
+ "sharing": {"visibility": "private", "sharedWith": []},
2725
+ "capabilities": {"defaultMode": "preview", "workflows": {workflow_id: {}}},
2726
+ "semantic": {"fields": [], "retrievable": []},
2727
+ "setup": {"state": "unconfigured", "answers": {}, "disabledFields": []},
2728
+ "createdBy": str(actor or "")[:120], "createdAt": stamp,
2729
+ "displayName": str(name or "")[:120],
2730
+ }
2731
+
2732
+
2733
+ def ensure_agent_contract(rt, agent_id, actor="", name=""):
2734
+ """Mint exactly one private event store and default Workflow for a stored Agent."""
2735
+ aid = str(agent_id or "").strip()
2736
+ if not aid or aid.startswith("field:") or aid == "system:odoo_sync":
2737
+ return None
2738
+ found = _agent_contracts(rt).get(aid)
2739
+ if isinstance(found, dict):
2740
+ return found
2741
+ fresh = _new_agent_contract(aid, actor, name)
2742
+ result = {}
2743
+ def up(raw):
2744
+ doc = dict(raw or {}) if isinstance(raw, dict) else {}
2745
+ rec = doc.get(aid)
2746
+ if not isinstance(rec, dict):
2747
+ rec = copy.deepcopy(fresh)
2748
+ doc[aid] = rec
2749
+ result.update(copy.deepcopy(rec))
2750
+ return doc
2751
+ rt.update(AGENT_CONTRACT_KEY, up, flush="sync")
2752
+ return result
2753
+
2754
+
2755
+ def _agent_update(rt, agent_id, fn):
2756
+ aid = str(agent_id or "").strip()
2757
+ result = {}
2758
+ def up(raw):
2759
+ doc = dict(raw or {}) if isinstance(raw, dict) else {}
2760
+ rec = copy.deepcopy(doc.get(aid))
2761
+ if not isinstance(rec, dict):
2762
+ raise ValueError("unknown stored Agent")
2763
+ rec = fn(rec)
2764
+ doc[aid] = rec
2765
+ result.update(copy.deepcopy(rec))
2766
+ return doc
2767
+ rt.update(AGENT_CONTRACT_KEY, up, flush="sync")
2768
+ return result
2769
+
2770
+
2771
+ def agent_contract_dto(rt, agent_id):
2772
+ rec = _agent_contracts(rt).get(str(agent_id or ""))
2773
+ if not isinstance(rec, dict):
2774
+ return None
2775
+ store = copy.deepcopy(rec.get("eventStore") or {})
2776
+ workflows = copy.deepcopy(rec.get("workflows") or [])
2777
+ schemas = copy.deepcopy(store.get("eventSchemas") or {})
2778
+ toc = {"eventSchemas": [{"type": key, "required": value.get("required", []),
2779
+ "optional": value.get("optional", [])}
2780
+ for key, value in sorted(schemas.items())],
2781
+ "workflows": [{"id": row.get("id"), "name": row.get("name"),
2782
+ "eventStoreId": row.get("eventStoreId")} for row in workflows],
2783
+ "setupState": str((rec.get("setup") or {}).get("state") or "unconfigured")}
2784
+ return {
2785
+ "schemaVersion": 1, "agentId": str(rec.get("agentId") or ""),
2786
+ "eventStore": store,
2787
+ "workflows": workflows,
2788
+ "sharing": copy.deepcopy(rec.get("sharing") or {"visibility": "private", "sharedWith": []}),
2789
+ "capabilities": copy.deepcopy(rec.get("capabilities") or {}),
2790
+ "semanticState": copy.deepcopy(rec.get("semantic") or {}),
2791
+ "setupInterview": setup_interview(rec),
2792
+ "harnessTableOfContents": toc,
2793
+ "eventCount": len(rec.get("events") or []),
2794
+ }
2795
+
2796
+
2797
+ def authorize_agent_principal(rt, agent_id, actor, is_admin=False):
2798
+ rec = _agent_contracts(rt).get(str(agent_id or "")) or {}
2799
+ sharing = rec.get("sharing") or {}
2800
+ if is_admin or rec.get("createdBy") == str(actor or "") or str(actor or "") in set(sharing.get("sharedWith") or []):
2801
+ return True
2802
+ raise PermissionError("this Agent is private or not shared with this principal")
2803
+
2804
+
2805
+ def append_agent_event(rt, agent_id, event_type, payload, actor="agent"):
2806
+ kind = str(event_type or "").strip().lower()
2807
+ schemas = _agent_event_schema()
2808
+ if kind not in schemas:
2809
+ raise ValueError("unsupported Agent event type")
2810
+ if not isinstance(payload, dict):
2811
+ raise ValueError("Agent event payload must be an object")
2812
+ missing = [key for key in schemas[kind]["required"] if key not in payload]
2813
+ if missing:
2814
+ raise ValueError("Agent event is missing: " + ", ".join(missing))
2815
+ allowed = set(schemas[kind]["required"] + schemas[kind]["optional"])
2816
+ unknown = sorted(set(payload) - allowed)
2817
+ if unknown:
2818
+ raise ValueError("unsupported Agent event fields: " + ", ".join(unknown))
2819
+ result = {}
2820
+ def mutate(rec):
2821
+ events = list(rec.get("events") or [])
2822
+ event = {"id": f"evt_{len(events) + 1}", "type": kind,
2823
+ "payload": copy.deepcopy(payload), "actor": str(actor or "agent")[:120],
2824
+ "createdAt": int(time.time())}
2825
+ events.append(event)
2826
+ rec["events"] = events[-1000:]
2827
+ result.update(copy.deepcopy(event))
2828
+ return rec
2829
+ _agent_update(rt, agent_id, mutate)
2830
+ return result
2831
+
2832
+
2833
+ def create_agent_workflow(rt, agent_id, name, purpose=""):
2834
+ label = " ".join(str(name or "").split())[:80]
2835
+ if not label:
2836
+ raise ValueError("name the Workflow")
2837
+ result = {}
2838
+ def mutate(rec):
2839
+ rows = list(rec.get("workflows") or [])
2840
+ wid = f"wf_{len(rows) + 1}"
2841
+ while any(row.get("id") == wid for row in rows):
2842
+ wid = f"wf_{len(rows) + int(time.time())}"
2843
+ stamp = int(time.time())
2844
+ row = {"id": wid, "name": label, "kind": "event_store_view",
2845
+ "eventStoreId": (rec.get("eventStore") or {}).get("id"),
2846
+ "purpose": " ".join(str(purpose or "").split())[:240],
2847
+ "createdAt": stamp, "updatedAt": stamp}
2848
+ rows.append(row)
2849
+ rec["workflows"] = rows
2850
+ caps = dict(rec.get("capabilities") or {})
2851
+ caps["workflows"] = {**dict(caps.get("workflows") or {}), wid: {}}
2852
+ rec["capabilities"] = caps
2853
+ result.update(copy.deepcopy(row))
2854
+ return rec
2855
+ _agent_update(rt, agent_id, mutate)
2856
+ return result
2857
+
2858
+
2859
+ def configure_agent_governance(rt, agent_id, raw, allowed_databases=None, allowed_users=None):
2860
+ """Store private sharing and named-field grants after the caller's wall has narrowed them."""
2861
+ body = raw if isinstance(raw, dict) else {}
2862
+ visibility = str(body.get("visibility") or "private")
2863
+ if visibility not in {"private", "shared"}:
2864
+ raise ValueError("Agent visibility is private or shared")
2865
+ users = sorted({str(v).strip()[:120] for v in body.get("sharedWith", []) if str(v).strip()})
2866
+ if allowed_users is not None and not set(users).issubset({str(v) for v in allowed_users}):
2867
+ raise PermissionError("Agent share recipient is outside the tenant user wall")
2868
+ field_wall = ({str(key): {str(value) for value in values}
2869
+ for key, values in allowed_databases.items()}
2870
+ if isinstance(allowed_databases, dict) else {})
2871
+ allowed = set(field_wall) if field_wall else set(str(v) for v in (allowed_databases or []))
2872
+ workflows = body.get("workflows") if isinstance(body.get("workflows"), dict) else {}
2873
+ result = {}
2874
+ def mutate(rec):
2875
+ known = {row.get("id") for row in rec.get("workflows") or []}
2876
+ clean_workflows = {}
2877
+ for wid, databases in workflows.items():
2878
+ if wid not in known or not isinstance(databases, dict):
2879
+ raise ValueError("unknown Workflow")
2880
+ clean_dbs = {}
2881
+ for table, grant in databases.items():
2882
+ if allowed and table not in allowed:
2883
+ raise PermissionError("database permission denied before Agent execution")
2884
+ if not isinstance(grant, dict):
2885
+ raise ValueError("database capability must be an object")
2886
+ mode = str(grant.get("mode") or "preview")
2887
+ if mode not in {"preview", "autonomous"}:
2888
+ raise ValueError("Workflow mode is preview or autonomous")
2889
+ clean = {"mode": mode, "read": bool(grant.get("read"))}
2890
+ for action in AGENT_ACTIONS[1:]:
2891
+ value = grant.get(action) or []
2892
+ if not isinstance(value, list):
2893
+ raise ValueError(f"{action} capability needs named fields")
2894
+ clean[action] = sorted({str(v).strip()[:120] for v in value if str(v).strip()})
2895
+ if field_wall and not set(clean[action]).issubset(field_wall.get(str(table), set())):
2896
+ raise PermissionError("field permission denied before Agent execution")
2897
+ clean_dbs[str(table)] = clean
2898
+ clean_workflows[str(wid)] = clean_dbs
2899
+ rec["sharing"] = {"visibility": visibility, "sharedWith": users if visibility == "shared" else []}
2900
+ rec["capabilities"] = {"defaultMode": "preview", "workflows": clean_workflows}
2901
+ result.update(copy.deepcopy(rec))
2902
+ return rec
2903
+ _agent_update(rt, agent_id, mutate)
2904
+ return result
2905
+
2906
+
2907
+ def authorize_agent_action(rt, agent_id, workflow_id, table, action, field="",
2908
+ actor_databases=None, actor_fields=None):
2909
+ """Capability intersection. This must run before a model or provider is invoked."""
2910
+ rec = _agent_contracts(rt).get(str(agent_id or "")) or {}
2911
+ actor_dbs = set(str(v) for v in (actor_databases or []))
2912
+ if str(table) not in actor_dbs:
2913
+ raise PermissionError("database permission denied before Agent execution")
2914
+ grant = ((((rec.get("capabilities") or {}).get("workflows") or {})
2915
+ .get(str(workflow_id)) or {}).get(str(table)) or {})
2916
+ act = str(action or "")
2917
+ if act == "read":
2918
+ if not grant.get("read"):
2919
+ raise PermissionError("Agent read capability denied before execution")
2920
+ if actor_fields is not None and str(field) not in set(str(v) for v in actor_fields):
2921
+ raise PermissionError("field permission denied before Agent execution")
2922
+ elif act in AGENT_ACTIONS[1:]:
2923
+ if str(field) not in set(grant.get(act) or []):
2924
+ raise PermissionError(f"Agent {act} capability denied before execution")
2925
+ if actor_fields is not None and str(field) not in set(str(v) for v in actor_fields):
2926
+ raise PermissionError("field permission denied before Agent execution")
2927
+ if grant.get("mode") == "preview" and act in {"create", "update"}:
2928
+ return {"allowed": True, "mode": "preview", "action": act}
2929
+ else:
2930
+ raise PermissionError("unknown Agent capability")
2931
+ return {"allowed": True, "mode": str(grant.get("mode") or "preview"), "action": act}
2932
+
2933
+
2934
+ def governed_agent_query_dry_run(rt, agent_id, workflow_id, table, field, prompt, query_tool,
2935
+ actor_databases=None, actor_fields=None):
2936
+ """Authorization and semantic readiness run before the injected C2 Query callable."""
2937
+ authorize_agent_action(rt, agent_id, workflow_id, table, "read", field,
2938
+ actor_databases=actor_databases, actor_fields=actor_fields)
2939
+ ready = (agent_contract_dto(rt, agent_id) or {}).get("semanticState", {}).get("retrievable", [])
2940
+ if {"database": str(table), "field": str(field)} not in ready:
2941
+ raise PermissionError("semantic field is not approved before Query execution")
2942
+ if not callable(query_tool):
2943
+ raise ValueError("governed Query is unavailable")
2944
+ result = query_tool(str(prompt or ""), {"agentId": str(agent_id), "workflowId": str(workflow_id),
2945
+ "database": str(table), "field": str(field)})
2946
+ if not isinstance(result, dict):
2947
+ raise ValueError("governed Query returned no typed result")
2948
+ append_agent_event(rt, agent_id, "message", {"text": str(prompt or "")[:2000], "role": "user",
2949
+ "channel": "voice"})
2950
+ append_agent_event(rt, agent_id, "run", {"state": "dry_run", "workflowId": str(workflow_id),
2951
+ "evidence": "governed_query"})
2952
+ return {"query": copy.deepcopy(result), "noProviderCalls": True, "providerCalls": 0}
2953
+
2954
+
2955
+ def set_semantic_readiness(rt, agent_id, fields):
2956
+ rows = fields if isinstance(fields, list) else []
2957
+ clean = [{"database": str(row.get("database") or ""), "field": str(row.get("field") or ""),
2958
+ "state": str(row.get("state") or "draft")}
2959
+ for row in rows if isinstance(row, dict) and row.get("database") and row.get("field")
2960
+ and str(row.get("state") or "draft") in {"draft", "approved", "disabled"}]
2961
+ def mutate(rec):
2962
+ rec["semantic"] = {"fields": clean,
2963
+ "retrievable": [{"database": row["database"], "field": row["field"]}
2964
+ for row in clean if row["state"] == "approved"]}
2965
+ return rec
2966
+ return _agent_update(rt, agent_id, mutate)
2967
+
2968
+
2969
+ def setup_interview(rec):
2970
+ setup = rec.get("setup") if isinstance(rec, dict) else {}
2971
+ setup = setup if isinstance(setup, dict) else {}
2972
+ answers = setup.get("answers") if isinstance(setup.get("answers"), dict) else {}
2973
+ questions = (
2974
+ ("purpose", "What should this Agent help with?", "Summarize the work this Agent should handle."),
2975
+ ("source", "Which approved database should it use?", "Choose one approved source."),
2976
+ ("workflow", "What should the first Workflow do?", "Describe one repeatable outcome."),
2977
+ )
2978
+ pending = next((row for row in questions if row[0] not in answers), None)
2979
+ if not pending:
2980
+ return {"state": "configured", "question": None, "progress": len(questions),
2981
+ "total": len(questions)}
2982
+ return {"state": "unconfigured", "question": {"key": pending[0], "text": pending[1],
2983
+ "suggestion": pending[2], "allowDisable": pending[0] == "source"},
2984
+ "progress": len(answers), "total": len(questions)}
2985
+
2986
+
2987
+ def answer_setup_interview(rt, agent_id, key, answer="", disable=False):
2988
+ result = {}
2989
+ def mutate(rec):
2990
+ current = setup_interview(rec).get("question")
2991
+ if not current or current.get("key") != str(key or ""):
2992
+ raise ValueError("answer the current setup question first")
2993
+ if disable and not current.get("allowDisable"):
2994
+ raise ValueError("this setup question cannot be disabled")
2995
+ text = " ".join(str(answer or "").split())[:240]
2996
+ if not text and not disable:
2997
+ raise ValueError("answer the setup question or disable this source")
2998
+ setup = dict(rec.get("setup") or {})
2999
+ answers = dict(setup.get("answers") or {})
3000
+ answers[str(key)] = {"answer": text, "disabled": bool(disable)}
3001
+ setup["answers"] = answers
3002
+ setup["state"] = "configured" if setup_interview({"setup": setup}).get("state") == "configured" else "unconfigured"
3003
+ rec["setup"] = setup
3004
+ result.update(copy.deepcopy(rec))
3005
+ return rec
3006
+ _agent_update(rt, agent_id, mutate)
3007
+ return setup_interview(result)
3008
+
3009
+
3010
  def tick_definitions(rt):
3011
  """Definitions for the external scheduler, cached until `_store_update` changes them.
3012
 
 
11437
  if "odoo_sync_not_run_here" not in web_notes:
11438
  web_notes.append("odoo_sync_not_run_here")
11439
  log("[aios-auto] odoo_sync: the Odoo pull runs on the connector's own "
11440
+ "schedule, not from this Workflow. Nothing was done")
11441
  counts["webBlocked"] += 1
11442
  continue
11443
  elif kind == "ai_enrich":
 
11454
  if "ai_enrich_not_run_here" not in web_notes:
11455
  web_notes.append("ai_enrich_not_run_here")
11456
  log("[aios-auto] ai_enrich: an AI column is filled from the column's own "
11457
+ "editor, not from this Workflow. Nothing was done")
11458
  counts["webBlocked"] += 1
11459
  continue
11460
  elif kind == "voice_agent":
api/formula_runtime.py ADDED
@@ -0,0 +1,750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Versioned, allowlisted server formula AST and evaluator.
2
+
3
+ The browser may preview the same fixtures, but values shipped by the product are produced here.
4
+ No Python ``eval`` is used; parsed nodes are interpreted by the closed grammar below.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import ast
9
+ import calendar
10
+ import datetime as dt
11
+ import hashlib
12
+ import json
13
+ import math
14
+ import re
15
+ import warnings
16
+ from decimal import Decimal, ROUND_FLOOR, ROUND_HALF_UP
17
+
18
+
19
+ CONTRACT_VERSION = 1
20
+ AST_VERSION = 1
21
+ MAX_SOURCE = 500
22
+ MAX_NODES = 200
23
+ MAX_DEPTH = 24
24
+ MAX_FIELD_KEY = 120
25
+ MAX_DEFINITIONS = 100
26
+ MAX_BATCH_ROWS = 1000
27
+ MANY = 30
28
+ AUTHORITY = "server"
29
+ CONSUMERS = ("preview", "grid", "filter", "export", "automation", "query", "timeseries")
30
+ FN_ARITY = {
31
+ "ABS": (1, 1), "ROUND": (1, 2), "ROUNDUP": (1, 2), "ROUNDDOWN": (1, 2),
32
+ "INT": (1, 1), "MOD": (2, 2), "SQRT": (1, 1), "POWER": (2, 2), "EXP": (1, 1),
33
+ "LN": (1, 1), "SUM": (1, MANY), "AVERAGE": (1, MANY), "COUNT": (1, MANY),
34
+ "COUNTA": (1, MANY), "MIN": (1, MANY), "MAX": (1, MANY), "IF": (2, 3),
35
+ "AND": (1, MANY), "OR": (1, MANY), "NOT": (1, 1), "IFERROR": (2, 2),
36
+ "ISBLANK": (1, 1), "SWITCH": (3, MANY), "CONCATENATE": (1, MANY),
37
+ "LEFT": (1, 2), "RIGHT": (1, 2), "MID": (3, 3), "LEN": (1, 1),
38
+ "TRIM": (1, 1), "UPPER": (1, 1), "LOWER": (1, 1), "PROPER": (1, 1),
39
+ "VALUE": (1, 1), "TEXT": (2, 2), "SUBSTITUTE": (3, 4), "FIND": (2, 3),
40
+ "REGEX_EXTRACT": (2, 2), "REGEX_REPLACE": (3, 3), "TODAY": (0, 0),
41
+ "YEAR": (1, 1), "MONTH": (1, 1), "DAY": (1, 1), "DAYS": (2, 2),
42
+ "DATEADD": (3, 3), "DATETIME_DIFF": (2, 3), "DATETIME_FORMAT": (2, 2),
43
+ }
44
+ ALIASES = {"CONCAT": "CONCATENATE"}
45
+
46
+ # Every accepted source token has a fixture. The AST stores the canonical token (``=`` and
47
+ # ``!=``), while the grammar publishes the spelling aliases so a browser never has to infer them.
48
+ OPERATOR_PARITY_FIXTURES = {
49
+ "neg": ("-5", {}, -5.0),
50
+ "add": ("{a} + {b}", {"a": 2, "b": 3}, 5.0),
51
+ "subtract": ("{a} - {b}", {"a": 7, "b": 2}, 5.0),
52
+ "multiply": ("{a} * {b}", {"a": 3, "b": 4}, 12.0),
53
+ "divide": ("{a} / {b}", {"a": 9, "b": 3}, 3.0),
54
+ "power": ("{a} ^ {b}", {"a": 2, "b": 3}, 8.0),
55
+ "concatenate": ("{a} & {b}", {"a": "A", "b": "B"}, "AB"),
56
+ "less_than": ("{a} < {b}", {"a": 2, "b": 3}, "TRUE"),
57
+ "less_or_equal": ("{a} <= {b}", {"a": 3, "b": 3}, "TRUE"),
58
+ "greater_than": ("{a} > {b}", {"a": 4, "b": 3}, "TRUE"),
59
+ "greater_or_equal": ("{a} >= {b}", {"a": 3, "b": 3}, "TRUE"),
60
+ "equal": ("{a} = {b}", {"a": "A", "b": "a"}, "TRUE"),
61
+ "equal_alias": ("{a} == {b}", {"a": 3, "b": 3}, "TRUE"),
62
+ "not_equal": ("{a} != {b}", {"a": 2, "b": 3}, "TRUE"),
63
+ "not_equal_alias": ("{a} <> {b}", {"a": 2, "b": 3}, "TRUE"),
64
+ }
65
+
66
+ PARSE_ERROR_FIXTURES = {
67
+ "empty": "",
68
+ "legacy_square_reference": "[amount] + 1",
69
+ "unknown_function": "UNKNOWN(1)",
70
+ "wrong_arity": "ABS(1, 2)",
71
+ "unclosed_reference": "{amount + 1",
72
+ "invalid_reference": "{amount-due} + 1",
73
+ "unterminated_text": '"amount',
74
+ "chained_comparison": "1 < 2 < 3",
75
+ "unsupported_operator": "5 % 2",
76
+ }
77
+
78
+ EVALUATION_ERROR_FIXTURES = {
79
+ "unknown_ref": ("{missing} + 1", {}, "unknown_ref"),
80
+ "div_zero": ("{amount} / 0", {"amount": 4}, "div_zero"),
81
+ }
82
+
83
+ # Shared contract fixture corpus. The API publishes this exact data so the browser preview gate
84
+ # can evaluate the same source/row/today triples without maintaining a second handwritten grammar.
85
+ PARITY_FIXTURES = {
86
+ "ABS": ("ABS(-2)", 2.0), "ROUND": ("ROUND(2.345, 2)", 2.35),
87
+ "ROUNDUP": ("ROUNDUP(2.341, 2)", 2.35), "ROUNDDOWN": ("ROUNDDOWN(2.349, 2)", 2.34),
88
+ "INT": ("INT(2.9)", 2), "MOD": ("MOD(7, 4)", 3.0), "SQRT": ("SQRT(9)", 3.0),
89
+ "POWER": ("POWER(2, 3)", 8.0), "EXP": ("EXP(0)", 1.0), "LN": ("LN(1)", 0.0),
90
+ "SUM": ("SUM(1, 2, 3)", 6.0), "AVERAGE": ("AVERAGE(2, 4)", 3.0),
91
+ "COUNT": ("COUNT(1, \"x\", 3)", 2), "COUNTA": ("COUNTA(1, \"x\", \"\")", 2),
92
+ "MIN": ("MIN(4, 2)", 2.0), "MAX": ("MAX(4, 2)", 4.0), "IF": ("IF(TRUE, 1, 2)", 1),
93
+ "AND": ("AND(TRUE, TRUE)", "TRUE"), "OR": ("OR(FALSE, TRUE)", "TRUE"),
94
+ "NOT": ("NOT(FALSE)", "TRUE"), "IFERROR": ("IFERROR(1 / 0, 7)", 7),
95
+ "ISBLANK": ("ISBLANK({empty})", "TRUE"), "SWITCH": ("SWITCH(\"A\", \"A\", 1, 0)", 1),
96
+ "CONCATENATE": ("CONCATENATE(\"A\", \"B\")", "AB"),
97
+ "LEFT": ("LEFT(\"ABC\", 2)", "AB"), "RIGHT": ("RIGHT(\"ABC\", 2)", "BC"),
98
+ "MID": ("MID(\"ABCD\", 2, 2)", "BC"), "LEN": ("LEN(\"ABC\")", 3),
99
+ "TRIM": ("TRIM(\" A B \" )", "A B"), "UPPER": ("UPPER(\"Ab\")", "AB"),
100
+ "LOWER": ("LOWER(\"Ab\")", "ab"), "PROPER": ("PROPER(\"hello world\")", "Hello World"),
101
+ "VALUE": ("VALUE(\"12.5\")", 12.5), "TEXT": ("TEXT(0.25, \"0%\")", "25%"),
102
+ "SUBSTITUTE": ("SUBSTITUTE(\"a-b\", \"-\", \"+\")", "a+b"),
103
+ "FIND": ("FIND(\"b\", \"abc\")", 2),
104
+ "REGEX_EXTRACT": ("REGEX_EXTRACT(\"SO-42\", \"SO-[0-9]+\")", "SO-42"),
105
+ "REGEX_REPLACE": ("REGEX_REPLACE(\"SO-42\", \"[0-9]+\", \"#\")", "SO-#"),
106
+ "TODAY": ("TODAY()", "2024-01-02"), "YEAR": ("YEAR(\"2024-01-02\")", 2024),
107
+ "MONTH": ("MONTH(\"2024-01-02\")", 1), "DAY": ("DAY(\"2024-01-02\")", 2),
108
+ "DAYS": ("DAYS(\"2024-01-05\", \"2024-01-02\")", 3),
109
+ "DATEADD": ("DATEADD(\"2024-01-31\", 1, \"months\")", "2024-02-29"),
110
+ "DATETIME_DIFF": ("DATETIME_DIFF(\"2024-01-16\", \"2024-01-02\", \"weeks\")", 2),
111
+ "DATETIME_FORMAT": ("DATETIME_FORMAT(\"2024-01-02\", \"YYYY-MM-DD\")", "2024-01-02"),
112
+ }
113
+
114
+
115
+ class FormulaError(ValueError):
116
+ pass
117
+
118
+
119
+ def _rewrite(source):
120
+ """Translate Excel punctuation to Python AST punctuation without touching strings."""
121
+ out, i, quote = [], 0, None
122
+ while i < len(source):
123
+ c = source[i]
124
+ if quote:
125
+ out.append(c)
126
+ if c == quote:
127
+ if i + 1 < len(source) and source[i + 1] == quote:
128
+ out.append(source[i + 1]); i += 2; continue
129
+ quote = None
130
+ i += 1; continue
131
+ if c in ("'", '"'):
132
+ quote = c; out.append(c); i += 1; continue
133
+ if c == "{":
134
+ end = source.find("}", i + 1)
135
+ if end < 0:
136
+ raise FormulaError("a field reference is missing its closing }")
137
+ key = source[i + 1:end].strip()
138
+ if not re.fullmatch(r"[A-Za-z0-9_]+", key) or len(key) > MAX_FIELD_KEY:
139
+ raise FormulaError("a field reference may contain only letters, digits and _")
140
+ out.append(f"REF({key!r})"); i = end + 1; continue
141
+ two = source[i:i + 2]
142
+ if two in ("<=", ">=", "!=", "=="):
143
+ out.append(two); i += 2; continue
144
+ if two == "<>":
145
+ out.append("!="); i += 2; continue
146
+ if c == "=":
147
+ out.append("==")
148
+ elif c == "^":
149
+ out.append("**")
150
+ else:
151
+ out.append(c)
152
+ i += 1
153
+ if quote:
154
+ raise FormulaError("a text value is missing its closing quote")
155
+ return "".join(out)
156
+
157
+
158
+ def _normal(node, depth=0):
159
+ if depth > MAX_DEPTH:
160
+ raise FormulaError("formula is nested too deeply")
161
+ if isinstance(node, ast.Constant) and isinstance(node.value, (int, float, str, bool)):
162
+ if isinstance(node.value, float) and not math.isfinite(node.value):
163
+ raise FormulaError("number is not finite")
164
+ return {"t": "const", "v": node.value}
165
+ if isinstance(node, ast.Name) and node.id.upper() in ("TRUE", "FALSE"):
166
+ return {"t": "const", "v": node.id.upper() == "TRUE"}
167
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
168
+ return {"t": "neg", "e": _normal(node.operand, depth + 1)}
169
+ if isinstance(node, ast.BinOp):
170
+ ops = {ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Div: "/", ast.Pow: "^",
171
+ ast.BitAnd: "&"}
172
+ op = ops.get(type(node.op))
173
+ if not op:
174
+ raise FormulaError("that operator is not supported")
175
+ return {"t": "bin", "op": op, "l": _normal(node.left, depth + 1),
176
+ "r": _normal(node.right, depth + 1)}
177
+ if isinstance(node, ast.Compare):
178
+ if len(node.ops) != 1 or len(node.comparators) != 1:
179
+ raise FormulaError("comparisons cannot be chained")
180
+ ops = {ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">=", ast.Eq: "=",
181
+ ast.NotEq: "!="}
182
+ op = ops.get(type(node.ops[0]))
183
+ if not op:
184
+ raise FormulaError("that comparison is not supported")
185
+ return {"t": "cmp", "op": op, "l": _normal(node.left, depth + 1),
186
+ "r": _normal(node.comparators[0], depth + 1)}
187
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
188
+ fn = ALIASES.get(node.func.id.upper(), node.func.id.upper())
189
+ if fn == "REF":
190
+ if len(node.args) != 1 or not isinstance(node.args[0], ast.Constant):
191
+ raise FormulaError("field reference is malformed")
192
+ return {"t": "ref", "k": str(node.args[0].value)}
193
+ if fn not in FN_ARITY or node.keywords:
194
+ raise FormulaError(f"{fn} is not a supported function")
195
+ lo, hi = FN_ARITY[fn]
196
+ if not lo <= len(node.args) <= hi:
197
+ raise FormulaError(f"{fn} takes {lo} to {hi} arguments")
198
+ return {"t": "call", "fn": fn, "args": [_normal(x, depth + 1) for x in node.args]}
199
+ raise FormulaError("formula contains unsupported syntax")
200
+
201
+
202
+ def parse_formula(source):
203
+ source = str(source or "")
204
+ if not source.strip():
205
+ raise FormulaError("the formula is empty")
206
+ if len(source) > MAX_SOURCE:
207
+ raise FormulaError(f"formula longer than {MAX_SOURCE} characters")
208
+ try:
209
+ # Regex patterns such as ``"\\s"`` are data for REGEX_* rather than Python escapes.
210
+ # Python 3.12 warns while parsing them even though the string is valid for this grammar.
211
+ with warnings.catch_warnings():
212
+ warnings.simplefilter("ignore", SyntaxWarning)
213
+ parsed = ast.parse(_rewrite(source), mode="eval")
214
+ except (SyntaxError, ValueError) as exc:
215
+ raise FormulaError("the formula could not be parsed") from exc
216
+ if sum(1 for _ in ast.walk(parsed)) > MAX_NODES:
217
+ raise FormulaError(f"formula has more than {MAX_NODES} nodes")
218
+ root = _normal(parsed.body)
219
+ refs = []
220
+ def walk(row):
221
+ if row["t"] == "ref" and row["k"] not in refs:
222
+ refs.append(row["k"])
223
+ for key in ("e", "l", "r"):
224
+ if isinstance(row.get(key), dict): walk(row[key])
225
+ for child in row.get("args") or (): walk(child)
226
+ walk(root)
227
+ return {"version": AST_VERSION, "source": source, "ast": root, "refs": refs}
228
+
229
+
230
+ def _num(v):
231
+ if isinstance(v, bool) or v is None or v == "": return None
232
+ try: n = float(v)
233
+ except (TypeError, ValueError): return None
234
+ return n if math.isfinite(n) else None
235
+
236
+
237
+ def _text(v):
238
+ if v is None: return ""
239
+ if isinstance(v, bool): return "TRUE" if v else "FALSE"
240
+ if isinstance(v, float) and v.is_integer(): return str(int(v))
241
+ return str(v)
242
+
243
+
244
+ def _date(v):
245
+ try: return dt.date.fromisoformat(str(v)[:10])
246
+ except (TypeError, ValueError): return None
247
+
248
+
249
+ def _round(v, places=0, mode=ROUND_HALF_UP):
250
+ n, p = _num(v), _num(places)
251
+ if n is None or p is None: return None
252
+ q = Decimal("1").scaleb(-int(p))
253
+ return float(Decimal(str(n)).quantize(q, rounding=mode))
254
+
255
+
256
+ def _safe_regex(pattern, subject):
257
+ pattern, subject = str(pattern), str(subject)
258
+ if len(pattern) > 120 or len(subject) > 10000 or "{" in pattern:
259
+ raise FormulaError("regular expression exceeds the safe bounds")
260
+ if re.search(r"\([^)]*[+*][^)]*\)[+*]", pattern):
261
+ raise FormulaError("nested unbounded regular expression is refused")
262
+ return pattern, subject
263
+
264
+
265
+ def _require_node_keys(node, expected):
266
+ if set(node) != set(expected):
267
+ raise FormulaError("formula AST node fields do not match the versioned schema")
268
+
269
+
270
+ def _validate_ast(node, depth=0, refs=None, count=None):
271
+ """Validate a serialized AST independently of the parser before strict API evaluation."""
272
+ refs = [] if refs is None else refs
273
+ count = [0] if count is None else count
274
+ count[0] += 1
275
+ if depth > MAX_DEPTH or count[0] > MAX_NODES or not isinstance(node, dict):
276
+ raise FormulaError("formula AST exceeds the safe bounds")
277
+ kind = node.get("t")
278
+ if kind == "const":
279
+ _require_node_keys(node, ("t", "v"))
280
+ value = node.get("v")
281
+ if not isinstance(value, (int, float, str, bool)) or (
282
+ isinstance(value, float) and not math.isfinite(value)):
283
+ raise FormulaError("formula AST constant is invalid")
284
+ elif kind == "ref":
285
+ _require_node_keys(node, ("t", "k"))
286
+ key = node.get("k")
287
+ if (not isinstance(key, str) or not re.fullmatch(r"[A-Za-z0-9_]+", key)
288
+ or len(key) > MAX_FIELD_KEY):
289
+ raise FormulaError("formula AST field reference is invalid")
290
+ if key not in refs:
291
+ refs.append(key)
292
+ elif kind == "neg":
293
+ _require_node_keys(node, ("t", "e"))
294
+ _validate_ast(node.get("e"), depth + 1, refs, count)
295
+ elif kind in ("bin", "cmp"):
296
+ _require_node_keys(node, ("t", "op", "l", "r"))
297
+ allowed = {"+", "-", "*", "/", "^", "&"} if kind == "bin" else {
298
+ "<", "<=", ">", ">=", "=", "!="}
299
+ if node.get("op") not in allowed:
300
+ raise FormulaError("formula AST operator is invalid")
301
+ _validate_ast(node.get("l"), depth + 1, refs, count)
302
+ _validate_ast(node.get("r"), depth + 1, refs, count)
303
+ elif kind == "call":
304
+ _require_node_keys(node, ("t", "fn", "args"))
305
+ fn, args = node.get("fn"), node.get("args")
306
+ if fn not in FN_ARITY or not isinstance(args, list):
307
+ raise FormulaError("formula AST function is invalid")
308
+ lo, hi = FN_ARITY[fn]
309
+ if not lo <= len(args) <= hi:
310
+ raise FormulaError("formula AST function arity is invalid")
311
+ for child in args:
312
+ _validate_ast(child, depth + 1, refs, count)
313
+ else:
314
+ raise FormulaError("formula AST node is not supported")
315
+ return refs
316
+
317
+
318
+ def validate_definition(definition, *, require_source=False):
319
+ """Refuse any serialized definition that is not exactly reproducible by this parser.
320
+
321
+ Checking the AST alone would let a caller display one ``source`` while asking the server to
322
+ execute a different tree. API consumers therefore send the parser-issued envelope and strict
323
+ evaluation reparses its source before accepting it.
324
+ """
325
+ if not isinstance(definition, dict) or isinstance(definition.get("version"), bool) or (
326
+ definition.get("version") != AST_VERSION):
327
+ raise FormulaError("formula AST version is not supported")
328
+ refs = _validate_ast(definition.get("ast"))
329
+ metadata_refs = definition.get("refs")
330
+ if not isinstance(metadata_refs, list) or metadata_refs != refs:
331
+ raise FormulaError("formula AST references do not match its metadata")
332
+ source = definition.get("source")
333
+ if require_source and not isinstance(source, str):
334
+ raise FormulaError("formula source is required for authoritative evaluation")
335
+ if isinstance(source, str):
336
+ reparsed = parse_formula(source)
337
+ if reparsed["ast"] != definition.get("ast") or reparsed["refs"] != metadata_refs:
338
+ raise FormulaError("formula source does not match its AST")
339
+ return refs
340
+
341
+
342
+ def evaluate_result(definition, row, *, today=None, strict=False):
343
+ """Evaluate one definition and return the shared value/error DTO."""
344
+ diagnostics = []
345
+ try:
346
+ if strict:
347
+ validate_definition(definition, require_source=True)
348
+ elif not isinstance(definition, dict) or definition.get("version") != AST_VERSION:
349
+ return {"value": None, "error": "invalid_definition"}
350
+ value = _eval(definition.get("ast"), row if isinstance(row, dict) else {},
351
+ today or dt.date.today().isoformat(), diagnostics)
352
+ if diagnostics:
353
+ value = None
354
+ if isinstance(value, bool):
355
+ value = "TRUE" if value else "FALSE"
356
+ elif isinstance(value, float) and not math.isfinite(value):
357
+ value = None
358
+ elif value is not None and not isinstance(value, (int, float, str)):
359
+ value = None
360
+ diagnostics.append("evaluation_error")
361
+ return {"value": value,
362
+ "error": None if value is not None else (diagnostics[0] if diagnostics else "blank")}
363
+ except FormulaError:
364
+ if strict:
365
+ raise
366
+ return {"value": None, "error": "invalid_definition"}
367
+ except (ArithmeticError, TypeError, ValueError, OverflowError, KeyError, re.error):
368
+ return {"value": None, "error": "evaluation_error"}
369
+
370
+
371
+ def evaluate(definition, row, *, today=None, strict=False):
372
+ """Backward-compatible value projection of :func:`evaluate_result`."""
373
+ return evaluate_result(definition, row, today=today, strict=strict)["value"]
374
+
375
+
376
+ def _diagnose(diagnostics, code):
377
+ if diagnostics is not None and code not in diagnostics:
378
+ diagnostics.append(code)
379
+
380
+
381
+ def _eval(node, row, today, diagnostics=None):
382
+ kind = node.get("t") if isinstance(node, dict) else None
383
+ if kind == "const": return node.get("v")
384
+ if kind == "ref":
385
+ key = node.get("k")
386
+ if key not in row:
387
+ _diagnose(diagnostics, "unknown_ref")
388
+ return row.get(key)
389
+ if kind == "neg":
390
+ n = _num(_eval(node["e"], row, today, diagnostics)); return None if n is None else -n
391
+ if kind == "bin":
392
+ left = _eval(node["l"], row, today, diagnostics)
393
+ right = _eval(node["r"], row, today, diagnostics)
394
+ if node["op"] == "&": return _text(left) + _text(right)
395
+ a, b = _num(left), _num(right)
396
+ if a is None or b is None: return None
397
+ if node["op"] == "/" and b == 0:
398
+ _diagnose(diagnostics, "div_zero")
399
+ return None
400
+ return {"+": lambda: a + b, "-": lambda: a - b, "*": lambda: a * b,
401
+ "/": lambda: a / b, "^": lambda: a ** b}[node["op"]]()
402
+ if kind == "cmp":
403
+ a = _eval(node["l"], row, today, diagnostics)
404
+ b = _eval(node["r"], row, today, diagnostics)
405
+ if a is None or b is None: return None
406
+ na, nb = _num(a), _num(b)
407
+ if (na is None) != (nb is None): return None
408
+ x, y = (na, nb) if na is not None else (str(a).casefold(), str(b).casefold())
409
+ return {"<": x < y, "<=": x <= y, ">": x > y, ">=": x >= y,
410
+ "=": x == y, "!=": x != y}[node["op"]]
411
+ if kind == "call":
412
+ fn = node["fn"]
413
+ # IF/IFERROR are lazy, so an unselected bad branch cannot blank the result.
414
+ if fn == "IF":
415
+ cond = _eval(node["args"][0], row, today, diagnostics)
416
+ if not isinstance(cond, bool): return None
417
+ pick = 1 if cond else 2
418
+ return (_eval(node["args"][pick], row, today, diagnostics)
419
+ if pick < len(node["args"]) else None)
420
+ if fn == "IFERROR":
421
+ # A handled failure is not an error of the whole formula, so diagnostics from the
422
+ # losing branch remain local.
423
+ try:
424
+ first = _eval(node["args"][0], row, today, [])
425
+ except (ArithmeticError, TypeError, ValueError, OverflowError, KeyError, re.error,
426
+ FormulaError):
427
+ first = None
428
+ return first if first is not None else _eval(
429
+ node["args"][1], row, today, diagnostics)
430
+ args = [_eval(x, row, today, diagnostics) for x in node.get("args") or ()]
431
+ return _call(fn, args, today)
432
+ raise FormulaError("formula AST node is not supported")
433
+
434
+
435
+ def _call(fn, a, today):
436
+ nums = [_num(x) for x in a]; present = [x for x in nums if x is not None]
437
+ if fn == "ABS": return abs(nums[0]) if nums[0] is not None else None
438
+ if fn == "ROUND": return _round(a[0], a[1] if len(a) > 1 else 0)
439
+ if fn == "ROUNDUP":
440
+ n, p = nums[0], int(nums[1] or 0); return None if n is None else math.copysign(math.ceil(abs(n)*10**p)/10**p, n)
441
+ if fn == "ROUNDDOWN":
442
+ n, p = nums[0], int(nums[1] or 0); return None if n is None else math.copysign(math.floor(abs(n)*10**p)/10**p, n)
443
+ if fn == "INT": return math.floor(nums[0]) if nums[0] is not None else None
444
+ if fn == "MOD": return None if None in nums or nums[1] == 0 else nums[0] % nums[1]
445
+ if fn == "SQRT": return math.sqrt(nums[0]) if nums[0] is not None and nums[0] >= 0 else None
446
+ if fn == "POWER": return None if None in nums else nums[0] ** nums[1]
447
+ if fn == "EXP": return math.exp(nums[0]) if nums[0] is not None else None
448
+ if fn == "LN": return math.log(nums[0]) if nums[0] is not None and nums[0] > 0 else None
449
+ if fn == "SUM": return sum(present)
450
+ if fn == "AVERAGE": return sum(present)/len(present) if present else None
451
+ if fn == "COUNT": return len(present)
452
+ if fn == "COUNTA": return sum(x is not None and x != "" for x in a)
453
+ if fn == "MIN": return min(present) if present else None
454
+ if fn == "MAX": return max(present) if present else None
455
+ if fn in ("AND", "OR"):
456
+ if not all(isinstance(x, bool) for x in a): return None
457
+ return all(a) if fn == "AND" else any(a)
458
+ if fn == "NOT": return not a[0] if isinstance(a[0], bool) else None
459
+ if fn == "ISBLANK": return a[0] is None or a[0] == ""
460
+ if fn == "SWITCH":
461
+ pairs = a[1:]; fallback = None
462
+ if len(pairs) % 2: fallback = pairs.pop()
463
+ for i in range(0, len(pairs), 2):
464
+ if str(a[0]).casefold() == str(pairs[i]).casefold(): return pairs[i+1]
465
+ return fallback
466
+ if fn == "CONCATENATE": return "".join(_text(x) for x in a)
467
+ if fn == "LEFT": return _text(a[0])[:int(nums[1] if len(a)>1 and nums[1] is not None else 1)]
468
+ if fn == "RIGHT": return _text(a[0])[-int(nums[1] if len(a)>1 and nums[1] is not None else 1):]
469
+ if fn == "MID": return _text(a[0])[max(0,int(nums[1] or 1)-1):max(0,int(nums[1] or 1)-1)+int(nums[2] or 0)]
470
+ if fn == "LEN": return len(_text(a[0]))
471
+ if fn == "TRIM": return " ".join(_text(a[0]).split())
472
+ if fn == "UPPER": return _text(a[0]).upper()
473
+ if fn == "LOWER": return _text(a[0]).lower()
474
+ if fn == "PROPER": return _text(a[0]).title()
475
+ if fn == "VALUE": return _num(a[0])
476
+ if fn == "TEXT":
477
+ n = _num(a[0]); fmt = str(a[1]);
478
+ if n is None: return None
479
+ if fmt == "0%": return f"{round(n*100):.0f}%"
480
+ if fmt in ("0.00", "#,##0.00", "$#,##0.00"): return ("$" if fmt.startswith("$") else "") + f"{n:,.2f}"
481
+ return None
482
+ if fn == "SUBSTITUTE":
483
+ text, old, new = map(_text, a[:3])
484
+ if len(a) == 3: return text.replace(old, new)
485
+ occurrence = int(nums[3] or 0); parts = text.split(old)
486
+ return old.join(parts[:occurrence]) + (new + old.join(parts[occurrence:]) if 0 < occurrence < len(parts) else "")
487
+ if fn == "FIND":
488
+ start = int(nums[2] or 1)-1 if len(a)>2 else 0; pos = _text(a[1]).find(_text(a[0]), start)
489
+ return pos+1 if pos >= 0 else None
490
+ if fn in ("REGEX_EXTRACT", "REGEX_REPLACE"):
491
+ pattern, subject = _safe_regex(a[1], a[0]); m = re.search(pattern, subject)
492
+ if fn == "REGEX_EXTRACT": return m.group(0) if m else None
493
+ return re.sub(pattern, _text(a[2]), subject)
494
+ if fn == "TODAY": return str(today)[:10]
495
+ if fn in ("YEAR", "MONTH", "DAY"):
496
+ d = _date(a[0]); return getattr(d, fn.lower()) if d else None
497
+ if fn == "DAYS":
498
+ x,y=_date(a[0]),_date(a[1]); return (x-y).days if x and y else None
499
+ if fn == "DATEADD":
500
+ d, n, unit = _date(a[0]), nums[1], _text(a[2]).lower()
501
+ if not d or n is None: return None
502
+ n=int(n)
503
+ if unit in ("day","days"): d += dt.timedelta(days=n)
504
+ elif unit in ("week","weeks"): d += dt.timedelta(weeks=n)
505
+ elif unit in ("month","months"):
506
+ month=d.month-1+n; year=d.year+month//12; month=month%12+1; d=d.replace(year=year,month=month,day=min(d.day,calendar.monthrange(year,month)[1]))
507
+ elif unit in ("year","years"): d=d.replace(year=d.year+n,day=min(d.day,calendar.monthrange(d.year+n,d.month)[1]))
508
+ else: return None
509
+ return d.isoformat()
510
+ if fn == "DATETIME_DIFF":
511
+ x,y=_date(a[0]),_date(a[1]); unit=_text(a[2] if len(a)>2 else "days").lower()
512
+ if not x or not y: return None
513
+ days=(x-y).days
514
+ return days if unit in ("day","days") else math.trunc(days/7) if unit in ("week","weeks") else None
515
+ if fn == "DATETIME_FORMAT":
516
+ d=_date(a[0]); fmt=_text(a[1]);
517
+ if not d: return None
518
+ tokens={"YYYY":f"{d.year:04d}","MM":f"{d.month:02d}","DD":f"{d.day:02d}","M":str(d.month),"D":str(d.day)}
519
+ for key in sorted(tokens,key=len,reverse=True): fmt=fmt.replace(key,tokens[key])
520
+ return fmt
521
+ raise FormulaError("formula function is not implemented")
522
+
523
+
524
+ def explain_recalculation(definition, field_revisions):
525
+ """Compact provenance; formula history stores definitions, never redundant cell snapshots."""
526
+ definition = definition if isinstance(definition, dict) else {}
527
+ field_revisions = field_revisions if isinstance(field_revisions, dict) else {}
528
+ canonical = {key: definition.get(key) for key in ("version", "source", "ast", "refs")}
529
+ digest = hashlib.sha256(json.dumps(
530
+ canonical, sort_keys=True, separators=(",", ":"), ensure_ascii=False
531
+ ).encode("utf-8")).hexdigest()
532
+ def revision(value, default):
533
+ if isinstance(value, bool):
534
+ return default
535
+ try:
536
+ return max(0, int(value))
537
+ except (TypeError, ValueError, OverflowError):
538
+ return default
539
+
540
+ return {"formulaRevision": revision(definition.get("revision"), 1) or 1,
541
+ "astVersion": revision(definition.get("version"), AST_VERSION) or AST_VERSION,
542
+ "definitionHash": f"sha256:{digest}",
543
+ "inputs": {key: revision(field_revisions.get(key), 0)
544
+ for key in definition.get("refs") or ()},
545
+ "valueSnapshotStored": False}
546
+
547
+
548
+ def evaluate_fields(definitions, row, *, today=None):
549
+ """Evaluate formula-over-formula dependencies once, refusing every member of a cycle."""
550
+ definitions = definitions if isinstance(definitions, dict) else {}
551
+ row = row if isinstance(row, dict) else {}
552
+ # Stored/client materialisations are never authority. A definition present in this batch
553
+ # always replaces a same-named row value through the server evaluator.
554
+ values = {key: value for key, value in row.items() if key not in definitions}
555
+ errors, active, resolved = {}, [], set()
556
+
557
+ def resolve(key):
558
+ if key in resolved or (key in values and key not in definitions):
559
+ return values[key]
560
+ if key in active:
561
+ start = active.index(key)
562
+ for member in active[start:]:
563
+ errors[member] = "cycle"
564
+ values[member] = None
565
+ return None
566
+ definition = definitions.get(key)
567
+ if not isinstance(definition, dict):
568
+ return None
569
+ active.append(key)
570
+ inputs = dict(values)
571
+ dependency_error = False
572
+ for ref in definition.get("refs") or ():
573
+ if ref in definitions:
574
+ inputs[ref] = resolve(ref)
575
+ dependency_error = dependency_error or ref in errors
576
+ elif ref in row:
577
+ inputs[ref] = row[ref]
578
+ if errors.get(key) == "cycle":
579
+ active.pop()
580
+ resolved.add(key)
581
+ return None
582
+ result = evaluate_result(definition, inputs, today=today)
583
+ active.pop()
584
+ values[key] = result["value"]
585
+ if result["error"]:
586
+ errors[key] = ("dependency_error"
587
+ if result["error"] == "blank" and dependency_error
588
+ else result["error"])
589
+ resolved.add(key)
590
+ return values.get(key)
591
+
592
+ for field_key in definitions:
593
+ resolve(field_key)
594
+ return {"values": {key: values.get(key) for key in definitions}, "errors": errors}
595
+
596
+
597
+ def evaluate_batch(definitions, rows, *, consumer, today=None, field_revisions=None):
598
+ """Evaluate a bounded set of formula definitions over typed consumer rows.
599
+
600
+ Grid, filter, export, automation, Query and Time Series all use this DTO. ``consumer`` is
601
+ attribution, never an evaluator switch: the result is deliberately identical for every
602
+ declared surface.
603
+ """
604
+ if consumer not in CONSUMERS:
605
+ raise FormulaError("formula consumer is not supported")
606
+ if not isinstance(definitions, dict) or not definitions:
607
+ raise FormulaError("formula definitions must be a non-empty object")
608
+ if len(definitions) > MAX_DEFINITIONS:
609
+ raise FormulaError(f"formula batch has more than {MAX_DEFINITIONS} definitions")
610
+ clean = {}
611
+ for key, definition in definitions.items():
612
+ if not isinstance(key, str) or not re.fullmatch(r"[A-Za-z0-9_]+", key):
613
+ raise FormulaError("formula definition key is invalid")
614
+ validate_definition(definition, require_source=True)
615
+ clean[key] = definition
616
+ if not isinstance(rows, list) or not rows:
617
+ raise FormulaError("formula rows must be a non-empty list")
618
+ if len(rows) > MAX_BATCH_ROWS:
619
+ raise FormulaError(f"formula batch has more than {MAX_BATCH_ROWS} rows")
620
+ output, seen_ids = [], set()
621
+ for item in rows:
622
+ if not isinstance(item, dict) or not isinstance(item.get("values"), dict):
623
+ raise FormulaError("each formula row needs an id and values object")
624
+ row_id = item.get("id")
625
+ if isinstance(row_id, bool) or not isinstance(row_id, (str, int)) or row_id in seen_ids:
626
+ raise FormulaError("each formula row id must be a unique string or integer")
627
+ seen_ids.add(row_id)
628
+ result = evaluate_fields(clean, item["values"], today=today)
629
+ output.append({"id": row_id, "values": result["values"], "errors": result["errors"]})
630
+ return {
631
+ "contractVersion": CONTRACT_VERSION,
632
+ "astVersion": AST_VERSION,
633
+ "authority": AUTHORITY,
634
+ "consumer": consumer,
635
+ "definitions": [
636
+ {"key": key, **explain_recalculation(definition, field_revisions or {})}
637
+ for key, definition in clean.items()
638
+ ],
639
+ "rows": output,
640
+ }
641
+
642
+
643
+ def contract_dto():
644
+ """Return the complete JSON-safe grammar and executable browser parity corpus."""
645
+ inverse_aliases = {}
646
+ for alias, canonical in ALIASES.items():
647
+ inverse_aliases.setdefault(canonical, []).append(alias)
648
+ functions = [
649
+ {"name": name, "minArgs": bounds[0], "maxArgs": bounds[1],
650
+ "aliases": sorted(inverse_aliases.get(name, []))}
651
+ for name, bounds in sorted(FN_ARITY.items())
652
+ ]
653
+ operators = [
654
+ {"kind": "unary", "canonical": "-", "aliases": []},
655
+ *({"kind": "binary", "canonical": token, "aliases": []}
656
+ for token in ("+", "-", "*", "/", "^", "&")),
657
+ *({"kind": "comparison", "canonical": token, "aliases": aliases}
658
+ for token, aliases in (("<", []), ("<=", []), (">", []), (">=", []),
659
+ ("=", ["=="]), ("!=", ["<>"]))),
660
+ ]
661
+ fixtures = [
662
+ {"id": f"function:{name.lower()}", "kind": "function", "function": name,
663
+ "source": source, "row": {"empty": None}, "today": "2024-01-02",
664
+ "expected": expected, "expectedError": None}
665
+ for name, (source, expected) in PARITY_FIXTURES.items()
666
+ ]
667
+ fixtures.extend(
668
+ {"id": f"operator:{name}", "kind": "operator", "operator": name,
669
+ "source": source, "row": row, "today": "2024-01-02",
670
+ "expected": expected, "expectedError": None}
671
+ for name, (source, row, expected) in OPERATOR_PARITY_FIXTURES.items()
672
+ )
673
+ errors = [
674
+ {"id": f"parse:{name}", "phase": "parse", "source": source,
675
+ "expectedStatus": 400, "expectedError": "bad_formula"}
676
+ for name, source in PARSE_ERROR_FIXTURES.items()
677
+ ]
678
+ errors.extend(
679
+ {"id": f"evaluate:{name}", "phase": "evaluate", "source": source,
680
+ "row": row, "today": "2024-01-02", "expected": None,
681
+ "expectedStatus": 200, "expectedError": expected_error}
682
+ for name, (source, row, expected_error) in EVALUATION_ERROR_FIXTURES.items()
683
+ )
684
+ errors.extend((
685
+ {"id": "definition:source_ast_mismatch", "phase": "definition",
686
+ "source": "{amount} + 1", "tamperedSource": "{amount} + 2",
687
+ "row": {"amount": 4}, "expectedStatus": 400, "expectedError": "bad_formula"},
688
+ {"id": "batch:cycle", "phase": "batch",
689
+ "sources": {"a": "{b} + 1", "b": "{a} + 1"},
690
+ "rows": [{"id": "2024-01", "values": {}}], "consumer": "timeseries",
691
+ "expectedStatus": 200, "expectedErrors": {"a": "cycle", "b": "cycle"}},
692
+ ))
693
+ return {
694
+ "contractVersion": CONTRACT_VERSION,
695
+ "astVersion": AST_VERSION,
696
+ "authority": AUTHORITY,
697
+ "consumers": list(CONSUMERS),
698
+ "grammar": {
699
+ "name": "aios-formula",
700
+ "reference": {"open": "{", "close": "}",
701
+ "pattern": r"\{[A-Za-z0-9_]+\}",
702
+ "example": "{amount}",
703
+ "legacySquareReferenceAccepted": False},
704
+ "literals": ["number", "text", "TRUE", "FALSE"],
705
+ "functionCall": "NAME(argument, ...)",
706
+ "operators": operators,
707
+ },
708
+ "ast": {
709
+ "definitionFields": ["version", "source", "ast", "refs"],
710
+ "nodes": [
711
+ {"type": "const", "fields": ["t", "v"]},
712
+ {"type": "ref", "fields": ["t", "k"]},
713
+ {"type": "neg", "fields": ["t", "e"]},
714
+ {"type": "bin", "fields": ["t", "op", "l", "r"]},
715
+ {"type": "cmp", "fields": ["t", "op", "l", "r"]},
716
+ {"type": "call", "fields": ["t", "fn", "args"]},
717
+ ],
718
+ },
719
+ "dto": {
720
+ "parseRequestRequired": ["source"],
721
+ "parseResponseRequired": ["contractVersion", "astVersion", "authority", "definition"],
722
+ "singleEvaluateRequestRequired": ["definition", "row"],
723
+ "singleEvaluateResponseRequired": ["contractVersion", "astVersion", "authority",
724
+ "value", "error", "recalculation"],
725
+ "batchEvaluateRequestRequired": ["consumer", "definitions", "rows"],
726
+ "batchEvaluateResponseRequired": ["contractVersion", "astVersion", "authority",
727
+ "consumer", "definitions", "rows"],
728
+ "batchRequestRowRequired": ["id", "values"],
729
+ "batchResponseRowRequired": ["id", "values", "errors"],
730
+ },
731
+ "batchFixture": {
732
+ "id": "timeseries:formula_dependency",
733
+ "consumer": "timeseries",
734
+ "sources": {"double": "{amount} * 2", "total": "{double} + 1"},
735
+ "rows": [{"id": "2024-01", "values": {"amount": 4}},
736
+ {"id": "2024-02", "values": {"amount": 7}}],
737
+ "expected": [
738
+ {"id": "2024-01", "values": {"double": 8.0, "total": 9.0}, "errors": {}},
739
+ {"id": "2024-02", "values": {"double": 14.0, "total": 15.0}, "errors": {}},
740
+ ],
741
+ },
742
+ "limits": {"sourceCharacters": MAX_SOURCE, "astNodes": MAX_NODES,
743
+ "astDepth": MAX_DEPTH, "definitionsPerBatch": MAX_DEFINITIONS,
744
+ "rowsPerBatch": MAX_BATCH_ROWS},
745
+ "functions": functions,
746
+ "errorCodes": ["bad_formula", "unknown_ref", "div_zero", "cycle", "blank",
747
+ "dependency_error", "evaluation_error"],
748
+ "fixtures": fixtures,
749
+ "errors": errors,
750
+ }
api/main.py CHANGED
@@ -832,7 +832,13 @@ def _rebuild_odoo_relational(why, previous_meta_fingerprint=None, meta_state_out
832
  if not _rel.is_royal("royal-imports"):
833
  return False
834
  _rt = _runtime.get_runtime("royal-imports")
 
 
835
  counts = _rel.refresh(_rt, "royal-imports")
 
 
 
 
836
  # ⭐⭐ AND THEN COMPUTE THE CELLS, which `refresh` does NOT do.
837
  #
838
  # ⛔ THE FAILURE THIS CLOSES IS THE WORST-LOOKING KIND. `refresh` writes rows and field
@@ -853,15 +859,21 @@ def _rebuild_odoo_relational(why, previous_meta_fingerprint=None, meta_state_out
853
  import automation_engine as _engine
854
  _engine.refresh_relations(_rt, log=lambda *_a: None)
855
  except Exception as e: # noqa: BLE001
 
856
  print(f"[aios-api] odoo relation cells failed ({why}): {type(e).__name__}: {e}")
857
  try:
858
  import rollup_sql as _rollup
859
  for _b, _key, _l, _f in _rel.TABLES:
860
  _rollup.compute(_rt, _key)
861
  except Exception as e: # noqa: BLE001
 
862
  print(f"[aios-api] odoo source rollups failed ({why}): {type(e).__name__}: {e}")
863
  print(f"[aios-api] odoo relational rebuild done ({why}): "
864
  + ", ".join(f"{k}={v}" for k, v in sorted((counts or {}).items())))
 
 
 
 
865
  meta_state = _rebuild_meta_relational(
866
  why, _rt, previous_fingerprint=previous_meta_fingerprint, force_relations=True)
867
  if isinstance(meta_state_out, dict):
@@ -876,6 +888,12 @@ def _rebuild_odoo_relational(why, previous_meta_fingerprint=None, meta_state_out
876
  # `BinderException` about a missing column is a different action from a timeout or an auth
877
  # failure, and the text alone often does not say which it was.
878
  print(f"[aios-api] odoo relational rebuild failed ({why}): {type(e).__name__}: {e}")
 
 
 
 
 
 
879
  return False
880
 
881
 
 
832
  if not _rel.is_royal("royal-imports"):
833
  return False
834
  _rt = _runtime.get_runtime("royal-imports")
835
+ from core import user_tables as _ut
836
+ _ut.record_odoo_sync_status(phase="syncing", st=_rt)
837
  counts = _rel.refresh(_rt, "royal-imports")
838
+ raw_models, schema_errors = _rel.authoritative_schema_snapshot()
839
+ _ut.record_odoo_schema_snapshot(raw_models, complete=not schema_errors,
840
+ errors=schema_errors, st=_rt)
841
+ rebuild_errors = []
842
  # ⭐⭐ AND THEN COMPUTE THE CELLS, which `refresh` does NOT do.
843
  #
844
  # ⛔ THE FAILURE THIS CLOSES IS THE WORST-LOOKING KIND. `refresh` writes rows and field
 
859
  import automation_engine as _engine
860
  _engine.refresh_relations(_rt, log=lambda *_a: None)
861
  except Exception as e: # noqa: BLE001
862
+ rebuild_errors.append(f"relations: {type(e).__name__}: {e}")
863
  print(f"[aios-api] odoo relation cells failed ({why}): {type(e).__name__}: {e}")
864
  try:
865
  import rollup_sql as _rollup
866
  for _b, _key, _l, _f in _rel.TABLES:
867
  _rollup.compute(_rt, _key)
868
  except Exception as e: # noqa: BLE001
869
+ rebuild_errors.append(f"rollups: {type(e).__name__}: {e}")
870
  print(f"[aios-api] odoo source rollups failed ({why}): {type(e).__name__}: {e}")
871
  print(f"[aios-api] odoo relational rebuild done ({why}): "
872
  + ", ".join(f"{k}={v}" for k, v in sorted((counts or {}).items())))
873
+ if rebuild_errors:
874
+ _ut.record_odoo_sync_status(phase="error", errors=rebuild_errors, st=_rt)
875
+ else:
876
+ _ut.record_odoo_sync_status(phase="ok", st=_rt)
877
  meta_state = _rebuild_meta_relational(
878
  why, _rt, previous_fingerprint=previous_meta_fingerprint, force_relations=True)
879
  if isinstance(meta_state_out, dict):
 
888
  # `BinderException` about a missing column is a different action from a timeout or an auth
889
  # failure, and the text alone often does not say which it was.
890
  print(f"[aios-api] odoo relational rebuild failed ({why}): {type(e).__name__}: {e}")
891
+ try:
892
+ if '_rt' in locals():
893
+ from core import user_tables as _ut
894
+ _ut.record_odoo_sync_status(phase="error", errors=[f"{type(e).__name__}: {e}"], st=_rt)
895
+ except Exception:
896
+ pass
897
  return False
898
 
899
 
api/odoo_relational.py CHANGED
@@ -1404,6 +1404,33 @@ TABLES = (
1404
  ("gl_lines", GL_LINES_KEY, "Odoo GL lines", gl_line_fields),
1405
  )
1406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1407
  #: store key -> the REAL-WORLD POPULATION that table presents (`core.registry`'s `subject`
1408
  #: vocabulary, same strings, one namespace). ⭐ W33-T41 / item 12a.
1409
  #:
 
1404
  ("gl_lines", GL_LINES_KEY, "Odoo GL lines", gl_line_fields),
1405
  )
1406
 
1407
+ # The grid declarations above are the stable mirror contract, not Odoo's schema. T03 snapshots
1408
+ # must come from Odoo's authoritative ``fields_get`` response so empty/default-off fields are not
1409
+ # silently lost. This helper is injectable in hermetic tests and keeps the live read narrow.
1410
+ ODOO_TABLE_MODELS = {
1411
+ INVOICES_KEY: "account.move", ORDERS_KEY: "sale.order", AGENTS_KEY: "res.partner",
1412
+ ACCOUNTS_KEY: "account.account", VENDORS_KEY: "res.partner", BILLS_KEY: "account.move",
1413
+ ORDER_LINES_KEY: "sale.order.line", GL_LINES_KEY: "account.move.line",
1414
+ }
1415
+
1416
+
1417
+ def authoritative_schema_snapshot():
1418
+ from core.odoo import get_odoo
1419
+ from harness.datastore import ENTITIES
1420
+ models = {}
1421
+ errors = []
1422
+ seen = set()
1423
+ for spec in ENTITIES.values():
1424
+ model = str(spec.get("model") or "")
1425
+ if model and model not in seen:
1426
+ seen.add(model)
1427
+ try:
1428
+ models[model] = get_odoo().fields_get(
1429
+ model, attributes=("string", "type", "required", "readonly", "relation"))
1430
+ except Exception as exc:
1431
+ errors.append(f"{model}: {type(exc).__name__}: {exc}")
1432
+ return models, errors
1433
+
1434
  #: store key -> the REAL-WORLD POPULATION that table presents (`core.registry`'s `subject`
1435
  #: vocabulary, same strings, one namespace). ⭐ W33-T41 / item 12a.
1436
  #:
api/operator_control.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Same-origin, capability-scoped Operator grants and audited setup records.
2
+
3
+ This module is deliberately transport-neutral. The browser and a future MCP adapter call the same
4
+ authorization function; neither receives a secret, provider credential, or cross-tenant wildcard.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import copy
9
+ import hashlib
10
+ import secrets
11
+ import time
12
+ from typing import Any
13
+
14
+
15
+ STORE_KEY = "operator_control"
16
+ SETUP_KEY = "operator_setup"
17
+ AUDIENCE = "loopable-operator"
18
+ CAPABILITIES = frozenset({"tenant.read", "tenant.configure", "voice.read", "voice.configure"})
19
+ SETUP_FIELDS = frozenset({"displayName", "timezone", "voicePurpose", "consentPolicy",
20
+ "queryEnabled", "providerLabel"})
21
+
22
+
23
+ class OperatorRefusal(ValueError):
24
+ pass
25
+
26
+
27
+ def _now() -> int:
28
+ return int(time.time())
29
+
30
+
31
+ def _hash(value: str) -> str:
32
+ return hashlib.sha256(str(value or "").encode("utf-8")).hexdigest()
33
+
34
+
35
+ def _origin(value: Any) -> str:
36
+ text = str(value or "").strip().lower().rstrip("/")
37
+ if not text.startswith(("https://", "http://localhost", "http://127.0.0.1")):
38
+ raise OperatorRefusal("Operator grants require the current Loopable origin")
39
+ if any(ch in text for ch in ("?", "#", "@")):
40
+ raise OperatorRefusal("Operator origin is invalid")
41
+ return text[:240]
42
+
43
+
44
+ def _document(rt: Any) -> dict:
45
+ try:
46
+ raw = rt.get(STORE_KEY) or {}
47
+ except Exception:
48
+ raw = {}
49
+ if not isinstance(raw, dict):
50
+ raw = {}
51
+ return {"grants": copy.deepcopy(raw.get("grants") or {}),
52
+ "audit": copy.deepcopy(raw.get("audit") or [])}
53
+
54
+
55
+ def _update(rt: Any, fn):
56
+ return rt.update(STORE_KEY, lambda raw: fn({
57
+ "grants": copy.deepcopy((raw or {}).get("grants") or {}),
58
+ "audit": copy.deepcopy((raw or {}).get("audit") or []),
59
+ }), flush="sync")
60
+
61
+
62
+ def _audit(rt: Any, *, actor: str, tenant: str, capability: str, action: str,
63
+ outcome: str, grant_id: str = "", source: str = "browser") -> dict:
64
+ event = {"id": f"opa_{_now()}_{secrets.token_hex(4)}", "at": _now(),
65
+ "actor": str(actor or "")[:120], "tenant": str(tenant or "")[:120],
66
+ "capability": str(capability or "")[:80], "action": str(action or "")[:120],
67
+ "outcome": str(outcome or "refused")[:40], "grantId": str(grant_id or "")[:120],
68
+ "source": "mcp" if source == "mcp" else "browser"}
69
+ def up(doc):
70
+ doc["audit"] = (list(doc.get("audit") or []) + [event])[-2000:]
71
+ return doc
72
+ _update(rt, up)
73
+ return event
74
+
75
+
76
+ def mint_grant(rt: Any, *, actor: str, tenant: str, capabilities: Any, origin: str,
77
+ audience: str = AUDIENCE, ttl_seconds: int = 900) -> dict:
78
+ target = str(tenant or "").strip().lower()
79
+ gid, outcome = "", "refused"
80
+ try:
81
+ if not target or target == "*":
82
+ raise OperatorRefusal("Operator grant needs one exact tenant")
83
+ requested = sorted({str(value) for value in (capabilities or [])})
84
+ if not requested or any(value not in CAPABILITIES for value in requested):
85
+ raise OperatorRefusal("Operator grant contains an unsupported capability")
86
+ if str(audience or "") != AUDIENCE:
87
+ raise OperatorRefusal("Operator grant audience is invalid")
88
+ bound_origin = _origin(origin)
89
+ ttl = max(60, min(int(ttl_seconds or 900), 3600))
90
+ token = secrets.token_urlsafe(32)
91
+ gid = "opg_" + secrets.token_hex(8)
92
+ rec = {"id": gid, "actor": str(actor or "")[:120], "tenant": target,
93
+ "capabilities": requested, "origin": bound_origin, "audience": AUDIENCE,
94
+ "tokenHash": _hash(token), "createdAt": _now(), "expiresAt": _now() + ttl,
95
+ "revokedAt": 0}
96
+ _update(rt, lambda doc: {**doc, "grants": {**doc["grants"], gid: rec}})
97
+ outcome = "allowed"
98
+ return {"grant": grant_dto(rec), "token": token}
99
+ finally:
100
+ _audit(rt, actor=actor, tenant=target, capability="grant.mint", action="mint",
101
+ outcome=outcome, grant_id=gid)
102
+
103
+
104
+ def grant_dto(rec: Any) -> dict:
105
+ row = rec if isinstance(rec, dict) else {}
106
+ return {key: copy.deepcopy(row.get(key)) for key in
107
+ ("id", "actor", "tenant", "capabilities", "origin", "audience",
108
+ "createdAt", "expiresAt", "revokedAt")}
109
+
110
+
111
+ def revoke_grant(rt: Any, grant_id: str, actor: str) -> dict:
112
+ result = {}
113
+ outcome = "refused"
114
+ def up(doc):
115
+ rec = doc["grants"].get(str(grant_id))
116
+ if not isinstance(rec, dict):
117
+ raise OperatorRefusal("unknown Operator grant")
118
+ rec = {**rec, "revokedAt": _now()}
119
+ doc["grants"][str(grant_id)] = rec
120
+ result.update(rec)
121
+ return doc
122
+ try:
123
+ _update(rt, up)
124
+ outcome = "allowed"
125
+ return grant_dto(result)
126
+ finally:
127
+ _audit(rt, actor=actor, tenant=result.get("tenant", ""), capability="grant.revoke",
128
+ action="revoke", outcome=outcome, grant_id=str(grant_id))
129
+
130
+
131
+ def authorize(rt: Any, *, token: str, actor: str, tenant: str, capability: str,
132
+ origin: str, audience: str = AUDIENCE, action: str = "read",
133
+ source: str = "browser") -> dict:
134
+ target, cap = str(tenant or "").strip().lower(), str(capability or "")
135
+ outcome, matched = "refused", None
136
+ try:
137
+ bound_origin = _origin(origin)
138
+ now = _now()
139
+ for rec in _document(rt)["grants"].values():
140
+ if isinstance(rec, dict) and secrets.compare_digest(str(rec.get("tokenHash") or ""),
141
+ _hash(token)):
142
+ matched = rec
143
+ break
144
+ if not matched or matched.get("actor") != str(actor or ""):
145
+ raise OperatorRefusal("Operator grant is invalid")
146
+ if matched.get("tenant") != target:
147
+ raise OperatorRefusal("Operator grant does not cover that tenant")
148
+ if matched.get("audience") != audience or audience != AUDIENCE:
149
+ raise OperatorRefusal("Operator grant audience is invalid")
150
+ if matched.get("origin") != bound_origin:
151
+ raise OperatorRefusal("Operator grant origin is invalid")
152
+ if matched.get("revokedAt") or int(matched.get("expiresAt") or 0) <= now:
153
+ raise OperatorRefusal("Operator grant is expired or revoked")
154
+ if cap not in set(matched.get("capabilities") or []):
155
+ raise OperatorRefusal("Operator capability is denied")
156
+ outcome = "allowed"
157
+ return grant_dto(matched)
158
+ finally:
159
+ _audit(rt, actor=actor, tenant=target, capability=cap, action=action,
160
+ outcome=outcome, grant_id=str((matched or {}).get("id") or ""), source=source)
161
+
162
+
163
+ def authorize_mcp(rt: Any, **kwargs) -> dict:
164
+ """Optional adapter seam. MCP gets the identical grant, audience, origin, and audit wall."""
165
+ return authorize(rt, source="mcp", **kwargs)
166
+
167
+
168
+ def setup_dto(rt: Any, tenant: str) -> dict:
169
+ try:
170
+ raw = rt.get(SETUP_KEY) or {}
171
+ except Exception:
172
+ raw = {}
173
+ row = raw if isinstance(raw, dict) else {}
174
+ safe = {key: copy.deepcopy(row.get(key)) for key in SETUP_FIELDS if key in row}
175
+ return {"tenant": str(tenant or ""), "setup": safe, "secretsPresent": False,
176
+ "rawProviderBindings": False}
177
+
178
+
179
+ def update_setup(rt: Any, tenant: str, raw: Any, actor: str) -> dict:
180
+ body = raw if isinstance(raw, dict) else {}
181
+ unknown = sorted(set(body) - SETUP_FIELDS)
182
+ if unknown:
183
+ raise OperatorRefusal("unsupported setup properties: " + ", ".join(unknown))
184
+ clean = {}
185
+ for key, value in body.items():
186
+ if key == "queryEnabled":
187
+ if not isinstance(value, bool):
188
+ raise OperatorRefusal("queryEnabled must be true or false")
189
+ clean[key] = value
190
+ else:
191
+ clean[key] = " ".join(str(value or "").split())[:240]
192
+ clean.update({"updatedBy": str(actor or "")[:120], "updatedAt": _now()})
193
+ rt.update(SETUP_KEY, lambda old: {**dict(old or {}), **clean}, flush="sync")
194
+ return setup_dto(rt, tenant)
195
+
196
+
197
+ def audit_rows(rt: Any, limit: int = 200) -> list[dict]:
198
+ rows = _document(rt)["audit"][-max(1, min(int(limit or 200), 500)):]
199
+ return [copy.deepcopy(row) for row in reversed(rows)]
200
+
201
+
202
+ def audit_attempt(rt: Any, *, actor: str, tenant: str, capability: str, action: str,
203
+ outcome: str, grant_id: str = "", source: str = "browser") -> dict:
204
+ """Public final-operation audit seam; authorization is not operation success."""
205
+ return _audit(rt, actor=actor, tenant=tenant, capability=capability, action=action,
206
+ outcome=outcome, grant_id=grant_id, source=source)
api/routes_admin.py CHANGED
@@ -46,6 +46,22 @@ router = APIRouter(prefix="/api/v1")
46
  #: (`data[username]`), so it is constrained rather than trusted: lowercase, no separators, no
47
  #: whitespace, nothing that could traverse or collide once it becomes part of a path or a filename.
48
  _UNAME_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{1,31}$")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  #: ⭐⭐ WAVE 37 · T03 (owner ruling R8) — AN EMAIL ADDRESS IS ALSO A USERNAME. Owner: the username
50
  #: IS the email, one identity. ⛔ THIS IS NOT A NEW CAPABILITY, IT IS THE DOOR CATCHING UP WITH THE
51
  #: DATA: measured on deployed staging before the change, FIVE of tenant #0's eight accounts already
@@ -818,6 +834,11 @@ def _module_fields(key, session=None):
818
  f"{key!r} has no permission-editor field schema. The editor governs "
819
  f"{sorted(providers)} and this tenant's own databases")
820
  src = list(provider())
 
 
 
 
 
821
  import core.perm_scope as perm_scope
822
  # ⭐⭐ W40-T05 / OWNER I16 — THE USER-GENERATED COLUMNS JOIN THE TOPIC'S VOCABULARY.
823
  # *"Permission Filters must be able to filter on user-generated Fields too."* The two topic
 
46
  #: (`data[username]`), so it is constrained rather than trusted: lowercase, no separators, no
47
  #: whitespace, nothing that could traverse or collide once it becomes part of a path or a filename.
48
  _UNAME_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{1,31}$")
49
+
50
+
51
+ @router.get("/admin/system-data")
52
+ def system_data_inspector(session: Session = Depends(require_session)):
53
+ """Definition-only Loopable system data, visible to platform admins and never mutable."""
54
+ if not platform_admin.is_platform_admin(session.user):
55
+ raise err(403, "platform_admin_only",
56
+ "System data is available only to a Loopable platform administrator")
57
+ from core import route_system, user_tables
58
+ definitions = user_tables.all_defs(st=session.runtime)
59
+ rows = []
60
+ for descriptor in route_system.system_table_descriptors():
61
+ stored = definitions.get(descriptor["key"]) or {}
62
+ rows.append({**descriptor, "fields": [dict(field) for field in stored.get("fields") or ()],
63
+ "readOnly": True})
64
+ return {"databases": rows, "readOnly": True, "source": "Loopable"}
65
  #: ⭐⭐ WAVE 37 · T03 (owner ruling R8) — AN EMAIL ADDRESS IS ALSO A USERNAME. Owner: the username
66
  #: IS the email, one identity. ⛔ THIS IS NOT A NEW CAPABILITY, IT IS THE DOOR CATCHING UP WITH THE
67
  #: DATA: measured on deployed staging before the change, FIVE of tenant #0's eight accounts already
 
834
  f"{key!r} has no permission-editor field schema. The editor governs "
835
  f"{sorted(providers)} and this tenant's own databases")
836
  src = list(provider())
837
+ if key == "product_data" and session is not None:
838
+ from core import user_tables
839
+ raw = user_tables.enabled_odoo_schema_fields(session.runtime, model="product.product")
840
+ raw_have = {f.get("key") for f in src if isinstance(f, dict)}
841
+ src.extend(f for f in raw if f.get("key") not in raw_have)
842
  import core.perm_scope as perm_scope
843
  # ⭐⭐ W40-T05 / OWNER I16 — THE USER-GENERATED COLUMNS JOIN THE TOPIC'S VOCABULARY.
844
  # *"Permission Filters must be able to filter on user-generated Fields too."* The two topic
api/routes_alerts.py CHANGED
@@ -84,6 +84,11 @@ AUTOMATION_TOPIC = "automation"
84
  _UT_TOPIC = re.compile(r"ut_[A-Za-z0-9_]+\Z")
85
 
86
 
 
 
 
 
 
87
  def route_for_topic(topic):
88
  """A grid SCOPE key -> the registry route that renders it, or None.
89
 
@@ -417,7 +422,8 @@ def _evaluate(session: Session, rec: dict, assemblies=None):
417
  measure_sets=g.get("measure_sets") or {},
418
  today=g.get("today"))
419
  pids = filter_eval.visible_pids(config.get("filters") or [], rows, g["fields"], ctx,
420
- member_pids=config.get("memberPids"))
 
421
  labels = {str(r.get("pid")): str(r.get("name") or r.get("pid")) for r in rows}
422
  return alerts.evaluate(rec.get("id"), [str(p) for p in pids],
423
  labels=labels, partial=False, st=session.runtime)
@@ -629,7 +635,15 @@ def notifications(session: Session = Depends(require_session)):
629
  continue # one bad alert must not empty the pane
630
  # ⭐ W32-T20 (C3): every item leaves through `inbox_view`, so a notification queued before
631
  # this wave carries a `target` too. See `notification_view`'s header for why it is derived.
632
- return inbox_view(alerts.inbox(session.uname, st=session.runtime))
 
 
 
 
 
 
 
 
633
 
634
 
635
  @router.post("/notifications/read")
@@ -642,8 +656,17 @@ def read_notifications(body: dict = Body(default=None),
642
  # ⚠ THE SAME ENRICHMENT ON BOTH DOORS. `mark_read` returns a fresh inbox, and the Inbox
643
  # module re-renders from it — an un-enriched answer here would strip `target` off every row
644
  # the moment somebody marked one read, i.e. the feature would work until first use.
645
- return inbox_view(alerts.mark_read(session.uname, ids, read=bool(body.get("read", True)),
646
- st=session.runtime))
 
 
 
 
 
 
 
 
 
647
 
648
 
649
  def after_write(session: Session, topic_key: str):
 
84
  _UT_TOPIC = re.compile(r"ut_[A-Za-z0-9_]+\Z")
85
 
86
 
87
+ def _tenant_today(session):
88
+ from core import route_system
89
+ return route_system.tenant_day_for_runtime(session.runtime)
90
+
91
+
92
  def route_for_topic(topic):
93
  """A grid SCOPE key -> the registry route that renders it, or None.
94
 
 
422
  measure_sets=g.get("measure_sets") or {},
423
  today=g.get("today"))
424
  pids = filter_eval.visible_pids(config.get("filters") or [], rows, g["fields"], ctx,
425
+ member_pids=config.get("memberPids"),
426
+ group_by=config.get("groupBy"))
427
  labels = {str(r.get("pid")): str(r.get("name") or r.get("pid")) for r in rows}
428
  return alerts.evaluate(rec.get("id"), [str(p) for p in pids],
429
  labels=labels, partial=False, st=session.runtime)
 
635
  continue # one bad alert must not empty the pane
636
  # ⭐ W32-T20 (C3): every item leaves through `inbox_view`, so a notification queued before
637
  # this wave carries a `target` too. See `notification_view`'s header for why it is derived.
638
+ box = inbox_view(alerts.inbox(session.uname, st=session.runtime))
639
+ from core import route_system
640
+ route_tasks = route_system.inbox_tasks(
641
+ session.runtime, session.uname, today=_tenant_today(session))
642
+ items = list(box.get("items") or []) + route_tasks
643
+ items.sort(key=lambda item: str(item.get("at") or ""), reverse=True)
644
+ box["items"] = items
645
+ box["unread"] = sum(1 for item in items if not item.get("read"))
646
+ return box
647
 
648
 
649
  @router.post("/notifications/read")
 
656
  # ⚠ THE SAME ENRICHMENT ON BOTH DOORS. `mark_read` returns a fresh inbox, and the Inbox
657
  # module re-renders from it — an un-enriched answer here would strip `target` off every row
658
  # the moment somebody marked one read, i.e. the feature would work until first use.
659
+ read = bool(body.get("read", True))
660
+ box = inbox_view(alerts.mark_read(session.uname, ids, read=read, st=session.runtime))
661
+ from core import route_system
662
+ route_system.reconcile_inbox_tasks(session.runtime, today=_tenant_today(session))
663
+ route_tasks = route_system.mark_inbox_tasks(
664
+ session.runtime, session.uname, ids, read=read)
665
+ items = list(box.get("items") or []) + route_tasks
666
+ items.sort(key=lambda item: str(item.get("at") or ""), reverse=True)
667
+ box["items"] = items
668
+ box["unread"] = sum(1 for item in items if not item.get("read"))
669
+ return box
670
 
671
 
672
  def after_write(session: Session, topic_key: str):
api/routes_assets.py CHANGED
@@ -37,9 +37,158 @@ from fastapi.responses import FileResponse
37
 
38
  from deps import Session, err, module_gate, require_session
39
  from routes_admin import admin_gate
 
 
40
 
41
  router = APIRouter(prefix="/api/v1")
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  #: Same grant as the product surface these images decorate (routes_products.MODULE, restated
44
  #: here to avoid importing that module for one string).
45
  MODULE = "product_data"
@@ -110,7 +259,7 @@ def _web_derivative(src, code):
110
  from PIL import Image
111
  except ImportError:
112
  raise err(503, "pillow_missing",
113
- "image derivatives need Pillow — `pip install pillow` on this host")
114
  with Image.open(src) as im:
115
  im.load()
116
  if im.mode not in ("RGBA", "RGB", "LA", "L"):
@@ -268,7 +417,7 @@ def editorial_upload(body: dict = Body(default=None),
268
  from PIL import Image
269
  except ImportError:
270
  raise err(503, "pillow_missing",
271
- "image validation needs Pillow — `pip install pillow` on this host")
272
  try:
273
  with Image.open(io.BytesIO(blob)) as im:
274
  im.load()
@@ -293,7 +442,7 @@ def editorial_upload(body: dict = Body(default=None),
293
  _assets().put_editorial(slug, blob, ext, buf.getvalue())
294
  except Exception:
295
  raise err(503, "asset_repo_unavailable",
296
- "the asset repo did not accept the upload — try again")
297
  return {"slug": slug, "source": "repo"}
298
 
299
 
@@ -368,7 +517,7 @@ def record_upload(body: dict = Body(default=None),
368
  from PIL import Image
369
  except ImportError:
370
  raise err(503, "pillow_missing",
371
- "image validation needs Pillow — `pip install pillow` on this host")
372
  try:
373
  with Image.open(io.BytesIO(blob)) as im:
374
  im.load()
@@ -396,7 +545,7 @@ def record_upload(body: dict = Body(default=None),
396
  _assets().put_record(tenant, asset_id, blob, ext, buf.getvalue())
397
  except Exception:
398
  raise err(503, "asset_repo_unavailable",
399
- "the asset repo did not accept the upload — try again")
400
  return {"ref": f"rec:{asset_id}", "source": "repo"}
401
 
402
 
 
37
 
38
  from deps import Session, err, module_gate, require_session
39
  from routes_admin import admin_gate
40
+ import application_registry as applications
41
+ import semantic_registry as semantic_rt
42
 
43
  router = APIRouter(prefix="/api/v1")
44
 
45
+
46
+ def _application_error(exc):
47
+ if isinstance(exc, PermissionError):
48
+ raise err(403, "forbidden", str(exc))
49
+ message = str(exc)
50
+ status = 404 if "does not exist" in message else 400
51
+ raise err(status, "application_not_found" if status == 404 else "bad_application", message)
52
+
53
+
54
+ def application_access_context(session, databases, *, strict=False):
55
+ """Return readable databases plus governed semantic records, without exposing refused names."""
56
+ from core import perm_scope
57
+ from harness import semantic as sem
58
+ allowed, records = set(), {}
59
+ for database in dict.fromkeys(str(value or "").strip() for value in databases or ()):
60
+ if not database:
61
+ continue
62
+ topic = next((row for row in sem.topics().values()
63
+ if isinstance(row, dict) and row.get("grid") == database), None)
64
+ readable = bool(topic and perm_scope.may_read(
65
+ session.user, database, st=session.runtime))
66
+ if not readable:
67
+ if strict:
68
+ raise PermissionError("that database is not available")
69
+ continue
70
+ allowed.add(database)
71
+ baseline = semantic_rt.topic_records(database, topic)
72
+ records[database] = semantic_rt.load(session.runtime, baseline)
73
+ return allowed, records
74
+
75
+
76
+ def _application_databases(runtime, application_id=None):
77
+ doc = applications.load(runtime)
78
+ if application_id:
79
+ app = doc["applications"].get(application_id)
80
+ return list(app.get("compatibleDatabases") or ()) if isinstance(app, dict) else []
81
+ return list(dict.fromkeys(
82
+ database for app in doc["applications"].values() if isinstance(app, dict)
83
+ for database in (app.get("compatibleDatabases") or ())))
84
+
85
+
86
+ @router.get("/applications")
87
+ def application_index(database: str = "", type: str = "", starred: bool | None = None,
88
+ session: Session = Depends(require_session)):
89
+ if type and type not in applications.APPLICATION_TYPES:
90
+ raise err(400, "bad_application", "application type is not recognized")
91
+ candidates = [database] if database else _application_databases(session.runtime)
92
+ try:
93
+ allowed, _ = application_access_context(session, candidates, strict=bool(database))
94
+ except PermissionError as exc:
95
+ _application_error(exc)
96
+ return {"applications": applications.list_apps(
97
+ session.runtime, session.uname, session.admin, database=database or None,
98
+ kind=type or None, starred=starred, allowed_databases=allowed)}
99
+
100
+
101
+ @router.post("/applications", status_code=201)
102
+ def create_application(body: dict = Body(default=None),
103
+ session: Session = Depends(require_session)):
104
+ if not session.runtime.available():
105
+ raise err(503, "store_unavailable", "the tenant store is unavailable. Nothing was saved.")
106
+ try:
107
+ compatible = (body or {}).get("compatibleDatabases")
108
+ allowed, records = application_access_context(session, compatible, strict=True)
109
+ return {"application": applications.create(
110
+ session.runtime, session.tenant, session.uname, body,
111
+ semantic_records=records, allowed_databases=allowed)}
112
+ except (applications.ApplicationError, PermissionError) as exc:
113
+ _application_error(exc)
114
+
115
+
116
+ @router.patch("/applications/{application_id}")
117
+ def update_application(application_id: str, body: dict = Body(default=None),
118
+ session: Session = Depends(require_session)):
119
+ try:
120
+ current = _application_databases(session.runtime, application_id)
121
+ if not current:
122
+ raise applications.ApplicationError("application does not exist")
123
+ allowed, _ = application_access_context(session, current)
124
+ if not allowed:
125
+ raise applications.ApplicationError("application does not exist")
126
+ proposed = ((body or {}).get("compatibleDatabases")
127
+ if "compatibleDatabases" in (body or {}) else current)
128
+ proposed_allowed, records = application_access_context(session, proposed, strict=True)
129
+ allowed |= proposed_allowed
130
+ return {"application": applications.mutate(
131
+ session.runtime, application_id, session.uname, session.admin, body,
132
+ semantic_records=records, allowed_databases=allowed,
133
+ target_database=next((database for database in proposed
134
+ if database in proposed_allowed), None))}
135
+ except (applications.ApplicationError, PermissionError) as exc:
136
+ _application_error(exc)
137
+
138
+
139
+ @router.post("/applications/{application_id}/duplicate", status_code=201)
140
+ def duplicate_application(application_id: str,
141
+ session: Session = Depends(require_session)):
142
+ try:
143
+ current = _application_databases(session.runtime, application_id)
144
+ if not current:
145
+ raise applications.ApplicationError("application does not exist")
146
+ allowed, records = application_access_context(session, current, strict=True)
147
+ return {"application": applications.duplicate(
148
+ session.runtime, application_id, session.tenant, session.uname, session.admin,
149
+ semantic_records=records, allowed_databases=allowed)}
150
+ except (applications.ApplicationError, PermissionError) as exc:
151
+ _application_error(exc)
152
+
153
+
154
+ @router.delete("/applications/{application_id}")
155
+ def delete_application(application_id: str,
156
+ session: Session = Depends(require_session)):
157
+ try:
158
+ current = _application_databases(session.runtime, application_id)
159
+ allowed, _ = application_access_context(session, current)
160
+ if not allowed:
161
+ raise applications.ApplicationError("application does not exist")
162
+ return applications.delete(session.runtime, application_id, session.uname, session.admin,
163
+ allowed_databases=allowed)
164
+ except (applications.ApplicationError, PermissionError) as exc:
165
+ _application_error(exc)
166
+
167
+
168
+ @router.put("/applications/defaults/{database}/{type}")
169
+ def set_application_default(database: str, type: str, body: dict = Body(default=None),
170
+ session: Session = Depends(require_session)):
171
+ try:
172
+ allowed, _ = application_access_context(session, [database], strict=True)
173
+ return applications.set_default(session.runtime, database, type,
174
+ str((body or {}).get("applicationId") or ""),
175
+ session.uname, session.admin,
176
+ allowed_databases=allowed)
177
+ except (applications.ApplicationError, PermissionError) as exc:
178
+ _application_error(exc)
179
+
180
+
181
+ @router.get("/applications/defaults/{database}/{type}")
182
+ def resolve_application_default(database: str, type: str,
183
+ session: Session = Depends(require_session)):
184
+ try:
185
+ allowed, _ = application_access_context(session, [database], strict=True)
186
+ return applications.resolve_default(session.runtime, database, type,
187
+ session.uname, session.admin,
188
+ allowed_databases=allowed)
189
+ except (applications.ApplicationError, PermissionError) as exc:
190
+ _application_error(exc)
191
+
192
  #: Same grant as the product surface these images decorate (routes_products.MODULE, restated
193
  #: here to avoid importing that module for one string).
194
  MODULE = "product_data"
 
259
  from PIL import Image
260
  except ImportError:
261
  raise err(503, "pillow_missing",
262
+ "image derivatives need Pillow. Install it with `pip install pillow` on this host")
263
  with Image.open(src) as im:
264
  im.load()
265
  if im.mode not in ("RGBA", "RGB", "LA", "L"):
 
417
  from PIL import Image
418
  except ImportError:
419
  raise err(503, "pillow_missing",
420
+ "image validation needs Pillow. Install it with `pip install pillow` on this host")
421
  try:
422
  with Image.open(io.BytesIO(blob)) as im:
423
  im.load()
 
442
  _assets().put_editorial(slug, blob, ext, buf.getvalue())
443
  except Exception:
444
  raise err(503, "asset_repo_unavailable",
445
+ "the asset repo did not accept the upload. Try again")
446
  return {"slug": slug, "source": "repo"}
447
 
448
 
 
517
  from PIL import Image
518
  except ImportError:
519
  raise err(503, "pillow_missing",
520
+ "image validation needs Pillow. Install it with `pip install pillow` on this host")
521
  try:
522
  with Image.open(io.BytesIO(blob)) as im:
523
  im.load()
 
545
  _assets().put_record(tenant, asset_id, blob, ext, buf.getvalue())
546
  except Exception:
547
  raise err(503, "asset_repo_unavailable",
548
+ "the asset repo did not accept the upload. Try again")
549
  return {"ref": f"rec:{asset_id}", "source": "repo"}
550
 
551
 
api/routes_automation.py CHANGED
@@ -12,6 +12,8 @@ one finite worker immediately. No shared tick secret or polling clock remains.
12
  import os
13
  import re
14
  import time
 
 
15
  from datetime import datetime, timezone
16
 
17
  from fastapi import APIRouter, Body, Depends, Header, Request
@@ -20,6 +22,7 @@ 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,6 +57,34 @@ MODULE = "automation"
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):
@@ -194,7 +225,7 @@ def voice_agent_options(session: Session = Depends(_GATE)):
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}
@@ -234,6 +265,116 @@ def voice_dry_run(voice_id: str, body: dict = Body(default=None), session: Sessi
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:
@@ -254,6 +395,7 @@ def _wire(defn, tenant, rt=None):
254
  if live:
255
  status = {**status, "state": "running", "startedAt": live.get("startedAt"),
256
  "step": live.get("step")}
 
257
  return {
258
  "id": defn.get("id"), "name": defn.get("name"), "kind": defn.get("kind"),
259
  "config": defn.get("config") or {}, "schedule": sched, "status": status,
@@ -342,6 +484,18 @@ def _wire(defn, tenant, rt=None):
342
  # an absent prop the client silently reads as undefined
343
  # [[flag-shipped-without-its-writer]].
344
  "agentActions": (_agent_marks(rt).get(str(defn.get("id") or "")) or {}) if rt else {},
 
 
 
 
 
 
 
 
 
 
 
 
345
  }
346
 
347
 
@@ -1837,6 +1991,8 @@ def create_automation(body: dict = Body(default=None), session: Session = Depend
1837
  notes=_notes)
1838
  if error:
1839
  raise err(400, "invalid_automation", error)
 
 
1840
  _sync_schedule_or_503(session.tenant, defn)
1841
  return {"automation": _wire(defn, session.tenant, rt=session.runtime), "notes": _notes}
1842
 
@@ -1883,6 +2039,8 @@ def patch_automation(auto_id: str, body: dict = Body(default=None),
1883
  raise err(400 if error != "no such automation" else 404,
1884
  "invalid_automation" if error != "no such automation" else "unknown_automation",
1885
  error)
 
 
1886
  # An action the user removed takes its annotation with it, or the mark outlives its subject
1887
  # and refuses an id nobody can see.
1888
  _prune_marks(session, auto_id)
@@ -1890,6 +2048,142 @@ def patch_automation(auto_id: str, body: dict = Body(default=None),
1890
  return {"automation": _wire(defn, session.tenant, rt=session.runtime), "notes": _notes}
1891
 
1892
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1893
  @router.delete("/automations/{auto_id}")
1894
  def delete_automation(auto_id: str, session: Session = Depends(_GATE)):
1895
  """Delete the DEFINITION. ⚠ The database it filled is NOT touched — an automation is the
 
12
  import os
13
  import re
14
  import time
15
+ import hashlib
16
+ import json
17
  from datetime import datetime, timezone
18
 
19
  from fastapi import APIRouter, Body, Depends, Header, Request
 
22
  import automation_control
23
  import automation_engine as engine
24
  import voice_control_plane as voice
25
+ import voice_provider_adapters as voice_adapters
26
  import oauth_connect
27
  import routes_oauth
28
  import scope_cache
 
57
  _GATE = module_gate(MODULE)
58
 
59
 
60
+ def _governed_query_tool(session, database=""):
61
+ """Adapt C4 dry-runs to B's mounted C2 Query door without owning Query authority."""
62
+ def invoke(prompt, context):
63
+ query_route = getattr(__import__("routes_query"), "governed_query", None)
64
+ if not callable(query_route):
65
+ raise ValueError("governed Query seam is unavailable until its mounted route is present")
66
+ context = context if isinstance(context, dict) else {}
67
+ result = query_route({
68
+ "database": str(context.get("database") or database or ""),
69
+ "prompt": str(prompt or ""),
70
+ }, session)
71
+ if not isinstance(result, dict):
72
+ raise ValueError("governed Query returned no typed result")
73
+ # C's no-dispatch dry-run intentionally sends no selected fields or resume token. B's
74
+ # governed door must therefore stop at its authenticated clarification boundary, before
75
+ # its planner/provider path. Any other result fails closed instead of becoming a fallback.
76
+ if result.get("status") != "clarification":
77
+ raise ValueError("governed Query dry-run did not stop before provider execution")
78
+ alignment = result.get("alignmentQuestion")
79
+ question = str((alignment or {}).get("question") or "") if isinstance(alignment, dict) else ""
80
+ if not question:
81
+ raise ValueError("governed Query clarification is incomplete")
82
+ return {"state": "clarification", "question": question,
83
+ "providerCalls": 0, "noExternalDispatch": True}
84
+
85
+ return invoke
86
+
87
+
88
  def _voice_view_revision(view):
89
  """One stable revision string for a server-owned saved View choice."""
90
  if not isinstance(view, dict):
 
225
  @router.post("/voice-agents")
226
  def create_voice_agent(body: dict = Body(default=None), session: Session = Depends(_GATE)):
227
  try:
228
+ saved = voice.save_draft(session.runtime, body or {}, session.uname, tenant_id=session.tenant)
229
  row = voice.get_browser_dto(session.runtime, saved["id"])
230
  row["audienceOptions"] = _voice_options(session)
231
  return {"voiceAgent": row}
 
265
  raise err(400 if "unknown" not in str(exc) else 404, "voice_refused", str(exc))
266
 
267
 
268
+ @router.post("/voice-agents/{voice_id}/whatsapp/telnyx/dry-run")
269
+ def telnyx_whatsapp_dry_run(voice_id: str, request: Request, body: dict = Body(default=None),
270
+ session: Session = Depends(_GATE)):
271
+ """Recorded-fixture proof only. No public webhook or provider transport is mounted."""
272
+ body = body or {}
273
+ payload = body.get("payload")
274
+ headers = body.get("headers") if isinstance(body.get("headers"), dict) else {}
275
+ verifier = getattr(request.app.state, "telnyx_verify_signature", None)
276
+ def query_tool(prompt, context):
277
+ # The provider adapter invokes this only after signature/timestamp verification.
278
+ ready = ((engine.agent_contract_dto(session.runtime, voice_id) or {})
279
+ .get("semanticState", {}).get("retrievable") or [])
280
+ return _governed_query_tool(
281
+ session, (ready[0] if ready else {}).get("database"))(prompt, context)
282
+ if not callable(verifier):
283
+ raise err(503, "voice_seam_unavailable", "verified Telnyx signature seam is unavailable")
284
+ try:
285
+ return voice.whatsapp_query_dry_run(
286
+ session.runtime, voice_id, payload,
287
+ headers, verifier, query_tool)
288
+ except (ValueError, voice.VoiceRefusal, voice_adapters.ProviderAdapterRefusal) as exc:
289
+ raise err(400, "whatsapp_fixture_refused", str(exc))
290
+
291
+
292
+ @router.post("/voice-agents/{voice_id}/whatsapp/telnyx/receipt")
293
+ async def telnyx_whatsapp_receipt(voice_id: str, request: Request,
294
+ ):
295
+ """Production receipt door: exact raw body/header verification before JSON parsing."""
296
+ raw = await request.body()
297
+ signature = request.headers.get("telnyx-signature-ed25519", "")
298
+ timestamp = request.headers.get("telnyx-timestamp", "")
299
+ try:
300
+ if not voice.verify_telnyx_raw_request(raw, signature, timestamp):
301
+ raise voice.VoiceRefusal("Telnyx webhook signature verification failed")
302
+ payload = json.loads(raw.decode("utf-8"))
303
+ from harness import runtime as _rt
304
+ matches = []
305
+ for slug in _rt.known_tenants():
306
+ try:
307
+ rt = _rt.get_runtime(slug)
308
+ row = (voice._store(rt).get("voice_agent") or {}).get(str(voice_id))
309
+ if isinstance(row, dict) and str(row.get("tenant_id") or slug) == str(slug):
310
+ matches.append((slug, rt, row))
311
+ except Exception:
312
+ continue
313
+ if len(matches) != 1:
314
+ raise voice.VoiceRefusal("Voice Agent receipt binding is absent or ambiguous")
315
+ slug, rt, agent_row = matches[0]
316
+ owner = str(agent_row.get("created_by") or "")
317
+ service = _voice_owner_session(slug, rt, owner)
318
+ engine.authorize_agent_principal(rt, voice_id, service.uname, service.admin)
319
+ contract = engine.agent_contract_dto(rt, voice_id) or {}
320
+ workflow = next(iter(contract.get("workflows") or []), {})
321
+ ready = (contract.get("semanticState") or {}).get("retrievable") or []
322
+ if not workflow or not ready:
323
+ raise voice.VoiceRefusal("Voice Agent has no approved governed Query field")
324
+ database, field = ready[0].get("database"), ready[0].get("field")
325
+ walls = _allowed_agent_databases(service)
326
+ if str(field) not in walls.get(str(database), set()):
327
+ raise voice.VoiceRefusal("Voice Agent field is outside the current owner wall")
328
+ return voice.whatsapp_query_dry_run(
329
+ rt, voice_id, payload,
330
+ {"telnyx-signature-ed25519": signature, "telnyx-timestamp": timestamp},
331
+ lambda *_: True,
332
+ lambda prompt, context: engine.governed_agent_query_dry_run(
333
+ rt, voice_id, workflow.get("id"), database, field, prompt,
334
+ _governed_query_tool(service),
335
+ actor_databases=walls.keys(), actor_fields=walls.get(str(database), set()))["query"],
336
+ verification="received_raw_callback")
337
+ except (ValueError, PermissionError, voice.VoiceRefusal, voice_adapters.ProviderAdapterRefusal) as exc:
338
+ raise err(400, "whatsapp_receipt_refused", str(exc))
339
+
340
+
341
+ @router.post("/voice-agents/{voice_id}/feedback/consent")
342
+ def feedback_consent(voice_id: str, body: dict = Body(default=None),
343
+ session: Session = Depends(_GATE)):
344
+ body = body or {}
345
+ try:
346
+ return {"consent": voice.set_feedback_consent(
347
+ session.runtime, voice_id, body.get("contactRef"), body.get("state"), body.get("purpose"))}
348
+ except voice.VoiceRefusal as exc:
349
+ raise err(400, "feedback_refused", str(exc))
350
+
351
+
352
+ @router.post("/voice-agents/{voice_id}/feedback/schedules")
353
+ def create_feedback_schedule(voice_id: str, body: dict = Body(default=None),
354
+ session: Session = Depends(_GATE)):
355
+ body = body or {}
356
+ try:
357
+ row = voice.create_feedback_schedule(
358
+ session.runtime, voice_id, body.get("contactRefs"), body.get("localTime") or "09:00",
359
+ body.get("timezone") or "UTC")
360
+ return {"schedule": voice.feedback_schedule_dto(session.runtime, row["id"]),
361
+ "adapter": voice.future_integration_adapter_contract()}
362
+ except voice.VoiceRefusal as exc:
363
+ raise err(400, "feedback_refused", str(exc))
364
+
365
+
366
+ @router.post("/voice-agents/{voice_id}/feedback/schedules/{schedule_id}/dry-run")
367
+ def feedback_schedule_dry_run(voice_id: str, schedule_id: str,
368
+ body: dict = Body(default=None),
369
+ session: Session = Depends(_GATE)):
370
+ body = body or {}
371
+ try:
372
+ return voice.feedback_dry_run(
373
+ session.runtime, voice_id, schedule_id, body.get("day"))
374
+ except voice.VoiceRefusal as exc:
375
+ raise err(400, "feedback_refused", str(exc))
376
+
377
+
378
  def _sync_schedule_or_503(tenant, defn):
379
  """Apply the exact native schedules after a definition write, never silently drift."""
380
  try:
 
395
  if live:
396
  status = {**status, "state": "running", "startedAt": live.get("startedAt"),
397
  "step": live.get("step")}
398
+ agent_contract = engine.agent_contract_dto(rt, defn.get("id")) if rt else None
399
  return {
400
  "id": defn.get("id"), "name": defn.get("name"), "kind": defn.get("kind"),
401
  "config": defn.get("config") or {}, "schedule": sched, "status": status,
 
484
  # an absent prop the client silently reads as undefined
485
  # [[flag-shipped-without-its-writer]].
486
  "agentActions": (_agent_marks(rt).get(str(defn.get("id") or "")) or {}) if rt else {},
487
+ **({
488
+ "privateEventStore": agent_contract["eventStore"],
489
+ "workflows": agent_contract["workflows"],
490
+ "sharing": agent_contract["sharing"],
491
+ "capabilities": agent_contract["capabilities"],
492
+ "semanticState": agent_contract["semanticState"],
493
+ "setupInterview": agent_contract["setupInterview"],
494
+ "providerStatus": {"configured": False, "referencesMasked": True},
495
+ } if agent_contract else {
496
+ "agentAvailability": {"state": "disabled", "reason":
497
+ "This system Agent is configured at its source."}
498
+ }),
499
  }
500
 
501
 
 
1991
  notes=_notes)
1992
  if error:
1993
  raise err(400, "invalid_automation", error)
1994
+ engine.ensure_agent_contract(session.runtime, defn.get("id"), session.uname,
1995
+ defn.get("name") or "")
1996
  _sync_schedule_or_503(session.tenant, defn)
1997
  return {"automation": _wire(defn, session.tenant, rt=session.runtime), "notes": _notes}
1998
 
 
2039
  raise err(400 if error != "no such automation" else 404,
2040
  "invalid_automation" if error != "no such automation" else "unknown_automation",
2041
  error)
2042
+ engine.ensure_agent_contract(session.runtime, defn.get("id"), session.uname,
2043
+ defn.get("name") or "")
2044
  # An action the user removed takes its annotation with it, or the mark outlives its subject
2045
  # and refuses an id nobody can see.
2046
  _prune_marks(session, auto_id)
 
2048
  return {"automation": _wire(defn, session.tenant, rt=session.runtime), "notes": _notes}
2049
 
2050
 
2051
+ def _stored_agent_or_404(session, agent_id):
2052
+ defn = engine.all_definitions(session.runtime).get(str(agent_id))
2053
+ if not isinstance(defn, dict):
2054
+ voice_row = (voice._store(session.runtime).get("voice_agent") or {}).get(str(agent_id))
2055
+ if not isinstance(voice_row, dict):
2056
+ raise err(404, "unknown_agent", "there is no stored Agent with that id")
2057
+ defn = {"id": str(agent_id), "createdBy": voice_row.get("created_by") or session.uname,
2058
+ "name": voice_row.get("display_name") or "Voice Agent"}
2059
+ engine.ensure_agent_contract(session.runtime, agent_id, defn.get("createdBy") or session.uname,
2060
+ defn.get("name") or "")
2061
+ contract = engine.agent_contract_dto(session.runtime, agent_id) or {}
2062
+ sharing = contract.get("sharing") or {}
2063
+ permitted = (session.admin or contract.get("agentId") and
2064
+ (defn.get("createdBy") == session.uname or
2065
+ session.uname in set(sharing.get("sharedWith") or [])))
2066
+ if not permitted:
2067
+ raise err(403, "agent_principal_refused", "this Agent is private or not shared with you")
2068
+ return defn
2069
+
2070
+
2071
+ def _allowed_agent_databases(session):
2072
+ allowed = {}
2073
+ for row in automation_tables(session).get("tables") or []:
2074
+ key = str(row.get("key") or "")
2075
+ if key:
2076
+ allowed[key] = {str(field.get("key") or "") for field in row.get("fields") or []
2077
+ if isinstance(field, dict) and field.get("key")}
2078
+ try:
2079
+ session.require("customer_data")
2080
+ from routes_customers import grid_assembly
2081
+ customer = grid_assembly(session, consume_corrections=False)
2082
+ allowed["customer_data"] = {str(field.get("key") or "")
2083
+ for field in customer.get("fields") or []
2084
+ if isinstance(field, dict) and field.get("key")}
2085
+ except Exception: # noqa: BLE001
2086
+ pass
2087
+ return allowed
2088
+
2089
+
2090
+ def _voice_owner_session(tenant, rt, owner):
2091
+ import core.users as user_registry
2092
+ rows = user_registry.registry() or {}
2093
+ raw = rows.get(str(owner or "")) if isinstance(rows, dict) else None
2094
+ if not isinstance(raw, dict) or raw.get("active", True) is False:
2095
+ raise voice.VoiceRefusal("Voice Agent owner is inactive or unavailable")
2096
+ user = user_registry._public(str(owner), raw)
2097
+ if str(user.get("tenant") or "").strip().lower() != str(tenant).strip().lower():
2098
+ raise voice.VoiceRefusal("Voice Agent owner is not in this tenant")
2099
+ return Session(str(tenant), user, {}, rt)
2100
+
2101
+
2102
+ @router.get("/agents/{agent_id}/contract")
2103
+ def get_agent_contract(agent_id: str, session: Session = Depends(_GATE)):
2104
+ _stored_agent_or_404(session, agent_id)
2105
+ return {"agent": engine.agent_contract_dto(session.runtime, agent_id)}
2106
+
2107
+
2108
+ @router.post("/agents/{agent_id}/workflows")
2109
+ def add_agent_workflow(agent_id: str, body: dict = Body(default=None),
2110
+ session: Session = Depends(_GATE)):
2111
+ _stored_agent_or_404(session, agent_id)
2112
+ try:
2113
+ row = engine.create_agent_workflow(session.runtime, agent_id,
2114
+ (body or {}).get("name"),
2115
+ (body or {}).get("purpose"))
2116
+ except ValueError as exc:
2117
+ raise err(400, "workflow_refused", str(exc))
2118
+ return {"workflow": row, "agent": engine.agent_contract_dto(session.runtime, agent_id)}
2119
+
2120
+
2121
+ @router.patch("/agents/{agent_id}/governance")
2122
+ def patch_agent_governance(agent_id: str, body: dict = Body(default=None),
2123
+ session: Session = Depends(_GATE)):
2124
+ _stored_agent_or_404(session, agent_id)
2125
+ try:
2126
+ import core.users as user_registry
2127
+ engine.configure_agent_governance(session.runtime, agent_id, body or {},
2128
+ _allowed_agent_databases(session),
2129
+ [row.get("username") for row in
2130
+ user_registry.assignable_identities(session.tenant)])
2131
+ except PermissionError as exc:
2132
+ raise err(403, "agent_scope_refused", str(exc))
2133
+ except ValueError as exc:
2134
+ raise err(400, "agent_governance_refused", str(exc))
2135
+ return {"agent": engine.agent_contract_dto(session.runtime, agent_id)}
2136
+
2137
+
2138
+ @router.post("/agents/{agent_id}/setup/answer")
2139
+ def answer_agent_setup(agent_id: str, body: dict = Body(default=None),
2140
+ session: Session = Depends(_GATE)):
2141
+ _stored_agent_or_404(session, agent_id)
2142
+ try:
2143
+ interview = engine.answer_setup_interview(
2144
+ session.runtime, agent_id, (body or {}).get("key"),
2145
+ (body or {}).get("answer"), bool((body or {}).get("disable")))
2146
+ except ValueError as exc:
2147
+ raise err(400, "setup_interview_refused", str(exc))
2148
+ return {"setupInterview": interview,
2149
+ "agent": engine.agent_contract_dto(session.runtime, agent_id)}
2150
+
2151
+
2152
+ @router.post("/agents/{agent_id}/governed-query/dry-run")
2153
+ def agent_governed_query_dry_run(agent_id: str, request: Request, body: dict = Body(default=None),
2154
+ session: Session = Depends(_GATE)):
2155
+ """C4's production door: all scope/readiness checks run before the injected C2 Query seam."""
2156
+ _stored_agent_or_404(session, agent_id)
2157
+ body = body or {}
2158
+ walls = _allowed_agent_databases(session)
2159
+ table, field = body.get("table"), body.get("field")
2160
+ query_tool = _governed_query_tool(session)
2161
+ try:
2162
+ return engine.governed_agent_query_dry_run(
2163
+ session.runtime, agent_id, body.get("workflowId"), table,
2164
+ field, body.get("prompt"), query_tool, actor_databases=walls.keys(),
2165
+ actor_fields=walls.get(str(table), set()))
2166
+ except PermissionError as exc:
2167
+ raise err(403, "agent_scope_refused", str(exc))
2168
+ except ValueError as exc:
2169
+ raise err(400, "agent_query_refused", str(exc))
2170
+
2171
+
2172
+ @router.put("/agents/{agent_id}/semantic-readiness")
2173
+ def set_agent_semantic_readiness(agent_id: str, body: dict = Body(default=None),
2174
+ session: Session = Depends(_GATE)):
2175
+ _stored_agent_or_404(session, agent_id)
2176
+ walls = _allowed_agent_databases(session)
2177
+ rows = (body or {}).get("fields")
2178
+ if not isinstance(rows, list) or any(
2179
+ str(row.get("database")) not in walls or
2180
+ str(row.get("field")) not in walls.get(str(row.get("database")), set())
2181
+ for row in rows if isinstance(row, dict)):
2182
+ raise err(403, "agent_scope_refused", "semantic readiness exceeds the acting user's field wall")
2183
+ return {"agent": engine.agent_contract_dto(
2184
+ session.runtime, agent_id) if engine.set_semantic_readiness(session.runtime, agent_id, rows) else None}
2185
+
2186
+
2187
  @router.delete("/automations/{auto_id}")
2188
  def delete_automation(auto_id: str, session: Session = Depends(_GATE)):
2189
  """Delete the DEFINITION. ⚠ The database it filled is NOT touched — an automation is the
api/routes_connectors.py CHANGED
@@ -22,10 +22,10 @@ from __future__ import annotations
22
 
23
  import os
24
 
25
- from fastapi import APIRouter, Depends
26
 
27
  import oauth_connect
28
- from deps import Session, require_session
29
  #: ⛔ W32-T10 — IMPORTED, NEVER RE-DERIVED. "Does the environment serve THIS tenant's Odoo?" is
30
  #: one question, and this module used to answer it with an unguarded `os.environ.get("ODOO_URL")`
31
  #: while `routes_keychain` answered it correctly. Importing the correct one is the fix; writing a
@@ -614,3 +614,87 @@ def connectors_directory(session: Session = Depends(require_session)):
614
  "counts": {"connected": sum(1 for r in rows if r["state"] == "connected"),
615
  "available": sum(1 for r in rows if r["state"] == "available"),
616
  "planned": sum(1 for r in rows if r["state"] == "planned")}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  import os
24
 
25
+ from fastapi import APIRouter, Body, Depends
26
 
27
  import oauth_connect
28
+ from deps import Session, err, require_session
29
  #: ⛔ W32-T10 — IMPORTED, NEVER RE-DERIVED. "Does the environment serve THIS tenant's Odoo?" is
30
  #: one question, and this module used to answer it with an unguarded `os.environ.get("ODOO_URL")`
31
  #: while `routes_keychain` answered it correctly. Importing the correct one is the fix; writing a
 
614
  "counts": {"connected": sum(1 for r in rows if r["state"] == "connected"),
615
  "available": sum(1 for r in rows if r["state"] == "available"),
616
  "planned": sum(1 for r in rows if r["state"] == "planned")}}
617
+
618
+
619
+ _ODOO_SCHEMA_ENABLEMENTS = "odoo_schema_enablements"
620
+ _ODOO_SYNC_STATUS = "odoo_sync_status"
621
+
622
+
623
+ def _odoo_admin(session):
624
+ if not session.admin:
625
+ raise err(403, "not_admin", "only an administrator can inspect the Odoo schema")
626
+
627
+
628
+ def _schema_catalog(session):
629
+ """Rows-free Odoo field catalogue; source fields remain discoverable when every value is empty."""
630
+ import core.user_tables as user_tables
631
+ enabled = session.runtime.get(_ODOO_SCHEMA_ENABLEMENTS) or {}
632
+ snapshot = user_tables.odoo_schema_snapshot(session.runtime)
633
+ raw_models = snapshot.get("models") or {}
634
+ if raw_models:
635
+ rows = []
636
+ for model, raw_fields in raw_models.items():
637
+ for raw_name, meta in (raw_fields or {}).items():
638
+ key = f"{model}.{raw_name}"
639
+ rows.append({"key": key, "model": model, "rawName": raw_name,
640
+ "label": str(meta.get("string") or raw_name),
641
+ "type": str(meta.get("type") or "text"), "source": "Odoo",
642
+ "emptyDiscoverable": True, "defaultEnabled": False,
643
+ "enabled": enabled.get(key) is True})
644
+ return sorted(rows, key=lambda row: row["label"].casefold())
645
+ # Never present compiled mirror declarations as an authoritative fields_get catalogue.
646
+ # Until a sync captures metadata, the schema is unavailable and enablement stays refused.
647
+ return []
648
+
649
+
650
+ @router.get("/connectors/odoo/status")
651
+ def odoo_status(session: Session = Depends(require_session)):
652
+ _odoo_admin(session)
653
+ import odoo_relational
654
+ cfg = odoo_relational.read_config(session.runtime)
655
+ stored = session.runtime.get(_ODOO_SYNC_STATUS) or {}
656
+ errors = stored.get("errors") if isinstance(stored.get("errors"), list) else []
657
+ phase = str(stored.get("phase") or "unknown")
658
+ return {"schedule": cfg.get("syncEvery"),
659
+ "health": "paused" if cfg.get("frozen") else "error" if errors else phase,
660
+ "lastRun": stored.get("lastRun"), "errors": errors[:20],
661
+ "frozen": cfg.get("frozen") is True}
662
+
663
+
664
+ @router.get("/connectors/odoo/schema")
665
+ def odoo_schema(session: Session = Depends(require_session)):
666
+ _odoo_admin(session)
667
+ fields = _schema_catalog(session)
668
+ import core.user_tables as user_tables
669
+ snapshot = user_tables.odoo_schema_snapshot(session.runtime)
670
+ return {"fields": fields, "default": "off", "adminOnly": True,
671
+ "complete": snapshot.get("complete") is True,
672
+ "capturedAt": snapshot.get("capturedAt"),
673
+ "errors": list(snapshot.get("errors") or ()), "source": "Odoo"}
674
+
675
+
676
+ @router.patch("/connectors/odoo/schema/{field_key}")
677
+ def odoo_schema_enable(field_key: str, body: dict = Body(default=None),
678
+ session: Session = Depends(require_session)):
679
+ _odoo_admin(session)
680
+ import core.user_tables as user_tables
681
+ _snapshot = user_tables.odoo_schema_snapshot(session.runtime)
682
+ if _snapshot.get("complete") is not True:
683
+ raise err(409, "odoo_schema_unavailable",
684
+ "run a successful schema sync before changing raw-field enablement")
685
+ known = {field["key"] for field in _schema_catalog(session)}
686
+ key = str(field_key or "").strip()
687
+ if key not in known:
688
+ raise err(404, "unknown_odoo_field", "that field is not in the Odoo schema catalogue")
689
+ enabled = (body or {}).get("enabled")
690
+ if not isinstance(enabled, bool):
691
+ raise err(400, "bad_enabled", "enabled must be true or false")
692
+ session.runtime.update(
693
+ _ODOO_SCHEMA_ENABLEMENTS,
694
+ lambda current: {**(current if isinstance(current, dict) else {}), key: enabled},
695
+ flush="sync")
696
+ for cache_key in list(getattr(session.runtime, "pool_cache", {}) or {}):
697
+ if isinstance(cache_key, tuple) and cache_key[:1] == ("product_pool",):
698
+ session.runtime.pool_cache.pop(cache_key, None)
699
+ return {"key": key, "enabled": enabled, "source": "Odoo",
700
+ "permissionWall": "normal field permissions"}
api/routes_customers.py CHANGED
@@ -21,6 +21,7 @@ SOURCE OF TRUTH; it does not make the two runtimes coherent. The fix is X4/Postg
21
  owner-blocked on B-3), and no test here may claim read-your-writes ACROSS runtimes — a TestClient
22
  proof is single-process and would report green on exactly the thing that is still broken.
23
  """
 
24
  import hashlib
25
  import json
26
  import math
@@ -519,6 +520,7 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
519
  for pid, cells in _ov.items()}
520
 
521
  today = time.strftime("%Y-%m-%d")
 
522
  stamp = _pool_stamp(rt, team_id, agent)
523
  # ⭐⭐ W38-T19 — THE METRICS CAPABILITY, AND THIS GRAIN NEEDS **THREE** GUARDS WHERE THE
524
  # OTHER TWO NEED ONE. `routes_products` and `routes_tables` funnel their cells and their
@@ -857,12 +859,18 @@ def _route_dto(route, allowed, active, session, share_mark=None):
857
  mark = share_mark if isinstance(share_mark, dict) else _route_share_mark(session, route)
858
  owns_route = bool(session.admin or (
859
  mark.get("owner") and mark.get("owner") == str(session.uname or "").strip().lower()))
 
 
860
  dto = {"id": route["id"], "name": route["name"], "color": route["color"],
861
  "number": route["number"], "visibleStopIds": visible,
862
  "outsideFilter": bool(active) and not bool(active.intersection(visible)),
863
- "permission": {"canEdit": (False if compatibility else owns_route and
864
- _route_view_can_edit(session, route.get("sourceViewId"))),
865
  "sourceViewId": route.get("sourceViewId")},
 
 
 
 
 
866
  "source": {"viewId": route.get("sourceViewId"),
867
  "revision": route.get("sourceViewRevision")},
868
  "owner": mark["owner"], "shared": mark["shared"],
@@ -876,16 +884,6 @@ def _route_dto(route, allowed, active, session, share_mark=None):
876
  return dto
877
 
878
 
879
- def _query_pids(raw):
880
- values = []
881
- for value in str(raw or "").split(","):
882
- try:
883
- values.append(int(value))
884
- except (TypeError, ValueError):
885
- continue
886
- return values
887
-
888
-
889
  def _route_or_404(session, route_id):
890
  route = next((item for item, _mark in _visible_normalized_routes(session)
891
  if item.get("id") == str(route_id)), None)
@@ -930,21 +928,114 @@ def _route_nav_mutation_context(session):
930
  return routes, folders, placements
931
 
932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
933
  @router.get("/customers/routes")
934
- def routes(visiblePids: str = "", currentPids: str = "",
935
- session: Session = Depends(module_gate(MODULE))):
936
- """Route picker DTO consumed by C1/C3; only permitted stops ever leave the server."""
 
 
 
 
937
  allowed = allowed_pids(session)
938
- active = _query_pids(currentPids or visiblePids)
939
  records = _route_share_records(session)
940
  navigation = _route_navigation(session, _compatible_routes(session, allowed, records))
941
  return {"routes": [_route_dto(
942
- route, allowed, active, session,
943
  _route_share_mark(session, route, records))
944
  for route in navigation["routes"]],
945
  "folders": navigation["folders"]}
946
 
947
 
 
 
 
 
 
 
 
948
  @router.post("/customers/routes", status_code=201)
949
  def create_route(body: dict = Body(default=None), session: Session = Depends(module_gate(MODULE))):
950
  from core import route_system
@@ -955,6 +1046,7 @@ def create_route(body: dict = Body(default=None), session: Session = Depends(mod
955
  permitted = allowed_pids(session)
956
  if any(pid not in permitted for pid in _route_input_pids(raw)):
957
  raise err(403, "out_of_scope", "a Route stop must be in your customer book")
 
958
  route = route_system.put_route(session.runtime, raw, tenant_id=session.tenant, created_by=session.uname)
959
  if route is None:
960
  raise err(400, "invalid_route", "a Route needs a name and an optional HTTPS Google Maps URL")
@@ -996,6 +1088,7 @@ def update_route(route_id: str, body: dict = Body(default=None),
996
  raw["id"] = prior["id"]
997
  if "stops" in raw and any(pid not in allowed_pids(session) for pid in _route_input_pids(raw)):
998
  raise err(403, "out_of_scope", "a Route stop must be in your customer book")
 
999
  route = route_system.put_route(session.runtime, raw, tenant_id=session.tenant, created_by=session.uname)
1000
  if route is None:
1001
  raise err(400, "invalid_route", "a Route needs a name and an optional HTTPS Google Maps URL")
@@ -1320,6 +1413,9 @@ def create_zone(body: dict = Body(default=None), session: Session = Depends(modu
1320
  from core import route_system
1321
  raw = dict(body or {})
1322
  _reject_client_create_id(raw, "Zone")
 
 
 
1323
  if not _zone_can_edit(session, raw.get("sourceViewId")):
1324
  raise err(403, "zone_view_read_only", "a Zone requires an editable source View")
1325
  zone = route_system.put_zone(session.runtime, raw, rows=_pool_rows(session),
@@ -1338,6 +1434,9 @@ def update_zone(zone_id: str, body: dict = Body(default=None),
1338
  if prior is None:
1339
  raise err(404, "zone_not_found", "that Zone does not exist")
1340
  raw = dict(body or {})
 
 
 
1341
  # A Zone keeps the View it was authored from. Editing its colour or boundary is not a
1342
  # second door for silently rebasing its permission wall onto another View.
1343
  source_view_id = prior.get("sourceViewId") or raw.get("sourceViewId")
@@ -1503,6 +1602,9 @@ def patch_customer(pid: int, body: dict = Body(default=None),
1503
  if not updates:
1504
  raise err(400, "empty_patch", "no fields to update")
1505
  from core import route_system
 
 
 
1506
  retired = {str(key) for key, proof in (route_system.read(session.runtime).get("legacyMigrations") or {}).items()
1507
  if isinstance(proof, dict) and proof.get("verified")}
1508
  if retired.intersection(updates):
@@ -2354,18 +2456,9 @@ def _route_delivery_recipient_or_400(session, raw, directory=None):
2354
  consume it yet. Staging-only identities can extend this one helper without leaking fixture
2355
  logic into Route persistence or falling through to a different account plane.
2356
  """
2357
- recipient = str(raw or "").strip()
2358
- try:
2359
- if directory is None:
2360
- import core.users as users
2361
- directory = users.registry
2362
- user = (directory() or {}).get(recipient)
2363
- except Exception: # registry unavailable is not permission to queue a phantom Inbox delivery
2364
- user = None
2365
- if not recipient or not isinstance(user, dict) or not user.get("active", True):
2366
- raise err(400, "unknown_route_recipient",
2367
- "choose an active account to receive this route in Inbox")
2368
- return recipient
2369
 
2370
 
2371
  def _route_view_revision(view_id, config):
 
21
  owner-blocked on B-3), and no test here may claim read-your-writes ACROSS runtimes — a TestClient
22
  proof is single-process and would report green on exactly the thing that is still broken.
23
  """
24
+ import datetime as _dt
25
  import hashlib
26
  import json
27
  import math
 
520
  for pid, cells in _ov.items()}
521
 
522
  today = time.strftime("%Y-%m-%d")
523
+ fields = aios_grid.project_date_recurrences(fields, today=today)
524
  stamp = _pool_stamp(rt, team_id, agent)
525
  # ⭐⭐ W38-T19 — THE METRICS CAPABILITY, AND THIS GRAIN NEEDS **THREE** GUARDS WHERE THE
526
  # OTHER TWO NEED ONE. `routes_products` and `routes_tables` funnel their cells and their
 
859
  mark = share_mark if isinstance(share_mark, dict) else _route_share_mark(session, route)
860
  owns_route = bool(session.admin or (
861
  mark.get("owner") and mark.get("owner") == str(session.uname or "").strip().lower()))
862
+ source_edit = _route_view_can_edit(session, route.get("sourceViewId"))
863
+ can_edit = bool(not compatibility and owns_route and source_edit)
864
  dto = {"id": route["id"], "name": route["name"], "color": route["color"],
865
  "number": route["number"], "visibleStopIds": visible,
866
  "outsideFilter": bool(active) and not bool(active.intersection(visible)),
867
+ "permission": {"canEdit": can_edit,
 
868
  "sourceViewId": route.get("sourceViewId")},
869
+ "capabilities": route_system.route_capabilities(
870
+ route, can_edit=can_edit, can_duplicate=source_edit,
871
+ can_delete=can_edit),
872
+ "assignee": route.get("assignee"), "date": route.get("date"),
873
+ "starred": route.get("starred") is True,
874
  "source": {"viewId": route.get("sourceViewId"),
875
  "revision": route.get("sourceViewRevision")},
876
  "owner": mark["owner"], "shared": mark["shared"],
 
884
  return dto
885
 
886
 
 
 
 
 
 
 
 
 
 
 
887
  def _route_or_404(session, route_id):
888
  route = next((item for item, _mark in _visible_normalized_routes(session)
889
  if item.get("id") == str(route_id)), None)
 
928
  return routes, folders, placements
929
 
930
 
931
+ def _route_assignee_people(session, directory=None):
932
+ """Return the active same-tenant accounts that may open Customer data.
933
+
934
+ This is deliberately narrower than the account registry: a people picker may not enumerate
935
+ another tenant, inactive users, or coworkers who cannot open the Route's own module.
936
+ ``directory`` is a focused test seam; production always reads the canonical registry.
937
+ """
938
+ from core import perm_scope
939
+ import core.users as users
940
+
941
+ tenant = str(getattr(session, "tenant", None) or "").strip().lower()
942
+ if not tenant:
943
+ return []
944
+ injected = directory is not None
945
+ source = users.registry if directory is None else directory
946
+ try:
947
+ records = source() if callable(source) else source
948
+ except Exception:
949
+ return []
950
+ if not isinstance(records, dict):
951
+ return []
952
+
953
+ people = {}
954
+ for raw_username, record in records.items():
955
+ if not isinstance(record, dict) or record.get("active") is False:
956
+ continue
957
+ username = str(raw_username or "").strip().lower()
958
+ if not username:
959
+ continue
960
+ default_tenant = tenant if injected else "royal-imports"
961
+ account_tenant = str(record.get("tenant") or default_tenant).strip().lower()
962
+ if account_tenant != tenant:
963
+ continue
964
+ try:
965
+ principal = users._public(username, record)
966
+ if not perm_scope.nav_may_open(principal, MODULE, st=session.runtime):
967
+ continue
968
+ except Exception:
969
+ continue
970
+ people.setdefault(username, {
971
+ "username": username,
972
+ "name": str(record.get("name") or username).strip()[:120] or username,
973
+ })
974
+ return sorted(people.values(), key=lambda item: (item["name"].casefold(), item["username"]))
975
+
976
+
977
+ def _route_assignee_or_400(session, raw, *, directory=None,
978
+ code="unknown_route_assignee",
979
+ message="choose a permitted person for this Route"):
980
+ username = str(raw or "").strip().lower()
981
+ people = _route_assignee_people(session, directory=directory)
982
+ if not username or username not in {person["username"] for person in people}:
983
+ # Non-enumerating by design: the refusal does not reveal whether an account is inactive,
984
+ # belongs to another tenant, or merely lacks Customer data access.
985
+ raise err(400, code, message)
986
+ return username
987
+
988
+
989
+ def _route_schedule_patch_or_400(session, raw, *, directory=None):
990
+ """Normalize an all-or-nothing assignee/date pair in-place."""
991
+ has_assignee, has_date = "assignee" in raw, "date" in raw
992
+ if has_assignee != has_date:
993
+ raise err(400, "route_schedule_pair", "assignee and date must be saved together")
994
+ if not has_assignee:
995
+ return raw
996
+ assignee = str(raw.get("assignee") or "").strip()
997
+ route_date = str(raw.get("date") or "").strip()
998
+ if bool(assignee) != bool(route_date):
999
+ raise err(400, "route_schedule_pair", "assignee and date must be saved together")
1000
+ if not assignee:
1001
+ raw["assignee"], raw["date"] = None, None
1002
+ return raw
1003
+ try:
1004
+ canonical_date = _dt.date.fromisoformat(route_date).isoformat()
1005
+ except ValueError:
1006
+ raise err(400, "invalid_route_date", "choose a valid Route date")
1007
+ if canonical_date != route_date:
1008
+ raise err(400, "invalid_route_date", "choose a valid Route date")
1009
+ raw["assignee"] = _route_assignee_or_400(session, assignee, directory=directory)
1010
+ raw["date"] = canonical_date
1011
+ return raw
1012
+
1013
+
1014
  @router.get("/customers/routes")
1015
+ def routes(session: Session = Depends(module_gate(MODULE))):
1016
+ """Constant-request Route catalogue; only permitted Route stops ever leave the server.
1017
+
1018
+ Filter membership is deliberately not encoded as a comma-delimited pid query. A grid with
1019
+ 50,000 visible records sends exactly the same request as an empty grid; a future annotation
1020
+ door may accept a compact saved-View/filter reference without reopening that row-sized wire.
1021
+ """
1022
  allowed = allowed_pids(session)
 
1023
  records = _route_share_records(session)
1024
  navigation = _route_navigation(session, _compatible_routes(session, allowed, records))
1025
  return {"routes": [_route_dto(
1026
+ route, allowed, (), session,
1027
  _route_share_mark(session, route, records))
1028
  for route in navigation["routes"]],
1029
  "folders": navigation["folders"]}
1030
 
1031
 
1032
+ @router.get("/customers/routes/assignees")
1033
+ def route_assignees(session: Session = Depends(module_gate(MODULE))):
1034
+ from core import route_system
1035
+ return {"today": route_system.tenant_day_for_runtime(session.runtime).isoformat(),
1036
+ "people": _route_assignee_people(session)}
1037
+
1038
+
1039
  @router.post("/customers/routes", status_code=201)
1040
  def create_route(body: dict = Body(default=None), session: Session = Depends(module_gate(MODULE))):
1041
  from core import route_system
 
1046
  permitted = allowed_pids(session)
1047
  if any(pid not in permitted for pid in _route_input_pids(raw)):
1048
  raise err(403, "out_of_scope", "a Route stop must be in your customer book")
1049
+ _route_schedule_patch_or_400(session, raw)
1050
  route = route_system.put_route(session.runtime, raw, tenant_id=session.tenant, created_by=session.uname)
1051
  if route is None:
1052
  raise err(400, "invalid_route", "a Route needs a name and an optional HTTPS Google Maps URL")
 
1088
  raw["id"] = prior["id"]
1089
  if "stops" in raw and any(pid not in allowed_pids(session) for pid in _route_input_pids(raw)):
1090
  raise err(403, "out_of_scope", "a Route stop must be in your customer book")
1091
+ _route_schedule_patch_or_400(session, raw)
1092
  route = route_system.put_route(session.runtime, raw, tenant_id=session.tenant, created_by=session.uname)
1093
  if route is None:
1094
  raise err(400, "invalid_route", "a Route needs a name and an optional HTTPS Google Maps URL")
 
1413
  from core import route_system
1414
  raw = dict(body or {})
1415
  _reject_client_create_id(raw, "Zone")
1416
+ if "memberships" in raw or "memberPids" in raw:
1417
+ raise err(400, "zone_membership_read_only",
1418
+ "Zone membership is worked out from current record coordinates")
1419
  if not _zone_can_edit(session, raw.get("sourceViewId")):
1420
  raise err(403, "zone_view_read_only", "a Zone requires an editable source View")
1421
  zone = route_system.put_zone(session.runtime, raw, rows=_pool_rows(session),
 
1434
  if prior is None:
1435
  raise err(404, "zone_not_found", "that Zone does not exist")
1436
  raw = dict(body or {})
1437
+ if "memberships" in raw or "memberPids" in raw:
1438
+ raise err(400, "zone_membership_read_only",
1439
+ "Zone membership is worked out from current record coordinates")
1440
  # A Zone keeps the View it was authored from. Editing its colour or boundary is not a
1441
  # second door for silently rebasing its permission wall onto another View.
1442
  source_view_id = prior.get("sourceViewId") or raw.get("sourceViewId")
 
1602
  if not updates:
1603
  raise err(400, "empty_patch", "no fields to update")
1604
  from core import route_system
1605
+ if route_system.ZONE_FIELD_KEY in updates or "zone" in updates:
1606
+ raise err(403, "zone_membership_read_only",
1607
+ "Zone membership is worked out from the record's current location")
1608
  retired = {str(key) for key, proof in (route_system.read(session.runtime).get("legacyMigrations") or {}).items()
1609
  if isinstance(proof, dict) and proof.get("verified")}
1610
  if retired.intersection(updates):
 
2456
  consume it yet. Staging-only identities can extend this one helper without leaking fixture
2457
  logic into Route persistence or falling through to a different account plane.
2458
  """
2459
+ return _route_assignee_or_400(
2460
+ session, raw, directory=directory, code="unknown_route_recipient",
2461
+ message="choose an active permitted account to receive this route in Inbox")
 
 
 
 
 
 
 
 
 
2462
 
2463
 
2464
  def _route_view_revision(view_id, config):
api/routes_geo.py CHANGED
@@ -244,12 +244,12 @@ def _clean_zone(raw, previous=None, *, zone_id=""):
244
 
245
  def _zone_wire(zone):
246
  wire = {key: zone.get(key) for key in ("id", "name", "color", "geometryGeoJson", "visible",
247
- "geographicField", "zipCodes", "memberships",
248
  "createdBy", "createdAt")}
249
  # Storage keeps ids as strings because table records may originate in several backends; Map
250
  # selection is numeric `pid`s. The wire performs that one boundary conversion explicitly.
251
  members = []
252
- for raw in zone.get("memberships") or ():
253
  try:
254
  pid = int(raw)
255
  except (TypeError, ValueError):
@@ -314,7 +314,7 @@ def _zone_context(session, raw_table_key):
314
  grid = product_assembly(session, consume_corrections=False)
315
  elif table_key.startswith("ut_"):
316
  from routes_tables import ut_assembly
317
- grid = ut_assembly(session, table_key, consume_corrections=False, with_rows=False)
318
  else:
319
  raise err(400, "invalid_zone_table", "choose a database before working with Zones")
320
  fields = {str(field.get("key") or "") for field in (grid.get("fields") or [])
@@ -323,8 +323,8 @@ def _zone_context(session, raw_table_key):
323
 
324
 
325
  def _zone_subject(session, table_key, zone_id):
326
- from core import user_tables
327
- zone = next((item for item in user_tables.zones(table_key, st=session.runtime)
328
  if str(item.get("id") or "") == str(zone_id)), None)
329
  if not isinstance(zone, dict):
330
  raise err(404, "unknown_zone", "no Zone with that id")
@@ -505,14 +505,14 @@ def geo_providers(session: Session = Depends(require_session)):
505
  @router.get("/geo/zones")
506
  def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(require_session)):
507
  """The canonical table-scoped Zone DTOs a Map may draw or filter by."""
508
- from core import user_tables
509
  table_key, _fields, pids, rows = _zone_context(session, tableKey)
510
- zones = user_tables.zones(table_key, st=session.runtime)
511
  # A hidden Zone remains recoverable to its creator/admin, but cannot become visible through a
512
  # second table simply because row ids happen to collide there.
513
  visible = [zone for zone in zones if zone.get("visible", True)
514
  or session.admin or str(zone.get("createdBy") or "") == session.uname]
515
- projected = [_zone_membership_union(zone, rows, pids) for zone in visible]
516
  return {"zones": [_zone_wire(zone) for zone in sorted(projected,
517
  key=lambda zone: (str(zone.get("name") or "").casefold(), str(zone.get("id") or "")))]}
518
 
@@ -520,46 +520,50 @@ def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(requ
520
  @router.post("/geo/zones")
521
  def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(require_session)):
522
  """Persist one Zone in the existing table-scoped Zone store and field/filter contract."""
523
- from core import user_tables
524
  body = body if isinstance(body, dict) else {}
525
  table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey"))
526
  try:
527
- zone = _clean_zone(body)
528
- zone = _zone_membership_union(zone, rows, pids, refuse_overflow=True)
 
 
 
 
 
 
 
529
  except ValueError as exc:
530
  raise err(400, "invalid_zone", str(exc))
531
  if not zone["id"]:
532
  raise err(400, "invalid_zone", "name this Zone")
533
- if any(str(item.get("id") or "") == zone["id"]
534
- for item in user_tables.zones(table_key, st=session.runtime)):
535
- raise err(409, "zone_exists", "a Zone with that name already exists")
536
- saved = user_tables.upsert_zone(table_key, zone, field_keys=field_keys,
537
- allowed_row_ids=pids, st=session.runtime,
538
- created_by=session.uname)
539
- if saved is None:
540
- raise err(400, "invalid_zone", "the Zone does not match this database's fields and records")
541
- return {"zone": _zone_wire(saved)}
542
 
543
 
544
  @router.patch("/geo/zones/{zone_id}")
545
  def geo_zone_update(zone_id: str, body: dict = Body(default=None),
546
  session: Session = Depends(require_session)):
547
  """Edit a table-scoped Zone while retaining creator, geometry and membership invariants."""
548
- from core import user_tables
549
  body = body if isinstance(body, dict) else {}
550
  table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey"))
551
  previous = _zone_subject(session, table_key, zone_id)
552
  try:
553
- zone = _clean_zone(body, previous, zone_id=str(zone_id))
554
- zone = _zone_membership_union(zone, rows, pids, refuse_overflow=True)
 
 
 
 
 
 
 
 
 
 
555
  except ValueError as exc:
556
  raise err(400, "invalid_zone", str(exc))
557
- saved = user_tables.upsert_zone(table_key, zone, field_keys=field_keys,
558
- allowed_row_ids=pids, st=session.runtime,
559
- created_by=session.uname)
560
- if saved is None:
561
- raise err(400, "invalid_zone", "the Zone does not match this database's fields and records")
562
- return {"zone": _zone_wire(saved)}
563
 
564
 
565
  @router.delete("/geo/zones/{zone_id}")
@@ -569,8 +573,8 @@ def geo_zone_delete(zone_id: str, body: dict = Body(default=None),
569
  body = body if isinstance(body, dict) else {}
570
  table_key, _fields, _pids, _rows = _zone_context(session, body.get("tableKey"))
571
  _zone_subject(session, table_key, zone_id)
572
- from core import user_tables
573
- if not user_tables.delete_zone(table_key, zone_id, st=session.runtime):
574
  raise err(404, "unknown_zone", "no Zone with that id")
575
  return {"deleted": str(zone_id)}
576
 
 
244
 
245
  def _zone_wire(zone):
246
  wire = {key: zone.get(key) for key in ("id", "name", "color", "geometryGeoJson", "visible",
247
+ "geographicField", "zipCodes",
248
  "createdBy", "createdAt")}
249
  # Storage keeps ids as strings because table records may originate in several backends; Map
250
  # selection is numeric `pid`s. The wire performs that one boundary conversion explicitly.
251
  members = []
252
+ for raw in zone.get("memberPids", zone.get("memberships")) or ():
253
  try:
254
  pid = int(raw)
255
  except (TypeError, ValueError):
 
314
  grid = product_assembly(session, consume_corrections=False)
315
  elif table_key.startswith("ut_"):
316
  from routes_tables import ut_assembly
317
+ grid = ut_assembly(session, table_key, consume_corrections=False, with_rows=True)
318
  else:
319
  raise err(400, "invalid_zone_table", "choose a database before working with Zones")
320
  fields = {str(field.get("key") or "") for field in (grid.get("fields") or [])
 
323
 
324
 
325
  def _zone_subject(session, table_key, zone_id):
326
+ from core import route_system
327
+ zone = next((item for item in route_system.list_zones(session.runtime)
328
  if str(item.get("id") or "") == str(zone_id)), None)
329
  if not isinstance(zone, dict):
330
  raise err(404, "unknown_zone", "no Zone with that id")
 
505
  @router.get("/geo/zones")
506
  def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(require_session)):
507
  """The canonical table-scoped Zone DTOs a Map may draw or filter by."""
508
+ from core import route_system
509
  table_key, _fields, pids, rows = _zone_context(session, tableKey)
510
+ zones = route_system.list_zones(session.runtime, rows)
511
  # A hidden Zone remains recoverable to its creator/admin, but cannot become visible through a
512
  # second table simply because row ids happen to collide there.
513
  visible = [zone for zone in zones if zone.get("visible", True)
514
  or session.admin or str(zone.get("createdBy") or "") == session.uname]
515
+ projected = [zone for zone in visible]
516
  return {"zones": [_zone_wire(zone) for zone in sorted(projected,
517
  key=lambda zone: (str(zone.get("name") or "").casefold(), str(zone.get("id") or "")))]}
518
 
 
520
  @router.post("/geo/zones")
521
  def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(require_session)):
522
  """Persist one Zone in the existing table-scoped Zone store and field/filter contract."""
523
+ from core import route_system
524
  body = body if isinstance(body, dict) else {}
525
  table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey"))
526
  try:
527
+ if any(key in body for key in ("memberships", "memberPids", "member_pids")):
528
+ raise ValueError("Zone membership is derived from current permitted rows")
529
+ zone = route_system.put_zone(session.runtime, {
530
+ "id": body.get("id"), "name": body.get("name"), "color": body.get("color"),
531
+ "geometryGeoJson": body.get("geometryGeoJson"), "zipCodes": body.get("zipCodes"),
532
+ "visible": body.get("visible"), "geographicField": body.get("geographicField")
533
+ }, rows=rows, tenant_id=session.tenant, created_by=session.uname)
534
+ if zone is None:
535
+ raise ValueError("the Zone does not match this database's fields and records")
536
  except ValueError as exc:
537
  raise err(400, "invalid_zone", str(exc))
538
  if not zone["id"]:
539
  raise err(400, "invalid_zone", "name this Zone")
540
+ return {"zone": _zone_wire(zone)}
 
 
 
 
 
 
 
 
541
 
542
 
543
  @router.patch("/geo/zones/{zone_id}")
544
  def geo_zone_update(zone_id: str, body: dict = Body(default=None),
545
  session: Session = Depends(require_session)):
546
  """Edit a table-scoped Zone while retaining creator, geometry and membership invariants."""
547
+ from core import route_system
548
  body = body if isinstance(body, dict) else {}
549
  table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey"))
550
  previous = _zone_subject(session, table_key, zone_id)
551
  try:
552
+ if any(key in body for key in ("memberships", "memberPids", "member_pids")):
553
+ raise ValueError("Zone membership is derived from current permitted rows")
554
+ zone = route_system.put_zone(session.runtime, {
555
+ "id": zone_id, "name": body.get("name", previous.get("name")),
556
+ "color": body.get("color", previous.get("color")),
557
+ "geometryGeoJson": body.get("geometryGeoJson", previous.get("geometryGeoJson")),
558
+ "zipCodes": body.get("zipCodes", previous.get("zipCodes")),
559
+ "visible": body.get("visible", previous.get("visible")),
560
+ "geographicField": body.get("geographicField", previous.get("geographicField"))
561
+ }, rows=rows, tenant_id=session.tenant, created_by=session.uname)
562
+ if zone is None:
563
+ raise ValueError("the Zone does not match this database's fields and records")
564
  except ValueError as exc:
565
  raise err(400, "invalid_zone", str(exc))
566
+ return {"zone": _zone_wire(zone)}
 
 
 
 
 
567
 
568
 
569
  @router.delete("/geo/zones/{zone_id}")
 
573
  body = body if isinstance(body, dict) else {}
574
  table_key, _fields, _pids, _rows = _zone_context(session, body.get("tableKey"))
575
  _zone_subject(session, table_key, zone_id)
576
+ from core import route_system
577
+ if not route_system.delete_zone(session.runtime, zone_id):
578
  raise err(404, "unknown_zone", "no Zone with that id")
579
  return {"deleted": str(zone_id)}
580
 
api/routes_grid.py CHANGED
@@ -24,7 +24,7 @@ back. A 200 over a write that evaporated is the failure this rule exists to prev
24
  import datetime as dt
25
  import time
26
 
27
- from fastapi import APIRouter, Body, Depends, HTTPException
28
 
29
  from deps import Session, err, module_gate, perms, require_session
30
 
@@ -332,6 +332,174 @@ def workspace(scope: str = "customer",
332
  return {"workspace": workspace}
333
 
334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
  # ─────────────────────────────────────────────── the TIME-SERIES channel (C-TS, 2026-08-02)
336
  _TS_BUCKETS = ("week", "month", "quarter", "year")
337
  _TS_MAX_BUCKETS = 120
@@ -740,6 +908,110 @@ def grid_calendar_metrics(body: dict = Body(default=None), scope: str = "custome
740
  return out
741
 
742
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
743
  #: ⭐⭐ THE BULK CELL DOOR'S OWN CEILING, and it is REPORTED rather than silently enforced. The
744
  #: standing no-cap rule governs data read from a connected source; this is a WRITE of team-typed
745
  #: values, so a bound is right — but R6's second sentence still binds, which is why exceeding it
@@ -856,13 +1128,19 @@ def recurrence_preview(body: dict = Body(default=None),
856
  """
857
  import aios_grid
858
 
859
- raw = (body or {}).get("recurrence")
860
- clean = aios_grid.clean_date_recurrence(raw)
861
- if clean is None:
862
- raise err(400, "bad_recurrence",
863
- "recurrence needs a start date and at least one supported repeat rule")
 
 
 
864
  return {
865
- "recurrence": aios_grid.recurrence_payload(clean, today=time.strftime("%Y-%m-%d")),
 
 
 
866
  "calendars": list(aios_grid.PUBLIC_HOLIDAY_CALENDARS),
867
  }
868
 
@@ -955,7 +1233,9 @@ def grid_events_route(body: dict = Body(default=None),
955
  resolved_ids=frozenset(g["measure_sets"]),
956
  cohort_ids=frozenset(c["id"] for c in g["lists"]),
957
  measure_offer=tuple(g["measures"]),
958
- visible_views=tuple(g["views"]))
 
 
959
 
960
  # Per-event results so the client can tell which of a batch landed — the component's own
961
  # bridge has no response channel at all, so this is strictly more than the embed gets.
 
24
  import datetime as dt
25
  import time
26
 
27
+ from fastapi import APIRouter, Body, Depends, HTTPException, Query
28
 
29
  from deps import Session, err, module_gate, perms, require_session
30
 
 
332
  return {"workspace": workspace}
333
 
334
 
335
+ def _shared_note_subject(session, scope, view_id):
336
+ """Resolve a note subject only after the ordinary workspace wall admits it."""
337
+ scope = _scope_or_400(scope)
338
+ payload = workspace(scope=scope, session=session)["workspace"]
339
+ if view_id:
340
+ view = next((item for item in (payload.get("views") or [])
341
+ if str(item.get("id") or "") == str(view_id)), None)
342
+ if view is None:
343
+ raise err(404, "view_not_found", "that View is not visible in this database")
344
+ return "view", f"{scope}:{view_id}", view
345
+ return "database", scope, None
346
+
347
+
348
+ @router.get("/grid/shared-note")
349
+ def get_shared_note(scope: str = "customer", viewId: str = "",
350
+ session: Session = Depends(require_session)):
351
+ """Return the one shared note attached to the open Database or View."""
352
+ from core import user_tables
353
+
354
+ kind, subject_id, _view = _shared_note_subject(session, scope, viewId)
355
+ return {"note": user_tables.shared_note(kind, subject_id, st=session.runtime)}
356
+
357
+
358
+ @router.put("/grid/shared-note")
359
+ def update_shared_note(scope: str = "customer", viewId: str = "",
360
+ body: dict = Body(default=None),
361
+ session: Session = Depends(require_session)):
362
+ """Edit a shared note through the same database/View permission wall as the grid."""
363
+ from core import table_store, user_tables
364
+
365
+ kind, subject_id, view = _shared_note_subject(session, scope, viewId)
366
+ may_edit = bool(session.admin)
367
+ if view is not None:
368
+ may_edit = table_store._may_edit(view, session.uname, session.admin)
369
+ elif scope.startswith("ut_"):
370
+ may_edit = user_tables.may_edit_database(
371
+ scope, session.uname, is_admin=session.admin, st=session.runtime)
372
+ if not may_edit:
373
+ raise err(403, "note_read_only", "your Database or View role does not allow note edits")
374
+ note = user_tables.put_shared_note(
375
+ kind, subject_id, (body or {}).get("body"), session.uname, st=session.runtime)
376
+ return {"note": note}
377
+
378
+
379
+ _RECURRENCE_CONDITION_OPS = frozenset({"eq", "neq", "isNotEmpty", "between"})
380
+ _RECURRENCE_ORDERED_TYPES = frozenset({
381
+ "date", "datetime", "int", "integer", "number", "currency", "pct", "rating",
382
+ })
383
+ _RECURRENCE_NUMERIC_TYPES = frozenset({
384
+ "int", "integer", "number", "currency", "pct", "rating",
385
+ })
386
+
387
+
388
+ def _recurrence_target_fields(session, table_key):
389
+ """Permission-projected fields for a linked recurrence target."""
390
+ target = str(table_key or "").strip()
391
+ mapped = {"customer_data": "customer", "product_data": "product"}.get(target, target)
392
+ if not (mapped in _SCOPES or mapped.startswith("ut_")):
393
+ raise ValueError("the linked recurrence database is not a supported visible database")
394
+ payload = workspace(scope=mapped, session=session)["workspace"]
395
+ return [field for field in (payload.get("fields") or [])
396
+ if isinstance(field, dict) and field.get("key")]
397
+
398
+
399
+ def _govern_recurrence_conditions(raw_conditions, current_fields):
400
+ """Validate each recurrence condition against the caller's visible field contract."""
401
+ if raw_conditions in (None, []):
402
+ return []
403
+ if not isinstance(raw_conditions, list) or len(raw_conditions) > 12:
404
+ raise ValueError("recurrence conditions must be a list of at most 12 field comparisons")
405
+ field_map = {str(field.get("key")): field for field in current_fields
406
+ if isinstance(field, dict) and field.get("key")}
407
+ normalized = []
408
+ for raw in raw_conditions:
409
+ if not isinstance(raw, dict) or "children" in raw:
410
+ raise ValueError("recurrence conditions must be individual visible-field comparisons")
411
+ col_id = str(raw.get("colId") or "").strip()
412
+ field = field_map.get(col_id)
413
+ if field is None:
414
+ raise ValueError("a recurrence condition names a field this account cannot see")
415
+ op = "isNotEmpty" if raw.get("op") == "not_empty" else str(raw.get("op") or "")
416
+ if op not in _RECURRENCE_CONDITION_OPS:
417
+ raise ValueError("a recurrence condition uses an unsupported comparison")
418
+ field_type = str(field.get("type") or "text").lower()
419
+ if op == "between" and field_type not in _RECURRENCE_ORDERED_TYPES:
420
+ raise ValueError("between is available only for Date, Date-time, or numeric fields")
421
+ value = "" if raw.get("value") is None else str(raw.get("value"))[:500]
422
+ value2 = "" if raw.get("value2") is None else str(raw.get("value2"))[:500]
423
+ if op != "isNotEmpty" and not value.strip():
424
+ raise ValueError("a recurrence condition needs a comparison value")
425
+ if op == "between" and not value2.strip():
426
+ raise ValueError("a between recurrence condition needs both boundary values")
427
+ if field_type in _RECURRENCE_NUMERIC_TYPES and op in {"eq", "neq", "between"}:
428
+ try:
429
+ float(value)
430
+ if op == "between":
431
+ float(value2)
432
+ except ValueError:
433
+ raise ValueError("a numeric recurrence condition needs numeric values")
434
+ if field_type in {"date", "datetime"} and op in {"eq", "neq", "between"}:
435
+ values = (value, value2) if op == "between" else (value,)
436
+ for item in values:
437
+ try:
438
+ dt.date.fromisoformat(item[:10])
439
+ except ValueError:
440
+ raise ValueError("a Date recurrence condition needs ISO date values")
441
+ normalized.append({"colId": col_id, "op": op, "value": value,
442
+ "value2": value2 if op == "between" else ""})
443
+ return normalized
444
+
445
+
446
+ def govern_date_recurrence(session, scope, current_fields, raw):
447
+ """One authority for preview and every externally reachable recurrence write door."""
448
+ import aios_grid
449
+
450
+ if raw is None:
451
+ return None
452
+ if not isinstance(raw, dict):
453
+ raise ValueError("recurrence must be an object")
454
+ raw_rules = raw.get("rules")
455
+ if not isinstance(raw_rules, list) or not raw_rules or len(raw_rules) > 12:
456
+ raise ValueError("recurrence needs between 1 and 12 repeat rules")
457
+ fields = [field for field in (current_fields or [])
458
+ if isinstance(field, dict) and field.get("key")]
459
+ current = {str(field.get("key")): field for field in fields}
460
+ anchor = raw.get("anchorField")
461
+ if not isinstance(anchor, dict):
462
+ raise ValueError("recurrence needs a same or linked Date/Date-time anchor")
463
+ table = str(anchor.get("table") or "same").strip()
464
+ field_key = str(anchor.get("field") or "").strip()
465
+ linked_via = str(anchor.get("linkedVia") or "").strip()
466
+ if not field_key:
467
+ raise ValueError("recurrence needs a Date or Date-time anchor field")
468
+ anchor_fields = current
469
+ if table == "same":
470
+ if linked_via:
471
+ raise ValueError("a same-database recurrence cannot name a Link field")
472
+ else:
473
+ link_field = current.get(linked_via) or {}
474
+ link = link_field.get("link") if isinstance(link_field.get("link"), dict) else {}
475
+ if not linked_via or str(link_field.get("type") or "") != "link" \
476
+ or str(link.get("table") or "") != table:
477
+ raise ValueError("the linked Date anchor must use a visible Link field to that database")
478
+ anchor_fields = {str(field.get("key")): field
479
+ for field in _recurrence_target_fields(session, table)}
480
+ if str((anchor_fields.get(field_key) or {}).get("type") or "").lower() \
481
+ not in {"date", "datetime"}:
482
+ raise ValueError("a recurrence anchor must be a visible Date or Date-time field")
483
+
484
+ conditions = _govern_recurrence_conditions(raw.get("conditions"), fields)
485
+ candidate = dict(raw)
486
+ candidate["anchorField"] = {"table": table, "field": field_key,
487
+ **({"linkedVia": linked_via} if table != "same" else {})}
488
+ candidate["conditions"] = conditions
489
+ # Server-derived only. The generic finite-shape cleaner consumes this admission list but
490
+ # never persists it, so a browser-authored `conditionFields` member has no authority.
491
+ candidate["conditionFields"] = list(current)
492
+ clean = aios_grid.clean_date_recurrence(candidate)
493
+ if clean is None or clean.get("anchorField") != candidate["anchorField"]:
494
+ raise ValueError("recurrence needs an anchor and at least one supported repeat rule")
495
+ if len(clean.get("rules") or []) != len(raw_rules):
496
+ raise ValueError("one or more recurrence rules are malformed or unsupported")
497
+ if conditions:
498
+ if clean.get("conditions") != conditions:
499
+ raise ValueError("one or more recurrence conditions are malformed")
500
+ return clean
501
+
502
+
503
  # ─────────────────────────────────────────────── the TIME-SERIES channel (C-TS, 2026-08-02)
504
  _TS_BUCKETS = ("week", "month", "quarter", "year")
505
  _TS_MAX_BUCKETS = 120
 
908
  return out
909
 
910
 
911
+ def _builtin_history_context(session, scope, *, restoring=False):
912
+ """Resolve history through the same assembly and write context as grid events."""
913
+ from routes_customers import grid_assembly
914
+ scope = _scope_or_400(scope)
915
+ if scope == "product":
916
+ from routes_products import MODULE as product_module, product_assembly
917
+ session.require(product_module)
918
+ g = product_assembly(session, consume_corrections=False)
919
+ else:
920
+ session.require(MODULE)
921
+ g = grid_assembly(session, scope=scope, consume_corrections=False)
922
+ ctx = _ctx(session, g["fields"], g["pids"], scope_key=scope,
923
+ history_kind="restore" if restoring else "edit")
924
+ return scope, g, ctx
925
+
926
+
927
+ @router.get("/grid/history")
928
+ def builtin_history(scope: str = "customer", rowId: str = Query(default=""),
929
+ retentionDays: int = Query(default=30),
930
+ session: Session = Depends(require_session)):
931
+ from core import user_tables
932
+ import core.platform_admin as platform_admin
933
+ scope, g, ctx = _builtin_history_context(session, scope)
934
+ if rowId and (not rowId.isdigit() or int(rowId) not in g["pids"]):
935
+ raise err(403, "out_of_scope", "that row is not in this database")
936
+ try:
937
+ history = user_tables.value_history(
938
+ scope, rowId or None, st=session.runtime, retention_days=retentionDays,
939
+ extended_entitled=platform_admin.is_platform_admin(session.user))
940
+ except PermissionError as exc:
941
+ raise err(403, "history_entitlement_required", str(exc))
942
+ except ValueError as exc:
943
+ raise err(400, "bad_history_retention", str(exc))
944
+ return user_tables.project_value_history(history, g["pids"], ctx.hidden_keys)
945
+
946
+
947
+ @router.post("/grid/history/{event_id}/restore")
948
+ def restore_builtin_history(event_id: str, scope: str = "customer",
949
+ body: dict = Body(default=None),
950
+ session: Session = Depends(require_session)):
951
+ from core import grid_events, user_tables
952
+ import core.platform_admin as platform_admin
953
+ body = body if isinstance(body, dict) else {}
954
+ scope, g, ctx = _builtin_history_context(session, scope, restoring=True)
955
+ row_id = str(body.get("rowId") or "").strip()
956
+ if not row_id:
957
+ raise err(400, "row_required", "choose a record to restore")
958
+ if not row_id.isdigit() or int(row_id) not in g["pids"]:
959
+ raise err(403, "out_of_scope", "that row is not in this database")
960
+ field_key = str(body.get("field") or "").strip() or None
961
+ if field_key and field_key in ctx.hidden_keys:
962
+ raise err(403, "field_hidden", "that field is not available to your account")
963
+ try:
964
+ days = int(body.get("retentionDays") or user_tables.HISTORY_RETENTION_DAYS)
965
+ except (TypeError, ValueError):
966
+ raise err(400, "bad_history_retention", "history retention must be 30 or 90 days")
967
+ entitled = platform_admin.is_platform_admin(session.user)
968
+ try:
969
+ updates = user_tables.history_restore_values(
970
+ scope, row_id, event_id, field_key=field_key, st=session.runtime,
971
+ retention_days=days, extended_entitled=entitled)
972
+ except PermissionError as exc:
973
+ raise err(403, "history_entitlement_required", str(exc))
974
+ except ValueError as exc:
975
+ raise err(400, "bad_history_retention", str(exc))
976
+ if updates is None:
977
+ raise err(404, "history_event_not_found", "that retained value version is unavailable")
978
+ if any(key in ctx.hidden_keys for key in updates):
979
+ raise err(403, "field_hidden", "that retained version includes a hidden field")
980
+ prior_history_ids = {
981
+ str(item.get("id")) for item in user_tables.value_history(
982
+ scope, row_id, st=session.runtime, retention_days=days,
983
+ extended_entitled=entitled).get("events", [])
984
+ }
985
+ stored_before = dict((((g.get("ws") or {}).get("overlays") or {}).get(row_id)) or {})
986
+ try:
987
+ grid_events.handle_one(
988
+ {"id": f"restore:{event_id}:{time.time_ns()}", "type": "overlay_patch",
989
+ "pid": int(row_id), "updates": updates}, ctx)
990
+ except grid_events.StoreUnavailable:
991
+ raise err(503, "store_unavailable", "the retained version was not restored")
992
+ stored = dict(((grid_events.table_workspace(
993
+ ctx, allowed_pids=g["pids"], consume_corrections=False).get("overlays") or {})
994
+ .get(row_id)) or {})
995
+ landed = all((key not in stored if value is None else stored.get(key) == str(value))
996
+ for key, value in updates.items())
997
+ newest = user_tables.project_value_history(user_tables.value_history(
998
+ scope, row_id, st=session.runtime, retention_days=days,
999
+ extended_entitled=entitled), g["pids"], ctx.hidden_keys)
1000
+ restore_event = next((item for item in newest["events"]
1001
+ if item.get("kind") == "restore"
1002
+ and str(item.get("id")) not in prior_history_ids), None)
1003
+ changed_keys = {
1004
+ key for key, value in updates.items()
1005
+ if (key in stored_before if value is None else stored_before.get(key) != str(value))
1006
+ }
1007
+ audited = (not changed_keys or (restore_event is not None
1008
+ and changed_keys.issubset(set(restore_event.get("changes") or {}))))
1009
+ if not landed or not audited:
1010
+ raise err(403, "restore_refused", "the retained version is outside your write authority")
1011
+ return {"ok": True, "rowId": int(row_id), "restoredFields": sorted(updates),
1012
+ "event": restore_event}
1013
+
1014
+
1015
  #: ⭐⭐ THE BULK CELL DOOR'S OWN CEILING, and it is REPORTED rather than silently enforced. The
1016
  #: standing no-cap rule governs data read from a connected source; this is a WRITE of team-typed
1017
  #: values, so a bound is right — but R6's second sentence still binds, which is why exceeding it
 
1128
  """
1129
  import aios_grid
1130
 
1131
+ body = body if isinstance(body, dict) else {}
1132
+ raw = body.get("recurrence")
1133
+ scope = _scope_or_400(body.get("scopeKey"))
1134
+ current = workspace(scope=scope, session=session)["workspace"]
1135
+ try:
1136
+ clean = govern_date_recurrence(session, scope, current.get("fields") or [], raw)
1137
+ except ValueError as exc:
1138
+ raise err(400, "bad_recurrence", str(exc))
1139
  return {
1140
+ "recurrence": aios_grid.recurrence_payload(
1141
+ clean, today=time.strftime("%Y-%m-%d"),
1142
+ condition_fields={str(field.get("key")) for field in current.get("fields") or []
1143
+ if isinstance(field, dict) and field.get("key")}),
1144
  "calendars": list(aios_grid.PUBLIC_HOLIDAY_CALENDARS),
1145
  }
1146
 
 
1233
  resolved_ids=frozenset(g["measure_sets"]),
1234
  cohort_ids=frozenset(c["id"] for c in g["lists"]),
1235
  measure_offer=tuple(g["measures"]),
1236
+ visible_views=tuple(g["views"]),
1237
+ recurrence_validator=lambda raw: govern_date_recurrence(
1238
+ session, scope, g["fields"], raw))
1239
 
1240
  # Per-event results so the client can tell which of a batch landed — the component's own
1241
  # bridge has no response channel at all, so this is strictly more than the embed gets.
api/routes_nav.py CHANGED
@@ -528,7 +528,8 @@ def nav(session: Session = Depends(require_session)):
528
  if not _perm_scope.nav_may_open(session.user, e["key"], st=_lent):
529
  continue
530
  pages.append({"key": e["key"], "label": e["label"],
531
- "source": e.get("source") or "Blank", "chrome": "main"})
 
532
  except Exception:
533
  # ⭐⭐ W31-T11 (owner item 6b) — STILL SWALLOWED, NO LONGER SILENT.
534
  #
@@ -563,6 +564,14 @@ def nav(session: Session = Depends(require_session)):
563
  # leak with no symptom until two tenants rename the same registry key. Copy the rows before
564
  # merging on the day that invariant changes.
565
  meta = _read_nav_meta(session.runtime)
 
 
 
 
 
 
 
 
566
  # ⛔⛔ W35-T43 (rulings R4/R7) — THE MARK-IMPORTANT COUNTS ARE NO LONGER COMPUTED HERE.
567
  #
568
  # W34-T10 put them on this payload with a 2.5 s budget and a `degraded` entry, spent in RECENTS
 
528
  if not _perm_scope.nav_may_open(session.user, e["key"], st=_lent):
529
  continue
530
  pages.append({"key": e["key"], "label": e["label"],
531
+ "source": e.get("source") or "Blank",
532
+ "sourceGroup": e.get("sourceGroup") or "Custom", "chrome": "main"})
533
  except Exception:
534
  # ⭐⭐ W31-T11 (owner item 6b) — STILL SWALLOWED, NO LONGER SILENT.
535
  #
 
564
  # leak with no symptom until two tenants rename the same registry key. Copy the rows before
565
  # merging on the day that invariant changes.
566
  meta = _read_nav_meta(session.runtime)
567
+ for page in pages:
568
+ source = str(page.get("source") or "")
569
+ key = str(page.get("key") or "")
570
+ if key in {"customer_data", "product_data"} or source.lower() == "odoo" \
571
+ or key.startswith("ut_odoo_"):
572
+ page["sourceGroup"] = "Odoo"
573
+ elif page.get("user_table") or source in {"", "Blank", "Custom"}:
574
+ page.setdefault("sourceGroup", "Custom")
575
  # ⛔⛔ W35-T43 (rulings R4/R7) — THE MARK-IMPORTANT COUNTS ARE NO LONGER COMPUTED HERE.
576
  #
577
  # W34-T10 put them on this payload with a 2.5 s budget and a `degraded` entry, spent in RECENTS
api/routes_platform_admin.py CHANGED
@@ -38,10 +38,12 @@ import sys
38
  import time
39
  from pathlib import Path
40
 
41
- from fastapi import APIRouter, Depends
42
 
43
  import core.platform_admin as platform_admin
44
  import core.store as store
 
 
45
  from deps import Session, err, require_session, users
46
 
47
  router = APIRouter(prefix="/api/v1/platform-admin")
@@ -67,6 +69,131 @@ def padmin_gate(session: Session = Depends(require_session)) -> Session:
67
  return session
68
 
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  # ══════════════════════════════════════════════════════════════════════════ tenants
71
 
72
 
 
38
  import time
39
  from pathlib import Path
40
 
41
+ from fastapi import APIRouter, Body, Depends, Header, Request
42
 
43
  import core.platform_admin as platform_admin
44
  import core.store as store
45
+ import operator_control
46
+ import voice_control_plane as voice
47
  from deps import Session, err, require_session, users
48
 
49
  router = APIRouter(prefix="/api/v1/platform-admin")
 
69
  return session
70
 
71
 
72
+ def _operator_origin(request: Request) -> str:
73
+ return str(request.headers.get("origin") or request.base_url).rstrip("/")
74
+
75
+
76
+ @router.post("/operator/grants")
77
+ def operator_grant(request: Request, body: dict = Body(default=None),
78
+ session: Session = Depends(padmin_gate)):
79
+ body = body or {}
80
+ try:
81
+ return operator_control.mint_grant(
82
+ session.runtime, actor=session.uname, tenant=body.get("tenant"),
83
+ capabilities=body.get("capabilities") or [], origin=_operator_origin(request),
84
+ audience=body.get("audience") or operator_control.AUDIENCE,
85
+ ttl_seconds=body.get("ttlSeconds") or 900)
86
+ except operator_control.OperatorRefusal as exc:
87
+ raise err(400, "operator_grant_refused", str(exc))
88
+
89
+
90
+ @router.delete("/operator/grants/{grant_id}")
91
+ def operator_revoke(grant_id: str, session: Session = Depends(padmin_gate)):
92
+ try:
93
+ return {"grant": operator_control.revoke_grant(session.runtime, grant_id, session.uname)}
94
+ except operator_control.OperatorRefusal as exc:
95
+ raise err(404, "operator_grant_refused", str(exc))
96
+
97
+
98
+ @router.get("/operator/audit")
99
+ def operator_audit(limit: int = 200, session: Session = Depends(padmin_gate)):
100
+ return {"audit": operator_control.audit_rows(session.runtime, limit)}
101
+
102
+
103
+ def _operator_authorize(request, session, token, tenant, capability, action):
104
+ try:
105
+ return operator_control.authorize(
106
+ session.runtime, token=token, actor=session.uname, tenant=tenant,
107
+ capability=capability, origin=_operator_origin(request), action=action)
108
+ except operator_control.OperatorRefusal as exc:
109
+ raise err(403, "operator_capability_refused", str(exc))
110
+
111
+
112
+ def _operator_final(session, tenant, capability, action, outcome):
113
+ operator_control.audit_attempt(session.runtime, actor=session.uname, tenant=tenant,
114
+ capability=capability, action=action, outcome=outcome)
115
+
116
+
117
+ @router.get("/operator/tenants/{tenant}/setup")
118
+ def operator_read_setup(request: Request, tenant: str,
119
+ x_loopable_operator_grant: str = Header(default=""),
120
+ session: Session = Depends(padmin_gate)):
121
+ try:
122
+ _operator_authorize(request, session, x_loopable_operator_grant, tenant,
123
+ "tenant.read", "read tenant setup")
124
+ rt, problem = _runtime_for(tenant)
125
+ if rt is None:
126
+ raise err(404, "operator_tenant_unavailable", problem or "tenant unavailable")
127
+ out = operator_control.setup_dto(rt, tenant)
128
+ except Exception:
129
+ _operator_final(session, tenant, "tenant.read", "read tenant setup", "refused")
130
+ raise
131
+ _operator_final(session, tenant, "tenant.read", "read tenant setup", "allowed")
132
+ return out
133
+
134
+
135
+ @router.patch("/operator/tenants/{tenant}/setup")
136
+ def operator_change_setup(request: Request, tenant: str, body: dict = Body(default=None),
137
+ x_loopable_operator_grant: str = Header(default=""),
138
+ session: Session = Depends(padmin_gate)):
139
+ try:
140
+ _operator_authorize(request, session, x_loopable_operator_grant, tenant,
141
+ "tenant.configure", "change tenant setup")
142
+ rt, problem = _runtime_for(tenant)
143
+ if rt is None:
144
+ raise err(404, "operator_tenant_unavailable", problem or "tenant unavailable")
145
+ out = operator_control.update_setup(rt, tenant, body or {}, session.uname)
146
+ except operator_control.OperatorRefusal as exc:
147
+ _operator_final(session, tenant, "tenant.configure", "change tenant setup", "refused")
148
+ raise err(400, "operator_setup_refused", str(exc))
149
+ except Exception:
150
+ _operator_final(session, tenant, "tenant.configure", "change tenant setup", "refused")
151
+ raise
152
+ _operator_final(session, tenant, "tenant.configure", "change tenant setup", "allowed")
153
+ return out
154
+
155
+
156
+ @router.get("/operator/tenants/{tenant}/voice-setup")
157
+ def operator_read_voice_setup(request: Request, tenant: str,
158
+ x_loopable_operator_grant: str = Header(default=""),
159
+ session: Session = Depends(padmin_gate)):
160
+ try:
161
+ _operator_authorize(request, session, x_loopable_operator_grant, tenant,
162
+ "voice.read", "read voice setup")
163
+ rt, problem = _runtime_for(tenant)
164
+ if rt is None:
165
+ raise err(404, "operator_tenant_unavailable", problem or "tenant unavailable")
166
+ out = {"tenant": tenant, "voice": voice.browser_options(rt),
167
+ "secretsPresent": False, "rawProviderBindings": False}
168
+ except Exception:
169
+ _operator_final(session, tenant, "voice.read", "read voice setup", "refused")
170
+ raise
171
+ _operator_final(session, tenant, "voice.read", "read voice setup", "allowed")
172
+ return out
173
+
174
+
175
+ @router.patch("/operator/tenants/{tenant}/voice-setup")
176
+ def operator_change_voice_setup(request: Request, tenant: str, body: dict = Body(default=None),
177
+ x_loopable_operator_grant: str = Header(default=""),
178
+ session: Session = Depends(padmin_gate)):
179
+ try:
180
+ _operator_authorize(request, session, x_loopable_operator_grant, tenant,
181
+ "voice.configure", "change voice setup")
182
+ rt, problem = _runtime_for(tenant)
183
+ if rt is None:
184
+ raise err(404, "operator_tenant_unavailable", problem or "tenant unavailable")
185
+ saved = operator_control.update_setup(rt, tenant, body or {}, session.uname)
186
+ except operator_control.OperatorRefusal as exc:
187
+ _operator_final(session, tenant, "voice.configure", "change voice setup", "refused")
188
+ raise err(400, "operator_setup_refused", str(exc))
189
+ except Exception:
190
+ _operator_final(session, tenant, "voice.configure", "change voice setup", "refused")
191
+ raise
192
+ _operator_final(session, tenant, "voice.configure", "change voice setup", "allowed")
193
+ return {**saved, "voiceConfigurationAccepted": True,
194
+ "secretsPresent": False, "rawProviderBindings": False}
195
+
196
+
197
  # ══════════════════════════════════════════════════════════════════════════ tenants
198
 
199
 
api/routes_products.py CHANGED
@@ -19,6 +19,9 @@ the product ops). ⛔ The separate bucket is load-bearing, not tidy: product pid
19
  hashes and customer pids are Odoo partner ids — one shared overlay bucket and a hash collision
20
  silently writes a product note onto somebody's customer.
21
  """
 
 
 
22
  import time
23
 
24
  from fastapi import Body, Depends
@@ -26,6 +29,7 @@ from fastapi import Body, Depends
26
  from fastapi import APIRouter
27
 
28
  import scope_cache
 
29
  from deps import Session, err, module_gate
30
 
31
  router = APIRouter(prefix="/api/v1")
@@ -51,6 +55,8 @@ def _pool_for(rt, team_id):
51
  return []
52
 
53
  import modules.product_data as pd
 
 
54
 
55
  # ⚠ Signature is (cache, key, ttl, build) — the wave-15 version passed `ttl=` as a keyword
56
  # after the build lambda and DIED on every call ("multiple values for 'ttl'"). Latent until
@@ -91,8 +97,16 @@ def _pool_for(rt, team_id):
91
  "this data source is paused and nothing has been read since — "
92
  "an admin can resume it under Settings → Connectors")
93
 
94
- return scope_cache.get(rt.pool_cache, key, _CACHE_TTL,
95
- lambda: pd.pool(team_id=team_id))
 
 
 
 
 
 
 
 
96
 
97
 
98
  def scoped_pool(session: Session):
@@ -129,6 +143,12 @@ def scoped_pool(session: Session):
129
  # so such a leaf denied every product row while the admin was told the rule saved. See
130
  # `perm_scope._enrich_for_wall`. This route is BOTH walls at once (it returns the pids the
131
  # write door uses), so there is no second call here to keep in step.
 
 
 
 
 
 
132
  rows_src = perm_scope.apply_row_scope(rows_src, session.user, MODULE, fields_base,
133
  st=session.runtime)
134
  pids = frozenset(r["pid"] for r in rows_src if r.get("pid") is not None)
@@ -332,6 +352,50 @@ def _hydrate_effective_choice_options(fields, rows_src, overlays, derived):
332
  fields, effective_rows, ignored_by_field={"supplier": {"(none)"}})
333
 
334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
  def product_assembly(session: Session, scope: str = "product", storage_key: str = "",
336
  consume_corrections: bool = True):
337
  """The product topic's mirror of `routes_customers.grid_assembly` — SAME g-dict keys, so
@@ -363,8 +427,6 @@ def product_assembly(session: Session, scope: str = "product", storage_key: str
363
  import aios_grid
364
  import core.perm_scope as perm_scope
365
  import modules.product_data as pd
366
- from core import grid_events
367
-
368
  pids, team_id, rows_src, fields_base = scoped_pool(session)
369
  shared_defs = pd.shared_fields(st=session.runtime)
370
 
@@ -438,6 +500,7 @@ def product_assembly(session: Session, scope: str = "product", storage_key: str
438
  }
439
 
440
  today = time.strftime("%Y-%m-%d")
 
441
  stamp = _measure_stamp(session.runtime, team_id)
442
  measures = product_measures(session)
443
 
 
19
  hashes and customer pids are Odoo partner ids — one shared overlay bucket and a hash collision
20
  silently writes a product note onto somebody's customer.
21
  """
22
+ import html
23
+ import json
24
+ import re
25
  import time
26
 
27
  from fastapi import Body, Depends
 
29
  from fastapi import APIRouter
30
 
31
  import scope_cache
32
+ from core import grid_events, user_tables
33
  from deps import Session, err, module_gate
34
 
35
  router = APIRouter(prefix="/api/v1")
 
55
  return []
56
 
57
  import modules.product_data as pd
58
+ from core import user_tables
59
+ enabled_raw = user_tables.enabled_odoo_schema_fields(rt, model="product.product")
60
 
61
  # ⚠ Signature is (cache, key, ttl, build) — the wave-15 version passed `ttl=` as a keyword
62
  # after the build lambda and DIED on every call ("multiple values for 'ttl'"). Latent until
 
97
  "this data source is paused and nothing has been read since — "
98
  "an admin can resume it under Settings → Connectors")
99
 
100
+ def build():
101
+ # Preserve the long-standing pool call shape when no raw field is enabled. Besides
102
+ # keeping existing adapters valid, this avoids paying for an unnecessary `extra_fields`
103
+ # branch on the overwhelmingly common/default-off path.
104
+ rows = (pd.pool(team_id=team_id,
105
+ raw_fields=[field.get("rawName") for field in enabled_raw])
106
+ if enabled_raw else pd.pool(team_id=team_id))
107
+ return _project_enabled_raw_rows(rows, enabled_raw, drop_source=True)
108
+
109
+ return scope_cache.get(rt.pool_cache, key, _CACHE_TTL, build)
110
 
111
 
112
  def scoped_pool(session: Session):
 
143
  # so such a leaf denied every product row while the admin was told the rule saved. See
144
  # `perm_scope._enrich_for_wall`. This route is BOTH walls at once (it returns the pids the
145
  # write door uses), so there is no second call here to keep in step.
146
+ enabled_raw = user_tables.enabled_odoo_schema_fields(session.runtime, model="product.product")
147
+ field_keys = {field.get("key") for field in fields_base if isinstance(field, dict)}
148
+ fields_base = list(fields_base) + [
149
+ field for field in enabled_raw if field.get("key") not in field_keys
150
+ ]
151
+ rows_src = _project_enabled_raw_rows(rows_src, enabled_raw, drop_source=True)
152
  rows_src = perm_scope.apply_row_scope(rows_src, session.user, MODULE, fields_base,
153
  st=session.runtime)
154
  pids = frozenset(r["pid"] for r in rows_src if r.get("pid") is not None)
 
352
  fields, effective_rows, ignored_by_field={"supplier": {"(none)"}})
353
 
354
 
355
+ def _project_enabled_raw_rows(rows, enabled, *, drop_source=False):
356
+ """Namespace enabled Odoo values as bounded grid scalars before the permission wall."""
357
+ def scalar(value, raw_type):
358
+ if raw_type == "boolean":
359
+ return bool(value)
360
+ if value is None or value is False:
361
+ return ""
362
+ if raw_type in {"many2one", "reference"}:
363
+ if isinstance(value, (list, tuple)):
364
+ value = value[1] if len(value) > 1 else (value[0] if value else "")
365
+ elif isinstance(value, dict):
366
+ value = value.get("display_name") or value.get("name") or value.get("id") or ""
367
+ elif raw_type in {"one2many", "many2many"}:
368
+ if isinstance(value, (list, tuple, set)):
369
+ value = ", ".join(str(item) for item in value)
370
+ elif raw_type == "binary":
371
+ # A binary field is discoverable and enableable, but a grid row never transports
372
+ # its base64 body. Presence is the only safe scalar representation at this seam.
373
+ return "[binary value]" if value else ""
374
+ elif raw_type == "html":
375
+ value = re.sub(r"<[^>]*>", " ", html.unescape(str(value)))
376
+ value = re.sub(r"\s+", " ", value).strip()
377
+ if isinstance(value, (dict, list, tuple, set)):
378
+ value = json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
379
+ if isinstance(value, (str, bytes, bytearray)):
380
+ if isinstance(value, (bytes, bytearray)):
381
+ return "[binary value]" if value else ""
382
+ return value[:32000]
383
+ return value
384
+
385
+ out = []
386
+ for row in rows or ():
387
+ item = dict(row or {})
388
+ for field in enabled or ():
389
+ key, name, model = field.get("key"), field.get("rawName"), field.get("model")
390
+ if key and name:
391
+ value = item.get(str(name), item.get(f"{model}.{name}"))
392
+ item[str(key)] = scalar(value, str(field.get("rawType") or "text"))
393
+ if drop_source and str(name) != str(key):
394
+ item.pop(str(name), None)
395
+ out.append(item)
396
+ return out
397
+
398
+
399
  def product_assembly(session: Session, scope: str = "product", storage_key: str = "",
400
  consume_corrections: bool = True):
401
  """The product topic's mirror of `routes_customers.grid_assembly` — SAME g-dict keys, so
 
427
  import aios_grid
428
  import core.perm_scope as perm_scope
429
  import modules.product_data as pd
 
 
430
  pids, team_id, rows_src, fields_base = scoped_pool(session)
431
  shared_defs = pd.shared_fields(st=session.runtime)
432
 
 
500
  }
501
 
502
  today = time.strftime("%Y-%m-%d")
503
+ fields = aios_grid.project_date_recurrences(fields, today=today)
504
  stamp = _measure_stamp(session.runtime, team_id)
505
  measures = product_measures(session)
506
 
api/routes_query.py CHANGED
@@ -7,12 +7,16 @@ citations and virtual views; it never opens or mutates a source workspace.
7
  import copy
8
  import csv
9
  import datetime as _dt
 
10
  import hashlib
 
11
  import io
12
  import json
13
  import os
14
  import re
 
15
  import sys
 
16
  import uuid
17
 
18
  from fastapi import APIRouter, Body, Depends, Response
@@ -45,6 +49,9 @@ MAX_HISTORY_CHARS = 6000
45
  MAX_RATING_REASON = 200
46
  QUERY_RATINGS = ("up", "down")
47
  MODEL_AUTO = "auto"
 
 
 
48
  # ⭐⭐ WAVE 36 · W36-T35 (R4 / contract C5) — THE LADDER IS DECLARED IN ONE PLACE NOW.
49
  #
50
  # ⛔ THIS BLOCK USED TO BE A SECOND COPY OF THE LADDER, and it said so: *"A SECOND DECLARATION IS A
@@ -60,6 +67,8 @@ MODEL_AUTO = "auto"
60
  # reconciles the two WITHOUT forcing the import, so a divergence is still reported and nobody pays
61
  # the eight seconds to hear about it.
62
  import providers as prov # noqa: E402
 
 
63
 
64
  #: The Messages API version header. ⚠ A DATE, NOT A MODEL: it pins the wire format, not the model,
65
  #: and Anthropic requires it on every request.
@@ -192,7 +201,8 @@ def model_status():
192
  rows_by_name = {row["provider"]: row for row in prov.llm_status()}
193
  live = [name for name, row in rows_by_name.items()
194
  if row["configured"] and row["capable"] and not row["outOfCredit"]]
195
- out = [{"model": MODEL_AUTO, "available": bool(live),
 
196
  "reason": "" if live else "no model can be reached from this deployment right now",
197
  "toolCalling": True, "jsonMode": True, "outOfCredit": False}]
198
  for name, row in rows_by_name.items():
@@ -204,11 +214,13 @@ def model_status():
204
  reason = f"{row['label']} cannot carry this kind of request"
205
  else:
206
  reason = ""
207
- out.append({"model": name, "available": name in live, "reason": reason,
 
208
  "toolCalling": row["toolCalling"], "jsonMode": row["jsonMode"],
209
  "outOfCredit": row["outOfCredit"]})
210
  # Anything the ANALYST's ladder carries that Query does not offer, once a chat has taught us.
211
- out.extend({"model": name, "available": False, "toolCalling": False, "jsonMode": False,
 
212
  "outOfCredit": False,
213
  "reason": "the platform can reach this model but Query does not offer it yet"}
214
  for name in _ladder_drift())
@@ -231,6 +243,11 @@ def _providers(model=MODEL_AUTO):
231
  "model": p.model, "wire": p.wire} for p in chain]
232
 
233
 
 
 
 
 
 
234
  def _history(state, thread_id):
235
  """The prior turns of THIS thread, oldest first, in the transport's own message shape.
236
 
@@ -795,7 +812,7 @@ def _validate(spec, fields):
795
  return None, "the assistant gave an unsupported aggregation", "bad_aggregation"
796
  if op == "count":
797
  field = None
798
- elif field not in keys or by_key.get(field) not in {"int", "currency", "pct"}:
799
  return None, "that aggregation needs one visible numeric field", "bad_aggregation"
800
 
801
  display = {"mode": kind}
@@ -968,6 +985,8 @@ def _public_view(view):
968
  "explain": view["explain"], "threadId": view["threadId"], "createdAt": view["createdAt"],
969
  "virtual": True, "source": _safe(source), "view": _safe(view["view"]),
970
  "citationIds": list(view["citationIds"]), "numeric": _safe(view["numeric"]),
 
 
971
  # ⚠ AN ARTEFACT MADE BEFORE THIS WAVE HAS NO ORIGINAL, so it reports `edited: false` and
972
  # sends no `original_spec` — and the client shows neither the badge nor Revert. C4 is
973
  # explicit that this is the right answer: a Revert with nothing to revert to is worse
@@ -1303,12 +1322,14 @@ def _submit(body, session, chat=None):
1303
  # ⚠ `_safe(view)` twice, not the same object twice: `view` is mutable and a
1304
  # shared reference would let an edit rewrite the original through the alias.
1305
  "original_spec": _safe(view),
1306
- "model": provider, "requestedModel": selected_model}
 
1307
 
1308
  assistant_message = {
1309
  "id": assistant_message_id, "threadId": thread_id, "role": "assistant", "createdAt": now,
1310
  "content": (said or _said_fallback(artifact)) if artifact else (refusal or "the assistant could not answer"),
1311
  "targetDatabase": target, "requestedModel": selected_model, "model": provider,
 
1312
  "reason": refusal_code, "viewId": artifact["id"] if artifact else None,
1313
  "citationIds": artifact["citationIds"] if artifact else [], "numeric": artifact["numeric"] if artifact else None,
1314
  }
@@ -1350,6 +1371,485 @@ def submit_chat(body: dict = Body(default=None), session: Session = Depends(requ
1350
  return _submit(body, session)
1351
 
1352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1353
  @router.delete("/query/threads/{tid}")
1354
  def delete_thread(tid: str, session: Session = Depends(require_session)):
1355
  """Remove one of the caller's own chats, and only the chat.
 
7
  import copy
8
  import csv
9
  import datetime as _dt
10
+ import base64
11
  import hashlib
12
+ import hmac
13
  import io
14
  import json
15
  import os
16
  import re
17
+ import secrets
18
  import sys
19
+ import time
20
  import uuid
21
 
22
  from fastapi import APIRouter, Body, Depends, Response
 
49
  MAX_RATING_REASON = 200
50
  QUERY_RATINGS = ("up", "down")
51
  MODEL_AUTO = "auto"
52
+ QUERY_RESUME_TTL_SECONDS = 300
53
+ _resume_env = os.environ.get("AIOS_QUERY_RESUME_SECRET") or os.environ.get("AIOS_SESSION_SECRET") or ""
54
+ _QUERY_RESUME_SECRET = (_resume_env.encode("utf-8") if _resume_env else secrets.token_bytes(32))
55
  # ⭐⭐ WAVE 36 · W36-T35 (R4 / contract C5) — THE LADDER IS DECLARED IN ONE PLACE NOW.
56
  #
57
  # ⛔ THIS BLOCK USED TO BE A SECOND COPY OF THE LADDER, and it said so: *"A SECOND DECLARATION IS A
 
67
  # reconciles the two WITHOUT forcing the import, so a divergence is still reported and nobody pays
68
  # the eight seconds to hear about it.
69
  import providers as prov # noqa: E402
70
+ import formula_runtime as formula_rt # noqa: E402
71
+ import semantic_registry as semantic_rt # noqa: E402
72
 
73
  #: The Messages API version header. ⚠ A DATE, NOT A MODEL: it pins the wire format, not the model,
74
  #: and Anthropic requires it on every request.
 
201
  rows_by_name = {row["provider"]: row for row in prov.llm_status()}
202
  live = [name for name, row in rows_by_name.items()
203
  if row["configured"] and row["capable"] and not row["outOfCredit"]]
204
+ out = [{"model": MODEL_AUTO, "provider": "automatic", "modelId": "automatic",
205
+ "available": bool(live),
206
  "reason": "" if live else "no model can be reached from this deployment right now",
207
  "toolCalling": True, "jsonMode": True, "outOfCredit": False}]
208
  for name, row in rows_by_name.items():
 
214
  reason = f"{row['label']} cannot carry this kind of request"
215
  else:
216
  reason = ""
217
+ out.append({"model": name, "provider": name, "modelId": row.get("model") or name,
218
+ "available": name in live, "reason": reason,
219
  "toolCalling": row["toolCalling"], "jsonMode": row["jsonMode"],
220
  "outOfCredit": row["outOfCredit"]})
221
  # Anything the ANALYST's ladder carries that Query does not offer, once a chat has taught us.
222
+ out.extend({"model": name, "provider": name, "modelId": name,
223
+ "available": False, "toolCalling": False, "jsonMode": False,
224
  "outOfCredit": False,
225
  "reason": "the platform can reach this model but Query does not offer it yet"}
226
  for name in _ladder_drift())
 
243
  "model": p.model, "wire": p.wire} for p in chain]
244
 
245
 
246
+ def _model_identity(provider):
247
+ row = next((item for item in prov.llm_status() if item.get("provider") == provider), None)
248
+ return {"provider": provider, "modelId": (row or {}).get("model") or provider}
249
+
250
+
251
  def _history(state, thread_id):
252
  """The prior turns of THIS thread, oldest first, in the transport's own message shape.
253
 
 
812
  return None, "the assistant gave an unsupported aggregation", "bad_aggregation"
813
  if op == "count":
814
  field = None
815
+ elif field not in keys or by_key.get(field) not in {"int", "currency", "pct", "formula"}:
816
  return None, "that aggregation needs one visible numeric field", "bad_aggregation"
817
 
818
  display = {"mode": kind}
 
985
  "explain": view["explain"], "threadId": view["threadId"], "createdAt": view["createdAt"],
986
  "virtual": True, "source": _safe(source), "view": _safe(view["view"]),
987
  "citationIds": list(view["citationIds"]), "numeric": _safe(view["numeric"]),
988
+ "provider": view.get("provider") or view.get("model"),
989
+ "modelId": view.get("modelId") or view.get("model"),
990
  # ⚠ AN ARTEFACT MADE BEFORE THIS WAVE HAS NO ORIGINAL, so it reports `edited: false` and
991
  # sends no `original_spec` — and the client shows neither the badge nor Revert. C4 is
992
  # explicit that this is the right answer: a Revert with nothing to revert to is worse
 
1322
  # ⚠ `_safe(view)` twice, not the same object twice: `view` is mutable and a
1323
  # shared reference would let an edit rewrite the original through the alias.
1324
  "original_spec": _safe(view),
1325
+ "model": provider, **_model_identity(provider),
1326
+ "requestedModel": selected_model}
1327
 
1328
  assistant_message = {
1329
  "id": assistant_message_id, "threadId": thread_id, "role": "assistant", "createdAt": now,
1330
  "content": (said or _said_fallback(artifact)) if artifact else (refusal or "the assistant could not answer"),
1331
  "targetDatabase": target, "requestedModel": selected_model, "model": provider,
1332
+ **_model_identity(provider),
1333
  "reason": refusal_code, "viewId": artifact["id"] if artifact else None,
1334
  "citationIds": artifact["citationIds"] if artifact else [], "numeric": artifact["numeric"] if artifact else None,
1335
  }
 
1371
  return _submit(body, session)
1372
 
1373
 
1374
+ # Governed Query contract (Wave 45 C2). The existing chat workspace remains the presentation
1375
+ # surface; this provider-neutral door is the shared execution seam for Assistant, Agents, voice,
1376
+ # Slack and future adapters.
1377
+ def _semantic_baseline(database):
1378
+ from harness import semantic as sem
1379
+ topic = next((row for row in sem.topics().values()
1380
+ if isinstance(row, dict) and row.get("grid") == database), None)
1381
+ if not topic:
1382
+ raise err(404, "semantic_source_unknown",
1383
+ "that database does not have a semantic contract")
1384
+ return semantic_rt.topic_records(database, topic)
1385
+
1386
+
1387
+ def _semantic_records(session, database):
1388
+ return semantic_rt.load(session.runtime, _semantic_baseline(database))
1389
+
1390
+
1391
+ def _semantic_authorize(session, database, *, require_answerable=False):
1392
+ status = assistant_source_status(session, [database]).get(database) or {}
1393
+ if not status.get("permitted"):
1394
+ raise err(403, "assistant_forbidden",
1395
+ "your current permissions do not allow this database")
1396
+ if require_answerable and not status.get("answerable"):
1397
+ raise err(409, "query_source_unavailable",
1398
+ str(status.get("reason") or "this database cannot answer Query yet"))
1399
+ return status
1400
+
1401
+
1402
+ @router.get("/query/semantics/{database}")
1403
+ def semantic_catalog(database: str, session: Session = Depends(require_session)):
1404
+ # Permission is resolved by the same source boundary Query uses. An empty field selection is
1405
+ # a schema-only authorization check and never widens to records.
1406
+ _semantic_authorize(session, database)
1407
+ records = _semantic_records(session, database)
1408
+ rows = [copy.deepcopy(row) for key, row in sorted(records.items())
1409
+ if key.startswith(f"{database}::")]
1410
+ for row in rows:
1411
+ row["markdown"] = semantic_rt.generated_markdown(row)
1412
+ return {"database": database, "fields": rows,
1413
+ "router": semantic_rt.router_projection(records, database)}
1414
+
1415
+
1416
+ @router.patch("/query/semantics/{database}/{field}")
1417
+ def update_semantic_field(database: str, field: str, body: dict = Body(default=None),
1418
+ session: Session = Depends(require_session)):
1419
+ _semantic_authorize(session, database)
1420
+ try:
1421
+ row = semantic_rt.update(session.runtime, _semantic_baseline(database), database, field,
1422
+ body, actor=session.uname, is_admin=session.admin)
1423
+ except semantic_rt.SemanticError as exc:
1424
+ code = "forbidden" if "only a tenant admin" in str(exc) else "bad_semantic_contract"
1425
+ raise err(403 if code == "forbidden" else 400, code, str(exc))
1426
+ row["markdown"] = semantic_rt.generated_markdown(row)
1427
+ return {"field": row}
1428
+
1429
+
1430
+ @router.post("/query/semantics/{database}/{field}/profile")
1431
+ def profile_semantic_field(database: str, field: str,
1432
+ session: Session = Depends(require_session)):
1433
+ """Profile values through Query's permissioned snapshot and persist only a bounded summary."""
1434
+ _semantic_authorize(session, database, require_answerable=True)
1435
+ baseline = _semantic_baseline(database)
1436
+ records = semantic_rt.load(session.runtime, baseline)
1437
+ try:
1438
+ current = records[semantic_rt.field_key(database, field)]
1439
+ except KeyError:
1440
+ raise err(404, "semantic_field_unknown", "that field is not in the database contract")
1441
+ if not session.admin:
1442
+ raise err(403, "forbidden", "only a tenant admin can profile semantic values")
1443
+ # Sensitive fields are redacted without reading one value. This order is part of the
1444
+ # contract: changing sensitivity cannot turn a profiling request into a disclosure.
1445
+ values = []
1446
+ if current.get("sensitivity") not in ("sensitive", "restricted"):
1447
+ snapshot = assistant_read_scope(session, database, fields=[field], filters=None)
1448
+ values = [row.get(field) for row in (snapshot.get("records") or ())]
1449
+ try:
1450
+ row = semantic_rt.set_value_profile(
1451
+ session.runtime, baseline, database, field, values,
1452
+ actor=session.uname, is_admin=session.admin)
1453
+ except semantic_rt.SemanticError as exc:
1454
+ raise err(400, "bad_semantic_contract", str(exc))
1455
+ row["markdown"] = semantic_rt.generated_markdown(row)
1456
+ return {"field": row}
1457
+
1458
+
1459
+ def _resume_b64(raw):
1460
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
1461
+
1462
+
1463
+ def _resume_unb64(value):
1464
+ encoded = str(value)
1465
+ decoded = base64.urlsafe_b64decode(encoded + "=" * (-len(encoded) % 4))
1466
+ if _resume_b64(decoded) != encoded:
1467
+ raise ValueError("resume token encoding is not canonical")
1468
+ return decoded
1469
+
1470
+
1471
+ def _resume_choices(approved):
1472
+ return [{"field": row["field"], "label": row["label"]}
1473
+ for row in list(approved.values())[:8]]
1474
+
1475
+
1476
+ def _mint_resume_token(session, database, question, choices, now=None):
1477
+ stamp = int(time.time() if now is None else now)
1478
+ claims = {"v": 1, "tenant": str(session.tenant), "user": str(session.uname),
1479
+ "database": str(database), "prompt": str(question),
1480
+ "choices": copy.deepcopy(choices), "issuedAt": stamp,
1481
+ "expiresAt": stamp + QUERY_RESUME_TTL_SECONDS}
1482
+ payload = json.dumps(claims, sort_keys=True, separators=(",", ":")).encode("utf-8")
1483
+ signature = hmac.new(_QUERY_RESUME_SECRET, payload, hashlib.sha256).digest()
1484
+ return f"{_resume_b64(payload)}.{_resume_b64(signature)}"
1485
+
1486
+
1487
+ def _verify_resume_token(token, session, database, question, approved, requested, now=None):
1488
+ """Authenticate one bounded clarification continuation before Query reads anything."""
1489
+ refused = lambda: err(403, "query_resume_refused",
1490
+ "that clarification cannot be resumed; ask Query again")
1491
+ if not isinstance(token, str) or token.count(".") != 1:
1492
+ raise refused()
1493
+ encoded, supplied = token.split(".", 1)
1494
+ try:
1495
+ payload = _resume_unb64(encoded)
1496
+ signature = _resume_unb64(supplied)
1497
+ except Exception:
1498
+ raise refused() from None
1499
+ expected = hmac.new(_QUERY_RESUME_SECRET, payload, hashlib.sha256).digest()
1500
+ if not hmac.compare_digest(signature, expected):
1501
+ raise refused()
1502
+ try:
1503
+ claims = json.loads(payload.decode("utf-8"))
1504
+ issued, expires = int(claims["issuedAt"]), int(claims["expiresAt"])
1505
+ except (KeyError, TypeError, ValueError, UnicodeDecodeError, json.JSONDecodeError):
1506
+ raise refused() from None
1507
+ stamp = int(time.time() if now is None else now)
1508
+ choices = _resume_choices(approved)
1509
+ expected_claims = {"v": 1, "tenant": str(session.tenant), "user": str(session.uname),
1510
+ "database": str(database), "prompt": str(question), "choices": choices}
1511
+ if (any(claims.get(key) != value for key, value in expected_claims.items())
1512
+ or expires - issued != QUERY_RESUME_TTL_SECONDS
1513
+ or stamp < issued or stamp >= expires
1514
+ or not requested
1515
+ or not set(requested).issubset({row["field"] for row in choices})):
1516
+ raise refused()
1517
+ return claims
1518
+
1519
+
1520
+ def _clarification(session, database, question, approved, now=None):
1521
+ choices = _resume_choices(approved)
1522
+ return {"status": "clarification", "alignmentQuestion": {
1523
+ "id": "align_fields", "question": "Which approved fields should this answer use?",
1524
+ "choices": choices, "maxSelections": 8},
1525
+ "resumeToken": _mint_resume_token(session, database, question, choices, now=now)}
1526
+
1527
+
1528
+ def _metric_dtos(offer, catalog):
1529
+ """Project compatible registered Metrics; channel variants are not registered Metric keys."""
1530
+ out, seen = [], set()
1531
+ for row in offer or ():
1532
+ if not isinstance(row, dict):
1533
+ continue
1534
+ key = str(row.get("key") or "")
1535
+ base = str(row.get("base_key") or key)
1536
+ metric = catalog.get(base) if isinstance(catalog, dict) else None
1537
+ if not key or base in seen or not isinstance(metric, dict):
1538
+ continue
1539
+ source = str(row.get("topic") or metric.get("topic") or "")
1540
+ if metric.get("topic") != source:
1541
+ continue
1542
+ seen.add(base)
1543
+ out.append({"key": base, "label": str(metric.get("label") or base),
1544
+ "description": str(metric.get("description") or ""),
1545
+ "format": str(metric.get("format") or ""), "source": source,
1546
+ "approved": True})
1547
+ return out
1548
+
1549
+
1550
+ def _compatible_metric_dtos(session, database):
1551
+ from core import perm_scope
1552
+ if not perm_scope.may_metrics(session.user, database):
1553
+ return []
1554
+ from harness import semantic as sem
1555
+ topic = sem.topic_for_grid(database)
1556
+ if not topic:
1557
+ return []
1558
+ return _metric_dtos(sem.entity_measures(topic), sem.metrics())
1559
+
1560
+
1561
+ @router.get("/query/metrics")
1562
+ def query_metrics(database: str = "", session: Session = Depends(require_session)):
1563
+ database = str(database or "").strip()
1564
+ if not database:
1565
+ raise err(400, "bad_request", "a database is required")
1566
+ _semantic_authorize(session, database)
1567
+ _semantic_records(session, database) # The same governed semantic source wall as Query.
1568
+ return {"metrics": _compatible_metric_dtos(session, database)}
1569
+
1570
+
1571
+ def _tool_spec(body, requested):
1572
+ supplied = body.get("view")
1573
+ if isinstance(supplied, dict):
1574
+ return copy.deepcopy(supplied)
1575
+ hidden = {str(value) for value in (body.get("hiddenFields") or ())}
1576
+ group = body.get("group")
1577
+ group_by = (str(group.get("field") or group.get("by") or "")
1578
+ if isinstance(group, dict) else str(group or ""))
1579
+ sorts = []
1580
+ for row in body.get("sorts") or ():
1581
+ if not isinstance(row, dict):
1582
+ continue
1583
+ sorts.append({"colId": str(row.get("colId") or row.get("field") or ""),
1584
+ "dir": "desc" if row.get("dir") == "desc"
1585
+ or row.get("direction") == "desc" else "asc"})
1586
+ return {"kind": str(body.get("kind") or "grid"), "name": "Query",
1587
+ "visible": [key for key in requested if key not in hidden],
1588
+ "filters": copy.deepcopy(body.get("filters") or []),
1589
+ "filterConj": "or" if body.get("filterConj") == "or" else "and",
1590
+ "sorts": sorts, "groupBy": group_by or None,
1591
+ "aggregation": copy.deepcopy(body.get("aggregation") or {"op": "count"})}
1592
+
1593
+
1594
+ def _tool_sort(rows, sorts):
1595
+ out = list(rows)
1596
+ for rule in reversed(sorts or []):
1597
+ key = rule.get("colId")
1598
+ if not key:
1599
+ continue
1600
+ present = [row for row in out if row.get(key) is not None]
1601
+ missing = [row for row in out if row.get(key) is None]
1602
+ present.sort(key=lambda row: ((0, float(row[key])) if isinstance(row.get(key), (int, float))
1603
+ and not isinstance(row.get(key), bool)
1604
+ else (1, str(row.get(key)).casefold())),
1605
+ reverse=rule.get("dir") == "desc")
1606
+ out = present + missing
1607
+ return out
1608
+
1609
+
1610
+ def _tool_groups(rows, view):
1611
+ key = view.get("groupBy")
1612
+ if not key:
1613
+ return []
1614
+ grouped = {}
1615
+ for row in rows:
1616
+ value = row.get(key)
1617
+ grouped.setdefault(str(value) if value is not None else "(blank)", []).append(row)
1618
+ return [{"value": value, "numeric": _numeric_result(view, members)}
1619
+ for value, members in sorted(grouped.items(), key=lambda item: item[0].casefold())]
1620
+
1621
+
1622
+ def _tool_wording(question, numeric, count, group_count=0):
1623
+ value = numeric.get("value")
1624
+ if isinstance(value, float) and value.is_integer():
1625
+ value = int(value)
1626
+ shown = "blank" if value is None else (f"{value:,}" if isinstance(value, (int, float)) else str(value))
1627
+ grouped = f" in {group_count} groups" if group_count else ""
1628
+ return (f"For {question}: {numeric.get('label') or 'Result'} is {shown} across "
1629
+ f"{count:,} matching record" + ("" if count == 1 else "s") + grouped + ".")
1630
+
1631
+
1632
+ def _tool_formula_snapshot(body, snapshot, requested):
1633
+ definitions = body.get("formulas")
1634
+ if definitions in (None, {}):
1635
+ return snapshot, {}
1636
+ if not isinstance(definitions, dict):
1637
+ raise err(400, "bad_formula", "formulas must be an object keyed by approved field")
1638
+ cleaned = {}
1639
+ for field, definition in definitions.items():
1640
+ field = str(field or "")
1641
+ if field not in requested or not isinstance(definition, dict):
1642
+ raise err(400, "bad_formula", "every formula must target a requested approved field")
1643
+ refs = list(definition.get("refs") or ())
1644
+ if not set(refs).issubset(set(requested)):
1645
+ raise err(403, "semantic_field_unapproved",
1646
+ "a formula references a field outside the approved request")
1647
+ try:
1648
+ formula_rt.evaluate(definition, {}, strict=True)
1649
+ except formula_rt.FormulaError as exc:
1650
+ raise err(400, "bad_formula", str(exc))
1651
+ cleaned[field] = copy.deepcopy(definition)
1652
+ projected = copy.deepcopy(snapshot)
1653
+ projected_rows = []
1654
+ for row in snapshot.get("records") or ():
1655
+ result = formula_rt.evaluate_fields(cleaned, row)
1656
+ if any(reason == "cycle" for reason in result["errors"].values()):
1657
+ raise err(400, "bad_formula", "formula dependencies contain a cycle")
1658
+ projected_rows.append({**row, **result["values"]})
1659
+ projected["records"] = projected_rows
1660
+ return projected, cleaned
1661
+
1662
+
1663
+ def _tool_plan(question, body, snapshot, session):
1664
+ """Use the existing governed planner only when a channel did not supply typed artifacts."""
1665
+ artifact_keys = {"view", "filters", "sorts", "group", "hiddenFields", "aggregation", "kind"}
1666
+ if any(key in body for key in artifact_keys):
1667
+ return _tool_spec(body, [field["key"] for field in snapshot.get("fields") or ()]), None, None
1668
+ selected_model = str(body.get("model") or MODEL_AUTO).strip().lower()
1669
+ if selected_model not in model_choices():
1670
+ raise err(400, "unknown_model", "that model is not available in Query")
1671
+ spec, said, provider, reason = _call_model(
1672
+ question, snapshot, model=selected_model, chat=None, history=None, session=session)
1673
+ if spec is None:
1674
+ return None, (said or "Query could not build an answer"), provider
1675
+ return spec, said, provider
1676
+
1677
+
1678
+ @router.post("/query/tool")
1679
+ def governed_query(body: dict = Body(default=None),
1680
+ session: Session = Depends(require_session)):
1681
+ """Deterministic Query substrate; it never knows or calls a model/provider."""
1682
+ body = body if isinstance(body, dict) else {}
1683
+ database = str(body.get("database") or "").strip()
1684
+ question = " ".join(str(body.get("prompt") or body.get("question") or "").split())
1685
+ if not database or not question:
1686
+ raise err(400, "bad_request", "a database and prompt are required")
1687
+ if len(question) > MAX_QUESTION:
1688
+ raise err(400, "question_too_long", f"a prompt must be under {MAX_QUESTION} characters")
1689
+ _semantic_authorize(session, database, require_answerable=True)
1690
+ records = _semantic_records(session, database)
1691
+ approved = semantic_rt.approved_fields(records, database)
1692
+ if not approved:
1693
+ raise err(409, "query_semantics_unconfigured",
1694
+ "this database has no approved semantic fields yet")
1695
+ raw_requested = body.get("fieldKeys")
1696
+ if raw_requested is not None and not isinstance(raw_requested, list):
1697
+ raise err(400, "bad_request", "fieldKeys must be a list")
1698
+ requested = list(dict.fromkeys(str(x) for x in (raw_requested or ()) if str(x)))
1699
+ if not requested:
1700
+ return _clarification(session, database, question, approved)
1701
+ _verify_resume_token(body.get("resumeToken"), session, database, question,
1702
+ approved, requested)
1703
+ try:
1704
+ selected = [semantic_rt.require_approved(records, database, key) for key in requested]
1705
+ except semantic_rt.SemanticError as exc:
1706
+ raise err(403, "semantic_field_unapproved", str(exc))
1707
+ snapshot = assistant_read_scope(session, database, fields=requested, filters=None)
1708
+ snapshot, formulas = _tool_formula_snapshot(body, snapshot, requested)
1709
+ spec, planned_wording, provider = _tool_plan(question, body, snapshot, session)
1710
+ if spec is None:
1711
+ return {"status": "refused", "wording": planned_wording,
1712
+ "speakable": planned_wording, "artifacts": None,
1713
+ "model": _model_identity(provider)}
1714
+ view, refusal, refusal_code = _validate(spec, snapshot.get("fields") or selected)
1715
+ if view is None:
1716
+ raise err(400, refusal_code or "bad_query_artifact", refusal or "that Query is invalid")
1717
+ filtered = _view_records(snapshot, view)
1718
+ ordered = _tool_sort(filtered, view.get("sorts"))
1719
+ rows = ordered[:50]
1720
+ row_ids = [str(row.get("pid") or row.get("id") or index)
1721
+ for index, row in enumerate(rows)]
1722
+ hidden = [key for key in requested if key not in set(view.get("visible") or ())]
1723
+ groups = _tool_groups(ordered, view)
1724
+ numeric = _numeric_result(view, ordered)
1725
+ artifacts = {"filters": _safe(view.get("filters") or []),
1726
+ "sorts": _safe(view.get("sorts") or []),
1727
+ "group": _safe(view.get("groupBy")),
1728
+ "hiddenFields": hidden,
1729
+ "formulas": _safe(formulas),
1730
+ "source": {"database": database, "fields": requested,
1731
+ "permissionScopeApplied": True}}
1732
+ wording = _tool_wording(question, numeric, len(ordered), len(groups))
1733
+ return {"status": "answered", "wording": wording, "speakable": wording,
1734
+ "citations": [{"database": database, "rowId": value} for value in row_ids],
1735
+ "rows": [{key: row.get(key) for key in view["visible"]} for row in rows],
1736
+ "groups": groups, "numeric": numeric,
1737
+ "artifacts": artifacts, "semanticRouter": semantic_rt.router_projection(records, database),
1738
+ "model": _model_identity(provider)}
1739
+
1740
+
1741
+ @router.post("/query/formulas/parse")
1742
+ def parse_formula(body: dict = Body(default=None), session: Session = Depends(require_session)):
1743
+ try:
1744
+ definition = formula_rt.parse_formula((body or {}).get("source"))
1745
+ return {"contractVersion": formula_rt.CONTRACT_VERSION,
1746
+ "astVersion": formula_rt.AST_VERSION,
1747
+ "authority": formula_rt.AUTHORITY,
1748
+ "definition": definition}
1749
+ except formula_rt.FormulaError as exc:
1750
+ raise err(400, "bad_formula", str(exc))
1751
+
1752
+
1753
+ @router.get("/query/formulas/fixtures")
1754
+ def formula_fixtures(session: Session = Depends(require_session)):
1755
+ return {**formula_rt.contract_dto(),
1756
+ "transport": {
1757
+ "parse": {"method": "POST", "path": "/api/v1/query/formulas/parse"},
1758
+ "evaluate": {"method": "POST", "path": "/api/v1/query/formulas/evaluate"},
1759
+ }}
1760
+
1761
+
1762
+ @router.post("/query/formulas/evaluate")
1763
+ def evaluate_formula(body: dict = Body(default=None),
1764
+ session: Session = Depends(require_session)):
1765
+ body = body if isinstance(body, dict) else {}
1766
+ try:
1767
+ if "definitions" in body or "rows" in body:
1768
+ if "definition" in body or "row" in body:
1769
+ raise formula_rt.FormulaError(
1770
+ "single and batch formula payloads cannot be mixed")
1771
+ return formula_rt.evaluate_batch(
1772
+ body.get("definitions"), body.get("rows"),
1773
+ consumer=str(body.get("consumer") or ""), today=body.get("today"),
1774
+ field_revisions=body.get("fieldRevisions") or {})
1775
+ definition = body.get("definition")
1776
+ if not isinstance(definition, dict):
1777
+ raise formula_rt.FormulaError("a parsed formula definition is required")
1778
+ if not isinstance(body.get("row", {}), dict):
1779
+ raise formula_rt.FormulaError("formula row must be an object")
1780
+ result = formula_rt.evaluate_result(
1781
+ definition, body.get("row") or {}, today=body.get("today"), strict=True)
1782
+ except formula_rt.FormulaError as exc:
1783
+ raise err(400, "bad_formula", str(exc))
1784
+ return {"contractVersion": formula_rt.CONTRACT_VERSION,
1785
+ "astVersion": formula_rt.AST_VERSION,
1786
+ "authority": formula_rt.AUTHORITY,
1787
+ **result,
1788
+ "recalculation": formula_rt.explain_recalculation(
1789
+ definition, body.get("fieldRevisions") or {})}
1790
+
1791
+
1792
+ def validate_timeseries_contract(body, records=None, approved_metric_keys=None):
1793
+ """Metric-first Time Series contract, pure so frontend fixtures can consume it."""
1794
+ body = body if isinstance(body, dict) else {}
1795
+ series = body.get("series") if isinstance(body.get("series"), list) else []
1796
+ if not series:
1797
+ raise ValueError("at least one series is required")
1798
+ metric_keys = set(approved_metric_keys or ())
1799
+ first = series[0] if isinstance(series[0], dict) else {}
1800
+ if first.get("kind") != "metric" or first.get("key") not in metric_keys:
1801
+ raise ValueError("the first Time Series series must be an approved compatible Metric")
1802
+ normalized = [{"kind": "metric", "key": first["key"]}]
1803
+ for index, item in enumerate(series[1:], 2):
1804
+ item = item if isinstance(item, dict) else {}
1805
+ if item.get("kind") == "metric" and item.get("key") in metric_keys:
1806
+ normalized.append({"kind": "metric", "key": item["key"]})
1807
+ continue
1808
+ if item.get("kind") != "field" or not item.get("key") or item.get("aggregation") not in (
1809
+ "sum", "avg", "min", "max", "count", "count_distinct"):
1810
+ raise ValueError(f"series {index} needs a Metric or a valid field aggregation")
1811
+ if not item.get("dateField"):
1812
+ raise ValueError(f"series {index} needs an explicit Date field")
1813
+ if records is not None:
1814
+ value_row = semantic_rt.require_approved(
1815
+ records, body.get("database"), item.get("key"))
1816
+ date_row = semantic_rt.require_approved(records, body.get("database"), item.get("dateField"))
1817
+ if date_row.get("dataType") not in ("date", "datetime"):
1818
+ raise ValueError(f"series {index} dateField is not a Date or Date-time")
1819
+ if item.get("aggregation") in ("sum", "avg", "min", "max") and (
1820
+ value_row.get("dataType") not in ("int", "currency", "pct", "formula")):
1821
+ raise ValueError(f"series {index} aggregation needs a numeric Field")
1822
+ normalized.append({"kind": "field", "key": item["key"],
1823
+ "aggregation": item["aggregation"],
1824
+ "dateField": item["dateField"]})
1825
+ return {"version": 1, "series": normalized,
1826
+ "formulaEvaluation": {
1827
+ "contractVersion": formula_rt.CONTRACT_VERSION,
1828
+ "astVersion": formula_rt.AST_VERSION,
1829
+ "authority": formula_rt.AUTHORITY,
1830
+ "consumer": "timeseries",
1831
+ "method": "POST",
1832
+ "path": "/api/v1/query/formulas/evaluate",
1833
+ "mode": "batch",
1834
+ }}
1835
+
1836
+
1837
+ @router.post("/query/timeseries/validate")
1838
+ def validate_timeseries(body: dict = Body(default=None),
1839
+ session: Session = Depends(require_session)):
1840
+ body = body if isinstance(body, dict) else {}
1841
+ database = str(body.get("database") or "").strip()
1842
+ if not database:
1843
+ raise err(400, "bad_timeseries", "a database is required")
1844
+ _semantic_authorize(session, database)
1845
+ records = _semantic_records(session, database)
1846
+ approved_metrics = {row["key"] for row in _compatible_metric_dtos(session, database)}
1847
+ try:
1848
+ return validate_timeseries_contract(body, records, approved_metrics)
1849
+ except (ValueError, semantic_rt.SemanticError) as exc:
1850
+ raise err(400, "bad_timeseries", str(exc))
1851
+
1852
+
1853
  @router.delete("/query/threads/{tid}")
1854
  def delete_thread(tid: str, session: Session = Depends(require_session)):
1855
  """Remove one of the caller's own chats, and only the chat.
api/routes_starred.py CHANGED
@@ -44,7 +44,7 @@ router = APIRouter(prefix="/api/v1")
44
  _STARRED_KEY = "starred"
45
 
46
  #: The four kinds C2 declares. `view` is the odd one out — see the header.
47
- KINDS = ("database", "agent", "query", "view")
48
 
49
  #: The three kinds this file's own bucket holds, and the payload key each answers under.
50
  _LIST_KINDS = {"database": "databases", "agent": "agents", "query": "queries"}
@@ -289,9 +289,20 @@ def _payload(session, keys=None, cache=None):
289
  if qresolved:
290
  lists["queries"] = [q for q in lists["queries"] if q in qnames]
291
  views, unread = _starred_views(session, keys, cache=cache)
 
 
 
 
 
 
 
 
 
 
 
292
  out = {"databases": lists["databases"], "agents": lists["agents"],
293
  "queries": lists["queries"], "queryNames": qnames,
294
- "views": views, "degraded": unread}
295
  if unread:
296
  # R6's second sentence, in the payload: the CAUSE and what it means, not a bare list.
297
  out["note"] = (f"{len(unread)} database(s) could not be read in time, so a view you "
@@ -497,6 +508,24 @@ def set_starred(body: dict = Body(default=None),
497
  cache = _refresh_one(session, cache, db_key)
498
  return _payload(session, cache=cache)
499
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
500
  field = _LIST_KINDS[kind]
501
  uname = session.uname
502
  # ⛔ THE CAP IS ENFORCED INSIDE THE TRANSACTION, NOT BY A READ BEFORE IT, AND THAT IS NOT
 
44
  _STARRED_KEY = "starred"
45
 
46
  #: The four kinds C2 declares. `view` is the odd one out — see the header.
47
+ KINDS = ("database", "agent", "query", "view", "application")
48
 
49
  #: The three kinds this file's own bucket holds, and the payload key each answers under.
50
  _LIST_KINDS = {"database": "databases", "agent": "agents", "query": "queries"}
 
289
  if qresolved:
290
  lists["queries"] = [q for q in lists["queries"] if q in qnames]
291
  views, unread = _starred_views(session, keys, cache=cache)
292
+ try:
293
+ import application_registry
294
+ import routes_assets
295
+ application_databases = routes_assets._application_databases(session.runtime)
296
+ allowed_databases, _ = routes_assets.application_access_context(
297
+ session, application_databases)
298
+ application_rows = application_registry.list_apps(
299
+ session.runtime, session.uname, session.admin, starred=True,
300
+ allowed_databases=allowed_databases)
301
+ except Exception:
302
+ application_rows = []
303
  out = {"databases": lists["databases"], "agents": lists["agents"],
304
  "queries": lists["queries"], "queryNames": qnames,
305
+ "views": views, "applications": application_rows, "degraded": unread}
306
  if unread:
307
  # R6's second sentence, in the payload: the CAUSE and what it means, not a bare list.
308
  out["note"] = (f"{len(unread)} database(s) could not be read in time, so a view you "
 
508
  cache = _refresh_one(session, cache, db_key)
509
  return _payload(session, cache=cache)
510
 
511
+ if kind == "application":
512
+ try:
513
+ import application_registry
514
+ import routes_assets
515
+ application_databases = routes_assets._application_databases(session.runtime, oid)
516
+ allowed_databases, _ = routes_assets.application_access_context(
517
+ session, application_databases)
518
+ if not allowed_databases:
519
+ raise application_registry.ApplicationError("application does not exist")
520
+ application_registry.mutate(session.runtime, oid, session.uname, session.admin,
521
+ {"starred": on}, allowed_databases=allowed_databases)
522
+ except PermissionError as exc:
523
+ raise err(403, "forbidden", str(exc))
524
+ except Exception:
525
+ # Same 404 for absent and unreadable, so an id guess is not an oracle.
526
+ raise err(404, "unknown_application", "that Application is not available")
527
+ return _payload(session)
528
+
529
  field = _LIST_KINDS[kind]
530
  uname = session.uname
531
  # ⛔ THE CAP IS ENFORCED INSIDE THE TRANSACTION, NOT BY A READ BEFORE IT, AND THAT IS NOT
api/routes_tables.py CHANGED
@@ -1315,11 +1315,15 @@ def ut_assembly(session: Session, table_key: str, storage_key: str = "",
1315
  # W43C C2: store compact recurrence configuration, then derive next/preview under the
1316
  # request's server day only after every field stratum is merged.
1317
  _recurrence_today = time.strftime("%Y-%m-%d")
 
 
1318
 
1319
  def _wire_recurrence(field):
1320
  if not isinstance(field, dict) or field.get("type") != "date":
1321
  return field
1322
- payload = aios_grid.recurrence_payload(field.get("recurrence"), today=_recurrence_today)
 
 
1323
  return dict(field, recurrence=payload) if payload else field
1324
 
1325
  fields = [_wire_recurrence(field) for field in fields]
@@ -1407,6 +1411,7 @@ def ut_assembly(session: Session, table_key: str, storage_key: str = "",
1407
  # so the closure covers this user's `custom_` and `measure_` columns too.
1408
  fields = _ut_contract_fields(table_key, fields, st=st)
1409
  fields, rows_src, hidden = _ut_field_wall(session, table_key, fields, rows_src, st=st)
 
1410
  if hidden and shared_cells:
1411
  # ⛔ BOTH WIRES, AND THE SHARED STRATUM IS A THIRD ONE. `strip_row` above cleaned the
1412
  # DEFINITION rows; these cells arrived by a different door and one narrowing cannot speak
@@ -1923,9 +1928,22 @@ def create_table(body: dict = Body(default=None),
1923
  if option_refusal:
1924
  raise err(400, "refused", option_refusal)
1925
  source = body.get("source")
 
 
 
 
 
 
 
 
 
 
1926
  try:
1927
- key = ut.create(label, session.uname, fields=body.get("fields"),
1928
- source=source, st=session.runtime)
 
 
 
1929
  except Exception:
1930
  raise err(503, "store_unavailable",
1931
  "the tenant store refused the write. Nothing was created")
@@ -2320,6 +2338,9 @@ def add_row(table_key: str, body: dict = Body(default=None),
2320
  values = (body or {}).get("values") or {}
2321
  if not isinstance(values, dict):
2322
  raise err(400, "bad_values", "values must be an object of {fieldKey: value}")
 
 
 
2323
  try:
2324
  rid = ut.add_row(table_key, values, session.uname, st=session.runtime,
2325
  rid=(body or {}).get("rid"))
@@ -2373,6 +2394,9 @@ def import_rows(table_key: str, body: dict = Body(default=None),
2373
  defn = _defn_or_refuse(session, table_key)
2374
  by_key = {f["key"]: f for f in (defn.get("fields") or [])}
2375
  asked = {k for r in rows_in for k in r}
 
 
 
2376
  unknown = sorted(k for k in asked if k not in by_key)
2377
  if unknown:
2378
  raise err(400, "unknown_field",
@@ -2469,7 +2493,15 @@ def add_field(table_key: str, body: dict = Body(default=None),
2469
  _managed_or_refuse(session, table_key, mutation=True)
2470
  _field_or_refuse(session, table_key)
2471
  ut = _ut()
2472
- field = ut.add_field(table_key, body or {}, st=session.runtime)
 
 
 
 
 
 
 
 
2473
  if not field:
2474
  # ⭐ D-46 CLOSED (wave 23) — the C8 flow law gets its OWN sentence. `add_field` answers
2475
  # None for every refusal, so this route said "check the name and type" to somebody whose
@@ -2592,6 +2624,8 @@ def patch_field(table_key: str, fkey: str, body: dict = Body(default=None),
2592
  _field_or_refuse(session, table_key, fkey)
2593
  ut = _ut()
2594
  body = body or {}
 
 
2595
  if 'deletionLocked' in body and not session.admin:
2596
  raise err(403, "owner_required", "only an Owner can change a field deletion lock")
2597
  migrated = None
@@ -2613,7 +2647,13 @@ def patch_field(table_key: str, fkey: str, body: dict = Body(default=None),
2613
  migrated = dict(migrated or {}, workspace=True)
2614
  except Exception: # noqa: BLE001
2615
  migrated = dict(migrated or {}, workspace=False)
2616
- field = ut.patch_field(table_key, fkey, body, st=session.runtime)
 
 
 
 
 
 
2617
  if not field:
2618
  # C3: the same narrator as `add_field`. Flagging a SECOND column is the same act as
2619
  # adding one, so it must get the same sentence naming the column that already holds the
@@ -2878,6 +2918,9 @@ def patch_row(table_key: str, pid: int, body: dict = Body(default=None),
2878
  updates = dict(body or {})
2879
  if not updates:
2880
  raise err(400, "empty_patch", "no fields to update")
 
 
 
2881
  _managed_or_refuse(session, table_key, mutation=True)
2882
  _records_or_refuse(session, table_key)
2883
  g = ut_assembly(session, table_key, consume_corrections=False)
@@ -2893,7 +2936,7 @@ def patch_row(table_key: str, pid: int, body: dict = Body(default=None),
2893
  st=session.runtime, # R6b (D-16)
2894
  scope_key=table_key, table=_ops(session, table_key))
2895
  try:
2896
- grid_events.handle_one(
2897
  {"id": f"patch:{table_key}:{pid}:{time.time_ns()}", "type": "overlay_patch",
2898
  "pid": pid, "updates": updates}, ctx)
2899
  except grid_events.StoreUnavailable:
@@ -2994,6 +3037,100 @@ def patch_row(table_key: str, pid: int, body: dict = Body(default=None),
2994
  return out
2995
 
2996
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2997
  # ── CONTRACT C1 (W36-T20): THE MIRROR READER ──────────────────────────────────────────────────
2998
  # ⭐⭐ R6. `core.perm_scope.scoped_table` is the ONE door to any database's rows and it answers for
2999
  # a MATERIALISED `ut_*` table entirely on its own — deliberately, so a cold process (E's sandbox
 
1315
  # W43C C2: store compact recurrence configuration, then derive next/preview under the
1316
  # request's server day only after every field stratum is merged.
1317
  _recurrence_today = time.strftime("%Y-%m-%d")
1318
+ _recurrence_keys = {str(field.get("key")) for field in fields
1319
+ if isinstance(field, dict) and field.get("key")}
1320
 
1321
  def _wire_recurrence(field):
1322
  if not isinstance(field, dict) or field.get("type") != "date":
1323
  return field
1324
+ payload = aios_grid.recurrence_payload(
1325
+ field.get("recurrence"), today=_recurrence_today,
1326
+ condition_fields=_recurrence_keys)
1327
  return dict(field, recurrence=payload) if payload else field
1328
 
1329
  fields = [_wire_recurrence(field) for field in fields]
 
1411
  # so the closure covers this user's `custom_` and `measure_` columns too.
1412
  fields = _ut_contract_fields(table_key, fields, st=st)
1413
  fields, rows_src, hidden = _ut_field_wall(session, table_key, fields, rows_src, st=st)
1414
+ fields = aios_grid.project_date_recurrences(fields, today=_recurrence_today)
1415
  if hidden and shared_cells:
1416
  # ⛔ BOTH WIRES, AND THE SHARED STRATUM IS A THIRD ONE. `strip_row` above cleaned the
1417
  # DEFINITION rows; these cells arrived by a different door and one narrowing cannot speak
 
1928
  if option_refusal:
1929
  raise err(400, "refused", option_refusal)
1930
  source = body.get("source")
1931
+ raw_fields = list(body.get("fields") or [])
1932
+ # Normalise the initial schema once without recurrence. Anchors and conditions are then
1933
+ # checked against the fields that would actually survive this create, never the raw list.
1934
+ base_fields = ut.clean_fields([
1935
+ {key: value for key, value in field.items() if key != "recurrence"}
1936
+ for field in raw_fields if isinstance(field, dict)
1937
+ ]) or []
1938
+ from routes_grid import govern_date_recurrence
1939
+ recurrence_validator = lambda raw: govern_date_recurrence(
1940
+ session, "same", base_fields, raw)
1941
  try:
1942
+ key = ut.create(label, session.uname, fields=raw_fields,
1943
+ source=source, st=session.runtime,
1944
+ recurrence_validator=recurrence_validator)
1945
+ except ValueError as exc:
1946
+ raise err(400, "bad_recurrence", str(exc))
1947
  except Exception:
1948
  raise err(503, "store_unavailable",
1949
  "the tenant store refused the write. Nothing was created")
 
2338
  values = (body or {}).get("values") or {}
2339
  if not isinstance(values, dict):
2340
  raise err(400, "bad_values", "values must be an object of {fieldKey: value}")
2341
+ if ut.ZONE_FIELD_KEY in values or "zone" in values:
2342
+ raise err(400, "zone_membership_read_only",
2343
+ "Zone membership is worked out from the record's current location")
2344
  try:
2345
  rid = ut.add_row(table_key, values, session.uname, st=session.runtime,
2346
  rid=(body or {}).get("rid"))
 
2394
  defn = _defn_or_refuse(session, table_key)
2395
  by_key = {f["key"]: f for f in (defn.get("fields") or [])}
2396
  asked = {k for r in rows_in for k in r}
2397
+ if ut.ZONE_FIELD_KEY in asked or "zone" in asked:
2398
+ raise err(400, "zone_membership_read_only",
2399
+ "Zone membership is worked out from current record coordinates")
2400
  unknown = sorted(k for k in asked if k not in by_key)
2401
  if unknown:
2402
  raise err(400, "unknown_field",
 
2493
  _managed_or_refuse(session, table_key, mutation=True)
2494
  _field_or_refuse(session, table_key)
2495
  ut = _ut()
2496
+ from routes_grid import govern_date_recurrence
2497
+ visible_fields = ut_write_ctx(session, table_key)["fields"]
2498
+ try:
2499
+ field = ut.add_field(
2500
+ table_key, body or {}, st=session.runtime,
2501
+ recurrence_validator=lambda raw: govern_date_recurrence(
2502
+ session, table_key, visible_fields, raw))
2503
+ except ValueError as exc:
2504
+ raise err(400, "bad_recurrence", str(exc))
2505
  if not field:
2506
  # ⭐ D-46 CLOSED (wave 23) — the C8 flow law gets its OWN sentence. `add_field` answers
2507
  # None for every refusal, so this route said "check the name and type" to somebody whose
 
2624
  _field_or_refuse(session, table_key, fkey)
2625
  ut = _ut()
2626
  body = body or {}
2627
+ from routes_grid import govern_date_recurrence
2628
+ visible_fields = ut_write_ctx(session, table_key)["fields"]
2629
  if 'deletionLocked' in body and not session.admin:
2630
  raise err(403, "owner_required", "only an Owner can change a field deletion lock")
2631
  migrated = None
 
2647
  migrated = dict(migrated or {}, workspace=True)
2648
  except Exception: # noqa: BLE001
2649
  migrated = dict(migrated or {}, workspace=False)
2650
+ try:
2651
+ field = ut.patch_field(
2652
+ table_key, fkey, body, st=session.runtime,
2653
+ recurrence_validator=lambda raw: govern_date_recurrence(
2654
+ session, table_key, visible_fields, raw))
2655
+ except ValueError as exc:
2656
+ raise err(400, "bad_recurrence", str(exc))
2657
  if not field:
2658
  # C3: the same narrator as `add_field`. Flagging a SECOND column is the same act as
2659
  # adding one, so it must get the same sentence naming the column that already holds the
 
2918
  updates = dict(body or {})
2919
  if not updates:
2920
  raise err(400, "empty_patch", "no fields to update")
2921
+ if _ut().ZONE_FIELD_KEY in updates or "zone" in updates:
2922
+ raise err(403, "zone_membership_read_only",
2923
+ "Zone membership is worked out from the record's current location")
2924
  _managed_or_refuse(session, table_key, mutation=True)
2925
  _records_or_refuse(session, table_key)
2926
  g = ut_assembly(session, table_key, consume_corrections=False)
 
2936
  st=session.runtime, # R6b (D-16)
2937
  scope_key=table_key, table=_ops(session, table_key))
2938
  try:
2939
+ refused = grid_events.handle_one(
2940
  {"id": f"patch:{table_key}:{pid}:{time.time_ns()}", "type": "overlay_patch",
2941
  "pid": pid, "updates": updates}, ctx)
2942
  except grid_events.StoreUnavailable:
 
3037
  return out
3038
 
3039
 
3040
+ @router.get("/tables/{table_key}/history")
3041
+ def table_history(table_key: str, rowId: str = Query(default=""),
3042
+ retentionDays: int = Query(default=30),
3043
+ session: Session = Depends(require_session)):
3044
+ g = ut_write_ctx(session, table_key)
3045
+ if rowId and (not str(rowId).isdigit() or int(rowId) not in g["pids"]):
3046
+ raise err(403, "out_of_scope", "that row is not in this database")
3047
+ import core.platform_admin as platform_admin
3048
+ try:
3049
+ history = _ut().value_history(
3050
+ table_key, rowId or None, st=session.runtime, retention_days=retentionDays,
3051
+ extended_entitled=platform_admin.is_platform_admin(session.user))
3052
+ return _ut().project_value_history(history, g["pids"], g.get("hidden") or ())
3053
+ except PermissionError as exc:
3054
+ raise err(403, "history_entitlement_required", str(exc))
3055
+ except ValueError as exc:
3056
+ raise err(400, "bad_history_retention", str(exc))
3057
+
3058
+
3059
+ @router.post("/tables/{table_key}/history/{event_id}/restore")
3060
+ def restore_history(table_key: str, event_id: str, body: dict = Body(default=None),
3061
+ session: Session = Depends(require_session)):
3062
+ from core import grid_events
3063
+
3064
+ _managed_or_refuse(session, table_key, mutation=True)
3065
+ _records_or_refuse(session, table_key)
3066
+ body = body if isinstance(body, dict) else {}
3067
+ row_id = str(body.get("rowId") or "").strip()
3068
+ if not row_id:
3069
+ raise err(400, "row_required", "choose a record to restore")
3070
+ g = ut_write_ctx(session, table_key)
3071
+ if not row_id.isdigit() or int(row_id) not in g["pids"]:
3072
+ raise err(403, "out_of_scope", "that row is not in this database")
3073
+ field_key = str(body.get("field") or "").strip() or None
3074
+ if field_key and field_key in (g.get("hidden") or ()):
3075
+ raise err(403, "field_hidden", "that field is not available to your account")
3076
+ import core.platform_admin as platform_admin
3077
+ try:
3078
+ days = int(body.get("retentionDays") or _ut().HISTORY_RETENTION_DAYS)
3079
+ except (TypeError, ValueError):
3080
+ raise err(400, "bad_history_retention", "history retention must be 30 or 90 days")
3081
+ entitled = platform_admin.is_platform_admin(session.user)
3082
+ try:
3083
+ updates = _ut().history_restore_values(
3084
+ table_key, row_id, event_id, field_key=field_key,
3085
+ st=session.runtime, retention_days=days,
3086
+ extended_entitled=entitled)
3087
+ except PermissionError as exc:
3088
+ raise err(403, "history_entitlement_required", str(exc))
3089
+ except ValueError as exc:
3090
+ raise err(400, "bad_history_retention", str(exc))
3091
+ if updates is None:
3092
+ raise err(404, "history_event_not_found", "that retained value version is unavailable")
3093
+ if any(key in (g.get("hidden") or ()) for key in updates):
3094
+ raise err(403, "field_hidden", "that retained version includes a hidden field")
3095
+ prior_history_ids = {
3096
+ str(item.get("id")) for item in _ut().value_history(
3097
+ table_key, row_id, st=session.runtime, retention_days=days,
3098
+ extended_entitled=entitled).get("events", [])
3099
+ }
3100
+ stored_before = dict((((_ut().get(table_key, st=session.runtime) or {}).get("rows") or {})
3101
+ .get(row_id)) or {})
3102
+ ctx = grid_events.EventCtx(
3103
+ uname=session.uname, allowed_pids=g["pids"], fields=g["fields"],
3104
+ admin=session.admin, fallback_ws=None, seen_ids={},
3105
+ hidden_keys=g.get("hidden") or frozenset(), history_kind="restore",
3106
+ st=session.runtime, scope_key=table_key, table=_ops(session, table_key))
3107
+ try:
3108
+ grid_events.handle_one(
3109
+ {"id": f"restore:{event_id}:{time.time_ns()}", "type": "overlay_patch",
3110
+ "pid": int(row_id), "updates": updates}, ctx)
3111
+ except grid_events.StoreUnavailable:
3112
+ raise err(503, "store_unavailable", "the retained version was not restored")
3113
+ stored = dict((((_ut().get(table_key, st=session.runtime) or {}).get("rows") or {})
3114
+ .get(row_id)) or {})
3115
+ landed = all((key not in stored if value is None else stored.get(key) == str(value))
3116
+ for key, value in updates.items())
3117
+ newest = _ut().project_value_history(_ut().value_history(
3118
+ table_key, row_id, st=session.runtime, retention_days=days,
3119
+ extended_entitled=entitled), g["pids"], g.get("hidden") or ())
3120
+ restore_event = next((item for item in newest["events"]
3121
+ if item.get("kind") == "restore"
3122
+ and str(item.get("id")) not in prior_history_ids), None)
3123
+ changed_keys = {
3124
+ key for key, value in updates.items()
3125
+ if (key in stored_before if value is None else stored_before.get(key) != str(value))
3126
+ }
3127
+ audited = (not changed_keys or (restore_event is not None
3128
+ and changed_keys.issubset(set(restore_event.get("changes") or {}))))
3129
+ if not landed or not audited:
3130
+ raise err(403, "restore_refused", "the retained version is outside your write authority")
3131
+ return {"row": stored, "event": restore_event}
3132
+
3133
+
3134
  # ── CONTRACT C1 (W36-T20): THE MIRROR READER ──────────────────────────────────────────────────
3135
  # ⭐⭐ R6. `core.perm_scope.scoped_table` is the ONE door to any database's rows and it answers for
3136
  # a MATERIALISED `ut_*` table entirely on its own — deliberately, so a cold process (E's sandbox
api/routes_templates.py CHANGED
@@ -84,6 +84,23 @@ def list_templates(table: str = "", session: Session = Depends(require_session))
84
  return {"table": table, "templates": vt.offer(fields, source or None)}
85
 
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  @router.post("/templates/{key}/apply")
88
  def apply_template(key: str, body: dict = Body(default=None),
89
  session: Session = Depends(require_session)):
@@ -112,7 +129,7 @@ def apply_template(key: str, body: dict = Body(default=None),
112
  raise err(404, "unknown_table", "that database does not exist")
113
  if not session.runtime.available():
114
  raise err(503, "store_unavailable",
115
- "the tenant store is unavailable — nothing was applied")
116
  import core.table_store as table_store
117
  ops = table_store.make(ws_key, st=session.runtime)
118
  applied = []
 
84
  return {"table": table, "templates": vt.offer(fields, source or None)}
85
 
86
 
87
+ @router.get("/templates/application-defaults")
88
+ def application_defaults(table: str = "", session: Session = Depends(require_session)):
89
+ """Deterministic starting Application for a new View, by type.
90
+
91
+ The View creator consumes only the returned reference. It never clones the Application's
92
+ config into the View, so two Views remain attached to one reusable asset.
93
+ """
94
+ _target_or_refuse(session, table)
95
+ import application_registry
96
+ return {"table": table, "defaults": {
97
+ kind: application_registry.resolve_default(
98
+ session.runtime, table, kind, session.uname, session.admin,
99
+ allowed_databases={table})
100
+ for kind in application_registry.APPLICATION_TYPES
101
+ }}
102
+
103
+
104
  @router.post("/templates/{key}/apply")
105
  def apply_template(key: str, body: dict = Body(default=None),
106
  session: Session = Depends(require_session)):
 
129
  raise err(404, "unknown_table", "that database does not exist")
130
  if not session.runtime.available():
131
  raise err(503, "store_unavailable",
132
+ "the tenant store is unavailable. Nothing was applied")
133
  import core.table_store as table_store
134
  ops = table_store.make(ws_key, st=session.runtime)
135
  applied = []
api/semantic_registry.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Governed, tenant-scoped semantic metadata.
2
+
3
+ Structured records are authoritative. Markdown and value summaries are projections of those
4
+ records and can never add information that was not admitted by the governance door here.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import copy
9
+ import hashlib
10
+ import json
11
+ from collections import Counter
12
+
13
+
14
+ SEMANTIC_STATES = ("draft", "approved", "disabled")
15
+ SENSITIVITY = ("public", "internal", "sensitive", "restricted")
16
+ VALUE_PROFILE_CAP = 50
17
+ VALUE_SAMPLE_CAP = 12
18
+ _KEY = "semantic_registry_v1"
19
+
20
+
21
+ class SemanticError(ValueError):
22
+ """A semantic contract was refused before persistence or retrieval."""
23
+
24
+
25
+ def _text(value, limit=500):
26
+ return " ".join(str(value or "").split())[:limit]
27
+
28
+
29
+ def _strings(values, *, limit=20):
30
+ out = []
31
+ for value in values if isinstance(values, (list, tuple)) else ():
32
+ item = _text(value, 80)
33
+ if item and item.casefold() not in {x.casefold() for x in out}:
34
+ out.append(item)
35
+ if len(out) >= limit:
36
+ break
37
+ return out
38
+
39
+
40
+ def field_key(database, field):
41
+ return f"{_text(database, 120)}::{_text(field, 120)}"
42
+
43
+
44
+ def model_record(database, topic, field):
45
+ """Build the governed baseline from a topic field declaration.
46
+
47
+ Existing topic files predate approval. They therefore enter as ``draft`` unless the
48
+ declaration explicitly says otherwise; merely having a label never grants retrieval.
49
+ """
50
+ field = field if isinstance(field, dict) else {}
51
+ semantic = field.get("semantic") if isinstance(field.get("semantic"), dict) else {}
52
+ state = str(semantic.get("state") or "draft").lower()
53
+ sensitivity = str(semantic.get("sensitivity") or "internal").lower()
54
+ if state not in SEMANTIC_STATES:
55
+ raise SemanticError(f"unknown semantic state {state!r}")
56
+ if sensitivity not in SENSITIVITY:
57
+ raise SemanticError(f"unknown sensitivity {sensitivity!r}")
58
+ return {
59
+ "database": _text(database, 120),
60
+ "topic": _text((topic or {}).get("key"), 120),
61
+ "field": _text(field.get("key"), 120),
62
+ "label": _text(field.get("label") or field.get("key"), 120),
63
+ "purpose": _text(semantic.get("purpose") or field.get("means"), 500),
64
+ "dataType": _text(field.get("type") or "text", 40),
65
+ "role": _text(semantic.get("role") or "attribute", 60),
66
+ "synonyms": _strings(semantic.get("synonyms")),
67
+ "sensitivity": sensitivity,
68
+ "state": state,
69
+ "valueProfile": None,
70
+ "revision": int(semantic.get("revision") or 1),
71
+ "approvedBy": _text(semantic.get("approvedBy"), 120) or None,
72
+ "disabledBy": _text(semantic.get("disabledBy"), 120) or None,
73
+ "profiledBy": _text(semantic.get("profiledBy"), 120) or None,
74
+ }
75
+
76
+
77
+ def topic_records(database, topic):
78
+ return {
79
+ field_key(database, row.get("key")): model_record(database, topic, row)
80
+ for row in (topic or {}).get("fields") or ()
81
+ if isinstance(row, dict) and row.get("key")
82
+ }
83
+
84
+
85
+ def _clean_override(raw, baseline, *, actor, is_admin):
86
+ if not is_admin:
87
+ raise SemanticError("only a tenant admin can change semantic approval")
88
+ raw = raw if isinstance(raw, dict) else {}
89
+ out = copy.deepcopy(baseline)
90
+ for key in ("purpose", "role"):
91
+ if key in raw:
92
+ out[key] = _text(raw[key], 500 if key == "purpose" else 60)
93
+ if "synonyms" in raw:
94
+ out["synonyms"] = _strings(raw["synonyms"])
95
+ if "sensitivity" in raw:
96
+ sensitivity = str(raw["sensitivity"] or "").lower()
97
+ if sensitivity not in SENSITIVITY:
98
+ raise SemanticError("sensitivity is not recognized")
99
+ previous = out.get("sensitivity")
100
+ out["sensitivity"] = sensitivity
101
+ # A profile admitted while a field was internal must not survive the transaction that
102
+ # makes it sensitive. The reverse transition clears the redacted placeholder too: only a
103
+ # fresh, permission-scoped profile may put values back.
104
+ if sensitivity in ("sensitive", "restricted"):
105
+ out["valueProfile"] = redacted_profile()
106
+ elif previous in ("sensitive", "restricted"):
107
+ out["valueProfile"] = None
108
+ if "state" in raw:
109
+ state = str(raw["state"] or "").lower()
110
+ if state not in SEMANTIC_STATES:
111
+ raise SemanticError("semantic state is not recognized")
112
+ out["state"] = state
113
+ out["approvedBy"] = _text(actor, 120) if state == "approved" else None
114
+ out["disabledBy"] = _text(actor, 120) if state == "disabled" else None
115
+ out["revision"] = int(baseline.get("revision") or 0) + 1
116
+ return out
117
+
118
+
119
+ def merge_records(baseline, persisted):
120
+ """Merge only records still present in the source contract.
121
+
122
+ A stale persisted field cannot resurrect a removed source field.
123
+ """
124
+ out = copy.deepcopy(baseline)
125
+ stored = (persisted or {}).get("fields") if isinstance(persisted, dict) else None
126
+ for key, raw in (stored or {}).items():
127
+ if key not in out or not isinstance(raw, dict):
128
+ continue
129
+ for name in ("purpose", "role", "synonyms", "sensitivity", "state", "valueProfile",
130
+ "revision", "approvedBy", "disabledBy", "profiledBy"):
131
+ if name in raw:
132
+ out[key][name] = copy.deepcopy(raw[name])
133
+ out[key] = enforce_redaction(out[key])
134
+ return out
135
+
136
+
137
+ def load(runtime, baseline):
138
+ try:
139
+ raw = runtime.get(_KEY) if runtime is not None else {}
140
+ except Exception:
141
+ raw = {}
142
+ return merge_records(baseline, raw)
143
+
144
+
145
+ def update(runtime, baseline, database, field, patch, *, actor, is_admin):
146
+ key = field_key(database, field)
147
+ if key not in baseline:
148
+ raise SemanticError("that field is not in the database contract")
149
+ current = load(runtime, baseline)[key]
150
+ changed = _clean_override(patch, current, actor=actor, is_admin=is_admin)
151
+
152
+ def apply(raw):
153
+ doc = copy.deepcopy(raw) if isinstance(raw, dict) else {}
154
+ fields = doc.setdefault("fields", {})
155
+ fields[key] = changed
156
+ return doc
157
+
158
+ runtime.update(_KEY, apply)
159
+ return enforce_redaction(changed)
160
+
161
+
162
+ def redacted_profile():
163
+ return {"redacted": True, "distinctCount": None, "values": [], "sample": []}
164
+
165
+
166
+ def enforce_redaction(record):
167
+ """Sanitize one record at every read/projection boundary, including legacy stored rows."""
168
+ row = copy.deepcopy(record) if isinstance(record, dict) else {}
169
+ if str(row.get("sensitivity") or "internal").lower() in ("sensitive", "restricted"):
170
+ row["valueProfile"] = redacted_profile()
171
+ return row
172
+
173
+
174
+ def set_value_profile(runtime, baseline, database, field, values, *, actor, is_admin):
175
+ """Persist one bounded profile without trusting a caller-supplied summary."""
176
+ if not is_admin:
177
+ raise SemanticError("only a tenant admin can profile semantic values")
178
+ key = field_key(database, field)
179
+ if key not in baseline:
180
+ raise SemanticError("that field is not in the database contract")
181
+ landed = {}
182
+
183
+ def apply(raw):
184
+ doc = copy.deepcopy(raw) if isinstance(raw, dict) else {}
185
+ current = merge_records(baseline, doc)[key]
186
+ current["valueProfile"] = value_profile(
187
+ values, sensitivity=current.get("sensitivity") or "internal")
188
+ current["revision"] = int(current.get("revision") or 0) + 1
189
+ current["profiledBy"] = _text(actor, 120) or None
190
+ doc.setdefault("fields", {})[key] = enforce_redaction(current)
191
+ landed.update(doc["fields"][key])
192
+ return doc
193
+
194
+ runtime.update(_KEY, apply)
195
+ return enforce_redaction(landed)
196
+
197
+
198
+ def is_approved(record):
199
+ return isinstance(record, dict) and record.get("state") == "approved"
200
+
201
+
202
+ def approved_fields(records, database):
203
+ prefix = f"{_text(database, 120)}::"
204
+ return {row["field"]: copy.deepcopy(row) for key, row in (records or {}).items()
205
+ if key.startswith(prefix) and is_approved(row)}
206
+
207
+
208
+ def require_approved(records, database, field):
209
+ row = (records or {}).get(field_key(database, field))
210
+ if not is_approved(row):
211
+ raise SemanticError(f"field {field!r} is not approved for Loopable retrieval")
212
+ return copy.deepcopy(row)
213
+
214
+
215
+ def value_profile(values, *, sensitivity="internal", distinct_cap=VALUE_PROFILE_CAP,
216
+ sample_cap=VALUE_SAMPLE_CAP):
217
+ """Return a bounded profile without ever serializing a sensitive value."""
218
+ sensitivity = str(sensitivity or "internal").lower()
219
+ if sensitivity in ("sensitive", "restricted"):
220
+ return redacted_profile()
221
+ distinct_cap = max(1, min(int(distinct_cap), VALUE_PROFILE_CAP))
222
+ sample_cap = max(1, min(int(sample_cap), VALUE_SAMPLE_CAP))
223
+ normalized, seen = [], set()
224
+ for value in values if isinstance(values, (list, tuple)) else ():
225
+ if value is None:
226
+ continue
227
+ if isinstance(value, (dict, list, tuple, set)):
228
+ text = json.dumps(value, sort_keys=True, default=str)
229
+ else:
230
+ text = str(value)
231
+ text = text[:240]
232
+ if text not in seen:
233
+ seen.add(text)
234
+ normalized.append(text)
235
+ count = len(normalized)
236
+ if count <= distinct_cap:
237
+ return {"redacted": False, "distinctCount": count, "values": normalized, "sample": []}
238
+ # Stable hash order prevents database order from turning a profile into a covert channel.
239
+ sample = sorted(normalized, key=lambda x: hashlib.sha256(x.encode("utf-8")).hexdigest())[:sample_cap]
240
+ return {"redacted": False, "distinctCount": count, "values": [], "sample": sample}
241
+
242
+
243
+ def generated_markdown(record):
244
+ """A deterministic projection. Sensitive profiles carry no values by construction."""
245
+ row = enforce_redaction(record)
246
+ profile = row.get("valueProfile") if isinstance(row.get("valueProfile"), dict) else None
247
+ lines = [f"# {row.get('label') or row.get('field') or 'Field'}",
248
+ f"- Field: `{row.get('field') or ''}`",
249
+ f"- State: {row.get('state') or 'draft'}",
250
+ f"- Type: {row.get('dataType') or 'text'}",
251
+ f"- Role: {row.get('role') or 'attribute'}",
252
+ f"- Sensitivity: {row.get('sensitivity') or 'internal'}",
253
+ f"- Purpose: {row.get('purpose') or 'Not configured'}"]
254
+ synonyms = _strings(row.get("synonyms"))
255
+ if synonyms:
256
+ lines.append("- Synonyms: " + ", ".join(synonyms))
257
+ if profile:
258
+ if profile.get("redacted"):
259
+ lines.append("- Values: Redacted")
260
+ elif profile.get("values"):
261
+ lines.append("- Values: " + ", ".join(profile["values"]))
262
+ else:
263
+ lines.append(f"- Distinct values: {profile.get('distinctCount', 0)}")
264
+ if profile.get("sample"):
265
+ lines.append("- Sample: " + ", ".join(profile["sample"]))
266
+ return "\n".join(lines) + "\n"
267
+
268
+
269
+ def router_projection(records, database):
270
+ """A provider-neutral table of contents over approved semantic sources."""
271
+ approved = approved_fields(records, database)
272
+ sections = []
273
+ for role, rows in sorted(_group_by_role(approved).items()):
274
+ sections.append({"role": role, "fields": [
275
+ {"key": row["field"], "label": row["label"], "purpose": row["purpose"]}
276
+ for row in rows
277
+ ]})
278
+ return {"database": database, "sections": sections, "fieldCount": len(approved)}
279
+
280
+
281
+ def _group_by_role(records):
282
+ grouped = {}
283
+ for row in records.values():
284
+ grouped.setdefault(row.get("role") or "attribute", []).append(row)
285
+ for rows in grouped.values():
286
+ rows.sort(key=lambda row: (row.get("label") or "").casefold())
287
+ return grouped
api/voice_control_plane.py CHANGED
@@ -9,7 +9,9 @@ records a normalized local event, and always reports ``noExternalDispatch: true`
9
  from __future__ import annotations
10
 
11
  import copy
 
12
  import hashlib
 
13
  import re
14
  import secrets
15
  import time
@@ -19,6 +21,7 @@ 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",
@@ -48,6 +51,29 @@ 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
 
@@ -60,7 +86,8 @@ def _now(value: Any = None) -> int:
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]:
@@ -131,7 +158,7 @@ def _reject_sensitive(value: Any) -> None:
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
 
@@ -254,7 +281,7 @@ def _provider_for(doc: dict[str, Any], connection_id: str, extension: Any) -> st
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)
@@ -302,7 +329,7 @@ def _agent_record(doc: dict[str, Any], raw: Any, previous: Any = None,
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,
@@ -319,14 +346,17 @@ def _agent_record(doc: dict[str, Any], raw: Any, previous: Any = None,
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
 
@@ -356,7 +386,7 @@ def server_register_provider_connection(rt: Any, provider: str, secret_ref: str,
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]:
@@ -631,8 +661,19 @@ def browser_dto(record: Any, document: Any = None) -> dict[str, Any]:
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]:
@@ -640,7 +681,14 @@ def get_browser_dto(rt: Any, voice_id: str) -> dict[str, Any]:
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]:
@@ -658,8 +706,8 @@ def browser_options(rt: Any) -> dict[str, Any]:
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,
@@ -675,8 +723,8 @@ def record_provider_event(rt: Any, provider: str, event_ref: str, voice_id: str,
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}
@@ -687,6 +735,39 @@ def record_provider_event(rt: Any, provider: str, event_ref: str, voice_id: str,
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."""
@@ -743,3 +824,156 @@ 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")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  from __future__ import annotations
10
 
11
  import copy
12
+ import hmac
13
  import hashlib
14
+ import os
15
  import re
16
  import secrets
17
  import time
 
21
 
22
 
23
  STORE_KEY = "voice_control_plane"
24
+ FEEDBACK_KEY = "voice_feedback_control"
25
  SCHEMA_VERSION = 1
26
  RECORD_TYPES = (
27
  "voice_provider_connection",
 
51
  """A request was structurally unsafe; its message is fit for the API client."""
52
 
53
 
54
+ def verify_telnyx_raw_request(raw_body: bytes, signature: str, timestamp: str) -> bool:
55
+ """Server-configured receipt verifier over exact received bytes; never browser input."""
56
+ public_key = os.environ.get("TELNYX_WEBHOOK_PUBLIC_KEY")
57
+ if not public_key:
58
+ raise VoiceRefusal("Telnyx receipt verifier is not configured")
59
+ try:
60
+ stamp = int(timestamp)
61
+ except (TypeError, ValueError):
62
+ raise VoiceRefusal("Telnyx webhook timestamp is invalid") from None
63
+ if abs(_now() - stamp) > 300:
64
+ raise VoiceRefusal("Telnyx webhook timestamp is outside the replay window")
65
+ try:
66
+ import base64
67
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
68
+ key = Ed25519PublicKey.from_public_bytes(base64.b64decode(public_key))
69
+ key.verify(base64.b64decode(str(signature or "")), str(timestamp).encode("utf-8") + b"|" + raw_body)
70
+ return True
71
+ except ImportError as exc:
72
+ raise VoiceRefusal("Telnyx Ed25519 verifier is unavailable") from exc
73
+ except Exception:
74
+ return False
75
+
76
+
77
  def _text(value: Any, limit: int = 160) -> str:
78
  return " ".join(str(value or "").split())[:limit]
79
 
 
86
 
87
 
88
  def _mint(prefix: str) -> str:
89
+ # Browser/API ids must satisfy the same lowercase reference grammar as supplied ids.
90
+ return f"{prefix}_{secrets.token_hex(12)}"
91
 
92
 
93
  def _empty_document() -> dict[str, Any]:
 
158
  elif isinstance(value, list):
159
  for item in value:
160
  _reject_sensitive(item)
161
+ elif isinstance(value, str) and _PHONE.search(value) and not _ID.fullmatch(value):
162
  raise VoiceRefusal("raw phone numbers are not accepted by the browser Voice API")
163
 
164
 
 
281
 
282
 
283
  def _agent_record(doc: dict[str, Any], raw: Any, previous: Any = None,
284
+ actor: str = "", tenant_id: str = "") -> dict[str, Any]:
285
  raw = raw if isinstance(raw, dict) else {}
286
  previous = previous if isinstance(previous, dict) else {}
287
  _reject_sensitive(raw)
 
329
  stamp = _now()
330
  return {
331
  "id": str(previous.get("id") or _mint("va")),
332
+ "tenant_id": str(previous.get("tenant_id") or tenant_id or ""),
333
  "display_name": name,
334
  "lifecycle": lifecycle,
335
  "provider_connection_id": connection_id,
 
346
  }
347
 
348
 
349
+ def save_draft(rt: Any, raw: Any, actor: str = "", tenant_id: str = "") -> dict[str, Any]:
350
  result: dict[str, Any] = {}
351
  def up(doc: dict[str, Any]) -> dict[str, Any]:
352
+ rec = _agent_record(doc, raw, actor=actor, tenant_id=tenant_id)
353
  doc["voice_agent"][rec["id"]] = rec
354
  result.update(rec)
355
  return doc
356
  _update(rt, up)
357
+ import automation_engine as _agent_engine
358
+ _agent_engine.ensure_agent_contract(rt, result.get("id"), actor,
359
+ result.get("display_name") or "")
360
  return result
361
 
362
 
 
386
  rec = {
387
  "id": _safe_id(connection_id, "provider connection") or _mint("vpc"),
388
  "tenant_id": str(tenant_id or "")[:120],
389
+ "provider": key, "secret_ref": ref, "visibility": "private", "status": "unconfigured",
390
  "last_probe_at": 0, "created_at": _now(), "updated_at": _now(),
391
  }
392
  def up(doc: dict[str, Any]) -> dict[str, Any]:
 
661
 
662
  def list_browser_dtos(rt: Any) -> list[dict[str, Any]]:
663
  doc = _store(rt)
664
+ import automation_engine as _agent_engine
665
+ rows = []
666
+ for _, rec in sorted(doc["voice_agent"].items()):
667
+ if not isinstance(rec, dict):
668
+ continue
669
+ row = browser_dto(rec, doc)
670
+ contract = _agent_engine.agent_contract_dto(rt, rec.get("id"))
671
+ if contract:
672
+ row.update({"privateEventStore": contract["eventStore"],
673
+ "workflows": contract["workflows"],
674
+ "setupInterview": contract["setupInterview"]})
675
+ rows.append(row)
676
+ return rows
677
 
678
 
679
  def get_browser_dto(rt: Any, voice_id: str) -> dict[str, Any]:
 
681
  rec = doc["voice_agent"].get(str(voice_id))
682
  if not isinstance(rec, dict):
683
  raise VoiceRefusal("unknown Voice agent")
684
+ row = browser_dto(rec, doc)
685
+ import automation_engine as _agent_engine
686
+ contract = _agent_engine.agent_contract_dto(rt, voice_id)
687
+ if contract:
688
+ row.update({"privateEventStore": contract["eventStore"],
689
+ "workflows": contract["workflows"],
690
+ "setupInterview": contract["setupInterview"]})
691
+ return row
692
 
693
 
694
  def browser_options(rt: Any) -> dict[str, Any]:
 
706
  "maxRecipientsCeiling": MAX_RECIPIENTS}
707
 
708
 
709
+ def _event_key(provider: str, event_ref: str, tenant_id: str = "", voice_id: str = "") -> str:
710
+ return hashlib.sha256(f"{tenant_id}:{voice_id}:{provider}:{event_ref}".encode("utf-8")).hexdigest()[:32]
711
 
712
 
713
  def record_provider_event(rt: Any, provider: str, event_ref: str, voice_id: str,
 
723
  if not isinstance(normalized_outcome, dict):
724
  raise VoiceRefusal("provider outcome must be a normalized object")
725
  _reject_sensitive(normalized_outcome)
726
+ eid = "vpe_" + _event_key(key, ref, tenant_id, voice_id)
727
+ rec = {"id": eid, "provider": key, "event_ref_hash": _event_key(key, ref, tenant_id, voice_id),
728
  "tenant_id": str(tenant_id or "")[:120], "voice_agent_id": str(voice_id or ""),
729
  "received_at": _now(received_at), "verification_state": verification_state,
730
  "normalized_outcome": copy.deepcopy(normalized_outcome), "raw_payload_stored": False}
 
735
  return rec
736
 
737
 
738
+ def _reserve_provider_event(rt: Any, provider: str, event_ref: str, voice_id: str,
739
+ tenant_id: str, received_at: Any = None) -> tuple[bool, dict[str, Any]]:
740
+ """One runtime update reserves a full tenant/Agent/provider replay identity before Query."""
741
+ eid = "vpe_" + _event_key(provider, event_ref, tenant_id, voice_id)
742
+ result: dict[str, Any] = {"_new": False}
743
+ def up(doc):
744
+ existing = doc["voice_provider_event"].get(eid)
745
+ if isinstance(existing, dict) and existing.get("deliveryState") in {"pending", "completed"}:
746
+ result.update(existing)
747
+ return doc
748
+ rec = {"id": eid, "provider": str(provider),
749
+ "event_ref_hash": _event_key(provider, event_ref, tenant_id, voice_id),
750
+ "tenant_id": tenant_id, "voice_agent_id": voice_id, "received_at": _now(received_at),
751
+ "verification_state": "verified", "deliveryState": "pending",
752
+ "normalized_outcome": {}, "raw_payload_stored": False}
753
+ doc["voice_provider_event"][eid] = rec
754
+ result.update(rec); result["_new"] = True
755
+ return doc
756
+ _update(rt, up)
757
+ return bool(result.pop("_new", False)), result
758
+
759
+
760
+ def _finish_provider_event(rt: Any, event_id: str, state: str, outcome: Any = None) -> None:
761
+ def up(doc):
762
+ rec = dict(doc["voice_provider_event"].get(event_id) or {})
763
+ if rec:
764
+ rec["deliveryState"] = state
765
+ rec["normalized_outcome"] = copy.deepcopy(outcome or {})
766
+ doc["voice_provider_event"][event_id] = rec
767
+ return doc
768
+ _update(rt, up)
769
+
770
+
771
  def dry_run(rt: Any, voice_id: str, audience: Any,
772
  resolve_view: Callable[[dict[str, Any]], dict[str, Any]]) -> dict[str, Any]:
773
  """Resolve one allowed saved View and record a redacted local event; never dispatch."""
 
824
  """The explicit ordinary-run/webhook/schedule wall until production activation is built."""
825
  raise VoiceRefusal(
826
  f"Voice {str(source or 'automation')} dispatch is not activated; use the no-dial harness")
827
+
828
+
829
+ def whatsapp_query_dry_run(rt: Any, voice_id: str, payload: Any, headers: Any,
830
+ verify_signature: Callable, query_tool: Callable,
831
+ now: Any = None, verification: str = "recorded_fixture") -> dict[str, Any]:
832
+ """Recorded Telnyx-shaped inbound proof over the provider-neutral Query seam."""
833
+ doc = _store(rt)
834
+ rec = doc["voice_agent"].get(str(voice_id))
835
+ if not isinstance(rec, dict):
836
+ raise VoiceRefusal("unknown Voice agent")
837
+ event_ref = str((payload.get("data") or {}).get("payload", {}).get("id") or "")
838
+ tenant_id = str(rec.get("tenant_id") or "")
839
+ # Authenticate the received body before considering a replay record.
840
+ adapters.verify_telnyx_inbound(payload, headers, verify_signature,
841
+ now=_now(now) if now is not None else None)
842
+ created, reservation = _reserve_provider_event(rt, "telnyx", event_ref, str(voice_id), tenant_id, now)
843
+ if not created:
844
+ return {"verifiedWebhook": True, "replayed": True, "deliveryState": reservation.get("deliveryState"),
845
+ "eventId": reservation["id"], "query": dict((reservation.get("normalized_outcome") or {}).get("query") or {}),
846
+ "noExternalDispatch": True, "externalDispatches": 0}
847
+ try:
848
+ result = adapters.telnyx_whatsapp_dry_run(payload, headers, verify_signature, query_tool,
849
+ now=_now(now) if now is not None else None)
850
+ except Exception:
851
+ _finish_provider_event(rt, reservation["id"], "failed")
852
+ raise
853
+ outcome = {"kind": "whatsapp_query_dry_run", "query": result["query"],
854
+ "noExternalDispatch": True, "externalDispatches": 0}
855
+ _finish_provider_event(rt, reservation["id"], "completed", outcome)
856
+ return {**result, "eventId": reservation["id"], "verification": verification}
857
+
858
+
859
+ def _feedback_document(rt: Any) -> dict[str, Any]:
860
+ try:
861
+ raw = rt.get(FEEDBACK_KEY) or {}
862
+ except Exception:
863
+ raw = {}
864
+ raw = raw if isinstance(raw, dict) else {}
865
+ return {"schedules": copy.deepcopy(raw.get("schedules") or {}),
866
+ "consents": copy.deepcopy(raw.get("consents") or {}),
867
+ "dryRuns": copy.deepcopy(raw.get("dryRuns") or {})}
868
+
869
+
870
+ def _feedback_update(rt: Any, fn):
871
+ return rt.update(FEEDBACK_KEY, lambda raw: fn({
872
+ "schedules": copy.deepcopy((raw or {}).get("schedules") or {}),
873
+ "consents": copy.deepcopy((raw or {}).get("consents") or {}),
874
+ "dryRuns": copy.deepcopy((raw or {}).get("dryRuns") or {}),
875
+ }), flush="sync")
876
+
877
+
878
+ def set_feedback_consent(rt: Any, voice_id: str, contact_ref: str, state: str, purpose: str) -> dict[str, Any]:
879
+ if str(voice_id or "") not in _store(rt).get("voice_agent", {}):
880
+ raise VoiceRefusal("unknown voice Agent")
881
+ _reject_sensitive({"contactRef": contact_ref, "purpose": purpose})
882
+ ref = _safe_id(contact_ref, "opaque contact", allow_empty=False)
883
+ value = str(state or "")
884
+ if value not in {"consented", "withdrawn"}:
885
+ raise VoiceRefusal("feedback consent is consented or withdrawn")
886
+ rec = {"contactRef": ref, "voiceAgentId": str(voice_id), "state": value,
887
+ "purpose": _text(purpose, 160), "updatedAt": _now()}
888
+ def up(doc):
889
+ doc["consents"][ref] = rec
890
+ return doc
891
+ _feedback_update(rt, up)
892
+ return copy.deepcopy(rec)
893
+
894
+
895
+ def create_feedback_schedule(rt: Any, voice_id: str, contact_refs: Any,
896
+ local_time: str = "09:00", timezone_name: str = "UTC") -> dict[str, Any]:
897
+ voice_key = str(voice_id or "")
898
+ if voice_key not in _store(rt).get("voice_agent", {}):
899
+ raise VoiceRefusal("unknown voice Agent")
900
+ if not isinstance(contact_refs, list) or not contact_refs:
901
+ raise VoiceRefusal("feedback schedule needs consented opaque contacts")
902
+ _reject_sensitive(contact_refs)
903
+ refs = [_safe_id(value, "opaque contact", allow_empty=False) for value in contact_refs]
904
+ _reject_sensitive(refs)
905
+ if not re.fullmatch(r"(?:[01]\d|2[0-3]):[0-5]\d", str(local_time or "")):
906
+ raise VoiceRefusal("feedback schedule time is invalid")
907
+ consents = _feedback_document(rt)["consents"]
908
+ if any((consents.get(ref) or {}).get("state") != "consented" or
909
+ (consents.get(ref) or {}).get("voiceAgentId") != voice_key for ref in refs):
910
+ raise VoiceRefusal("every feedback contact needs current consent for this Voice Agent")
911
+ sid = "vfs_" + hashlib.sha256(
912
+ f"{voice_key}:{','.join(sorted(refs))}".encode("utf-8")).hexdigest()[:18]
913
+ rec = {"id": sid, "voiceAgentId": voice_key, "contactRefs": sorted(set(refs)),
914
+ "localTime": str(local_time), "timezone": _text(timezone_name, 80),
915
+ "enabled": False, "activationState": "disabled",
916
+ "eventSchema": {"transcript": "agent_event/transcript",
917
+ "consent": "agent_event/consent", "run": "agent_event/run"},
918
+ "activationRequirements": ["all_contacts_consented", "agent_configured",
919
+ "private_provider_adapter", "explicit_activation_release"],
920
+ "createdAt": _now()}
921
+ def up(doc):
922
+ doc["schedules"][sid] = rec
923
+ return doc
924
+ _feedback_update(rt, up)
925
+ return copy.deepcopy(rec)
926
+
927
+
928
+ def feedback_schedule_dto(rt: Any, schedule_id: str) -> dict[str, Any]:
929
+ rec = _feedback_document(rt)["schedules"].get(str(schedule_id))
930
+ if not isinstance(rec, dict):
931
+ raise VoiceRefusal("unknown feedback schedule")
932
+ return {**copy.deepcopy(rec), "contactRefs": ["opaque" for _ in rec.get("contactRefs") or []],
933
+ "noExternalDispatch": True, "externalDispatches": 0}
934
+
935
+
936
+ def feedback_dry_run(rt: Any, voice_id: str, schedule_id: str, day: str) -> dict[str, Any]:
937
+ doc = _feedback_document(rt)
938
+ rec = doc["schedules"].get(str(schedule_id))
939
+ if not isinstance(rec, dict):
940
+ raise VoiceRefusal("unknown feedback schedule")
941
+ if rec.get("voiceAgentId") != str(voice_id or ""):
942
+ raise VoiceRefusal("feedback schedule does not belong to this Voice Agent")
943
+ if rec.get("enabled") or rec.get("activationState") != "disabled":
944
+ raise VoiceRefusal("feedback activation is unavailable in this release")
945
+ voice_rec = _store(rt).get("voice_agent", {}).get(str(voice_id)) or {}
946
+ connection = _store(rt).get("voice_provider_connection", {}).get(
947
+ str(voice_rec.get("provider_connection_id") or ""))
948
+ if not isinstance(connection, dict) or connection.get("visibility") != "private":
949
+ raise VoiceRefusal("feedback requires a private server-owned provider connection")
950
+ if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", str(day or "")):
951
+ raise VoiceRefusal("feedback dry-run day is invalid")
952
+ import automation_engine as _agent_engine
953
+ configured = ((_agent_engine.agent_contract_dto(rt, voice_id) or {})
954
+ .get("setupInterview", {}).get("state") == "configured")
955
+ if not configured:
956
+ raise VoiceRefusal("configure the Agent before feedback dry-run")
957
+ missing = [ref for ref in rec.get("contactRefs") or []
958
+ if (doc["consents"].get(ref) or {}).get("state") != "consented" or
959
+ (doc["consents"].get(ref) or {}).get("voiceAgentId") != str(voice_id)]
960
+ if missing:
961
+ raise VoiceRefusal("every feedback contact needs current consent")
962
+ key = f"{schedule_id}:{day}"
963
+ if key in doc["dryRuns"]:
964
+ raise VoiceRefusal("feedback schedule was already dry-run for that day")
965
+ result = {"scheduleId": str(schedule_id), "day": str(day),
966
+ "dueCount": len(rec.get("contactRefs") or []), "state": "dry_run_complete",
967
+ "noExternalDispatch": True, "externalDispatches": 0,
968
+ "activationState": "disabled", "adapterVisibility": "private"}
969
+ def up(current):
970
+ current["dryRuns"].setdefault(key, result)
971
+ return current
972
+ _feedback_update(rt, up)
973
+ return copy.deepcopy(result)
974
+
975
+
976
+ def future_integration_adapter_contract() -> dict[str, Any]:
977
+ return {"version": 1, "interface": ["normalizeInbound", "renderQueryResult", "dryRun"],
978
+ "providers": [], "makeImplemented": False, "nangoImplemented": False,
979
+ "externalDispatch": False}
api/voice_provider_adapters.py CHANGED
@@ -8,6 +8,9 @@ Results contain counts and readiness classes only, never provider identifiers or
8
  from __future__ import annotations
9
 
10
  from dataclasses import dataclass
 
 
 
11
  from typing import Any, Callable
12
 
13
 
@@ -55,9 +58,24 @@ _EXTENSIONS: dict[str, dict[str, tuple[type, ...]]] = {
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]]:
@@ -71,6 +89,7 @@ def providers() -> list[dict[str, Any]]:
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
  ]
@@ -85,7 +104,7 @@ def clean_extension(provider: str, raw: Any) -> dict[str, Any]:
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):
@@ -187,3 +206,59 @@ 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")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  from __future__ import annotations
9
 
10
  from dataclasses import dataclass
11
+ import copy
12
+ import json
13
+ import time
14
  from typing import Any, Callable
15
 
16
 
 
58
  "stability": (int, float),
59
  "similarityBoost": (int, float),
60
  },
61
+ "telnyx": {
62
+ "messagingProfileRef": (str,),
63
+ },
64
  }
65
 
66
+ _LABELS = {"retell": "Retell", "elevenlabs": "ElevenLabs", "telnyx": "Telnyx"}
67
+
68
+ _CAPABILITIES = {
69
+ "retell": {"inboundVoice": "supported", "outboundVoice": "supported",
70
+ "whatsAppMessaging": "unsupported", "whatsAppCalling": "unproven",
71
+ "governedQuery": "supported"},
72
+ "elevenlabs": {"inboundVoice": "supported", "outboundVoice": "supported",
73
+ "whatsAppMessaging": "supported", "whatsAppCalling": "unproven",
74
+ "governedQuery": "supported"},
75
+ "telnyx": {"inboundVoice": "carrier_dependent", "outboundVoice": "carrier_dependent",
76
+ "whatsAppMessaging": "supported", "whatsAppCalling": "unproven",
77
+ "governedQuery": "supported"},
78
+ }
79
 
80
 
81
  def providers() -> list[dict[str, Any]]:
 
89
  {"key": name, "type": "number" if float in types else "text"}
90
  for name, types in fields.items()
91
  ],
92
+ "capabilities": copy.deepcopy(_CAPABILITIES[key]),
93
  }
94
  for key, fields in _EXTENSIONS.items()
95
  ]
 
104
  key = str(provider or "").strip().lower()
105
  allowed = _EXTENSIONS.get(key)
106
  if allowed is None:
107
+ raise ProviderAdapterRefusal("select Retell, ElevenLabs, or Telnyx")
108
  if raw in (None, ""):
109
  return {"provider": key, "version": 1, "config": {}}
110
  if not isinstance(raw, dict):
 
206
  """Public negative control for transports that want an explicit verb guard."""
207
  if str(method or "").upper() != "GET":
208
  raise ProviderAdapterRefusal("provider reconciliation accepts GET inventory only")
209
+
210
+
211
+ def verify_telnyx_inbound(payload: Any, headers: Any, verify_signature: Callable,
212
+ now: int | None = None) -> tuple[str, str]:
213
+ """Verify one recorded Telnyx-shaped inbound event and simulate a Query reply.
214
+
215
+ There is intentionally no transport argument. A verified event can reach governed Query and a
216
+ local formatter only; sending, dialing, and provider mutation are structurally unavailable.
217
+ """
218
+ if not isinstance(payload, dict) or not isinstance(headers, dict):
219
+ raise ProviderAdapterRefusal("Telnyx webhook fixture is invalid")
220
+ signature = str(headers.get("telnyx-signature-ed25519") or "")
221
+ timestamp = str(headers.get("telnyx-timestamp") or "")
222
+ try:
223
+ stamp = int(timestamp)
224
+ except (TypeError, ValueError):
225
+ raise ProviderAdapterRefusal("Telnyx webhook timestamp is invalid") from None
226
+ clock = int(now if now is not None else time.time())
227
+ if abs(clock - stamp) > 300:
228
+ raise ProviderAdapterRefusal("Telnyx webhook timestamp is outside the replay window")
229
+ canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
230
+ if not callable(verify_signature) or not verify_signature(signature, f"{timestamp}|{canonical}"):
231
+ raise ProviderAdapterRefusal("Telnyx webhook signature verification failed")
232
+ data = payload.get("data") if isinstance(payload.get("data"), dict) else {}
233
+ event = data.get("payload") if isinstance(data.get("payload"), dict) else {}
234
+ if str(data.get("event_type") or "") != "message.received":
235
+ raise ProviderAdapterRefusal("Telnyx fixture is not an inbound message")
236
+ message_id = str(event.get("id") or "").strip()
237
+ text = str((event.get("text") or event.get("body") or "")).strip()[:2000]
238
+ if not message_id or not text:
239
+ raise ProviderAdapterRefusal("Telnyx inbound message is incomplete")
240
+ return message_id, text
241
+
242
+
243
+ def telnyx_whatsapp_dry_run(payload: Any, headers: Any, verify_signature: Callable,
244
+ query_tool: Callable, now: int | None = None) -> dict[str, Any]:
245
+ """Verify one recorded Telnyx-shaped inbound event and simulate a Query reply."""
246
+ message_id, text = verify_telnyx_inbound(payload, headers, verify_signature, now)
247
+ if not callable(query_tool):
248
+ raise ProviderAdapterRefusal("governed Query is unavailable")
249
+ query = query_tool(text, {"channel": "whatsapp", "provider": "telnyx"})
250
+ if not isinstance(query, dict):
251
+ raise ProviderAdapterRefusal("governed Query returned no typed result")
252
+ state = str(query.get("state") or "complete")
253
+ if state == "clarification":
254
+ reply = str(query.get("question") or "Please clarify your request.")[:1000]
255
+ else:
256
+ reply = str(query.get("speakable") or "")[:2000]
257
+ if not reply:
258
+ raise ProviderAdapterRefusal("governed Query returned no speakable answer")
259
+ return {"provider": "telnyx", "channel": "whatsapp", "verifiedWebhook": True,
260
+ "eventRefHash": __import__("hashlib").sha256(message_id.encode()).hexdigest()[:24],
261
+ "query": {"state": state, "clarification": state == "clarification"},
262
+ "simulatedReply": {"text": reply, "status": "simulated"},
263
+ "rawPhoneReturned": False, "rawMessageReturned": False,
264
+ "noExternalDispatch": True, "externalDispatches": 0}
platform/aios_grid.py CHANGED
@@ -24,6 +24,7 @@ Design notes:
24
  injected-HTML path remains a read/local-write fallback when component assets are absent.
25
  """
26
  import datetime as _dt
 
27
  import json
28
  import math
29
  import re
@@ -804,7 +805,7 @@ def public_holidays(calendar, year):
804
  return frozenset(days)
805
 
806
 
807
- def clean_date_recurrence(raw):
808
  """One date field's recurrence config, or ``None`` for absent/malformed input.
809
 
810
  ``rules`` are an intentional union: selecting weekday + public holiday means either makes
@@ -814,7 +815,17 @@ def clean_date_recurrence(raw):
814
  if not isinstance(raw, dict):
815
  return None
816
  start = _iso_day(raw.get('startDate', raw.get('anchor')))
817
- if start is None:
 
 
 
 
 
 
 
 
 
 
818
  return None
819
  out_rules = []
820
  for raw_rule in list(raw.get('rules') or [])[:12]:
@@ -831,7 +842,9 @@ def clean_date_recurrence(raw):
831
  weekdays = sorted({day for day in (raw_rule.get('weekdays') or [])
832
  if isinstance(day, int) and not isinstance(day, bool)
833
  and 0 <= day <= 6})
834
- rule['weekdays'] = weekdays or [start.weekday()]
 
 
835
  elif kind == 'monthly':
836
  # ``day: 1`` means the first of every N months. ``ordinal`` + ``weekday`` adds
837
  # Google-Calendar-style first Monday / last Friday without a competing model.
@@ -844,12 +857,13 @@ def clean_date_recurrence(raw):
844
  continue
845
  rule.update({'ordinal': ordinal, 'weekday': weekday})
846
  else:
847
- day = raw_rule.get('day', start.day)
848
  if not isinstance(day, int) or isinstance(day, bool) or not 1 <= day <= 31:
849
  continue
850
  rule['day'] = day
851
  elif kind == 'yearly':
852
- month, day = raw_rule.get('month', start.month), raw_rule.get('day', start.day)
 
853
  if (not isinstance(month, int) or isinstance(month, bool) or not 1 <= month <= 12
854
  or not isinstance(day, int) or isinstance(day, bool) or not 1 <= day <= 31):
855
  continue
@@ -876,8 +890,18 @@ def clean_date_recurrence(raw):
876
  preview_count = raw.get('previewCount', raw.get('preview', 10))
877
  if not isinstance(preview_count, int) or isinstance(preview_count, bool):
878
  preview_count = 10
879
- return {'startDate': start.isoformat(), 'rules': out_rules,
880
- 'previewCount': max(1, min(preview_count, 50))}
 
 
 
 
 
 
 
 
 
 
881
 
882
 
883
  def _recurrence_matches(day, start, rule):
@@ -903,13 +927,17 @@ def _recurrence_matches(day, start, rule):
903
  return False
904
 
905
 
906
- def recurrence_preview(raw, today=None, count=None):
907
  """The next distinct ISO dates, anchored to the server's supplied/current day."""
908
- config = clean_date_recurrence(raw)
909
  if config is None:
910
  return []
911
  now = _iso_day(today) or _dt.date.today()
912
- start = _iso_day(config['startDate'])
 
 
 
 
913
  want = config['previewCount'] if count is None else max(1, min(int(count), 50))
914
  lower = max(start, now)
915
  # A preview of at most fifty values needs no unbounded search. Ten years also makes an
@@ -935,16 +963,37 @@ def recurrence_preview(raw, today=None, count=None):
935
  return [item.isoformat() for item in sorted(found)[:want]]
936
 
937
 
938
- def recurrence_payload(raw, today=None):
939
  """Durable config plus server-authoritative ``nextDate`` and finite ``preview``."""
940
- config = clean_date_recurrence(raw)
941
  if config is None:
942
  return None
943
- preview = recurrence_preview(config, today=today)
944
  return {**config, 'nextDate': preview[0] if preview else None, 'preview': preview}
945
 
946
 
947
- def _field_extras(saved, ftype):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
948
  """createdBy / permissions / format / scope — the validated passthrough the created strata
949
  share (wave 5). `createdBy` is only ever WRITTEN host-side (the handler stamps it); here it
950
  is carried so the client can gate its menus and the handler can enforce against it.
@@ -987,7 +1036,9 @@ def _field_extras(saved, ftype):
987
  # W43C C2 — the ISO date remains scalar in each row; recurrence is field metadata. Serve
988
  # the compact persisted config together with a server-derived next date and preview so the
989
  # client never substitutes its browser clock or holiday library for the tenant contract.
990
- recurrence = recurrence_payload(saved.get("recurrence")) if ftype == "date" else None
 
 
991
  if recurrence:
992
  out["recurrence"] = recurrence
993
  corrected_from = saved.get("labelCorrectedFrom")
@@ -1153,6 +1204,7 @@ def fields_from_workspace(workspace=None, cohorts=False, scope_key=None, fields_
1153
  out = []
1154
  base_fields = fields_base if fields_base is not None else FIELDS
1155
  base_keys = {field["key"] for field in base_fields}
 
1156
  for base in base_fields:
1157
  meta = saved.get(base["key"]) or {}
1158
  field = dict(base)
@@ -1194,7 +1246,8 @@ def fields_from_workspace(workspace=None, cohorts=False, scope_key=None, fields_
1194
  # fields need this explicit read half because their override is otherwise rebuilt from
1195
  # the immutable contract on every workspace projection.
1196
  if base.get("type") == "date" and "recurrence" in meta:
1197
- recurrence = recurrence_payload(meta.get("recurrence"))
 
1198
  if recurrence:
1199
  field["recurrence"] = recurrence
1200
  out.append(field)
@@ -1229,7 +1282,7 @@ def fields_from_workspace(workspace=None, cohorts=False, scope_key=None, fields_
1229
  else "sum" if mtype in ("currency", "int") else None),
1230
  "note": str(field.get("note") or "")[:2000],
1231
  "measure": {"key": mkey[:80], "window": window},
1232
- **_field_extras(field, mtype),
1233
  })
1234
  continue
1235
  if not str(key).startswith("custom_"):
@@ -1255,7 +1308,7 @@ def fields_from_workspace(workspace=None, cohorts=False, scope_key=None, fields_
1255
  "default": bool(field.get("default", True)),
1256
  "custom": True,
1257
  "note": str(field.get("note") or "")[:2000],
1258
- **_field_extras(field, ftype),
1259
  }
1260
  if ftype == "formula":
1261
  formula = _clean_formula(field.get("formula"))
@@ -1297,7 +1350,7 @@ def fields_from_workspace(workspace=None, cohorts=False, scope_key=None, fields_
1297
  # string. Absent = `plain`, which is what an unconfigured code column renders as.
1298
  **({"code": _clean_code(field.get("code"))}
1299
  if ftype == "code" and _clean_code(field.get("code")) else {}),
1300
- **_field_extras(field, ftype),
1301
  })
1302
  if cohorts and not any(f.get('key') == COHORT_COLUMN for f in out):
1303
  # ⚠ The emptiness check is WAVE 19's, and it is about the topics R9 opened this column to.
@@ -1831,10 +1884,37 @@ _HEX6 = re.compile(r'^#[0-9A-Fa-f]{6}$')
1831
  TS_DELTA_KINDS = ('abs', 'pct', 'yoy', 'ytd')
1832
  TS_MAX_CUSTOM_ROWS = 12
1833
  TS_MAX_STYLES = 200
1834
- #: R2 — a formula row's `expr` is stored VERBATIM and NEVER parsed here (evaluation is client
1835
- #: law; the client refuses unknown refs/cycles/div-zero itself). The charset wall is the whole
1836
- #: server-side contract: row refs `[...]`, arithmetic, numbers — no markup, no control chars.
1837
- _TS_EXPR_OK = re.compile(r'^[A-Za-z0-9_ .+\-*/()\[\]]+$')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1838
 
1839
  #: Old wire value -> the value we store today. Applied AFTER the membership test so an unknown
1840
  #: mode is still rejected rather than accidentally aliased.
@@ -2256,12 +2336,11 @@ def _clean_display(raw, valid_keys):
2256
  one = {'id': rid, 'kind': r_kind, 'label': label.strip()[:120]}
2257
  if r_kind == 'formula':
2258
  expr = r.get('expr')
2259
- if (isinstance(expr, str) and expr.strip()
2260
- and len(expr) <= 200 and _TS_EXPR_OK.match(expr)):
2261
  one['expr'] = expr
2262
- # else: keep the ROW, drop the EXPR — it renders "—". Vanishing the row
2263
- # would delete the user's label to punish their arithmetic (GRID's dated
2264
- # asymmetry amendment; the calendarMetrics per-entry-drop precedent).
2265
  seen_r.add(rid)
2266
  clean_r.append(one)
2267
  if clean_r:
@@ -2726,14 +2805,21 @@ def clean_filter_tree(raw, valid_keys, depth=1, budget=None, cohort_ids=None,
2726
  leaf['locked'] = True
2727
  out.append(leaf)
2728
  continue
2729
- if node.get('colId') in valid_keys and node.get('op') in FILTER_OPS:
 
 
 
 
 
 
 
2730
  budget[0] -= 1
2731
  # `or ''` would be wrong here: it maps every FALSY value to '', and '' is the
2732
  # signal for "inactive". A numeric 0 (or 0.0, or False) is a real value the client
2733
  # treats as active — `0 === ""` is false in TS — so `revenue = 0` would silently
2734
  # stop filtering and show every row instead of the zero-revenue ones.
2735
  val, val2 = node.get('value'), node.get('value2')
2736
- leaf = {'colId': node['colId'], 'op': node['op'],
2737
  'value': ('' if val is None else str(val))[:500],
2738
  'value2': ('' if val2 is None else str(val2))[:500]}
2739
  # CG-8. A MEASURE condition ("Sales, in the last 90 days, > 5,000") carries two
@@ -2789,6 +2875,51 @@ def clean_filter_tree(raw, valid_keys, depth=1, budget=None, cohort_ids=None,
2789
  return out
2790
 
2791
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2792
  def preserve_locked_view_records(prior_config, filters, sorts):
2793
  """Return authoritative filter/sort records when an in-place lock was touched.
2794
 
 
24
  injected-HTML path remains a read/local-write fallback when component assets are absent.
25
  """
26
  import datetime as _dt
27
+ import copy
28
  import json
29
  import math
30
  import re
 
805
  return frozenset(days)
806
 
807
 
808
+ def clean_date_recurrence(raw, condition_fields=None):
809
  """One date field's recurrence config, or ``None`` for absent/malformed input.
810
 
811
  ``rules`` are an intentional union: selecting weekday + public holiday means either makes
 
815
  if not isinstance(raw, dict):
816
  return None
817
  start = _iso_day(raw.get('startDate', raw.get('anchor')))
818
+ anchor_raw = raw.get('anchorField')
819
+ anchor = None
820
+ if isinstance(anchor_raw, dict):
821
+ table = str(anchor_raw.get('table') or 'same').strip()[:80]
822
+ field = str(anchor_raw.get('field') or '').strip()[:80]
823
+ via = str(anchor_raw.get('linkedVia') or '').strip()[:80]
824
+ if field and (table == 'same' or via):
825
+ anchor = {'table': table, 'field': field}
826
+ if via:
827
+ anchor['linkedVia'] = via
828
+ if start is None and anchor is None:
829
  return None
830
  out_rules = []
831
  for raw_rule in list(raw.get('rules') or [])[:12]:
 
842
  weekdays = sorted({day for day in (raw_rule.get('weekdays') or [])
843
  if isinstance(day, int) and not isinstance(day, bool)
844
  and 0 <= day <= 6})
845
+ rule['weekdays'] = weekdays or ([start.weekday()] if start else [])
846
+ if not rule['weekdays']:
847
+ continue
848
  elif kind == 'monthly':
849
  # ``day: 1`` means the first of every N months. ``ordinal`` + ``weekday`` adds
850
  # Google-Calendar-style first Monday / last Friday without a competing model.
 
857
  continue
858
  rule.update({'ordinal': ordinal, 'weekday': weekday})
859
  else:
860
+ day = raw_rule.get('day', start.day if start else None)
861
  if not isinstance(day, int) or isinstance(day, bool) or not 1 <= day <= 31:
862
  continue
863
  rule['day'] = day
864
  elif kind == 'yearly':
865
+ month = raw_rule.get('month', start.month if start else None)
866
+ day = raw_rule.get('day', start.day if start else None)
867
  if (not isinstance(month, int) or isinstance(month, bool) or not 1 <= month <= 12
868
  or not isinstance(day, int) or isinstance(day, bool) or not 1 <= day <= 31):
869
  continue
 
890
  preview_count = raw.get('previewCount', raw.get('preview', 10))
891
  if not isinstance(preview_count, int) or isinstance(preview_count, bool):
892
  preview_count = 10
893
+ out = {'rules': out_rules, 'previewCount': max(1, min(preview_count, 50))}
894
+ if start:
895
+ out['startDate'] = start.isoformat()
896
+ if anchor:
897
+ out['anchorField'] = anchor
898
+ admitted_conditions = (condition_fields if condition_fields is not None
899
+ else raw.get('conditionFields'))
900
+ conditions = clean_filter_tree(raw.get('conditions') or [], valid_keys={
901
+ str(key) for key in admitted_conditions or () if str(key)})
902
+ if conditions:
903
+ out['conditions'] = conditions
904
+ return out
905
 
906
 
907
  def _recurrence_matches(day, start, rule):
 
927
  return False
928
 
929
 
930
+ def recurrence_preview(raw, today=None, count=None, condition_fields=None):
931
  """The next distinct ISO dates, anchored to the server's supplied/current day."""
932
+ config = clean_date_recurrence(raw, condition_fields=condition_fields)
933
  if config is None:
934
  return []
935
  now = _iso_day(today) or _dt.date.today()
936
+ start = _iso_day(config.get('startDate'))
937
+ if start is None and isinstance(raw, dict):
938
+ start = _iso_day(raw.get('resolvedAnchorDate'))
939
+ if start is None:
940
+ return []
941
  want = config['previewCount'] if count is None else max(1, min(int(count), 50))
942
  lower = max(start, now)
943
  # A preview of at most fifty values needs no unbounded search. Ten years also makes an
 
963
  return [item.isoformat() for item in sorted(found)[:want]]
964
 
965
 
966
+ def recurrence_payload(raw, today=None, condition_fields=None):
967
  """Durable config plus server-authoritative ``nextDate`` and finite ``preview``."""
968
+ config = clean_date_recurrence(raw, condition_fields=condition_fields)
969
  if config is None:
970
  return None
971
+ preview = recurrence_preview(config, today=today, condition_fields=condition_fields)
972
  return {**config, 'nextDate': preview[0] if preview else None, 'preview': preview}
973
 
974
 
975
+ def project_date_recurrences(fields, today=None):
976
+ """Re-project recurrence metadata against the final visible field contract."""
977
+ valid_keys = {str(field.get('key')) for field in fields or ()
978
+ if isinstance(field, dict) and field.get('key')}
979
+ out = []
980
+ for field in fields or ():
981
+ if not isinstance(field, dict) or field.get('type') != 'date' \
982
+ or not isinstance(field.get('recurrence'), dict):
983
+ out.append(field)
984
+ continue
985
+ item = dict(field)
986
+ recurrence = recurrence_payload(
987
+ field.get('recurrence'), today=today, condition_fields=valid_keys)
988
+ if recurrence:
989
+ item['recurrence'] = recurrence
990
+ else:
991
+ item.pop('recurrence', None)
992
+ out.append(item)
993
+ return out
994
+
995
+
996
+ def _field_extras(saved, ftype, condition_fields=None):
997
  """createdBy / permissions / format / scope — the validated passthrough the created strata
998
  share (wave 5). `createdBy` is only ever WRITTEN host-side (the handler stamps it); here it
999
  is carried so the client can gate its menus and the handler can enforce against it.
 
1036
  # W43C C2 — the ISO date remains scalar in each row; recurrence is field metadata. Serve
1037
  # the compact persisted config together with a server-derived next date and preview so the
1038
  # client never substitutes its browser clock or holiday library for the tenant contract.
1039
+ recurrence = (recurrence_payload(saved.get("recurrence"),
1040
+ condition_fields=condition_fields)
1041
+ if ftype == "date" else None)
1042
  if recurrence:
1043
  out["recurrence"] = recurrence
1044
  corrected_from = saved.get("labelCorrectedFrom")
 
1204
  out = []
1205
  base_fields = fields_base if fields_base is not None else FIELDS
1206
  base_keys = {field["key"] for field in base_fields}
1207
+ recurrence_keys = base_keys | {str(key) for key in saved}
1208
  for base in base_fields:
1209
  meta = saved.get(base["key"]) or {}
1210
  field = dict(base)
 
1246
  # fields need this explicit read half because their override is otherwise rebuilt from
1247
  # the immutable contract on every workspace projection.
1248
  if base.get("type") == "date" and "recurrence" in meta:
1249
+ recurrence = recurrence_payload(
1250
+ meta.get("recurrence"), condition_fields=recurrence_keys)
1251
  if recurrence:
1252
  field["recurrence"] = recurrence
1253
  out.append(field)
 
1282
  else "sum" if mtype in ("currency", "int") else None),
1283
  "note": str(field.get("note") or "")[:2000],
1284
  "measure": {"key": mkey[:80], "window": window},
1285
+ **_field_extras(field, mtype, condition_fields=recurrence_keys),
1286
  })
1287
  continue
1288
  if not str(key).startswith("custom_"):
 
1308
  "default": bool(field.get("default", True)),
1309
  "custom": True,
1310
  "note": str(field.get("note") or "")[:2000],
1311
+ **_field_extras(field, ftype, condition_fields=recurrence_keys),
1312
  }
1313
  if ftype == "formula":
1314
  formula = _clean_formula(field.get("formula"))
 
1350
  # string. Absent = `plain`, which is what an unconfigured code column renders as.
1351
  **({"code": _clean_code(field.get("code"))}
1352
  if ftype == "code" and _clean_code(field.get("code")) else {}),
1353
+ **_field_extras(field, ftype, condition_fields=recurrence_keys),
1354
  })
1355
  if cohorts and not any(f.get('key') == COHORT_COLUMN for f in out):
1356
  # ⚠ The emptiness check is WAVE 19's, and it is about the topics R9 opened this column to.
 
1884
  TS_DELTA_KINDS = ('abs', 'pct', 'yoy', 'ytd')
1885
  TS_MAX_CUSTOM_ROWS = 12
1886
  TS_MAX_STYLES = 200
1887
+ TS_MAX_EXPR = 500
1888
+
1889
+
1890
+ def _ts_formula_source_ok(expr):
1891
+ """Transport wall for a Time Series formula governed by the shared server parser.
1892
+
1893
+ This function deliberately does not duplicate the formula grammar. It preserves any bounded
1894
+ source, including quotes and regex punctuation, for the API parser to accept or explain. The
1895
+ sole syntax-shaped refusal is an unquoted square bracket: the shared contract declares that
1896
+ legacy ``[field]`` references cannot enter the braces-only grammar. Brackets inside a quoted
1897
+ regex/text literal remain ordinary source and round-trip byte-for-byte.
1898
+ """
1899
+ if not isinstance(expr, str) or len(expr) > TS_MAX_EXPR:
1900
+ return False
1901
+ quote, i = None, 0
1902
+ while i < len(expr):
1903
+ char = expr[i]
1904
+ if quote:
1905
+ if char == quote:
1906
+ if i + 1 < len(expr) and expr[i + 1] == quote:
1907
+ i += 2
1908
+ continue
1909
+ quote = None
1910
+ i += 1
1911
+ continue
1912
+ if char in ("'", '"'):
1913
+ quote = char
1914
+ elif char in '[]':
1915
+ return False
1916
+ i += 1
1917
+ return True
1918
 
1919
  #: Old wire value -> the value we store today. Applied AFTER the membership test so an unknown
1920
  #: mode is still rejected rather than accidentally aliased.
 
2336
  one = {'id': rid, 'kind': r_kind, 'label': label.strip()[:120]}
2337
  if r_kind == 'formula':
2338
  expr = r.get('expr')
2339
+ if _ts_formula_source_ok(expr):
 
2340
  one['expr'] = expr
2341
+ # Else keep the ROW and drop only the source. Legacy square references and
2342
+ # over-bound transport cannot enter the shared formula parser; deleting the row
2343
+ # would also delete the user's label and its saved order.
2344
  seen_r.add(rid)
2345
  clean_r.append(one)
2346
  if clean_r:
 
2805
  leaf['locked'] = True
2806
  out.append(leaf)
2807
  continue
2808
+ # Wave 45 C1: ``zone`` was the pre-canonical projection key. A saved View is migrated
2809
+ # at its ordinary validated save door, rather than kept as a second readable field or
2810
+ # dropped as an unknown condition. The migration is admissible only when this database
2811
+ # actually exposes ``__zone__``; on every other database an unknown ``zone`` leaf keeps
2812
+ # the longstanding fail-closed behaviour.
2813
+ column = ('__zone__' if node.get('colId') == 'zone' and '__zone__' in valid_keys
2814
+ else node.get('colId'))
2815
+ if column in valid_keys and node.get('op') in FILTER_OPS:
2816
  budget[0] -= 1
2817
  # `or ''` would be wrong here: it maps every FALSY value to '', and '' is the
2818
  # signal for "inactive". A numeric 0 (or 0.0, or False) is a real value the client
2819
  # treats as active — `0 === ""` is false in TS — so `revenue = 0` would silently
2820
  # stop filtering and show every row instead of the zero-revenue ones.
2821
  val, val2 = node.get('value'), node.get('value2')
2822
+ leaf = {'colId': column, 'op': node['op'],
2823
  'value': ('' if val is None else str(val))[:500],
2824
  'value2': ('' if val2 is None else str(val2))[:500]}
2825
  # CG-8. A MEASURE condition ("Sales, in the last 90 days, > 5,000") carries two
 
2875
  return out
2876
 
2877
 
2878
+ def migrate_zone_projection_config(raw):
2879
+ """Copy one saved View config while renaming every legacy ``zone`` field reference.
2880
+
2881
+ Filter leaves are validated later by ``clean_filter_tree``. The other members are field-key
2882
+ projections and can be migrated structurally here, before their normal allow-list checks.
2883
+ This retains old View intent without re-publishing ``zone`` as a writable or readable field.
2884
+ """
2885
+ config = copy.deepcopy(raw if isinstance(raw, dict) else {})
2886
+
2887
+ def key(value):
2888
+ return '__zone__' if value == 'zone' else value
2889
+
2890
+ def filters(nodes):
2891
+ for node in nodes or ():
2892
+ if not isinstance(node, dict):
2893
+ continue
2894
+ if isinstance(node.get('children'), list):
2895
+ filters(node['children'])
2896
+ else:
2897
+ if node.get('colId') == 'zone':
2898
+ node['colId'] = '__zone__'
2899
+ rank_scope = node.get('rankScope')
2900
+ if isinstance(rank_scope, dict):
2901
+ for member in ('field', 'groupBy'):
2902
+ if member in rank_scope:
2903
+ rank_scope[member] = key(rank_scope.get(member))
2904
+
2905
+ raw_filters = config.get('filters')
2906
+ filters((raw_filters.get('nodes') or raw_filters.get('children') or ())
2907
+ if isinstance(raw_filters, dict) else raw_filters)
2908
+ for member in ('sorts',):
2909
+ for item in config.get(member) or ():
2910
+ if isinstance(item, dict) and item.get('colId') == 'zone':
2911
+ item['colId'] = '__zone__'
2912
+ for member in ('order', 'visible'):
2913
+ if isinstance(config.get(member), list):
2914
+ config[member] = list(dict.fromkeys(key(value) for value in config[member]))
2915
+ if isinstance(config.get('widths'), dict) and 'zone' in config['widths']:
2916
+ config['widths']['__zone__'] = config['widths'].pop('zone')
2917
+ for member in ('groupBy', 'colorBy', 'stackField'):
2918
+ if config.get(member) == 'zone':
2919
+ config[member] = '__zone__'
2920
+ return config
2921
+
2922
+
2923
  def preserve_locked_view_records(prior_config, filters, sorts):
2924
  """Return authoritative filter/sort records when an in-place lock was touched.
2925
 
platform/core/assets.py CHANGED
@@ -23,6 +23,7 @@ import time
23
  from pathlib import Path
24
 
25
  DEFAULT_REPO = 'royal-imports/product-assets'
 
26
  _MANIFEST_TTL = 300
27
  #: (fetched_at, {"CODE": {...}}, {"slug": {...}}) — one manifest read per process per TTL.
28
  #: DEBT-5 (2026-08-04): the same manifest.json now carries a second, NON-SKU half under
@@ -216,3 +217,19 @@ def put_record(tenant, asset_id, orig_bytes, ext, web_png):
216
  def reset_cache():
217
  """Drop the memoized manifest — for gates and for a post-ingest refresh."""
218
  _MANIFEST.update(at=0.0, codes=None, editorial=None, records=None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  from pathlib import Path
24
 
25
  DEFAULT_REPO = 'royal-imports/product-assets'
26
+ APPLICATION_TYPES = ('chart', 'route', 'map', 'timeseries')
27
  _MANIFEST_TTL = 300
28
  #: (fetched_at, {"CODE": {...}}, {"slug": {...}}) — one manifest read per process per TTL.
29
  #: DEBT-5 (2026-08-04): the same manifest.json now carries a second, NON-SKU half under
 
217
  def reset_cache():
218
  """Drop the memoized manifest — for gates and for a post-ingest refresh."""
219
  _MANIFEST.update(at=0.0, codes=None, editorial=None, records=None)
220
+
221
+
222
+ def application_open_target(application):
223
+ """Stable typed target shared by Home, Starred and the Application selector.
224
+
225
+ Application assets are tenant-store records, not image-manifest entries. This helper lives
226
+ here only as the common asset-address contract and performs no I/O.
227
+ """
228
+ row = application if isinstance(application, dict) else {}
229
+ kind = str(row.get('type') or '').lower()
230
+ app_id = str(row.get('id') or '').strip()
231
+ if kind not in APPLICATION_TYPES or not app_id:
232
+ return None
233
+ databases = row.get('compatibleDatabases') if isinstance(row.get('compatibleDatabases'), list) else []
234
+ return {'kind': 'application', 'id': app_id, 'type': kind,
235
+ 'database': str(databases[0]) if databases else None}
platform/core/grid_events.py CHANGED
@@ -45,7 +45,7 @@ from dataclasses import dataclass, field
45
  # `field(default_factory=list)` written inside one of those functions would resolve to the local
46
  # dict and raise. The alias is unshadowable, so D-291's channel cannot be broken by a rename.
47
  from dataclasses import field as dataclass_field
48
- from typing import List, MutableMapping, Optional
49
 
50
  import core.store as store
51
  import core.table_store as _tstore # wave-9 I17: the shared-view authorisation predicates
@@ -152,6 +152,14 @@ class EventCtx:
152
  #: naming the key, because `overlay_keys` only asks whether the column exists. Empty means
153
  #: "nothing hidden", which is every legacy record and therefore every caller today.
154
  hidden_keys: frozenset = frozenset()
 
 
 
 
 
 
 
 
155
  scope_key: str = 'customer'
156
  #: Wave 16 C-TOPIC — the TABLE OPS this ctx reads and writes (a `core.table_store.make`
157
  #: object). None = the CUSTOMER table (`modules.customer_data.TABLE_OPS`), which keeps
@@ -1253,6 +1261,16 @@ def handle_one(event, ctx):
1253
  for stale in list(seen)[:200]:
1254
  seen.pop(stale, None)
1255
  kind = event.get('type')
 
 
 
 
 
 
 
 
 
 
1256
  field_by_key = {f['key']: f for f in fields}
1257
  # A Product shared-select option can have been admitted by an earlier event while this
1258
  # EventCtx remains alive. The renderer gets the persisted choice projection on refresh,
@@ -1339,12 +1357,12 @@ def handle_one(event, ctx):
1339
  requested_name = name
1340
  if not view_id or not name:
1341
  return False
1342
- cfg = raw['config']
1343
  # The filter TREE (leaf conditions and/or nested condition groups) is
1344
  # validated by the module-agnostic grid contract helper — imported lazily
1345
  # here for the same reason the page does it: a missing embed build must
1346
  # never break page import.
1347
  import aios_grid as _ag
 
1348
  # A MEASURE key is valid in a FILTER and nowhere else (CG-8): it may not be ordered,
1349
  # shown, grouped or coloured by, because it is not a column of this table. Hence the
1350
  # widened key set here and the plain `valid_keys` everywhere below.
@@ -2015,7 +2033,18 @@ def handle_one(event, ctx):
2015
  if 'recurrence' not in raw and recurrence_raw is None and not shared_field:
2016
  previous = (ws.get('fields') or {}).get(key)
2017
  recurrence_raw = previous.get('recurrence') if isinstance(previous, dict) else None
2018
- recurrence = _ag2.clean_date_recurrence(recurrence_raw)
 
 
 
 
 
 
 
 
 
 
 
2019
  if recurrence:
2020
  field['recurrence'] = recurrence
2021
  else:
@@ -2969,6 +2998,13 @@ def handle_one(event, ctx):
2969
  pid = event.get('pid')
2970
  if not isinstance(pid, int) or pid not in allowed_pids:
2971
  return False
 
 
 
 
 
 
 
2972
  updates = {}
2973
  refused = False
2974
  stage_moved = False
@@ -2980,7 +3016,9 @@ def handle_one(event, ctx):
2980
  choice_additions = {}
2981
  raw_updates = event.get('updates') if isinstance(event.get('updates'), dict) else {}
2982
  for key, value in raw_updates.items():
2983
- if key not in overlay_keys or not isinstance(value, (str, int, float)):
 
 
2984
  refused = True
2985
  continue
2986
  # C-PERM: a field this caller's permissions HIDE cannot be written, only refused.
@@ -3110,6 +3148,12 @@ def handle_one(event, ctx):
3110
  if isinstance(_auto, dict) and (_auto.get('flowId') or _auto.get('preset')):
3111
  refused = True
3112
  continue
 
 
 
 
 
 
3113
  # ⭐ WAVE 23 (C7) — the json wall, BEFORE the generic 10 000-char truncation, which
3114
  # would otherwise cut a document in half and store the halves as valid text. A json
3115
  # column promises its readers a parseable document; a write that is not one is
@@ -3221,6 +3265,20 @@ def handle_one(event, ctx):
3221
  _ut_ev.emit_row_event({'type': 'event_field', 'table': str(ctx.scope_key),
3222
  'rowId': str(pid), 'field': _k, 'after': _v,
3223
  'st': ctx.table.st, 'user': uname})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3224
  # Wave-6 item 3: the client's cell already shows the typed value — rerun ONLY when
3225
  # some of what it shows was refused or clamped and must be repainted to the truth.
3226
  # A stage move reruns too: its `arrive` side-effects (the tracked flag) changed cells
 
45
  # `field(default_factory=list)` written inside one of those functions would resolve to the local
46
  # dict and raise. The alias is unshadowable, so D-291's channel cannot be broken by a rename.
47
  from dataclasses import field as dataclass_field
48
+ from typing import Callable, List, MutableMapping, Optional
49
 
50
  import core.store as store
51
  import core.table_store as _tstore # wave-9 I17: the shared-view authorisation predicates
 
152
  #: naming the key, because `overlay_keys` only asks whether the column exists. Empty means
153
  #: "nothing hidden", which is every legacy record and therefore every caller today.
154
  hidden_keys: frozenset = frozenset()
155
+ # Wave 45 R15: the transport adapter supplies the authority-aware recurrence validator.
156
+ # Core can normalise a recurrence's finite shape, but it cannot decide whether a named
157
+ # same/linked field is visible to this caller without reaching upward into the API layer.
158
+ recurrence_validator: Optional[Callable[[object], Optional[dict]]] = None
159
+ # Value-history restore reuses the ordinary cell wall. This stamp changes only the audit
160
+ # event kind and admits ``None`` as "remove the prior cell" after every normal field/row
161
+ # permission check has passed; browser-authored edits never set it.
162
+ history_kind: str = 'edit'
163
  scope_key: str = 'customer'
164
  #: Wave 16 C-TOPIC — the TABLE OPS this ctx reads and writes (a `core.table_store.make`
165
  #: object). None = the CUSTOMER table (`modules.customer_data.TABLE_OPS`), which keeps
 
1261
  for stale in list(seen)[:200]:
1262
  seen.pop(stale, None)
1263
  kind = event.get('type')
1264
+ from core import user_tables as _zone_contract
1265
+ _zone_key = _zone_contract.ZONE_FIELD_KEY
1266
+ _offered_keys = set((event.get('updates') or {}).keys()) if isinstance(
1267
+ event.get('updates'), dict) else set()
1268
+ _raw_field = event.get('field') if isinstance(event.get('field'), dict) else {}
1269
+ if _offered_keys.intersection({_zone_key, 'zone'}) \
1270
+ or str(_raw_field.get('key') or '') in {_zone_key, 'zone'}:
1271
+ return _refuse(ctx, 'zone_membership_read_only',
1272
+ "Zone membership is worked out from the record's current location",
1273
+ key=_zone_key, event=str(kind or 'grid_event'))
1274
  field_by_key = {f['key']: f for f in fields}
1275
  # A Product shared-select option can have been admitted by an earlier event while this
1276
  # EventCtx remains alive. The renderer gets the persisted choice projection on refresh,
 
1357
  requested_name = name
1358
  if not view_id or not name:
1359
  return False
 
1360
  # The filter TREE (leaf conditions and/or nested condition groups) is
1361
  # validated by the module-agnostic grid contract helper — imported lazily
1362
  # here for the same reason the page does it: a missing embed build must
1363
  # never break page import.
1364
  import aios_grid as _ag
1365
+ cfg = _ag.migrate_zone_projection_config(raw['config'])
1366
  # A MEASURE key is valid in a FILTER and nowhere else (CG-8): it may not be ordered,
1367
  # shown, grouped or coloured by, because it is not a column of this table. Hence the
1368
  # widened key set here and the plain `valid_keys` everywhere below.
 
2033
  if 'recurrence' not in raw and recurrence_raw is None and not shared_field:
2034
  previous = (ws.get('fields') or {}).get(key)
2035
  recurrence_raw = previous.get('recurrence') if isinstance(previous, dict) else None
2036
+ if 'recurrence' in raw:
2037
+ if recurrence_raw is not None and ctx.recurrence_validator is None:
2038
+ return _refuse(
2039
+ ctx, 'bad_recurrence',
2040
+ 'recurrence needs the server field-authority validator', key)
2041
+ try:
2042
+ recurrence = (ctx.recurrence_validator(recurrence_raw)
2043
+ if ctx.recurrence_validator is not None else None)
2044
+ except (TypeError, ValueError) as exc:
2045
+ return _refuse(ctx, 'bad_recurrence', str(exc)[:240], key)
2046
+ else:
2047
+ recurrence = _ag2.clean_date_recurrence(recurrence_raw)
2048
  if recurrence:
2049
  field['recurrence'] = recurrence
2050
  else:
 
2998
  pid = event.get('pid')
2999
  if not isinstance(pid, int) or pid not in allowed_pids:
3000
  return False
3001
+ _history_table = str(ctx.scope_key or 'customer')
3002
+ if _history_table.startswith('ut_') and ctx.table is not None:
3003
+ import core.user_tables as _ut_history
3004
+ _history_before = dict((((_ut_history.get(
3005
+ _history_table, st=ctx.table.st) or {}).get('rows') or {}).get(str(pid)) or {}))
3006
+ else:
3007
+ _history_before = dict(((ws.get('overlays') or {}).get(str(pid)) or {}))
3008
  updates = {}
3009
  refused = False
3010
  stage_moved = False
 
3016
  choice_additions = {}
3017
  raw_updates = event.get('updates') if isinstance(event.get('updates'), dict) else {}
3018
  for key, value in raw_updates.items():
3019
+ restoring_absence = value is None and ctx.history_kind == 'restore'
3020
+ if key not in overlay_keys or (
3021
+ not restoring_absence and not isinstance(value, (str, int, float))):
3022
  refused = True
3023
  continue
3024
  # C-PERM: a field this caller's permissions HIDE cannot be written, only refused.
 
3148
  if isinstance(_auto, dict) and (_auto.get('flowId') or _auto.get('preset')):
3149
  refused = True
3150
  continue
3151
+ # A restore of an event whose before-value was absent removes the cell. It reaches
3152
+ # this branch only after the same hidden, edit-role, automation and computed-field
3153
+ # checks as an ordinary edit. A browser-authored null remains refused above.
3154
+ if restoring_absence:
3155
+ updates[key] = None
3156
+ continue
3157
  # ⭐ WAVE 23 (C7) — the json wall, BEFORE the generic 10 000-char truncation, which
3158
  # would otherwise cut a document in half and store the halves as valid text. A json
3159
  # column promises its readers a parseable document; a write that is not one is
 
3265
  _ut_ev.emit_row_event({'type': 'event_field', 'table': str(ctx.scope_key),
3266
  'rowId': str(pid), 'field': _k, 'after': _v,
3267
  'st': ctx.table.st, 'user': uname})
3268
+ if updates or row_events:
3269
+ import core.user_tables as _ut_history
3270
+ if _history_table.startswith('ut_') and ctx.table is not None:
3271
+ _history_after = dict((((_ut_history.get(
3272
+ _history_table, st=ctx.table.st) or {}).get('rows') or {}).get(str(pid)) or {}))
3273
+ _history_st = ctx.table.st
3274
+ else:
3275
+ _history_after = dict(_history_before)
3276
+ _history_after.update(updates)
3277
+ _history_after.update(dict(row_events))
3278
+ _history_st = ctx.st
3279
+ _ut_history.append_value_history(
3280
+ _history_table, pid, _history_before, _history_after, uname, st=_history_st,
3281
+ kind=ctx.history_kind)
3282
  # Wave-6 item 3: the client's cell already shows the typed value — rerun ONLY when
3283
  # some of what it shows was refused or clamped and must be repainted to the truth.
3284
  # A stage move reruns too: its `arrive` side-effects (the tracked flag) changed cells
platform/core/route_system.py CHANGED
@@ -12,12 +12,15 @@ import hashlib
12
  import math
13
  import re
14
  import uuid
 
15
 
16
  MANAGED_BY = "loopable"
17
  LOOPABLE_FOLDER_ID = "loopable"
18
  LOOPABLE_FOLDER = {"id": LOOPABLE_FOLDER_ID, "name": "Loopable", "managedBy": MANAGED_BY}
19
  ROUTES_KEY, ZONES_KEY = "ut_odoo_customers_routes", "ut_odoo_customers_zones"
20
  SYSTEM_TABLES = {ROUTES_KEY: "Odoo Customers - Routes", ZONES_KEY: "Odoo Customers - Zones"}
 
 
21
 
22
  # TenantRuntime namespaces this bucket. User-table rows are scalar user data; route stops are a
23
  # protected relation (route id + customer id + order), so they cannot be a generic Link field.
@@ -174,6 +177,18 @@ def _route(raw, *, ordinal=0, created_by="", tenant_id="", prior=None):
174
  source_view = str(source_view or "").strip()[:120] or None
175
  revision = raw.get("sourceViewRevision", prior.get("sourceViewRevision"))
176
  revision = str(revision or "").strip()[:128] or None
 
 
 
 
 
 
 
 
 
 
 
 
177
  stops_raw = raw.get("stops") if "stops" in raw else prior.get("stops")
178
  maps_url = str(raw.get("mapsUrl", prior.get("mapsUrl")) or "").strip()[:2048]
179
  if maps_url and not _GOOGLE_MAPS_URL_RE.match(maps_url):
@@ -186,6 +201,8 @@ def _route(raw, *, ordinal=0, created_by="", tenant_id="", prior=None):
186
  "sourceViewRevision": revision, "stops": _stops(stops_raw), "managedBy": MANAGED_BY,
187
  "createdBy": str(prior.get("createdBy") or created_by or "")[:120],
188
  "shareKey": share_key,
 
 
189
  "createdAt": prior.get("createdAt") or stamp, "updatedAt": stamp}
190
  if maps_url:
191
  out["mapsUrl"] = maps_url
@@ -226,11 +243,78 @@ def _polygon_contains(geometry, lon, lat):
226
  return False
227
 
228
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  def _zone(raw, *, ordinal=0, created_by="", tenant_id="", prior=None):
230
  raw = raw if isinstance(raw, dict) else {}
231
  prior = prior if isinstance(prior, dict) else {}
232
  name = _name(raw.get("name", prior.get("name")))
233
- geometry = raw.get("geometryGeoJson", prior.get("geometryGeoJson"))
234
  zips_raw = raw.get("zipCodes", prior.get("zipCodes", ()))
235
  zips, seen = [], set()
236
  for value in zips_raw or ():
@@ -238,7 +322,7 @@ def _zone(raw, *, ordinal=0, created_by="", tenant_id="", prior=None):
238
  if text and text not in seen and _ZIP_RE.fullmatch(text):
239
  seen.add(text)
240
  zips.append(text)
241
- if not name or (geometry is not None and not isinstance(geometry, dict)) or (geometry is None and not zips):
242
  return None
243
  zid = str(raw.get("id") or prior.get("id") or "zone_" + uuid.uuid4().hex)[:96]
244
  source_view = raw.get("sourceViewId", prior.get("sourceViewId"))
@@ -248,11 +332,14 @@ def _zone(raw, *, ordinal=0, created_by="", tenant_id="", prior=None):
248
  stamp = _now()
249
  return {"id": zid, "tenantId": str(tenant_id or prior.get("tenantId") or ""), "name": name,
250
  "color": _color(raw.get("color", prior.get("color")), ordinal),
251
- "geometryGeoJson": copy.deepcopy(geometry) if isinstance(geometry, dict) else None,
252
  "zipCodes": zips, "visible": raw.get("visible", prior.get("visible", True)) is not False,
253
  "sourceViewId": source_view, "geographicField": geographic_field,
254
  "membershipRevision": int(prior.get("membershipRevision") or 0),
255
  "memberPids": [int(pid) for pid in prior.get("memberPids") or [] if _pid(pid) is not None],
 
 
 
256
  "managedBy": MANAGED_BY, "createdBy": str(prior.get("createdBy") or created_by or "")[:120],
257
  "createdAt": prior.get("createdAt") or stamp, "updatedAt": stamp}
258
 
@@ -267,21 +354,18 @@ def _customer_zip(row):
267
 
268
 
269
  def zone_members(zone, rows):
270
- """Polygon-or-ZIP UNION, recalculated from the current customer address projection."""
271
- zips = set(zone.get("zipCodes") or ())
272
  out = []
273
  for row in rows or ():
274
  pid = _pid((row or {}).get("pid"))
275
  if pid is None:
276
  continue
277
- zip_match = _customer_zip(row) in zips
278
  try:
279
  lon, lat = float(row.get("lon")), float(row.get("lat"))
280
- polygon_match = math.isfinite(lon) and math.isfinite(lat) and _polygon_contains(
281
- zone.get("geometryGeoJson"), lon, lat)
282
  except (TypeError, ValueError):
283
- polygon_match = False
284
- if zip_match or polygon_match:
285
  out.append(pid)
286
  return out
287
 
@@ -313,6 +397,7 @@ def _persist(st, mutate):
313
  state.setdefault("zones", [])
314
  state.setdefault("legacyMigrations", {})
315
  state.setdefault("routeNavigation", {})
 
316
  next_state, value = mutate(state)
317
  result["value"] = copy.deepcopy(value)
318
  return next_state
@@ -327,6 +412,7 @@ def read(st, rows=None):
327
  state.setdefault("zones", [])
328
  state.setdefault("legacyMigrations", {})
329
  state.setdefault("routeNavigation", {})
 
330
  return refresh_zone_memberships(state, rows or ()) if rows is not None else state
331
 
332
 
@@ -359,6 +445,129 @@ def duplicate_route(st, route_id, *, tenant_id, created_by, name=None):
359
  return put_route(st, raw, tenant_id=tenant_id, created_by=created_by)
360
 
361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
  def _nav_user(username):
363
  return str(username or "").strip().lower()[:120]
364
 
@@ -562,7 +771,7 @@ def list_zones(st, rows=None):
562
  return [copy.deepcopy(zone) for zone in read(st, rows).get("zones") or [] if isinstance(zone, dict)]
563
 
564
 
565
- def put_route(st, raw, *, tenant_id, created_by):
566
  """Dedicated normalized Route writer. Generic table endpoints cannot call this."""
567
  wanted = str((raw or {}).get("id") or "").strip()
568
 
@@ -580,6 +789,7 @@ def put_route(st, raw, *, tenant_id, created_by):
580
  else:
581
  routes[prior_index] = clean
582
  state["routes"] = routes
 
583
  return state, clean
584
 
585
  return _persist(st, mutate)
@@ -642,7 +852,7 @@ def set_stop_membership(st, route_id, customer_pid, present, *, tenant_id, creat
642
  return _persist(st, mutate)
643
 
644
 
645
- def delete_route(st, route_id):
646
  route_id = str(route_id or "").strip()
647
 
648
  def mutate(state):
@@ -664,12 +874,17 @@ def delete_route(st, route_id):
664
  nav["order"] = [value for value in nav.get("order") or () if str(value) != route_id]
665
  navigation[username] = nav
666
  state["routeNavigation"] = navigation
 
667
  return state, len(prior) != len(state["routes"])
668
 
669
  return bool(_persist(st, mutate))
670
 
671
 
672
  def put_zone(st, raw, *, rows, tenant_id, created_by):
 
 
 
 
673
  wanted = str((raw or {}).get("id") or "").strip()
674
 
675
  def mutate(state):
@@ -727,8 +942,9 @@ def customer_projection_fields(routes, zones):
727
  return [field_axes({"key": "routes", "label": "Routes", "type": "multiselect",
728
  "source": "odoo", "derived": True, "readOnly": True,
729
  "options": route_names}),
730
- field_axes({"key": "zone", "label": "Zone", "type": "multiselect",
731
  "source": "odoo", "derived": True, "readOnly": True,
 
732
  "options": zone_names})]
733
 
734
 
@@ -740,7 +956,10 @@ def apply_customer_projections(rows, routes, zones):
740
  item = dict(row)
741
  values = projection.get(item.get("pid"), projection.get(str(item.get("pid")), {})) or {}
742
  item["routes"] = ", ".join(str(name) for name in values.get("Routes", ()) if name)
743
- item["zone"] = ", ".join(str(name) for name in values.get("Zone", ()) if name)
 
 
 
744
  out.append(item)
745
  return out
746
 
 
12
  import math
13
  import re
14
  import uuid
15
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
16
 
17
  MANAGED_BY = "loopable"
18
  LOOPABLE_FOLDER_ID = "loopable"
19
  LOOPABLE_FOLDER = {"id": LOOPABLE_FOLDER_ID, "name": "Loopable", "managedBy": MANAGED_BY}
20
  ROUTES_KEY, ZONES_KEY = "ut_odoo_customers_routes", "ut_odoo_customers_zones"
21
  SYSTEM_TABLES = {ROUTES_KEY: "Odoo Customers - Routes", ZONES_KEY: "Odoo Customers - Zones"}
22
+ ZONE_FIELD_KEY = "__zone__"
23
+ CLIENT_ZONE_MEMBERSHIP_KEYS = frozenset(("memberPids", "member_pids", "memberships"))
24
 
25
  # TenantRuntime namespaces this bucket. User-table rows are scalar user data; route stops are a
26
  # protected relation (route id + customer id + order), so they cannot be a generic Link field.
 
177
  source_view = str(source_view or "").strip()[:120] or None
178
  revision = raw.get("sourceViewRevision", prior.get("sourceViewRevision"))
179
  revision = str(revision or "").strip()[:128] or None
180
+ assignee = str(raw.get("assignee", prior.get("assignee")) or "").strip().lower()[:120] or None
181
+ route_date = str(raw.get("date", prior.get("date")) or "").strip() or None
182
+ if route_date:
183
+ try:
184
+ route_date = _dt.date.fromisoformat(route_date).isoformat()
185
+ except ValueError:
186
+ return None
187
+ if (assignee is None) != (route_date is None):
188
+ # A Route assignment is one fact. Persisting either half would make the Inbox task
189
+ # appear at an unknowable time or for nobody, and a later PATCH could accidentally
190
+ # complete a schedule the user never submitted together.
191
+ return None
192
  stops_raw = raw.get("stops") if "stops" in raw else prior.get("stops")
193
  maps_url = str(raw.get("mapsUrl", prior.get("mapsUrl")) or "").strip()[:2048]
194
  if maps_url and not _GOOGLE_MAPS_URL_RE.match(maps_url):
 
201
  "sourceViewRevision": revision, "stops": _stops(stops_raw), "managedBy": MANAGED_BY,
202
  "createdBy": str(prior.get("createdBy") or created_by or "")[:120],
203
  "shareKey": share_key,
204
+ "assignee": assignee, "date": route_date,
205
+ "starred": raw.get("starred", prior.get("starred", False)) is True,
206
  "createdAt": prior.get("createdAt") or stamp, "updatedAt": stamp}
207
  if maps_url:
208
  out["mapsUrl"] = maps_url
 
243
  return False
244
 
245
 
246
+ def clean_zone_geometry(raw):
247
+ """Return the one bounded polygon/circle geometry accepted by every Zone writer."""
248
+ if not isinstance(raw, dict):
249
+ return None
250
+ kind = raw.get("type")
251
+ if kind == "Circle":
252
+ center = raw.get("center")
253
+ try:
254
+ lon, lat = float(center[0]), float(center[1])
255
+ radius = float(raw.get("radiusMeters"))
256
+ except (TypeError, ValueError, IndexError):
257
+ return None
258
+ if not (math.isfinite(lon) and math.isfinite(lat) and math.isfinite(radius)):
259
+ return None
260
+ if not (-180 <= lon <= 180 and -90 <= lat <= 90 and 0 < radius <= 2_000_000):
261
+ return None
262
+ return {"type": "Circle", "center": [lon, lat], "radiusMeters": radius}
263
+ coords = raw.get("coordinates")
264
+ polygons = [coords] if kind == "Polygon" else coords if kind == "MultiPolygon" else None
265
+ if not isinstance(polygons, list) or not polygons:
266
+ return None
267
+ clean_polygons = []
268
+ for polygon in polygons:
269
+ if not isinstance(polygon, list) or not polygon:
270
+ return None
271
+ clean_rings = []
272
+ for ring in polygon:
273
+ if not isinstance(ring, list) or len(ring) < 4:
274
+ return None
275
+ clean_ring = []
276
+ for point in ring:
277
+ try:
278
+ lon, lat = float(point[0]), float(point[1])
279
+ except (TypeError, ValueError, IndexError):
280
+ return None
281
+ if not (math.isfinite(lon) and math.isfinite(lat)) or not (
282
+ -180 <= lon <= 180 and -90 <= lat <= 90):
283
+ return None
284
+ clean_ring.append([lon, lat])
285
+ if clean_ring[0] != clean_ring[-1]:
286
+ return None
287
+ clean_rings.append(clean_ring)
288
+ clean_polygons.append(clean_rings)
289
+ return {"type": kind,
290
+ "coordinates": clean_polygons[0] if kind == "Polygon" else clean_polygons}
291
+
292
+
293
+ def point_in_zone(geometry, lon, lat):
294
+ """The single backend point-in-shape implementation for polygon and circle Zones."""
295
+ try:
296
+ lon, lat = float(lon), float(lat)
297
+ except (TypeError, ValueError):
298
+ return False
299
+ if not (math.isfinite(lon) and math.isfinite(lat)):
300
+ return False
301
+ clean = clean_zone_geometry(geometry)
302
+ if clean is None:
303
+ return False
304
+ if clean["type"] != "Circle":
305
+ return _polygon_contains(clean, lon, lat)
306
+ center_lon, center_lat = clean["center"]
307
+ mean_lat = math.radians((center_lat + lat) / 2)
308
+ dx = math.radians(lon - center_lon) * math.cos(mean_lat)
309
+ dy = math.radians(lat - center_lat)
310
+ return math.hypot(dx, dy) * 6_371_008.8 <= clean["radiusMeters"]
311
+
312
+
313
  def _zone(raw, *, ordinal=0, created_by="", tenant_id="", prior=None):
314
  raw = raw if isinstance(raw, dict) else {}
315
  prior = prior if isinstance(prior, dict) else {}
316
  name = _name(raw.get("name", prior.get("name")))
317
+ geometry = clean_zone_geometry(raw.get("geometryGeoJson", prior.get("geometryGeoJson")))
318
  zips_raw = raw.get("zipCodes", prior.get("zipCodes", ()))
319
  zips, seen = [], set()
320
  for value in zips_raw or ():
 
322
  if text and text not in seen and _ZIP_RE.fullmatch(text):
323
  seen.add(text)
324
  zips.append(text)
325
+ if not name or geometry is None:
326
  return None
327
  zid = str(raw.get("id") or prior.get("id") or "zone_" + uuid.uuid4().hex)[:96]
328
  source_view = raw.get("sourceViewId", prior.get("sourceViewId"))
 
332
  stamp = _now()
333
  return {"id": zid, "tenantId": str(tenant_id or prior.get("tenantId") or ""), "name": name,
334
  "color": _color(raw.get("color", prior.get("color")), ordinal),
335
+ "geometryGeoJson": geometry,
336
  "zipCodes": zips, "visible": raw.get("visible", prior.get("visible", True)) is not False,
337
  "sourceViewId": source_view, "geographicField": geographic_field,
338
  "membershipRevision": int(prior.get("membershipRevision") or 0),
339
  "memberPids": [int(pid) for pid in prior.get("memberPids") or [] if _pid(pid) is not None],
340
+ "legacyMembershipEvidence": [int(pid) for pid in (
341
+ prior.get("legacyMembershipEvidence") or prior.get("memberships") or ())
342
+ if _pid(pid) is not None],
343
  "managedBy": MANAGED_BY, "createdBy": str(prior.get("createdBy") or created_by or "")[:120],
344
  "createdAt": prior.get("createdAt") or stamp, "updatedAt": stamp}
345
 
 
354
 
355
 
356
  def zone_members(zone, rows):
357
+ """Recalculate membership only from current exact coordinates and visible geometry."""
 
358
  out = []
359
  for row in rows or ():
360
  pid = _pid((row or {}).get("pid"))
361
  if pid is None:
362
  continue
 
363
  try:
364
  lon, lat = float(row.get("lon")), float(row.get("lat"))
365
+ geometry_match = point_in_zone(zone.get("geometryGeoJson"), lon, lat)
 
366
  except (TypeError, ValueError):
367
+ geometry_match = False
368
+ if geometry_match:
369
  out.append(pid)
370
  return out
371
 
 
397
  state.setdefault("zones", [])
398
  state.setdefault("legacyMigrations", {})
399
  state.setdefault("routeNavigation", {})
400
+ state.setdefault("inboxTasks", [])
401
  next_state, value = mutate(state)
402
  result["value"] = copy.deepcopy(value)
403
  return next_state
 
412
  state.setdefault("zones", [])
413
  state.setdefault("legacyMigrations", {})
414
  state.setdefault("routeNavigation", {})
415
+ state.setdefault("inboxTasks", [])
416
  return refresh_zone_memberships(state, rows or ()) if rows is not None else state
417
 
418
 
 
445
  return put_route(st, raw, tenant_id=tenant_id, created_by=created_by)
446
 
447
 
448
+ def route_capabilities(route, *, can_edit=False, can_duplicate=False, can_delete=False):
449
+ """Explicit asset-menu capabilities; clients never infer rights from button visibility."""
450
+ compatibility = (route or {}).get("compatibility") == "legacy-route-order"
451
+ editable = bool(can_edit and not compatibility)
452
+ return {"rename": editable, "duplicate": bool(can_duplicate and not compatibility), "star": editable,
453
+ "share": editable, "delete": bool(can_delete and not compatibility)}
454
+
455
+
456
+ def tenant_day(timezone_name="UTC", *, now=None):
457
+ """Return the tenant-local calendar day from an explicit IANA timezone."""
458
+ stamp = now or _dt.datetime.now(_dt.timezone.utc)
459
+ if stamp.tzinfo is None:
460
+ stamp = stamp.replace(tzinfo=_dt.timezone.utc)
461
+ try:
462
+ zone = ZoneInfo(str(timezone_name or "UTC"))
463
+ except (ZoneInfoNotFoundError, ValueError):
464
+ zone = ZoneInfo("UTC")
465
+ return stamp.astimezone(zone).date()
466
+
467
+
468
+ def tenant_day_for_runtime(st, *, now=None):
469
+ """Resolve the calendar day from one tenant runtime, failing safely to UTC."""
470
+ config = getattr(getattr(st, "tenant", None), "config", None) or {}
471
+ return tenant_day(config.get("timezone") or config.get("timeZone") or "UTC", now=now)
472
+
473
+
474
+ def _inbox_day(value, *, st=None):
475
+ if isinstance(value, _dt.datetime):
476
+ return value.date()
477
+ if isinstance(value, _dt.date):
478
+ return value
479
+ fallback = tenant_day_for_runtime(st) if st is not None else tenant_day()
480
+ try:
481
+ return _dt.date.fromisoformat(str(value or fallback.isoformat())[:10])
482
+ except (TypeError, ValueError):
483
+ return fallback
484
+
485
+
486
+ def _reconcile_inbox_state(state, day):
487
+ """Project exactly one canonical task for every due Route assignment.
488
+
489
+ The semantic identity is Route + date + normalized assignee. Old duplicate ids are folded
490
+ into the deterministic id while preserving a read receipt from any copy. Rebuilt rows also
491
+ make rename/reschedule/delete changes visible in the same atomic state mutation.
492
+ """
493
+ routes = [item for item in state.get("routes") or () if isinstance(item, dict)]
494
+ existing = {}
495
+ for item in state.get("inboxTasks") or ():
496
+ if not isinstance(item, dict):
497
+ continue
498
+ key = (str(item.get("routeId") or ""), str(item.get("routeDate") or ""),
499
+ str(item.get("assignee") or "").strip().lower())
500
+ if all(key):
501
+ existing[key] = bool(existing.get(key)) or item.get("read") is True
502
+
503
+ tasks = []
504
+ seen = set()
505
+ for route in routes:
506
+ route_id = str(route.get("id") or "")
507
+ route_date = str(route.get("date") or "")
508
+ assignee = str(route.get("assignee") or "").strip().lower()
509
+ key = (route_id, route_date, assignee)
510
+ if not all(key) or key in seen:
511
+ continue
512
+ try:
513
+ due = _dt.date.fromisoformat(route_date)
514
+ except ValueError:
515
+ continue
516
+ if due > day:
517
+ continue
518
+ seen.add(key)
519
+ task_id = "route-task:" + hashlib.sha256(
520
+ f"{route_id}|{route_date}|{assignee}".encode("utf-8")).hexdigest()[:24]
521
+ tasks.append({
522
+ "id": task_id, "kind": "route_task", "subject": route.get("name") or "Route",
523
+ "routeId": route_id, "routeDate": route_date, "assignee": assignee,
524
+ "source": "Loopable Routes",
525
+ "target": {"module": "customer_data", "application": "map", "routeId": route_id},
526
+ "read": bool(existing.get(key)), "at": route_date,
527
+ })
528
+ state["inboxTasks"] = sorted(
529
+ tasks, key=lambda item: (item.get("at", ""), item["id"]), reverse=True)
530
+ return state["inboxTasks"]
531
+
532
+
533
+ def reconcile_inbox_tasks(st, *, today=None):
534
+ """Materialize one persistent task for each due Route assignee/day, idempotently."""
535
+ day = _inbox_day(today, st=st)
536
+
537
+ def mutate(state):
538
+ _reconcile_inbox_state(state, day)
539
+ return state, copy.deepcopy(state["inboxTasks"])
540
+
541
+ return _persist(st, mutate) or []
542
+
543
+
544
+ def inbox_tasks(st, assignee, *, today=None):
545
+ return [task for task in reconcile_inbox_tasks(st, today=today)
546
+ if str(task.get("assignee") or "").lower() == str(assignee or "").lower()]
547
+
548
+
549
+ def mark_inbox_tasks(st, assignee, ids=None, *, read=True):
550
+ """Set read state only on this assignee's persistent Route tasks."""
551
+ who = str(assignee or "").lower()
552
+ wanted = None if ids is None else {str(value) for value in ids}
553
+
554
+ def mutate(state):
555
+ tasks = []
556
+ for raw in state.get("inboxTasks") or ():
557
+ item = dict(raw) if isinstance(raw, dict) else None
558
+ if item is None:
559
+ continue
560
+ if (str(item.get("assignee") or "").lower() == who
561
+ and (wanted is None or str(item.get("id")) in wanted)):
562
+ item["read"] = bool(read)
563
+ tasks.append(item)
564
+ state["inboxTasks"] = tasks
565
+ return state, [dict(item) for item in tasks
566
+ if str(item.get("assignee") or "").lower() == who]
567
+
568
+ return _persist(st, mutate) or []
569
+
570
+
571
  def _nav_user(username):
572
  return str(username or "").strip().lower()[:120]
573
 
 
771
  return [copy.deepcopy(zone) for zone in read(st, rows).get("zones") or [] if isinstance(zone, dict)]
772
 
773
 
774
+ def put_route(st, raw, *, tenant_id, created_by, today=None):
775
  """Dedicated normalized Route writer. Generic table endpoints cannot call this."""
776
  wanted = str((raw or {}).get("id") or "").strip()
777
 
 
789
  else:
790
  routes[prior_index] = clean
791
  state["routes"] = routes
792
+ _reconcile_inbox_state(state, _inbox_day(today, st=st))
793
  return state, clean
794
 
795
  return _persist(st, mutate)
 
852
  return _persist(st, mutate)
853
 
854
 
855
+ def delete_route(st, route_id, *, today=None):
856
  route_id = str(route_id or "").strip()
857
 
858
  def mutate(state):
 
874
  nav["order"] = [value for value in nav.get("order") or () if str(value) != route_id]
875
  navigation[username] = nav
876
  state["routeNavigation"] = navigation
877
+ _reconcile_inbox_state(state, _inbox_day(today, st=st))
878
  return state, len(prior) != len(state["routes"])
879
 
880
  return bool(_persist(st, mutate))
881
 
882
 
883
  def put_zone(st, raw, *, rows, tenant_id, created_by):
884
+ # Membership is always derived from the permission-scoped current rows supplied by the
885
+ # mounted route. Refuse forged membership keys instead of silently lending them authority.
886
+ if not isinstance(raw, dict) or any(key in raw for key in CLIENT_ZONE_MEMBERSHIP_KEYS):
887
+ return None
888
  wanted = str((raw or {}).get("id") or "").strip()
889
 
890
  def mutate(state):
 
942
  return [field_axes({"key": "routes", "label": "Routes", "type": "multiselect",
943
  "source": "odoo", "derived": True, "readOnly": True,
944
  "options": route_names}),
945
+ field_axes({"key": ZONE_FIELD_KEY, "label": "Zone", "type": "multiselect",
946
  "source": "odoo", "derived": True, "readOnly": True,
947
+ "multi": True, "system": True, "protected": True,
948
  "options": zone_names})]
949
 
950
 
 
956
  item = dict(row)
957
  values = projection.get(item.get("pid"), projection.get(str(item.get("pid")), {})) or {}
958
  item["routes"] = ", ".join(str(name) for name in values.get("Routes", ()) if name)
959
+ item[ZONE_FIELD_KEY] = ", ".join(str(name) for name in values.get("Zone", ()) if name)
960
+ # Read-only migration evidence for saved filters created before ``__zone__`` became
961
+ # canonical. New contracts never publish this alias as a field.
962
+ item.pop("zone", None)
963
  out.append(item)
964
  return out
965
 
platform/core/user_tables.py CHANGED
@@ -56,11 +56,18 @@ from core.route_system import MAX_OPTIONS
56
 
57
  STORE_KEY = 'user_tables'
58
  ZONE_STORE_KEY = 'table_zones'
 
 
 
 
 
59
  # A reserved, derived multi-select field. It is table data backed by durable Zone membership,
60
  # not a user-editable column and therefore cannot collide with a field a user creates.
61
  ZONE_FIELD_KEY = '__zone__'
62
  MAX_TABLES = 40
63
  MAX_LABEL = 60
 
 
64
 
65
  #: ⭐ THE PER-TABLE ROW CEILING — 5,000 until 2026-08-09, and it was never a property of the
66
  #: substrate. Owner: *"Why do we keep having this MAX_ROWS problem, 5000 is too little. We need to
@@ -944,7 +951,7 @@ def _clean_format(raw):
944
  return out or None
945
 
946
 
947
- def clean_fields(raw):
948
  """Validate a caller-supplied field list into the stored shape — refuse junk, never store
949
  it. Returns a list of `{key,label,type,source}` dicts (source is always 'overlay': every
950
  base column of a user table is user-editable by construction), or None when nothing
@@ -1089,7 +1096,10 @@ def clean_fields(raw):
1089
  # type: the row still stores ``YYYY-MM-DD`` while this durable bag lets the server project
1090
  # the next date and preview consistently for every reader.
1091
  if entry is not None and ftype == 'date' and f.get('recurrence') is not None:
1092
- recurrence = _ag_recurrence(f.get('recurrence'))
 
 
 
1093
  if recurrence:
1094
  entry['recurrence'] = recurrence
1095
  if entry is None:
@@ -1174,7 +1184,7 @@ _ZONE_ID_RE = re.compile(r'^[A-Za-z0-9_-]{1,96}$')
1174
  _ZONE_FIELD_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_]{0,79}$')
1175
  _ZONE_COLOR_RE = re.compile(r'^#[0-9A-Fa-f]{6}$')
1176
  _ZONE_ZIP_RE = re.compile(r'^\d{5}(?:-\d{4})?$')
1177
- _ZONE_GEOMETRIES = frozenset({'Polygon', 'MultiPolygon'})
1178
  MAX_ZONE_ZIP_CODES = 500
1179
 
1180
 
@@ -1205,25 +1215,9 @@ def _zone_ring(raw):
1205
 
1206
 
1207
  def _clean_zone_geometry(raw):
1208
- """A bounded GeoJSON Polygon/MultiPolygon geometry, with no executable/foreign members."""
1209
- if not isinstance(raw, dict) or raw.get('type') not in _ZONE_GEOMETRIES:
1210
- return None
1211
- kind, coords = raw['type'], raw.get('coordinates')
1212
- if kind == 'Polygon':
1213
- rings = [_zone_ring(ring) for ring in (coords if isinstance(coords, list) else [])]
1214
- if not rings or any(ring is None for ring in rings):
1215
- return None
1216
- clean = rings
1217
- else:
1218
- clean = []
1219
- for polygon in (coords if isinstance(coords, list) else []):
1220
- rings = [_zone_ring(ring) for ring in (polygon if isinstance(polygon, list) else [])]
1221
- if not rings or any(ring is None for ring in rings):
1222
- return None
1223
- clean.append(rings)
1224
- if not clean:
1225
- return None
1226
- return {'type': kind, 'coordinates': clean}
1227
 
1228
 
1229
  def clean_zone(raw, field_keys=None, allowed_row_ids=None):
@@ -1245,9 +1239,9 @@ def clean_zone(raw, field_keys=None, allowed_row_ids=None):
1245
  if zip_code not in seen_zips:
1246
  seen_zips.add(zip_code)
1247
  zip_codes.append(zip_code)
1248
- # Existing polygon Zones remain valid byte-for-byte. Wave 44 also permits a ZIP-only Zone;
1249
- # the two shapes share this record rather than inventing a second persistence model.
1250
- if not name or (geometry is None and not zip_codes):
1251
  return None
1252
  out = {'name': name,
1253
  'color': (str(raw.get('color') or '#1F4E78').upper()),
@@ -1276,7 +1270,12 @@ def clean_zone(raw, field_keys=None, allowed_row_ids=None):
1276
  continue
1277
  seen.add(pid)
1278
  memberships.append(pid)
1279
- out['memberships'] = memberships
 
 
 
 
 
1280
  creator = str(raw.get('createdBy') or '').strip()[:120]
1281
  created_at = str(raw.get('createdAt') or '').strip()[:64]
1282
  if creator:
@@ -1353,7 +1352,8 @@ def zone_field(table_key, st=None):
1353
  names.append(name)
1354
  seen.add(name)
1355
  return {'key': ZONE_FIELD_KEY, 'label': 'Zone', 'type': 'multiselect', 'source': 'odoo',
1356
- 'derived': True, 'multi': True, 'default': True, 'options': names,
 
1357
  'colorCodeOptions': True}
1358
 
1359
 
@@ -1367,12 +1367,13 @@ def with_zone_field(table_key, fields, st=None):
1367
  def zone_cells(table_key, rows, allowed_row_ids=None, st=None):
1368
  """Layer canonical Zone memberships into ordinary row cells for FilterBuilder/evaluator use."""
1369
  allowed = ({str(pid) for pid in allowed_row_ids} if allowed_row_ids is not None else None)
 
1370
  labels_by_pid = {}
1371
  for zone in zones(table_key, st=st):
1372
  name = str(zone.get('name') or '').strip()
1373
  if not name:
1374
  continue
1375
- for pid in zone.get('memberships') or ():
1376
  key = str(pid)
1377
  if allowed is not None and key not in allowed:
1378
  continue
@@ -1420,7 +1421,8 @@ def is_managed_system_table(table_key, st=None, definition=None):
1420
  return route_system.is_managed(definition if definition is not None else (get(table_key, st) or table_key))
1421
 
1422
 
1423
- def create(label, username, fields=None, source=None, st=None, *, managed_by=None, capability=None):
 
1424
  """Create a blank table. Returns its key, or None if refused.
1425
 
1426
  Refuses rather than raises on the ordinary conditions (no name, duplicate, cap reached) —
@@ -1453,8 +1455,9 @@ def create(label, username, fields=None, source=None, st=None, *, managed_by=Non
1453
  'source': (source if source in (BLANK_SOURCE, AUTOMATION_SOURCE) else BLANK_SOURCE),
1454
  'createdBy': username,
1455
  'created': _dt.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
1456
- 'fields': clean_fields(fields) or [{'key': 'name', 'label': 'Name', 'type': 'text',
1457
- 'source': 'overlay', 'default': True}],
 
1458
  'rows': {},
1459
  }
1460
  if managed_by:
@@ -2634,7 +2637,7 @@ def note_human_edit(table_key, values, row_id, st=None):
2634
  return sorted(touched)
2635
 
2636
 
2637
- def _clean_field(raw, previous=None):
2638
  """One field dict → the stored shape, or None. The single validator for create AND patch, so
2639
  a column cannot be typed one way on the way in and another on the way back."""
2640
  prev = previous or {}
@@ -2958,7 +2961,9 @@ def _clean_field(raw, previous=None):
2958
  recurrence_raw = (raw.get('recurrence') if 'recurrence' in raw
2959
  else (prev.get('recurrence') if ftype == 'date' else None))
2960
  if recurrence_raw is not None:
2961
- recurrence = _ag_recurrence(recurrence_raw)
 
 
2962
  if recurrence and ftype == 'date':
2963
  out['recurrence'] = recurrence
2964
  return out
@@ -3511,15 +3516,18 @@ def flow_bound(bag, st=None):
3511
  return False
3512
 
3513
 
3514
- def add_field(table_key, raw, st=None):
3515
  """Append one column to the shared schema. Returns the stored field, or None if refused."""
 
 
 
3516
  if not is_user_table(table_key, st):
3517
  return None
3518
  defn = get(table_key, st) or {}
3519
  have = [f for f in (defn.get('fields') or [])]
3520
  if len(have) >= MAX_FIELDS:
3521
  return None
3522
- field = _clean_field(raw)
3523
  if not field or any(f.get('key') == field['key'] for f in have):
3524
  return None
3525
  if not dynamic_link_filter_valid(field, have):
@@ -3694,13 +3702,16 @@ def sync_reciprocal_link(table_key, field_key, st=None):
3694
  return result
3695
 
3696
 
3697
- def patch_field(table_key, fkey, raw, st=None):
3698
  """Edit one column's definition IN PLACE. Returns the stored field, or None if refused.
3699
 
3700
  ⚠ THE KEY NEVER MOVES. A field's key is what every stored cell is filed under, so accepting
3701
  a new one here would orphan every value in the column while looking like a rename. The
3702
  LABEL is the renameable thing; the key is identity.
3703
  """
 
 
 
3704
  if not is_user_table(table_key, st):
3705
  return None
3706
  fields = [dict(f) for f in ((get(table_key, st) or {}).get('fields') or [])]
@@ -3724,7 +3735,7 @@ def patch_field(table_key, fkey, raw, st=None):
3724
  if 'description' in merged and isinstance(fields[idx].get('automation'), dict) \
3725
  and fields[idx]['automation'].get('preset') is True:
3726
  merged.pop('description')
3727
- field = _clean_field(merged, fields[idx])
3728
  if not field:
3729
  return None
3730
  if not dynamic_link_filter_valid(field, fields):
@@ -3917,9 +3928,17 @@ def patch_cells(table_key, row_id, values, st=None):
3917
  def _set(cur):
3918
  t = cur.get(str(table_key))
3919
  if t is not None:
3920
- clean = {str(k): str(v) for k, v in (values or {}).items()}
3921
- t.setdefault('rows', {}).setdefault(str(row_id), {}).update(clean)
3922
- _hydrate_choice_options(t.get('fields') or [], [clean])
 
 
 
 
 
 
 
 
3923
  return cur
3924
 
3925
  _st(st).update(STORE_KEY, _set, flush='sync')
@@ -4163,6 +4182,21 @@ def may_open(table_key, viewer, is_admin=False, st=None):
4163
  return False
4164
 
4165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4166
  #: ⭐⭐ W31-T10 / CONTRACT C1 — THE TWO BUCKETS `may_open` READS, LENT FOR THE LENGTH OF ONE PASS.
4167
  #:
4168
  #: `core/store.py:Store.get` deep-copies the WHOLE tenant document on every call, hit or miss,
@@ -4261,6 +4295,229 @@ def lend_defs(st=None):
4261
  return lend(st, **{STORE_KEY: all_defs(st)})
4262
 
4263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4264
  def nav_entries(viewer=None, is_admin=False, st=None):
4265
  """Registry-SHAPED dicts so the nav can render user tables beside real modules with no
4266
  special-casing: the same keys the flat nav reads (`key`, `label`, `source`).
@@ -4286,7 +4543,13 @@ def nav_entries(viewer=None, is_admin=False, st=None):
4286
  key=lambda kv: (kv[1].get('label') or '').lower()):
4287
  if viewer is not None and not may_open(key, viewer, is_admin, st=lent):
4288
  continue
 
 
 
 
 
 
4289
  out.append({'key': key, 'label': t.get('label') or key,
4290
- 'source': t.get('source') or BLANK_SOURCE,
4291
  'user_table': True, 'nav': True, 'validate': False})
4292
  return out
 
56
 
57
  STORE_KEY = 'user_tables'
58
  ZONE_STORE_KEY = 'table_zones'
59
+ VALUE_HISTORY_KEY = 'value_history'
60
+ SHARED_NOTES_KEY = 'shared_notes'
61
+ ODOO_SCHEMA_SNAPSHOT_KEY = 'odoo_schema_snapshot'
62
+ ODOO_SCHEMA_ENABLEMENTS_KEY = 'odoo_schema_enablements'
63
+ ODOO_SYNC_STATUS_KEY = 'odoo_sync_status'
64
  # A reserved, derived multi-select field. It is table data backed by durable Zone membership,
65
  # not a user-editable column and therefore cannot collide with a field a user creates.
66
  ZONE_FIELD_KEY = '__zone__'
67
  MAX_TABLES = 40
68
  MAX_LABEL = 60
69
+ HISTORY_RETENTION_DAYS = 30
70
+ HISTORY_EXTENDED_DAYS = 90
71
 
72
  #: ⭐ THE PER-TABLE ROW CEILING — 5,000 until 2026-08-09, and it was never a property of the
73
  #: substrate. Owner: *"Why do we keep having this MAX_ROWS problem, 5000 is too little. We need to
 
951
  return out or None
952
 
953
 
954
+ def clean_fields(raw, recurrence_validator=None):
955
  """Validate a caller-supplied field list into the stored shape — refuse junk, never store
956
  it. Returns a list of `{key,label,type,source}` dicts (source is always 'overlay': every
957
  base column of a user table is user-editable by construction), or None when nothing
 
1096
  # type: the row still stores ``YYYY-MM-DD`` while this durable bag lets the server project
1097
  # the next date and preview consistently for every reader.
1098
  if entry is not None and ftype == 'date' and f.get('recurrence') is not None:
1099
+ if recurrence_validator is None:
1100
+ raise ValueError('recurrence needs the server field-authority validator')
1101
+ recurrence = (recurrence_validator(f.get('recurrence'))
1102
+ if recurrence_validator is not None else None)
1103
  if recurrence:
1104
  entry['recurrence'] = recurrence
1105
  if entry is None:
 
1184
  _ZONE_FIELD_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_]{0,79}$')
1185
  _ZONE_COLOR_RE = re.compile(r'^#[0-9A-Fa-f]{6}$')
1186
  _ZONE_ZIP_RE = re.compile(r'^\d{5}(?:-\d{4})?$')
1187
+ _ZONE_GEOMETRIES = frozenset({'Polygon', 'MultiPolygon', 'Circle'})
1188
  MAX_ZONE_ZIP_CODES = 500
1189
 
1190
 
 
1215
 
1216
 
1217
  def _clean_zone_geometry(raw):
1218
+ """Delegate to the one Route/Zone geometry authority."""
1219
+ from core import route_system
1220
+ return route_system.clean_zone_geometry(raw)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1221
 
1222
 
1223
  def clean_zone(raw, field_keys=None, allowed_row_ids=None):
 
1239
  if zip_code not in seen_zips:
1240
  seen_zips.add(zip_code)
1241
  zip_codes.append(zip_code)
1242
+ # Wave 45 makes visible geometry authoritative. ZIP codes remain migration metadata but may
1243
+ # not create a membership-bearing Zone without a polygon or circle.
1244
+ if not name or geometry is None:
1245
  return None
1246
  out = {'name': name,
1247
  'color': (str(raw.get('color') or '#1F4E78').upper()),
 
1270
  continue
1271
  seen.add(pid)
1272
  memberships.append(pid)
1273
+ # Historical hand-selected membership is retained only as migration evidence. Membership
1274
+ # returned to Grid is always recomputed from current exact coordinates in ``zone_cells``.
1275
+ evidence = raw.get('legacyMembershipEvidence') or memberships
1276
+ out['memberships'] = []
1277
+ if evidence:
1278
+ out['legacyMembershipEvidence'] = list(dict.fromkeys(str(pid) for pid in evidence if str(pid)))
1279
  creator = str(raw.get('createdBy') or '').strip()[:120]
1280
  created_at = str(raw.get('createdAt') or '').strip()[:64]
1281
  if creator:
 
1352
  names.append(name)
1353
  seen.add(name)
1354
  return {'key': ZONE_FIELD_KEY, 'label': 'Zone', 'type': 'multiselect', 'source': 'odoo',
1355
+ 'derived': True, 'readOnly': True, 'system': True, 'protected': True,
1356
+ 'multi': True, 'default': True, 'options': names,
1357
  'colorCodeOptions': True}
1358
 
1359
 
 
1367
  def zone_cells(table_key, rows, allowed_row_ids=None, st=None):
1368
  """Layer canonical Zone memberships into ordinary row cells for FilterBuilder/evaluator use."""
1369
  allowed = ({str(pid) for pid in allowed_row_ids} if allowed_row_ids is not None else None)
1370
+ from core import route_system
1371
  labels_by_pid = {}
1372
  for zone in zones(table_key, st=st):
1373
  name = str(zone.get('name') or '').strip()
1374
  if not name:
1375
  continue
1376
+ for pid in route_system.zone_members(zone, rows):
1377
  key = str(pid)
1378
  if allowed is not None and key not in allowed:
1379
  continue
 
1421
  return route_system.is_managed(definition if definition is not None else (get(table_key, st) or table_key))
1422
 
1423
 
1424
+ def create(label, username, fields=None, source=None, st=None, *, managed_by=None, capability=None,
1425
+ recurrence_validator=None):
1426
  """Create a blank table. Returns its key, or None if refused.
1427
 
1428
  Refuses rather than raises on the ordinary conditions (no name, duplicate, cap reached) —
 
1455
  'source': (source if source in (BLANK_SOURCE, AUTOMATION_SOURCE) else BLANK_SOURCE),
1456
  'createdBy': username,
1457
  'created': _dt.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
1458
+ 'fields': clean_fields(fields, recurrence_validator=recurrence_validator) or [
1459
+ {'key': 'name', 'label': 'Name', 'type': 'text',
1460
+ 'source': 'overlay', 'default': True}],
1461
  'rows': {},
1462
  }
1463
  if managed_by:
 
2637
  return sorted(touched)
2638
 
2639
 
2640
+ def _clean_field(raw, previous=None, recurrence_validator=None):
2641
  """One field dict → the stored shape, or None. The single validator for create AND patch, so
2642
  a column cannot be typed one way on the way in and another on the way back."""
2643
  prev = previous or {}
 
2961
  recurrence_raw = (raw.get('recurrence') if 'recurrence' in raw
2962
  else (prev.get('recurrence') if ftype == 'date' else None))
2963
  if recurrence_raw is not None:
2964
+ recurrence = (recurrence_validator(recurrence_raw)
2965
+ if recurrence_validator is not None
2966
+ else _ag_recurrence(recurrence_raw))
2967
  if recurrence and ftype == 'date':
2968
  out['recurrence'] = recurrence
2969
  return out
 
3516
  return False
3517
 
3518
 
3519
+ def add_field(table_key, raw, st=None, recurrence_validator=None):
3520
  """Append one column to the shared schema. Returns the stored field, or None if refused."""
3521
+ if isinstance(raw, dict) and raw.get('recurrence') is not None \
3522
+ and recurrence_validator is None:
3523
+ raise ValueError('recurrence needs the server field-authority validator')
3524
  if not is_user_table(table_key, st):
3525
  return None
3526
  defn = get(table_key, st) or {}
3527
  have = [f for f in (defn.get('fields') or [])]
3528
  if len(have) >= MAX_FIELDS:
3529
  return None
3530
+ field = _clean_field(raw, recurrence_validator=recurrence_validator)
3531
  if not field or any(f.get('key') == field['key'] for f in have):
3532
  return None
3533
  if not dynamic_link_filter_valid(field, have):
 
3702
  return result
3703
 
3704
 
3705
+ def patch_field(table_key, fkey, raw, st=None, recurrence_validator=None):
3706
  """Edit one column's definition IN PLACE. Returns the stored field, or None if refused.
3707
 
3708
  ⚠ THE KEY NEVER MOVES. A field's key is what every stored cell is filed under, so accepting
3709
  a new one here would orphan every value in the column while looking like a rename. The
3710
  LABEL is the renameable thing; the key is identity.
3711
  """
3712
+ if isinstance(raw, dict) and raw.get('recurrence') is not None \
3713
+ and recurrence_validator is None:
3714
+ raise ValueError('recurrence needs the server field-authority validator')
3715
  if not is_user_table(table_key, st):
3716
  return None
3717
  fields = [dict(f) for f in ((get(table_key, st) or {}).get('fields') or [])]
 
3735
  if 'description' in merged and isinstance(fields[idx].get('automation'), dict) \
3736
  and fields[idx]['automation'].get('preset') is True:
3737
  merged.pop('description')
3738
+ field = _clean_field(merged, fields[idx], recurrence_validator=recurrence_validator)
3739
  if not field:
3740
  return None
3741
  if not dynamic_link_filter_valid(field, fields):
 
3928
  def _set(cur):
3929
  t = cur.get(str(table_key))
3930
  if t is not None:
3931
+ clean = {str(k): (None if v is None else str(v))
3932
+ for k, v in (values or {}).items()}
3933
+ row = t.setdefault('rows', {}).setdefault(str(row_id), {})
3934
+ for key, value in clean.items():
3935
+ if value is None:
3936
+ row.pop(key, None)
3937
+ else:
3938
+ row[key] = value
3939
+ _hydrate_choice_options(t.get('fields') or [], [
3940
+ {key: value for key, value in clean.items() if value is not None}
3941
+ ])
3942
  return cur
3943
 
3944
  _st(st).update(STORE_KEY, _set, flush='sync')
 
4182
  return False
4183
 
4184
 
4185
+ def may_edit_database(table_key, viewer, is_admin=False, st=None):
4186
+ """Canonical Database-note/editor authority: owner/admin or an editor grant."""
4187
+ table = get(table_key, st)
4188
+ if not table:
4189
+ return False
4190
+ if bool(is_admin) or table.get('createdBy') == viewer:
4191
+ return True
4192
+ try:
4193
+ import core.shares as shares
4194
+ return shares.may_edit('database', table_key, viewer,
4195
+ is_admin=is_admin, st=st)
4196
+ except Exception:
4197
+ return False
4198
+
4199
+
4200
  #: ⭐⭐ W31-T10 / CONTRACT C1 — THE TWO BUCKETS `may_open` READS, LENT FOR THE LENGTH OF ONE PASS.
4201
  #:
4202
  #: `core/store.py:Store.get` deep-copies the WHOLE tenant document on every call, hit or miss,
 
4295
  return lend(st, **{STORE_KEY: all_defs(st)})
4296
 
4297
 
4298
+ def _utc_now():
4299
+ return _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0)
4300
+
4301
+
4302
+ def record_odoo_schema_snapshot(models, *, complete, errors=(), st=None):
4303
+ """Store an authoritative fields_get snapshot supplied by the sync lifecycle."""
4304
+ clean_models = {}
4305
+ for model, fields in (models or {}).items():
4306
+ if not isinstance(fields, dict):
4307
+ continue
4308
+ clean_fields = {}
4309
+ for name, meta in fields.items():
4310
+ if not str(name).strip() or not isinstance(meta, dict):
4311
+ continue
4312
+ clean_fields[str(name)] = {
4313
+ key: meta.get(key) for key in
4314
+ ('string', 'type', 'required', 'readonly', 'relation') if key in meta
4315
+ }
4316
+ clean_models[str(model)] = clean_fields
4317
+ row = {'models': clean_models, 'complete': bool(complete),
4318
+ 'errors': [str(error)[:500] for error in errors][:50],
4319
+ 'capturedAt': _utc_now().isoformat()}
4320
+ _st(st).update(ODOO_SCHEMA_SNAPSHOT_KEY, lambda _current: row, flush='sync')
4321
+ return row
4322
+
4323
+
4324
+ def odoo_schema_snapshot(st=None):
4325
+ row = _st(st).get(ODOO_SCHEMA_SNAPSHOT_KEY) or {}
4326
+ return dict(row) if isinstance(row, dict) else {}
4327
+
4328
+
4329
+ def enabled_odoo_schema_fields(st=None, model=None):
4330
+ """Product assembly seam: enabled raw metadata, still subject to its normal field wall."""
4331
+ enabled = _st(st).get(ODOO_SCHEMA_ENABLEMENTS_KEY) or {}
4332
+ snapshot = odoo_schema_snapshot(st)
4333
+ rows = []
4334
+ for model_name, fields in (snapshot.get('models') or {}).items():
4335
+ if model and str(model_name) != str(model):
4336
+ continue
4337
+ for name, meta in (fields or {}).items():
4338
+ key = f'{model_name}.{name}'
4339
+ if enabled.get(key) is True:
4340
+ raw_type = str(meta.get('type') or 'text')
4341
+ # The browser's FieldType vocabulary is closed. Odoo's vocabulary is not, so
4342
+ # an unknown/add-on type must degrade to text rather than reaching the client as
4343
+ # an impossible union member. Float is text because the grid has no neutral
4344
+ # decimal type (``currency`` would fabricate a dollar sign and ``int`` rounds).
4345
+ grid_type = {
4346
+ 'boolean': 'checkbox',
4347
+ 'integer': 'int',
4348
+ 'monetary': 'currency',
4349
+ 'date': 'date',
4350
+ 'datetime': 'date',
4351
+ 'char': 'text',
4352
+ 'text': 'text',
4353
+ 'html': 'text',
4354
+ 'float': 'text',
4355
+ 'selection': 'text',
4356
+ 'reference': 'text',
4357
+ 'many2one': 'text',
4358
+ 'one2many': 'text',
4359
+ 'many2many': 'text',
4360
+ 'binary': 'text',
4361
+ }.get(raw_type, 'text')
4362
+ rows.append({'key': key, 'model': model_name, 'rawName': name,
4363
+ 'label': str(meta.get('string') or name),
4364
+ 'type': grid_type, 'rawType': raw_type, 'source': 'odoo'})
4365
+ return rows
4366
+
4367
+
4368
+ def record_odoo_sync_status(*, phase, errors=(), st=None):
4369
+ """Lifecycle writer seam for the out-of-fence sync runner."""
4370
+ clean_phase = str(phase or 'unknown').strip().lower()
4371
+ if clean_phase not in {'syncing', 'ok', 'error', 'unknown'}:
4372
+ clean_phase = 'unknown'
4373
+ row = {'phase': clean_phase,
4374
+ 'lastRun': _utc_now().isoformat(),
4375
+ 'errors': [str(error)[:500] for error in errors][:50]}
4376
+ _st(st).update(ODOO_SYNC_STATUS_KEY, lambda _current: row, flush='sync')
4377
+ return row
4378
+
4379
+
4380
+ def append_value_history(table_key, row_id, before, after, actor, *, st=None,
4381
+ retention_days=HISTORY_RETENTION_DAYS, extended_entitled=False,
4382
+ kind='edit'):
4383
+ """Append one compact before/after event and prune by the entitled retention window."""
4384
+ days = int(retention_days or HISTORY_RETENTION_DAYS)
4385
+ if days == HISTORY_EXTENDED_DAYS and not extended_entitled:
4386
+ raise PermissionError('90-day history requires a Loopable-admin entitlement')
4387
+ if days not in (HISTORY_RETENTION_DAYS, HISTORY_EXTENDED_DAYS):
4388
+ raise ValueError('history retention must be 30 or 90 days')
4389
+ before = dict(before or {})
4390
+ after = dict(after or {})
4391
+ keys = sorted(key for key in set(before) | set(after) if before.get(key) != after.get(key))
4392
+ if not keys:
4393
+ return None
4394
+ now = _utc_now()
4395
+ event = {'id': 'vh_' + _uuid.uuid4().hex, 'table': str(table_key), 'rowId': str(row_id),
4396
+ 'kind': str(kind), 'actor': str(actor or '')[:120], 'at': now.isoformat(),
4397
+ 'changes': {key: {'before': before.get(key), 'after': after.get(key)} for key in keys}}
4398
+ # Never let a 30-day reader/edit destroy history that the tenant may be
4399
+ # entitled to inspect for 90 days. Visibility is applied by value_history.
4400
+ cutoff = now - _dt.timedelta(days=HISTORY_EXTENDED_DAYS)
4401
+
4402
+ def _append(current):
4403
+ rows = [item for item in (current or []) if isinstance(item, dict)]
4404
+ kept = []
4405
+ for item in rows:
4406
+ try:
4407
+ stamp = _dt.datetime.fromisoformat(str(item.get('at') or '').replace('Z', '+00:00'))
4408
+ except ValueError:
4409
+ continue
4410
+ if stamp.tzinfo is None:
4411
+ stamp = stamp.replace(tzinfo=_dt.timezone.utc)
4412
+ if stamp >= cutoff:
4413
+ kept.append(item)
4414
+ return (kept + [event])[-10000:]
4415
+
4416
+ _st(st).update(VALUE_HISTORY_KEY, _append, flush='sync')
4417
+ return event
4418
+
4419
+
4420
+ def value_history(table_key, row_id=None, *, st=None,
4421
+ retention_days=HISTORY_RETENTION_DAYS, extended_entitled=False):
4422
+ days = int(retention_days or HISTORY_RETENTION_DAYS)
4423
+ if days == HISTORY_EXTENDED_DAYS and not extended_entitled:
4424
+ raise PermissionError('90-day history requires a Loopable-admin entitlement')
4425
+ if days not in (HISTORY_RETENTION_DAYS, HISTORY_EXTENDED_DAYS):
4426
+ raise ValueError('history retention must be 30 or 90 days')
4427
+ cutoff = _utc_now() - _dt.timedelta(days=days)
4428
+ rows = _st(st).get(VALUE_HISTORY_KEY) or []
4429
+ out = []
4430
+ for item in rows:
4431
+ if (not isinstance(item, dict) or str(item.get('table')) != str(table_key)
4432
+ or (row_id is not None and str(item.get('rowId')) != str(row_id))):
4433
+ continue
4434
+ try:
4435
+ stamp = _dt.datetime.fromisoformat(str(item.get('at') or '').replace('Z', '+00:00'))
4436
+ except ValueError:
4437
+ continue
4438
+ if stamp.tzinfo is None:
4439
+ stamp = stamp.replace(tzinfo=_dt.timezone.utc)
4440
+ if stamp >= cutoff:
4441
+ out.append(dict(item))
4442
+ out.sort(key=lambda item: str(item.get('at') or ''), reverse=True)
4443
+ encoded = _json.dumps(out, separators=(',', ':'), ensure_ascii=False).encode('utf-8')
4444
+ return {'events': out, 'metering': {'events': len(out), 'bytes': len(encoded)}}
4445
+
4446
+
4447
+ def project_value_history(history, allowed_row_ids, hidden_keys=()):
4448
+ """Apply the normal row/field visibility closure to already-retained events."""
4449
+ allowed = {str(row_id) for row_id in (allowed_row_ids or ())}
4450
+ hidden = {str(key) for key in (hidden_keys or ())}
4451
+ events = []
4452
+ for item in (history or {}).get('events') or []:
4453
+ if str(item.get('rowId')) not in allowed:
4454
+ continue
4455
+ changes = {str(key): dict(value) for key, value in
4456
+ (item.get('changes') or {}).items()
4457
+ if str(key) not in hidden and isinstance(value, dict)}
4458
+ if not changes:
4459
+ continue
4460
+ projected = dict(item)
4461
+ projected['changes'] = changes
4462
+ events.append(projected)
4463
+ encoded = _json.dumps(events, separators=(',', ':'), ensure_ascii=False).encode('utf-8')
4464
+ return {'events': events, 'metering': {'events': len(events), 'bytes': len(encoded)}}
4465
+
4466
+
4467
+ def history_restore_values(table_key, row_id, event_id, *, field_key=None, st=None,
4468
+ retention_days=HISTORY_RETENTION_DAYS,
4469
+ extended_entitled=False):
4470
+ """Resolve retained prior values only; the caller must use its ordinary write door."""
4471
+ event = next((item for item in value_history(
4472
+ table_key, row_id, st=st, retention_days=retention_days,
4473
+ extended_entitled=extended_entitled)['events']
4474
+ if str(item.get('id')) == str(event_id)), None)
4475
+ if event is None:
4476
+ return None
4477
+ changes = event.get('changes') or {}
4478
+ wanted = [str(field_key)] if field_key else list(changes)
4479
+ if not wanted or any(key not in changes for key in wanted):
4480
+ return None
4481
+ return {key: changes[key].get('before') for key in wanted}
4482
+
4483
+
4484
+ def restore_row_values(table_key, row_id, event_id, actor, *, field_key=None, st=None,
4485
+ retention_days=HISTORY_RETENTION_DAYS, extended_entitled=False):
4486
+ """Retired unsafe raw-store restore door; routes must resolve then use overlay_patch."""
4487
+ raise RuntimeError('restore_row_values is retired; restore through the ordinary patch authority')
4488
+
4489
+
4490
+ def shared_note(subject_kind, subject_id, *, st=None):
4491
+ key = f"{subject_kind}:{subject_id}"
4492
+ row = (_st(st).get(SHARED_NOTES_KEY) or {}).get(key) or {}
4493
+ return dict(row) if isinstance(row, dict) else {}
4494
+
4495
+
4496
+ def put_shared_note(subject_kind, subject_id, body, actor, *, st=None):
4497
+ """One shared rich note per Database/View, with append-only revisions."""
4498
+ if subject_kind not in {'database', 'view'}:
4499
+ return None
4500
+ key, text = f"{subject_kind}:{subject_id}", str(body or '')[:100000]
4501
+ result = {}
4502
+
4503
+ def _put(current):
4504
+ current = dict(current or {})
4505
+ prior = current.get(key) if isinstance(current.get(key), dict) else {}
4506
+ revisions = list(prior.get('revisions') or [])[-99:]
4507
+ revision = {'version': int(prior.get('version') or 0) + 1, 'body': text,
4508
+ 'author': str(actor or '')[:120], 'at': _utc_now().isoformat()}
4509
+ row = {'subjectKind': subject_kind, 'subjectId': str(subject_id),
4510
+ 'version': revision['version'], 'body': text,
4511
+ 'author': revision['author'], 'updated': revision['at'],
4512
+ 'revisions': revisions + [revision]}
4513
+ current[key] = row
4514
+ result.update(row)
4515
+ return current
4516
+
4517
+ _st(st).update(SHARED_NOTES_KEY, _put, flush='sync')
4518
+ return result
4519
+
4520
+
4521
  def nav_entries(viewer=None, is_admin=False, st=None):
4522
  """Registry-SHAPED dicts so the nav can render user tables beside real modules with no
4523
  special-casing: the same keys the flat nav reads (`key`, `label`, `source`).
 
4543
  key=lambda kv: (kv[1].get('label') or '').lower()):
4544
  if viewer is not None and not may_open(key, viewer, is_admin, st=lent):
4545
  continue
4546
+ from core import route_system
4547
+ if route_system.is_managed(t) or route_system.is_managed(key):
4548
+ continue
4549
+ source = str(t.get('source') or BLANK_SOURCE)
4550
+ source_group = ('Odoo' if source.lower() == 'odoo' or key.startswith('ut_odoo_')
4551
+ else 'Custom' if source == BLANK_SOURCE else source)
4552
  out.append({'key': key, 'label': t.get('label') or key,
4553
+ 'source': source, 'sourceGroup': source_group,
4554
  'user_table': True, 'nav': True, 'validate': False})
4555
  return out
platform/core/view_templates.py CHANGED
@@ -144,7 +144,7 @@ TEMPLATES = [
144
  # The owner's own example (C12). One view, one job, and it is a DATA-QUALITY view: the
145
  # brand a customer buys from decides which BU-scoped account can see them at all, so a
146
  # blank DBA is a customer nobody's book contains.
147
- 'desc': 'Customers with no brand recorded — they fall outside every scoped book.',
148
  'source': 'odoo_customer',
149
  'alert': True,
150
  'views': [
@@ -171,7 +171,7 @@ TEMPLATES = [
171
  {
172
  'key': 'buy_list_companion',
173
  'label': 'Buy-list companion',
174
- 'desc': 'What is running out, and what it costs to bring in — beside the buy list.',
175
  'source': 'odoo_product',
176
  'views': [
177
  _view(
@@ -209,7 +209,7 @@ TEMPLATES = [
209
  _view(
210
  'tpl_ig_candidates_board', 'Review board',
211
  'Discovered profiles grouped by category. Move a card to say what you '
212
- 'decided about it — the automation never decides for you.',
213
  # ⚠ WAVE 26 (R6): `tracked` was here and the column is DELETED. The owner
214
  # retired it because the per-automation stage field already tracks a record's
215
  # progress, and two progress columns that can disagree is worse than one. A
@@ -299,3 +299,27 @@ def offer(field_keys, source=None):
299
  'source': t['source'], 'views': len(t.get('views') or ()),
300
  'alert': bool(t.get('alert'))})
301
  return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  # The owner's own example (C12). One view, one job, and it is a DATA-QUALITY view: the
145
  # brand a customer buys from decides which BU-scoped account can see them at all, so a
146
  # blank DBA is a customer nobody's book contains.
147
+ 'desc': 'Customers with no brand recorded; they fall outside every scoped book.',
148
  'source': 'odoo_customer',
149
  'alert': True,
150
  'views': [
 
171
  {
172
  'key': 'buy_list_companion',
173
  'label': 'Buy-list companion',
174
+ 'desc': 'What is running out and what it costs to bring in, beside the buy list.',
175
  'source': 'odoo_product',
176
  'views': [
177
  _view(
 
209
  _view(
210
  'tpl_ig_candidates_board', 'Review board',
211
  'Discovered profiles grouped by category. Move a card to say what you '
212
+ 'decided about it. The automation never decides for you.',
213
  # ⚠ WAVE 26 (R6): `tracked` was here and the column is DELETED. The owner
214
  # retired it because the per-automation stage field already tracks a record's
215
  # progress, and two progress columns that can disagree is worse than one. A
 
299
  'source': t['source'], 'views': len(t.get('views') or ()),
300
  'alert': bool(t.get('alert'))})
301
  return out
302
+
303
+
304
+ def application_ref(view):
305
+ """Return a View's reusable Application reference, never an embedded config copy."""
306
+ config = (view or {}).get('config') if isinstance(view, dict) else None
307
+ ref = (config or {}).get('application') if isinstance(config, dict) else None
308
+ if not isinstance(ref, dict) or not ref.get('id') or not ref.get('type'):
309
+ return None
310
+ return {'id': str(ref['id']), 'type': str(ref['type']),
311
+ 'revision': int(ref.get('revision') or 0)}
312
+
313
+
314
+ def bind_application(view, application):
315
+ """Copy a View shell and bind identity/revision only; Application config remains single-source."""
316
+ import copy
317
+ import core.assets as assets
318
+ target = assets.application_open_target(application)
319
+ if not target:
320
+ raise ValueError('that Application has no stable typed target')
321
+ out = copy.deepcopy(view) if isinstance(view, dict) else {}
322
+ config = out.setdefault('config', {})
323
+ config['application'] = {'id': target['id'], 'type': target['type'],
324
+ 'revision': int((application or {}).get('revision') or 0)}
325
+ return out
platform/harness/semantic.py CHANGED
@@ -160,6 +160,44 @@ def metrics():
160
  return dict(_model()["metrics"])
161
 
162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  def describe(key):
164
  """Full metadata for a metric (the dictionary page / AI describe_topic feed)."""
165
  m = _model()["metrics"].get(key)
 
160
  return dict(_model()["metrics"])
161
 
162
 
163
+ def semantic_fields(topic_key):
164
+ """Structured semantic suggestions for one topic, before tenant governance overrides.
165
+
166
+ ``means`` remains accepted as the historical purpose source, but this projection is the one
167
+ consumers use: every field has all governance axes and enters as draft unless the model
168
+ explicitly disables it. Presence in a topic is never approval for retrieval.
169
+ """
170
+ topic = _model()["topics"].get(str(topic_key))
171
+ if not topic:
172
+ raise ModelError(f"unknown topic {topic_key!r}")
173
+ out = {}
174
+ for field in topic.get("fields") or ():
175
+ if not isinstance(field, dict) or not field.get("key"):
176
+ continue
177
+ meta = field.get("semantic") if isinstance(field.get("semantic"), dict) else {}
178
+ state = str(meta.get("state") or "draft").lower()
179
+ sensitivity = str(meta.get("sensitivity") or "internal").lower()
180
+ if state not in ("draft", "approved", "disabled"):
181
+ raise ModelError(f"topic {topic_key!r} field {field['key']!r}: bad semantic state")
182
+ if sensitivity not in ("public", "internal", "sensitive", "restricted"):
183
+ raise ModelError(f"topic {topic_key!r} field {field['key']!r}: bad sensitivity")
184
+ out[field["key"]] = {
185
+ "field": field["key"], "label": field.get("label") or field["key"],
186
+ "purpose": meta.get("purpose") or field.get("means") or "",
187
+ "dataType": field.get("type") or "text",
188
+ "role": meta.get("role") or "attribute",
189
+ "synonyms": list(meta.get("synonyms") or ()),
190
+ "sensitivity": sensitivity, "state": state,
191
+ }
192
+ return out
193
+
194
+
195
+ def metric_catalog(topic_key=None):
196
+ """Existing validated Metrics only; no customer measure is inferred from a numeric field."""
197
+ return {key: dict(row) for key, row in _model()["metrics"].items()
198
+ if topic_key is None or row.get("topic") == topic_key}
199
+
200
+
201
  def describe(key):
202
  """Full metadata for a metric (the dictionary page / AI describe_topic feed)."""
203
  m = _model()["metrics"].get(key)
platform/model/topics/odoo_customers.yml CHANGED
@@ -35,11 +35,21 @@ fields:
35
  label: "Customer"
36
  type: text
37
  kind: data
 
 
 
 
 
38
  means: "The customer's name in Odoo. One row per customer who ordered in the last 24 months."
39
  - key: partner_id
40
  label: "Odoo ID"
41
  type: int
42
  kind: data
 
 
 
 
 
43
  means: "The Odoo res.partner id — this row's identity, and the key every Odoo document joins on. W33-T43 / owner item 12: 'One unique ID per database always.' It is DERIVED rather than read off the pool row because a customer row's pid IS the partner id, so the value is already on every row and a second copy in the pool would be a second source for one fact."
44
  - key: odoo_status
45
  label: "Odoo record"
@@ -65,6 +75,11 @@ fields:
65
  label: "Street"
66
  type: text
67
  kind: data
 
 
 
 
 
68
  means: "First address line, from res.partner directly - not the geocoder, so a customer the map cannot place still shows its address."
69
  - key: street2
70
  label: "Street 2"
@@ -215,6 +230,11 @@ fields:
215
  label: "Notes"
216
  type: text
217
  kind: data
 
 
 
 
 
218
  means: "Your notes on this customer. Saved in this app only, visible only to you."
219
 
220
  ai_context: >
 
35
  label: "Customer"
36
  type: text
37
  kind: data
38
+ semantic:
39
+ state: draft
40
+ role: entity_name
41
+ synonyms: [customer name, account name]
42
+ sensitivity: internal
43
  means: "The customer's name in Odoo. One row per customer who ordered in the last 24 months."
44
  - key: partner_id
45
  label: "Odoo ID"
46
  type: int
47
  kind: data
48
+ semantic:
49
+ state: draft
50
+ role: entity_id
51
+ synonyms: [customer id, Odoo partner id]
52
+ sensitivity: restricted
53
  means: "The Odoo res.partner id — this row's identity, and the key every Odoo document joins on. W33-T43 / owner item 12: 'One unique ID per database always.' It is DERIVED rather than read off the pool row because a customer row's pid IS the partner id, so the value is already on every row and a second copy in the pool would be a second source for one fact."
54
  - key: odoo_status
55
  label: "Odoo record"
 
75
  label: "Street"
76
  type: text
77
  kind: data
78
+ semantic:
79
+ state: draft
80
+ role: address
81
+ synonyms: [address, street address]
82
+ sensitivity: sensitive
83
  means: "First address line, from res.partner directly - not the geocoder, so a customer the map cannot place still shows its address."
84
  - key: street2
85
  label: "Street 2"
 
230
  label: "Notes"
231
  type: text
232
  kind: data
233
+ semantic:
234
+ state: disabled
235
+ role: private_note
236
+ synonyms: []
237
+ sensitivity: restricted
238
  means: "Your notes on this customer. Saved in this app only, visible only to you."
239
 
240
  ai_context: >
platform/modules/product_data.py CHANGED
@@ -584,7 +584,7 @@ def _catalogue_by_code():
584
  return products.catalogue()
585
 
586
 
587
- def pool(team_id=None, t=None):
588
  """One row per ACTIVE product — the PRODUCT analogue of `customer_data.pool`.
589
 
590
  CATALOGUE-FIRST, REVENUE LEFT-JOINED (R12 — see decision 4 in the module header). The row set
@@ -609,7 +609,7 @@ def pool(team_id=None, t=None):
609
  # both degrade to `{}` on a read failure rather than taking the grid down: they are columns,
610
  # not the row set.
611
  try:
612
- _prods = products.active_products() # ONE read, shared by both (see its docstring)
613
  except Exception: # noqa: BLE001
614
  _prods = None
615
  tiers, _tier_report = products.tier_prices_by_code(_prods)
@@ -628,6 +628,8 @@ def pool(team_id=None, t=None):
628
  # out. `validate()` asserts that of Odoo rather than assuming it, and reports the revenue
629
  # that therefore sits outside the grid (MEASURED 2026-08-11: 3 codes, $0.00 YTD / $294.50 LY).
630
  rev = {r["code"]: r for r in products.directory(t=t, team_id=team_id)}
 
 
631
 
632
  rows = []
633
  for code, meta in cat.items():
@@ -687,6 +689,11 @@ def pool(team_id=None, t=None):
687
  "qty_ytd": r.get("qty_ytd", 0.0) if r else None,
688
  "orders_ytd": r.get("orders_ytd", 0) if r else None,
689
  }
 
 
 
 
 
690
  # ⭐⭐ W37-T14 / T15 — THE HONEST SETS. These answer "how many prices/units does this SKU
691
  # actually have" across every list. The numbered per-list cells below select Fisch,
692
  # Royal 1, and Royal 2 without rebuilding a legacy base-price payload.
 
584
  return products.catalogue()
585
 
586
 
587
+ def pool(team_id=None, t=None, raw_fields=()):
588
  """One row per ACTIVE product — the PRODUCT analogue of `customer_data.pool`.
589
 
590
  CATALOGUE-FIRST, REVENUE LEFT-JOINED (R12 — see decision 4 in the module header). The row set
 
609
  # both degrade to `{}` on a read failure rather than taking the grid down: they are columns,
610
  # not the row set.
611
  try:
612
+ _prods = products.active_products(extra_fields=raw_fields) # ONE read, shared by both
613
  except Exception: # noqa: BLE001
614
  _prods = None
615
  tiers, _tier_report = products.tier_prices_by_code(_prods)
 
628
  # out. `validate()` asserts that of Odoo rather than assuming it, and reports the revenue
629
  # that therefore sits outside the grid (MEASURED 2026-08-11: 3 codes, $0.00 YTD / $294.50 LY).
630
  rev = {r["code"]: r for r in products.directory(t=t, team_id=team_id)}
631
+ raw_by_code = {(p.get("default_code") or f"pid:{p.get('id')}"): p
632
+ for p in (_prods or []) if p.get("default_code") or p.get("id")}
633
 
634
  rows = []
635
  for code, meta in cat.items():
 
689
  "qty_ytd": r.get("qty_ytd", 0.0) if r else None,
690
  "orders_ytd": r.get("orders_ytd", 0) if r else None,
691
  }
692
+ raw = raw_by_code.get(code) or {}
693
+ if raw_fields and raw:
694
+ for field in raw_fields:
695
+ if field in raw:
696
+ row[field] = raw.get(field)
697
  # ⭐⭐ W37-T14 / T15 — THE HONEST SETS. These answer "how many prices/units does this SKU
698
  # actually have" across every list. The numbered per-list cells below select Fisch,
699
  # Royal 1, and Royal 2 without rebuilding a legacy base-price payload.
platform/modules/products.py CHANGED
@@ -554,7 +554,7 @@ def tier_cap_overflow(tiers):
554
  if name in declared and n > PRICELIST_TIER_DEPTH}
555
 
556
 
557
- def active_products(limit=50000):
558
  """`[{id, default_code, product_tmpl_id}]` for every ACTIVE product — read ONCE and shared.
559
 
560
  ⛔ RAISES ON A SHORT PULL, like `catalogue()` and for the same reason: a truncated product read
@@ -564,7 +564,8 @@ def active_products(limit=50000):
564
  on this connection, on a path that is somebody's first page load.
565
  """
566
  dom = [('active', '=', True)]
567
- prods = O.search_read('product.product', dom, ['id', 'default_code', 'product_tmpl_id'],
 
568
  limit=limit)
569
  n = O.get_odoo().search_count('product.product', dom)
570
  if len(prods) != n:
 
554
  if name in declared and n > PRICELIST_TIER_DEPTH}
555
 
556
 
557
+ def active_products(limit=50000, extra_fields=()):
558
  """`[{id, default_code, product_tmpl_id}]` for every ACTIVE product — read ONCE and shared.
559
 
560
  ⛔ RAISES ON A SHORT PULL, like `catalogue()` and for the same reason: a truncated product read
 
564
  on this connection, on a path that is somebody's first page load.
565
  """
566
  dom = [('active', '=', True)]
567
+ fields = ['id', 'default_code', 'product_tmpl_id'] + [str(f) for f in extra_fields if str(f) not in {'id', 'default_code', 'product_tmpl_id'}]
568
+ prods = O.search_read('product.product', dom, fields,
569
  limit=limit)
570
  n = O.get_odoo().search_count('product.product', dom)
571
  if len(prods) != n:
web/src/assistant/AssistantPage.tsx CHANGED
@@ -8,11 +8,13 @@ import { queryGroups, QueryRail } from "../query/queryParts";
8
  import { DbIcon } from "../shell/dbFrame";
9
  import { ASSISTANT_ROUTE, databaseEntries, QUERY_ROUTE, routeKeyOf } from "../shell/nav";
10
  import type { NavEntry } from "../shell/nav";
 
11
  import {
12
  deleteQuery, deleteThread, fetchQueries, rateMessage, submitChat, type QueryCitation,
13
  type QueryIndex, type QueryMessage, type SavedQuery,
14
  } from "../query/queryApi";
15
  import "./assistant.css";
 
16
 
17
  /**
18
  * ⭐ LAZY ON PURPOSE. `QueryPage` imports `CustomerGrid`, the largest module in the client; a
@@ -165,14 +167,27 @@ function ThumbIcon({ down = false }: { down?: boolean }) {
165
  );
166
  }
167
 
168
- export function AssistantMessage({ message, view, citations, onPreview, onRate }: {
 
 
 
 
 
 
 
 
169
  message: QueryMessage; view?: SavedQuery; citations: QueryCitation[]; onPreview: (id: string) => void;
170
  /** Optional so the message can be rendered outside a live conversation without a rating door. */
171
  onRate?: (id: string, rating: "up" | "down" | null, reason?: string) => void;
 
 
172
  }) {
173
  const [openSources, setOpenSources] = useState(false);
174
  const [askWhy, setAskWhy] = useState(false);
175
  const [why, setWhy] = useState("");
 
 
 
176
  const matching = citations.filter((citation) => (message.citationIds || []).includes(citation.id));
177
  if (message.role === "user") {
178
  return (
@@ -185,6 +200,61 @@ export function AssistantMessage({ message, view, citations, onPreview, onRate }
185
  return (
186
  <article className={"as-message as-message--assistant" + (message.reason ? " is-refusal" : "")}>
187
  <p className="as-message-text">{message.content}</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  {numeric && numeric.value !== null && numeric.value !== undefined ? (
189
  <p className="as-numeric">
190
  <span className="as-numeric-label">{numeric.label}</span>
@@ -299,6 +369,13 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
299
  const [activeQuery, setActiveQuery] = useState("");
300
  /** Bumped on delete so the hosted workspace's own copy of the list cannot go stale behind us. */
301
  const [queryRefresh, setQueryRefresh] = useState(0);
 
 
 
 
 
 
 
302
  const openCancel = useRef<(() => void) | null>(null);
303
  const foot = useRef<HTMLDivElement | null>(null);
304
  /** A counter, not a random id: the optimistic message only has to be unique within this page. */
@@ -347,12 +424,25 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
347
  }, []);
348
 
349
  useEffect(() => { void reload(); }, [reload]);
 
 
 
 
 
350
  useEffect(() => () => openCancel.current?.(), []);
351
  useEffect(() => {
352
  const permitted = databases.map((entry) => entry.key);
353
  setSelected((current) => current.filter((key) => permitted.includes(key)));
354
  setTarget((current) => permitted.includes(current) ? current : "");
355
  }, [databases]);
 
 
 
 
 
 
 
 
356
  // The conversation reads bottom-up, like every chat the owner named.
357
  useEffect(() => { foot.current?.scrollIntoView({ block: "end" }); }, [messages.length, busy]);
358
 
@@ -464,19 +554,35 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
464
  * the model as if it had [[undo-capture-before-the-write]]. The typed text goes back in the
465
  * composer too: losing somebody's sentence to a failed request is the second injury.
466
  */
467
- const ask = useCallback(async () => {
468
- const text = question.trim();
469
- if (!text || !target || !selected.includes(target) || busy) return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
470
  const pendingId = `pending_${(pending.current += 1)}`;
471
  const optimistic: QueryMessage = {
472
  id: pendingId, threadId: activeThread, role: "user", content: text,
473
- createdAt: new Date().toISOString(), targetDatabase: target,
474
  sources: selected, requestedModel: model,
475
  };
476
  const withoutPending = (rows: QueryMessage[]) => rows.filter((row) => row.id !== pendingId);
477
- setBusy(true); setProblem(""); setQuestion("");
478
  setIndex((current) => ({ ...current, messages: [...current.messages, optimistic] }));
479
- const result = await submitChat({ question: text, database: target, sources: selected,
480
  ...(activeThread ? { threadId: activeThread } : {}), model });
481
  setBusy(false);
482
  if (!result.ok) {
@@ -486,6 +592,7 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
486
  return;
487
  }
488
  setActiveThread(result.value.thread.id);
 
489
  setIndex((current) => ({
490
  ...current,
491
  threads: [result.value.thread, ...current.threads.filter((row) => row.id !== result.value.thread.id)],
@@ -495,7 +602,7 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
495
  views: result.value.view ? [result.value.view, ...current.views.filter((row) => row.id !== result.value.view?.id)] : current.views,
496
  citations: [...current.citations, ...result.value.citations],
497
  }));
498
- }, [activeThread, busy, model, question, selected, target]);
499
 
500
  /** ⛔ The chat goes; the views it built STAY (they live in Query). Two-click, in the row. */
501
  const removeThread = useCallback(async (id: string) => {
@@ -533,6 +640,18 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
533
  const empty = messages.length === 0;
534
  const composer = (
535
  <div className="as-composer">
 
 
 
 
 
 
 
 
 
 
 
 
536
  <div className="as-field">
537
  <textarea
538
  className="as-prompt"
@@ -719,6 +838,8 @@ export default function AssistantPage({ granted }: AssistantPageProps) {
719
  <AssistantMessage key={message.id} message={message}
720
  view={message.viewId ? viewById.get(message.viewId) : undefined}
721
  citations={index.citations} onPreview={preview}
 
 
722
  onRate={message.role === "assistant" && !message.id.startsWith("pending_")
723
  ? rate : undefined} />
724
  ))}
 
8
  import { DbIcon } from "../shell/dbFrame";
9
  import { ASSISTANT_ROUTE, databaseEntries, QUERY_ROUTE, routeKeyOf } from "../shell/nav";
10
  import type { NavEntry } from "../shell/nav";
11
+ import { getQueryModelCatalog, persistQueryArtifacts, runQueryTool, type QueryModelIdentity, type QueryToolArtifacts } from "../automation/automationApi";
12
  import {
13
  deleteQuery, deleteThread, fetchQueries, rateMessage, submitChat, type QueryCitation,
14
  type QueryIndex, type QueryMessage, type SavedQuery,
15
  } from "../query/queryApi";
16
  import "./assistant.css";
17
+ import "../styles/wave45/agent-operator.css";
18
 
19
  /**
20
  * ⭐ LAZY ON PURPOSE. `QueryPage` imports `CustomerGrid`, the largest module in the client; a
 
167
  );
168
  }
169
 
170
+ export function AssistantMessage({
171
+ message,
172
+ view,
173
+ citations,
174
+ onPreview,
175
+ onRate,
176
+ identity,
177
+ governedArtifacts,
178
+ }: {
179
  message: QueryMessage; view?: SavedQuery; citations: QueryCitation[]; onPreview: (id: string) => void;
180
  /** Optional so the message can be rendered outside a live conversation without a rating door. */
181
  onRate?: (id: string, rating: "up" | "down" | null, reason?: string) => void;
182
+ identity?: QueryModelIdentity;
183
+ governedArtifacts?: QueryToolArtifacts;
184
  }) {
185
  const [openSources, setOpenSources] = useState(false);
186
  const [askWhy, setAskWhy] = useState(false);
187
  const [why, setWhy] = useState("");
188
+ const [slackOpen, setSlackOpen] = useState(false);
189
+ const [artifacts, setArtifacts] = useState<QueryToolArtifacts | null>(governedArtifacts || null);
190
+ const [artifactStatus, setArtifactStatus] = useState("");
191
  const matching = citations.filter((citation) => (message.citationIds || []).includes(citation.id));
192
  if (message.role === "user") {
193
  return (
 
200
  return (
201
  <article className={"as-message as-message--assistant" + (message.reason ? " is-refusal" : "")}>
202
  <p className="as-message-text">{message.content}</p>
203
+ <p className="w45-model-id" aria-label="Model and provider">
204
+ Provider <strong>{identity?.provider || message.model || "Not reported"}</strong>
205
+ Model <strong>{identity?.modelId || "Not reported"}</strong>
206
+ </p>
207
+ {view && artifacts ? (
208
+ <section className="w45-contract-card" aria-labelledby={`query-artifacts-${message.id}`}>
209
+ <h4 id={`query-artifacts-${message.id}`}>Query setup</h4>
210
+ <div className="w45-artifacts">
211
+ {(["filters", "sorts", "group", "hiddenFields", "source"] as const).map((key) => (
212
+ <label className="w45-artifact" key={key}>
213
+ <span>{key === "hiddenFields" ? "Hidden fields" : key[0].toUpperCase() + key.slice(1)}</span>
214
+ <input
215
+ defaultValue={JSON.stringify(artifacts[key])}
216
+ onBlur={(event) => {
217
+ try { const value = JSON.parse(event.currentTarget.value) as never; setArtifacts((current) => ({ ...(current as QueryToolArtifacts), [key]: value })); }
218
+ catch { setArtifactStatus(`${key} must be valid JSON.`); }
219
+ }}
220
+ />
221
+ </label>
222
+ ))}
223
+ </div>
224
+ <div className="w45-chip-row">
225
+ <button type="button" className="w45-quiet" onClick={async () => {
226
+ setArtifactStatus("");
227
+ try { await persistQueryArtifacts(view.id, view.view, artifacts); setArtifactStatus("Query setup saved"); }
228
+ catch (error) { setArtifactStatus(error instanceof Error ? error.message : "Query setup could not be saved."); }
229
+ }}>Save Query setup</button>
230
+ <button type="button" className="w45-quiet" onClick={() => setSlackOpen(true)}>
231
+ Correct in Slack
232
+ </button>
233
+ <button type="button" className="w45-quiet" onClick={() => onPreview(view.id)}>
234
+ Open in Loopable
235
+ </button>
236
+ </div>
237
+ {artifactStatus ? <p className="w45-safe" role="status">{artifactStatus}</p> : null}
238
+ {slackOpen ? (
239
+ <div className="w45-contract-card" role="dialog" aria-label="Slack correction">
240
+ <h4>Slack correction</h4>
241
+ <p>Slack can correct Filter, Sort, and Group after the Query capability check. Complex edits open the exact server-returned Query in Loopable.</p>
242
+ {(["filters", "sorts", "group"] as const).map((key) => <label className="w45-artifact" key={key}>
243
+ <span>{key[0].toUpperCase() + key.slice(1)}</span>
244
+ <input defaultValue={JSON.stringify(artifacts[key])} onBlur={(event) => {
245
+ try { const value = JSON.parse(event.currentTarget.value) as never; setArtifacts((current) => ({ ...(current as QueryToolArtifacts), [key]: value })); }
246
+ catch { setArtifactStatus(`${key} must be valid JSON.`); }
247
+ }} />
248
+ </label>)}
249
+ <p className="w45-safe">Draft only. No Slack message was sent.</p>
250
+ <button type="button" className="w45-quiet" onClick={() => onPreview(view.id)}>Open in Loopable</button>
251
+ <button type="button" className="w45-quiet" onClick={() => setSlackOpen(false)}>
252
+ Close
253
+ </button>
254
+ </div>
255
+ ) : null}
256
+ </section>
257
+ ) : null}
258
  {numeric && numeric.value !== null && numeric.value !== undefined ? (
259
  <p className="as-numeric">
260
  <span className="as-numeric-label">{numeric.label}</span>
 
369
  const [activeQuery, setActiveQuery] = useState("");
370
  /** Bumped on delete so the hosted workspace's own copy of the list cannot go stale behind us. */
371
  const [queryRefresh, setQueryRefresh] = useState(0);
372
+ const [modelCatalog, setModelCatalog] = useState<QueryModelIdentity[]>([]);
373
+ const [artifactByView, setArtifactByView] = useState<Record<string, QueryToolArtifacts>>({});
374
+ const [alignment, setAlignment] = useState<null | {
375
+ prompt: string; database: string; resumeToken: string;
376
+ question: string; choices: Array<{ field: string; label: string }>; maxSelections: number;
377
+ }>(null);
378
+ const [alignmentFields, setAlignmentFields] = useState<string[]>([]);
379
  const openCancel = useRef<(() => void) | null>(null);
380
  const foot = useRef<HTMLDivElement | null>(null);
381
  /** A counter, not a random id: the optimistic message only has to be unique within this page. */
 
424
  }, []);
425
 
426
  useEffect(() => { void reload(); }, [reload]);
427
+ useEffect(() => {
428
+ const controller = new AbortController();
429
+ void getQueryModelCatalog(controller.signal).then(setModelCatalog).catch(() => setModelCatalog([]));
430
+ return () => controller.abort();
431
+ }, []);
432
  useEffect(() => () => openCancel.current?.(), []);
433
  useEffect(() => {
434
  const permitted = databases.map((entry) => entry.key);
435
  setSelected((current) => current.filter((key) => permitted.includes(key)));
436
  setTarget((current) => permitted.includes(current) ? current : "");
437
  }, [databases]);
438
+ // A resume token is bound to the database/source wall that produced it. Changing either
439
+ // invalidates the clarification instead of replaying the token against a different target.
440
+ useEffect(() => {
441
+ if (alignment && (alignment.database !== target || !selected.includes(alignment.database))) {
442
+ setAlignment(null);
443
+ setAlignmentFields([]);
444
+ }
445
+ }, [alignment, selected, target]);
446
  // The conversation reads bottom-up, like every chat the owner named.
447
  useEffect(() => { foot.current?.scrollIntoView({ block: "end" }); }, [messages.length, busy]);
448
 
 
554
  * the model as if it had [[undo-capture-before-the-write]]. The typed text goes back in the
555
  * composer too: losing somebody's sentence to a failed request is the second injury.
556
  */
557
+ const ask = useCallback(async (approvedFields?: string[]) => {
558
+ const text = approvedFields && alignment ? alignment.prompt : question.trim();
559
+ const database = approvedFields && alignment ? alignment.database : target;
560
+ if (!text || !database || !selected.includes(database) || busy) return;
561
+ setBusy(true); setProblem("");
562
+ let governed: Awaited<ReturnType<typeof runQueryTool>>;
563
+ try {
564
+ governed = await runQueryTool({ database, prompt: text,
565
+ ...(approvedFields ? { fieldKeys: approvedFields, resumeToken: alignment?.resumeToken } : {}) });
566
+ } catch (error) {
567
+ setBusy(false); setProblem(error instanceof Error ? error.message : "Query capability check failed."); return;
568
+ }
569
+ if (governed.status === "clarification") {
570
+ setBusy(false); setAlignmentFields([]); setAlignment({ prompt: text, database,
571
+ resumeToken: governed.resumeToken, question: governed.alignmentQuestion.question,
572
+ choices: governed.alignmentQuestion.choices, maxSelections: governed.alignmentQuestion.maxSelections });
573
+ return;
574
+ }
575
+ setAlignment(null);
576
  const pendingId = `pending_${(pending.current += 1)}`;
577
  const optimistic: QueryMessage = {
578
  id: pendingId, threadId: activeThread, role: "user", content: text,
579
+ createdAt: new Date().toISOString(), targetDatabase: database,
580
  sources: selected, requestedModel: model,
581
  };
582
  const withoutPending = (rows: QueryMessage[]) => rows.filter((row) => row.id !== pendingId);
583
+ setQuestion("");
584
  setIndex((current) => ({ ...current, messages: [...current.messages, optimistic] }));
585
+ const result = await submitChat({ question: text, database, sources: selected,
586
  ...(activeThread ? { threadId: activeThread } : {}), model });
587
  setBusy(false);
588
  if (!result.ok) {
 
592
  return;
593
  }
594
  setActiveThread(result.value.thread.id);
595
+ if (result.value.view) setArtifactByView((current) => ({ ...current, [result.value.view!.id]: governed.artifacts }));
596
  setIndex((current) => ({
597
  ...current,
598
  threads: [result.value.thread, ...current.threads.filter((row) => row.id !== result.value.thread.id)],
 
602
  views: result.value.view ? [result.value.view, ...current.views.filter((row) => row.id !== result.value.view?.id)] : current.views,
603
  citations: [...current.citations, ...result.value.citations],
604
  }));
605
+ }, [activeThread, alignment, busy, model, question, selected, target]);
606
 
607
  /** ⛔ The chat goes; the views it built STAY (they live in Query). Two-click, in the row. */
608
  const removeThread = useCallback(async (id: string) => {
 
640
  const empty = messages.length === 0;
641
  const composer = (
642
  <div className="as-composer">
643
+ {alignment ? <section className="w45-contract-card" aria-label="Alignment question">
644
+ <h4>Clarify</h4><p>{alignment.question}</p>
645
+ <div className="w45-chip-row">{alignment.choices.map((choice) => {
646
+ const on = alignmentFields.includes(choice.field);
647
+ return <button type="button" className={`w45-chip ${on ? "is-on" : "is-off"}`} key={choice.field}
648
+ aria-pressed={on} onClick={() => setAlignmentFields((current) => on
649
+ ? current.filter((field) => field !== choice.field)
650
+ : current.length < alignment.maxSelections ? [...current, choice.field] : current)}>{choice.label}</button>;
651
+ })}</div>
652
+ <button type="button" className="w45-quiet" disabled={!alignmentFields.length || busy}
653
+ onClick={() => void ask(alignmentFields)}>Resume with approved selection</button>
654
+ </section> : null}
655
  <div className="as-field">
656
  <textarea
657
  className="as-prompt"
 
838
  <AssistantMessage key={message.id} message={message}
839
  view={message.viewId ? viewById.get(message.viewId) : undefined}
840
  citations={index.citations} onPreview={preview}
841
+ identity={modelCatalog.find((row) => row.model === message.model || row.provider === message.model)}
842
+ governedArtifacts={message.viewId ? artifactByView[message.viewId] : undefined}
843
  onRate={message.role === "assistant" && !message.id.startsWith("pending_")
844
  ? rate : undefined} />
845
  ))}
web/src/automation/AutomationBuilder.tsx CHANGED
@@ -49,6 +49,7 @@ import type {
49
  StatementWorld,
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
@@ -84,6 +85,8 @@ const ACTION_DRAG_TYPE = "application/x-loopable-action";
84
 
85
  interface Props {
86
  automation: Automation;
 
 
87
  /**
88
  * THE AUTOMATION'S NAME (item 15b, C-DETAIL) — it left the page header and Properties is where
89
  * it went, at the top, above whatever step is selected. REQUIRED, all three: an optional prop
@@ -430,6 +433,7 @@ function tableLabel(tables: UserTable[], key: string): string {
430
 
431
  export default function AutomationBuilder({
432
  automation,
 
433
  name,
434
  onNameText,
435
  onNameCommit,
@@ -1597,6 +1601,21 @@ export default function AutomationBuilder({
1597
  />
1598
  </div>
1599
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1600
  {sel.kind === "trigger" ? (
1601
  <TriggerProps
1602
  automation={automation}
 
49
  StatementWorld,
50
  TriggerOption,
51
  UserTable,
52
+ AgentContract,
53
  } from "./automationApi";
54
  import type { VoiceAgent } from "./voiceAgentTypes";
55
  // ⭐ WAVE 26 · ITEM 22 / D-70 — the Run guard, imported rather than re-derived. This file and
 
85
 
86
  interface Props {
87
  automation: Automation;
88
+ /** The authoritative Agent sharing and event-store facts shown in Properties. */
89
+ agentContract?: AgentContract | null;
90
  /**
91
  * THE AUTOMATION'S NAME (item 15b, C-DETAIL) — it left the page header and Properties is where
92
  * it went, at the top, above whatever step is selected. REQUIRED, all three: an optional prop
 
433
 
434
  export default function AutomationBuilder({
435
  automation,
436
+ agentContract,
437
  name,
438
  onNameText,
439
  onNameCommit,
 
1601
  />
1602
  </div>
1603
 
1604
+ {agentContract ? <section className="w45-contract-card" aria-labelledby="agent-storage-heading">
1605
+ <h3 id="agent-storage-heading">Agent data</h3>
1606
+ <p>
1607
+ Runs and setup answers stay in event store {agentContract.eventStore.id}.
1608
+ {agentContract.eventStore.hiddenFromData ? " It is hidden from Data." : " It is visible in Data."}
1609
+ </p>
1610
+ <div className="w45-chip-row" aria-label="Sharing state">
1611
+ <span className="w45-chip is-on">Event store {agentContract.eventStore.visibility}</span>
1612
+ <span className={"w45-chip " + (agentContract.sharing.visibility === "shared" ? "is-on" : "is-off")}>
1613
+ Agent {agentContract.sharing.visibility}
1614
+ </span>
1615
+ {agentContract.sharing.sharedWith.map((recipient) => <span className="w45-chip is-on" key={recipient}>{recipient}</span>)}
1616
+ </div>
1617
+ </section> : null}
1618
+
1619
  {sel.kind === "trigger" ? (
1620
  <TriggerProps
1621
  automation={automation}
web/src/automation/AutomationChat.tsx CHANGED
@@ -20,9 +20,13 @@ import { useCallback, useEffect, useRef, useState } from "react";
20
 
21
  import type { QueryModelStatus } from "../query/queryApi";
22
  import { fetchQueries } from "../query/queryApi";
23
- import type { AutomationDraft } from "./automationApi";
24
- import { AutomationError, draftAutomation } from "./automationApi";
 
 
 
25
  import "./automation.css";
 
26
 
27
  /**
28
  * ⭐⭐ CONTRACT C5 (W36-T34, owner item 3, ruling R4) — ONE LIST, ONE DOOR.
@@ -44,6 +48,12 @@ const MODEL_WORDS: Record<string, string> = {
44
  openrouter: "OpenRouter",
45
  };
46
  const modelWord = (key: string) => MODEL_WORDS[key] ?? key;
 
 
 
 
 
 
47
 
48
  /**
49
  * One turn. `error` is a KIND of message rather than a separate banner, because a failed turn is
@@ -71,13 +81,22 @@ export interface AutomationChatProps {
71
  * reasoning that makes `ActionProps` an EXPORT rather than a private function.
72
  */
73
  initialModels?: QueryModelStatus[];
 
 
 
74
  }
75
 
76
  /** How many steps a draft may carry before the accept bar states the number rather than implying
77
  * it. Not a limit — a limit here would be a second, quieter copy of the server's. */
78
  const MANY_STEPS = 6;
79
 
80
- export default function AutomationChat({ onAccept, initialModels }: AutomationChatProps) {
 
 
 
 
 
 
81
  const [turns, setTurns] = useState<Turn[]>([]);
82
  const [text, setText] = useState("");
83
  const [busy, setBusy] = useState(false);
@@ -85,6 +104,7 @@ export default function AutomationChat({ onAccept, initialModels }: AutomationCh
85
  const [applying, setApplying] = useState(false);
86
  const [model, setModel] = useState("auto");
87
  const [models, setModels] = useState<QueryModelStatus[] | null>(initialModels ?? null);
 
88
  const logRef = useRef<HTMLDivElement | null>(null);
89
 
90
  /*
@@ -136,7 +156,7 @@ export default function AutomationChat({ onAccept, initialModels }: AutomationCh
136
  who: "agent",
137
  text: actions.length
138
  ? `I drafted ${label} with ${actions.length} step${actions.length === 1 ? "" : "s"}. `
139
- + "Nothing is saved yet. Read it below and put it on the Canvas if it is right."
140
  : `I could not turn that into steps. Try naming the database and what should happen.`,
141
  // ⚠ BOTH CHANNELS, and they are different questions. `dropped` is what the SAVE-DOOR
142
  // validator discarded from the model's answer; `notes` is what the ROUTE corrected or
@@ -186,7 +206,7 @@ export default function AutomationChat({ onAccept, initialModels }: AutomationCh
186
  setPending(null);
187
  setTurns((t) => [...t, {
188
  who: "agent",
189
- text: "Put it on the Canvas. Edit it there like any other agent.",
190
  }]);
191
  } catch (e) {
192
  setTurns((t) => [...t, {
@@ -285,6 +305,14 @@ export default function AutomationChat({ onAccept, initialModels }: AutomationCh
285
  </select>
286
  </label>
287
  ) : null}
 
 
 
 
 
 
 
 
288
  <button
289
  type="button"
290
  className="autoc-send"
@@ -321,12 +349,35 @@ export default function AutomationChat({ onAccept, initialModels }: AutomationCh
321
  <div className="autoc-chat">
322
  {!turns.length ? (
323
  <div className="autoc-opening">
324
- <h2 className="autoc-opening-h">How can I help?</h2>
325
- <p className="autoc-opening-p">
326
- Say what this agent should do and it drafts the steps. Nothing is saved until you put
327
- them on the Canvas.
328
- </p>
329
- {composer}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
  </div>
331
  ) : null}
332
  {/*
@@ -402,7 +453,7 @@ export default function AutomationChat({ onAccept, initialModels }: AutomationCh
402
  <span className="autoc-accept-note">
403
  {steps} step{steps === 1 ? "" : "s"} drafted
404
  {steps > MANY_STEPS ? ", which is a long flow. Read it before you accept." : "."}{" "}
405
- Nothing is saved until you put it on the Canvas.
406
  </span>
407
  <button
408
  type="button"
@@ -418,7 +469,7 @@ export default function AutomationChat({ onAccept, initialModels }: AutomationCh
418
  disabled={applying}
419
  onClick={() => void accept()}
420
  >
421
- {applying ? "Adding" : "Put it on the Canvas"}
422
  </button>
423
  </div>
424
  ) : null}
 
20
 
21
  import type { QueryModelStatus } from "../query/queryApi";
22
  import { fetchQueries } from "../query/queryApi";
23
+ import type { AgentContract, AutomationDraft } from "./automationApi";
24
+ import {
25
+ AutomationError,
26
+ draftAutomation,
27
+ } from "./automationApi";
28
  import "./automation.css";
29
+ import "../styles/wave45/agent-operator.css";
30
 
31
  /**
32
  * ⭐⭐ CONTRACT C5 (W36-T34, owner item 3, ruling R4) — ONE LIST, ONE DOOR.
 
48
  openrouter: "OpenRouter",
49
  };
50
  const modelWord = (key: string) => MODEL_WORDS[key] ?? key;
51
+ const MODEL_IDENTITY: Record<string, { provider: string; model: string }> = {
52
+ anthropic: { provider: "Anthropic", model: "claude-opus-5" },
53
+ cerebras: { provider: "Cerebras", model: "gpt-oss-120b" },
54
+ groq: { provider: "Groq", model: "openai/gpt-oss-120b" },
55
+ openrouter: { provider: "OpenRouter", model: "openai/gpt-4o-mini" },
56
+ };
57
 
58
  /**
59
  * One turn. `error` is a KIND of message rather than a separate banner, because a failed turn is
 
81
  * reasoning that makes `ActionProps` an EXPORT rather than a private function.
82
  */
83
  initialModels?: QueryModelStatus[];
84
+ unconfigured?: boolean;
85
+ setupInterview?: AgentContract["setupInterview"] | null;
86
+ onSetupAnswer?: (key: string, answer: string, disable: boolean) => Promise<void> | void;
87
  }
88
 
89
  /** How many steps a draft may carry before the accept bar states the number rather than implying
90
  * it. Not a limit — a limit here would be a second, quieter copy of the server's. */
91
  const MANY_STEPS = 6;
92
 
93
+ export default function AutomationChat({
94
+ onAccept,
95
+ initialModels,
96
+ unconfigured = false,
97
+ setupInterview = null,
98
+ onSetupAnswer,
99
+ }: AutomationChatProps) {
100
  const [turns, setTurns] = useState<Turn[]>([]);
101
  const [text, setText] = useState("");
102
  const [busy, setBusy] = useState(false);
 
104
  const [applying, setApplying] = useState(false);
105
  const [model, setModel] = useState("auto");
106
  const [models, setModels] = useState<QueryModelStatus[] | null>(initialModels ?? null);
107
+ const [setupBusy, setSetupBusy] = useState(false);
108
  const logRef = useRef<HTMLDivElement | null>(null);
109
 
110
  /*
 
156
  who: "agent",
157
  text: actions.length
158
  ? `I drafted ${label} with ${actions.length} step${actions.length === 1 ? "" : "s"}. `
159
+ + "Nothing is saved yet. Read it below and add it to Workflows if it is right."
160
  : `I could not turn that into steps. Try naming the database and what should happen.`,
161
  // ⚠ BOTH CHANNELS, and they are different questions. `dropped` is what the SAVE-DOOR
162
  // validator discarded from the model's answer; `notes` is what the ROUTE corrected or
 
206
  setPending(null);
207
  setTurns((t) => [...t, {
208
  who: "agent",
209
+ text: "Added it to Workflows. Edit it there like any other agent.",
210
  }]);
211
  } catch (e) {
212
  setTurns((t) => [...t, {
 
305
  </select>
306
  </label>
307
  ) : null}
308
+ {model !== "auto" && MODEL_IDENTITY[model] ? (
309
+ <span className="w45-model-id" aria-label="Selected provider and model">
310
+ Provider <strong>{MODEL_IDENTITY[model].provider}</strong>
311
+ Model <strong>{MODEL_IDENTITY[model].model}</strong>
312
+ </span>
313
+ ) : (
314
+ <span className="w45-model-id">Provider and model selected at run time</span>
315
+ )}
316
  <button
317
  type="button"
318
  className="autoc-send"
 
349
  <div className="autoc-chat">
350
  {!turns.length ? (
351
  <div className="autoc-opening">
352
+ {unconfigured && setupInterview?.question ? (
353
+ <section className="w45-interview" aria-live="polite">
354
+ <h2 className="autoc-opening-h">Set up agent</h2>
355
+ <p className="autoc-opening-p">{setupInterview.question.text}</p>
356
+ <div className="w45-interview-actions">
357
+ <button type="button" disabled={setupBusy} onClick={async () => {
358
+ setSetupBusy(true);
359
+ try { await onSetupAnswer?.(setupInterview.question!.key, setupInterview.question!.suggestion, false); }
360
+ finally { setSetupBusy(false); }
361
+ }}>{setupInterview.question.suggestion}</button>
362
+ {setupInterview.question.allowDisable ? (
363
+ <button type="button" disabled={setupBusy} onClick={async () => {
364
+ setSetupBusy(true);
365
+ try { await onSetupAnswer?.(setupInterview.question!.key, "", true); }
366
+ finally { setSetupBusy(false); }
367
+ }}>Disable for now</button>
368
+ ) : null}
369
+ </div>
370
+ </section>
371
+ ) : (
372
+ <>
373
+ <h2 className="autoc-opening-h">How can I help?</h2>
374
+ <p className="autoc-opening-p">
375
+ Say what this agent should do and it drafts the steps. Nothing is saved until you
376
+ add them to Workflows.
377
+ </p>
378
+ {composer}
379
+ </>
380
+ )}
381
  </div>
382
  ) : null}
383
  {/*
 
453
  <span className="autoc-accept-note">
454
  {steps} step{steps === 1 ? "" : "s"} drafted
455
  {steps > MANY_STEPS ? ", which is a long flow. Read it before you accept." : "."}{" "}
456
+ Nothing is saved until you add it to Workflows.
457
  </span>
458
  <button
459
  type="button"
 
469
  disabled={applying}
470
  onClick={() => void accept()}
471
  >
472
+ {applying ? "Adding" : "Add to Workflows"}
473
  </button>
474
  </div>
475
  ) : null}
web/src/automation/AutomationDetail.tsx CHANGED
@@ -55,6 +55,9 @@ import type {
55
  TickState,
56
  TriggerOption,
57
  UserTable,
 
 
 
58
  } from "./automationApi";
59
  import type { VoiceAgent } from "./voiceAgentTypes";
60
  import {
@@ -74,7 +77,12 @@ import {
74
  sendStatementBatch,
75
  statementBatch,
76
  toggleNode,
 
 
 
 
77
  } from "./automationApi";
 
78
 
79
  interface Props {
80
  automation: Automation;
@@ -411,6 +419,48 @@ export default function AutomationDetail({
411
  for exactly the people who used the Canvas once.
412
  */
413
  const [view, setView] = useState<"canvas" | "chat">("chat");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
414
  /*
415
  ⭐⭐ W36-T32 — THE RIGHT RAIL FOLDS, AND THE CHOICE SURVIVES A RELOAD.
416
  Owner: *"Add a 'III' so the user can hide it so they have the full Chat interface."*
@@ -471,7 +521,7 @@ export default function AutomationDetail({
471
  );
472
  const viewTabs = (
473
  <div className="autox-views" role="radiogroup" aria-label="Editor view">
474
- {([["chat", "Chat"], ["canvas", "Canvas"]] as const).map(([k, label]) => (
475
  <button
476
  key={k}
477
  type="button"
@@ -505,7 +555,8 @@ export default function AutomationDetail({
505
  describes rather than contradicts: hiding this rail is what gives "the full Chat
506
  interface" (owner item 3), so a Chat that lived INSIDE the rail would disappear with it.
507
  Read left to right across the head, the four words are the ruling's four words. */}
508
- {([["properties", "Properties"], ["harness", "Harness"],
 
509
  ["runs", "Run history"]] as const).map(([k, label]) => (
510
  <button
511
  key={k}
@@ -1704,6 +1755,65 @@ export default function AutomationDetail({
1704
  panels out of the accessibility tree exactly as `hidden` does.
1705
  */}
1706
  <div className={"auto-work" + (railShut ? " autod-folded" : "")}>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1707
  {/*
1708
  ⛔ THE VIEW IS CHOSEN, NEVER INFERRED (C14 leg 1). This block used to be
1709
  `{board ? <Board/> : <Steps/>}` — the page's SHAPE decided by whether a fetch had
@@ -1734,6 +1844,12 @@ export default function AutomationDetail({
1734
  * automation; the selection is the cheaper thing to lose.
1735
  */
1736
  <AutomationChat
 
 
 
 
 
 
1737
  onAccept={async (draft) => {
1738
  await writeDefinition({
1739
  ...(draft.name ? { name: draft.name } : {}),
@@ -1757,6 +1873,7 @@ export default function AutomationDetail({
1757
  */}
1758
  <>
1759
  <AutomationBuilder
 
1760
  flowHidden={view === "chat"}
1761
  /* ⭐ W36-T69 / R9 — straight off the payload, never re-derived. */
1762
  {...(automation.agentActions ? { agentMarks: automation.agentActions } : {})}
@@ -1833,8 +1950,15 @@ export default function AutomationDetail({
1833
  <div className="auto-panel-head">
1834
  {panelTabs}
1835
  </div>
1836
- {aside === "harness" ? <HarnessPanel agentId={automation.id} /> : null}
 
 
1837
  </aside>
 
 
 
 
 
1838
  <aside
1839
  className="auto-panel is-appearing"
1840
  aria-label="Run history"
 
55
  TickState,
56
  TriggerOption,
57
  UserTable,
58
+ AgentContract,
59
+ AgentDatabaseGrant,
60
+ AgentWorkflowSummary,
61
  } from "./automationApi";
62
  import type { VoiceAgent } from "./voiceAgentTypes";
63
  import {
 
77
  sendStatementBatch,
78
  statementBatch,
79
  toggleNode,
80
+ answerAgentSetup,
81
+ createAgentWorkflow,
82
+ getAgentContract,
83
+ updateAgentGovernance,
84
  } from "./automationApi";
85
+ import "../styles/wave45/agent-operator.css";
86
 
87
  interface Props {
88
  automation: Automation;
 
419
  for exactly the people who used the Canvas once.
420
  */
421
  const [view, setView] = useState<"canvas" | "chat">("chat");
422
+ const [agentContract, setAgentContract] = useState<AgentContract | null>(null);
423
+ const workflows: AgentWorkflowSummary[] = agentContract?.workflows ?? [];
424
+ const [activeWorkflow, setActiveWorkflow] = useState("");
425
+ const [governanceDatabase, setGovernanceDatabase] = useState("");
426
+ useEffect(() => {
427
+ if (automation.system) { setAgentContract(null); return; }
428
+ const controller = new AbortController();
429
+ void getAgentContract(automation.id, controller.signal).then(({ agent }) => {
430
+ setAgentContract(agent);
431
+ setActiveWorkflow((current) => agent.workflows.some((row) => row.id === current)
432
+ ? current : agent.workflows[0]?.id || "");
433
+ }).catch((error) => setProblem(error instanceof Error ? error.message : "Agent contract unavailable."));
434
+ return () => controller.abort();
435
+ }, [automation.id, automation.system]);
436
+ useEffect(() => {
437
+ const offered = tables.map((table) => table.key);
438
+ setGovernanceDatabase((current) => offered.includes(current)
439
+ ? current : (offered.includes(targetTable) ? targetTable : offered[0] || ""));
440
+ }, [tables, targetTable]);
441
+ const addWorkflow = async () => {
442
+ const asked = window.prompt("Workflow name", `Workflow ${workflows.length + 1}`)?.trim();
443
+ if (!asked) return;
444
+ try {
445
+ const { workflow, agent } = await createAgentWorkflow(automation.id, asked);
446
+ setAgentContract(agent); setActiveWorkflow(workflow.id); setView("canvas");
447
+ } catch (error) { setProblem(error instanceof Error ? error.message : "Workflow could not be created."); }
448
+ };
449
+ const saveGovernance = async (nextGrant?: AgentDatabaseGrant) => {
450
+ if (!agentContract) return;
451
+ const database = governanceDatabase;
452
+ const existing = agentContract.capabilities.workflows;
453
+ const workflowGrants = { ...(existing[activeWorkflow] || {}) };
454
+ if (nextGrant && database) workflowGrants[database] = nextGrant;
455
+ try {
456
+ const { agent } = await updateAgentGovernance(automation.id, {
457
+ visibility: agentContract.sharing.visibility,
458
+ sharedWith: agentContract.sharing.sharedWith,
459
+ workflows: { ...existing, [activeWorkflow]: workflowGrants },
460
+ });
461
+ setAgentContract(agent);
462
+ } catch (error) { setProblem(error instanceof Error ? error.message : "Agent governance could not be saved."); }
463
+ };
464
  /*
465
  ⭐⭐ W36-T32 — THE RIGHT RAIL FOLDS, AND THE CHOICE SURVIVES A RELOAD.
466
  Owner: *"Add a 'III' so the user can hide it so they have the full Chat interface."*
 
521
  );
522
  const viewTabs = (
523
  <div className="autox-views" role="radiogroup" aria-label="Editor view">
524
+ {([["chat", "Chat"], ["canvas", "Workflows"]] as const).map(([k, label]) => (
525
  <button
526
  key={k}
527
  type="button"
 
555
  describes rather than contradicts: hiding this rail is what gives "the full Chat
556
  interface" (owner item 3), so a Chat that lived INSIDE the rail would disappear with it.
557
  Read left to right across the head, the four words are the ruling's four words. */}
558
+ {([["properties", "Properties"],
559
+ ...(automation.kind === "field_agent" ? [] : [["harness", "Harness"]] as const),
560
  ["runs", "Run history"]] as const).map(([k, label]) => (
561
  <button
562
  key={k}
 
1755
  panels out of the accessibility tree exactly as `hidden` does.
1756
  */}
1757
  <div className={"auto-work" + (railShut ? " autod-folded" : "")}>
1758
+ {view === "canvas" ? (
1759
+ <div className="w45-workflow-bar" aria-label="Workflow selection">
1760
+ <label htmlFor="agent-workflow">Workflow</label>
1761
+ <select
1762
+ id="agent-workflow"
1763
+ value={activeWorkflow}
1764
+ onChange={(event) => setActiveWorkflow(event.currentTarget.value)}
1765
+ >
1766
+ {workflows.map((workflow) => (
1767
+ <option key={workflow.id} value={workflow.id}>{workflow.name}</option>
1768
+ ))}
1769
+ </select>
1770
+ <button type="button" className="w45-quiet" onClick={() => void addWorkflow()}>Add workflow</button>
1771
+ {agentContract ? (
1772
+ <>
1773
+ <button type="button" className="w45-quiet" onClick={async () => {
1774
+ const visibility = agentContract.sharing.visibility === "private" ? "shared" : "private";
1775
+ const recipient = visibility === "shared" ? window.prompt("Tenant username to share with", "")?.trim() : "";
1776
+ if (visibility === "shared" && !recipient) return;
1777
+ try {
1778
+ const { agent } = await updateAgentGovernance(automation.id, {
1779
+ visibility, sharedWith: visibility === "shared"
1780
+ ? Array.from(new Set([...agentContract.sharing.sharedWith, recipient!])) : [],
1781
+ workflows: agentContract.capabilities.workflows,
1782
+ }); setAgentContract(agent);
1783
+ } catch (error) { setProblem(error instanceof Error ? error.message : "Sharing could not be saved."); }
1784
+ }}>{agentContract.sharing.visibility === "private" ? "Share agent" : "Make private"}</button>
1785
+ </>
1786
+ ) : null}
1787
+ {agentContract && activeWorkflow ? (() => {
1788
+ const grant = agentContract.capabilities.workflows[activeWorkflow]?.[governanceDatabase];
1789
+ const editable = grant || { mode: agentContract.capabilities.defaultMode, read: true,
1790
+ create: [], update: [], overwrite: [], delete: [] } as AgentDatabaseGrant;
1791
+ const fields = tables.find((table) => table.key === governanceDatabase)?.fields || [];
1792
+ const operations = ["create", "update", "overwrite", "delete"] as const;
1793
+ return <fieldset className="w45-governance" aria-label="Workflow database capabilities">
1794
+ <legend>Capabilities</legend>
1795
+ <label>Database<select value={governanceDatabase} onChange={(event) => setGovernanceDatabase(event.currentTarget.value)}>
1796
+ {tables.map((table) => <option key={table.key} value={table.key}>{table.label}</option>)}
1797
+ </select></label>
1798
+ <span className={"w45-chip " + (grant ? "is-on" : "is-off")}>{grant ? `Read ${String(grant.read)} · ${grant.mode}` : "Not granted"}</span>
1799
+ <div className="w45-chip-row" aria-label="Execution mode">
1800
+ {(["preview", "autonomous"] as const).map((mode) => <button type="button" className="w45-quiet" key={mode}
1801
+ aria-pressed={grant?.mode === mode} onClick={() => void saveGovernance({ ...editable, mode })}>{mode}</button>)}
1802
+ </div>
1803
+ {operations.map((operation) => <div className="w45-field-grants" key={operation}>
1804
+ <strong>{operation}</strong>
1805
+ {fields.map((field) => <label key={field.key}><input type="checkbox" checked={editable[operation].includes(field.key)}
1806
+ onChange={(event) => {
1807
+ const selected = event.currentTarget.checked
1808
+ ? Array.from(new Set([...editable[operation], field.key]))
1809
+ : editable[operation].filter((key) => key !== field.key);
1810
+ void saveGovernance({ ...editable, [operation]: selected });
1811
+ }} />{field.label}</label>)}
1812
+ </div>)}
1813
+ </fieldset>;
1814
+ })() : null}
1815
+ </div>
1816
+ ) : null}
1817
  {/*
1818
  ⛔ THE VIEW IS CHOSEN, NEVER INFERRED (C14 leg 1). This block used to be
1819
  `{board ? <Board/> : <Steps/>}` — the page's SHAPE decided by whether a fetch had
 
1844
  * automation; the selection is the cheaper thing to lose.
1845
  */
1846
  <AutomationChat
1847
+ unconfigured={!automation.flow?.actions?.length || automation.unconfigured.length > 0}
1848
+ setupInterview={agentContract?.setupInterview}
1849
+ onSetupAnswer={async (key, answer, disable) => {
1850
+ const result = await answerAgentSetup(automation.id, key, answer, disable);
1851
+ setAgentContract(result.agent);
1852
+ }}
1853
  onAccept={async (draft) => {
1854
  await writeDefinition({
1855
  ...(draft.name ? { name: draft.name } : {}),
 
1873
  */}
1874
  <>
1875
  <AutomationBuilder
1876
+ agentContract={agentContract}
1877
  flowHidden={view === "chat"}
1878
  /* ⭐ W36-T69 / R9 — straight off the payload, never re-derived. */
1879
  {...(automation.agentActions ? { agentMarks: automation.agentActions } : {})}
 
1950
  <div className="auto-panel-head">
1951
  {panelTabs}
1952
  </div>
1953
+ {aside === "harness" && automation.kind !== "field_agent" ? (
1954
+ <HarnessPanel agentId={automation.id} />
1955
+ ) : null}
1956
  </aside>
1957
+ {automation.kind === "field_agent" ? (
1958
+ <p className="w45-refusal" role="status">
1959
+ Synthetic field agents do not expose a Harness. Manage the source field instead.
1960
+ </p>
1961
+ ) : null}
1962
  <aside
1963
  className="auto-panel is-appearing"
1964
  aria-label="Run history"
web/src/automation/AutomationSurface.tsx CHANGED
@@ -40,6 +40,7 @@ import {
40
  } from "./automationApi";
41
  import type { VoiceAgent } from "./voiceAgentTypes";
42
  import "../styles/wave44/voice-agent.css";
 
43
 
44
  /**
45
  * ⭐⭐ WAVE 30 · T21 (owner items 4 + 5) — THE EDITOR STOPS SHIPPING INSIDE THE LIST.
@@ -521,7 +522,9 @@ export default function AutomationSurface() {
521
  setOpenRequest(null);
522
  }, [openRequest, data, select]);
523
 
524
- const items = data?.automations || [];
 
 
525
  /*
526
  * W44 QA: AI field agents are derived from field definitions, so they cannot be added as
527
  * ordinary flow actions. The list endpoint already composed and permission-filtered the safe
 
40
  } from "./automationApi";
41
  import type { VoiceAgent } from "./voiceAgentTypes";
42
  import "../styles/wave44/voice-agent.css";
43
+ import "../styles/wave45/agent-operator.css";
44
 
45
  /**
46
  * ⭐⭐ WAVE 30 · T21 (owner items 4 + 5) — THE EDITOR STOPS SHIPPING INSIDE THE LIST.
 
522
  setOpenRequest(null);
523
  }, [openRequest, data, select]);
524
 
525
+ // Odoo sync belongs to its Connector. The server remains the delete/run wall; this projection
526
+ // prevents a system connector schedule from masquerading as a user-created Agent.
527
+ const items = (data?.automations || []).filter((agent) => agent.system !== "odoo_sync");
528
  /*
529
  * W44 QA: AI field agents are derived from field definitions, so they cannot be added as
530
  * ordinary flow actions. The list endpoint already composed and permission-filtered the safe
web/src/automation/VoiceAgentProperties.tsx CHANGED
@@ -4,6 +4,10 @@ import { useState } from "react";
4
  import {
5
  AutomationError,
6
  dryRunVoiceAgent,
 
 
 
 
7
  patchVoiceAgent,
8
  } from "./automationApi";
9
  import type {
@@ -12,6 +16,10 @@ import type {
12
  VoiceAudienceOption,
13
  VoiceHarnessInput,
14
  VoiceHarnessResult,
 
 
 
 
15
  } from "./voiceAgentTypes";
16
 
17
  interface Props {
@@ -123,6 +131,12 @@ export default function VoiceAgentProperties({ agent, onSaved }: Props) {
123
  phoneField: agent.audience.phoneFieldKey,
124
  }));
125
  const [result, setResult] = useState<VoiceHarnessResult | null>(null);
 
 
 
 
 
 
126
  const [error, setError] = useState("");
127
  const [saveError, setSaveError] = useState("");
128
  const [saveReceipt, setSaveReceipt] = useState("");
@@ -280,6 +294,56 @@ export default function VoiceAgentProperties({ agent, onSaved }: Props) {
280
  </section>
281
  </div>
282
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  <section className="voice-agent-section" aria-labelledby="voice-config-heading">
284
  <div className="voice-agent-section-head">
285
  <h2 id="voice-config-heading">Configuration</h2>
@@ -460,10 +524,11 @@ export default function VoiceAgentProperties({ agent, onSaved }: Props) {
460
  <div>
461
  <h2 id="voice-harness-heading">Test harness</h2>
462
  <p className="voice-agent-note">
463
- Validate a saved View and phone-type field without external dispatch.
 
464
  </p>
465
  </div>
466
- <span className="voice-agent-harness-state">No external dispatch</span>
467
  </div>
468
  <div className="voice-agent-harness-fields">
469
  <label>
 
4
  import {
5
  AutomationError,
6
  dryRunVoiceAgent,
7
+ dryRunWhatsApp,
8
+ setVoiceFeedbackConsent,
9
+ createVoiceFeedbackSchedule,
10
+ dryRunVoiceFeedback,
11
  patchVoiceAgent,
12
  } from "./automationApi";
13
  import type {
 
16
  VoiceAudienceOption,
17
  VoiceHarnessInput,
18
  VoiceHarnessResult,
19
+ WhatsAppDryRunResult,
20
+ VoiceConsentResult,
21
+ VoiceFeedbackSchedule,
22
+ VoiceFeedbackDryRun,
23
  } from "./voiceAgentTypes";
24
 
25
  interface Props {
 
131
  phoneField: agent.audience.phoneFieldKey,
132
  }));
133
  const [result, setResult] = useState<VoiceHarnessResult | null>(null);
134
+ const [whatsAppInput, setWhatsAppInput] = useState("");
135
+ const [whatsAppResult, setWhatsAppResult] = useState<WhatsAppDryRunResult | null>(null);
136
+ const [contactRef, setContactRef] = useState("");
137
+ const [consent, setConsent] = useState<VoiceConsentResult | null>(null);
138
+ const [feedbackSchedule, setFeedbackSchedule] = useState<VoiceFeedbackSchedule | null>(null);
139
+ const [feedbackResult, setFeedbackResult] = useState<VoiceFeedbackDryRun | null>(null);
140
  const [error, setError] = useState("");
141
  const [saveError, setSaveError] = useState("");
142
  const [saveReceipt, setSaveReceipt] = useState("");
 
294
  </section>
295
  </div>
296
 
297
+ <section className="voice-agent-section" aria-labelledby="voice-channels-heading">
298
+ <h2 id="voice-channels-heading">Channels</h2>
299
+ <dl className="voice-agent-details">
300
+ <div><dt>Provider</dt><dd>{agent.providerOption?.label || agent.providerConnection?.label || "Not configured"}</dd></div>
301
+ <div><dt>Provider binding</dt><dd>{agent.providerConnection ? `${statusLabel(agent.providerConnection.status)} · masked` : "Not bound"}</dd></div>
302
+ <div><dt>Inbound voice</dt><dd>{statusLabel(agent.providerOption?.capabilities.inboundVoice || "not reported")}</dd></div>
303
+ <div><dt>Outbound voice</dt><dd>{statusLabel(agent.providerOption?.capabilities.outboundVoice || "not reported")}</dd></div>
304
+ <div><dt>WhatsApp messages</dt><dd>{statusLabel(agent.providerOption?.capabilities.whatsAppMessaging || "not reported")}</dd></div>
305
+ <div><dt>WhatsApp calls</dt><dd>{statusLabel(agent.providerOption?.capabilities.whatsAppCalling || "not reported")}</dd></div>
306
+ <div><dt>Query access</dt><dd>{statusLabel(agent.providerOption?.capabilities.governedQuery || "not reported")}</dd></div>
307
+ <div><dt>Webhook</dt><dd>{whatsAppResult?.verifiedWebhook ? "Verified by dry run" : "Not verified in this session"}</dd></div>
308
+ </dl>
309
+ <label className="voice-agent-field is-wide">Recorded Telnyx fixture JSON<textarea value={whatsAppInput} onChange={(event) => setWhatsAppInput(event.currentTarget.value)} placeholder='{"payload": {…}, "headers": {…}}' /></label>
310
+ <button type="button" className="voice-agent-harness-submit" disabled={!whatsAppInput.trim()} onClick={async () => {
311
+ setError(""); setWhatsAppResult(null);
312
+ try { const parsed = JSON.parse(whatsAppInput) as { payload?: unknown; headers?: Record<string, string> }; setWhatsAppResult(await dryRunWhatsApp(agent.automationId, parsed.payload, parsed.headers || {})); }
313
+ catch (reason) { setError(reason instanceof Error ? reason.message : "WhatsApp dry run failed."); }
314
+ }}>Run verified WhatsApp simulation</button>
315
+ {whatsAppResult ? <p className="w45-safe">
316
+ {whatsAppResult.replayed
317
+ ? `Repeated event ${whatsAppResult.eventId} recognized (${whatsAppResult.deliveryState}); no new simulated reply was created.`
318
+ : `${whatsAppResult.simulatedReply.status}: ${whatsAppResult.simulatedReply.text}.`}
319
+ {whatsAppResult.noExternalDispatch ? " No external dispatch occurred." : " No-send was not confirmed."}
320
+ </p> : null}
321
+ </section>
322
+
323
+ <section className="voice-agent-section" aria-labelledby="voice-feedback-heading">
324
+ <h2 id="voice-feedback-heading">Daily feedback</h2>
325
+ <dl className="voice-agent-details">
326
+ <div><dt>Consent</dt><dd>{consent ? statusLabel(consent.state) : "Required"}</dd></div>
327
+ <div><dt>Schedule</dt><dd>{feedbackSchedule ? `${feedbackSchedule.localTime} ${feedbackSchedule.timezone}` : "Not created"}</dd></div>
328
+ <div><dt>Activation</dt><dd>{statusLabel(feedbackSchedule?.activationState || agent.activationState)}</dd></div>
329
+ </dl>
330
+ <label className="voice-agent-field"><span>Opaque contact reference</span><input value={contactRef} onChange={(event) => setContactRef(event.currentTarget.value)} /></label>
331
+ <button type="button" className="w45-quiet" disabled={!contactRef.trim()} onClick={async () => {
332
+ try { setConsent((await setVoiceFeedbackConsent(agent.automationId, contactRef.trim(), "consented", "daily feedback")).consent); }
333
+ catch (reason) { setError(reason instanceof Error ? reason.message : "Consent could not be stored."); }
334
+ }}>Record consent</button>
335
+ <button type="button" className="w45-quiet" disabled={!consent || consent.state !== "consented"} onClick={async () => {
336
+ try { setFeedbackSchedule((await createVoiceFeedbackSchedule(agent.automationId, [contactRef.trim()], "09:00", "UTC")).schedule); }
337
+ catch (reason) { setError(reason instanceof Error ? reason.message : "Schedule could not be created."); }
338
+ }}>Create disabled schedule</button>
339
+ <button type="button" className="w45-quiet" disabled={!feedbackSchedule} onClick={async () => {
340
+ try { setFeedbackResult(await dryRunVoiceFeedback(agent.automationId, feedbackSchedule!.id, new Date().toISOString().slice(0, 10))); }
341
+ catch (reason) { setError(reason instanceof Error ? reason.message : "Feedback dry run failed."); }
342
+ }}>Dry run feedback</button>
343
+ <button type="button" className="voice-agent-disabled-control" disabled>Daily calls disabled</button>
344
+ {feedbackResult ? <p className="w45-safe">{feedbackResult.dueCount} due. {feedbackResult.noExternalDispatch ? "No external dispatch occurred." : "No-send was not confirmed."}</p> : <p className="voice-agent-note">Activation remains unavailable; schedules are disabled.</p>}
345
+ </section>
346
+
347
  <section className="voice-agent-section" aria-labelledby="voice-config-heading">
348
  <div className="voice-agent-section-head">
349
  <h2 id="voice-config-heading">Configuration</h2>
 
524
  <div>
525
  <h2 id="voice-harness-heading">Test harness</h2>
526
  <p className="voice-agent-note">
527
+ Validate a saved View and phone-type field. No external dispatch is possible from
528
+ this dry run.
529
  </p>
530
  </div>
531
+ <span className="voice-agent-harness-state">Dry-run route</span>
532
  </div>
533
  <div className="voice-agent-harness-fields">
534
  <label>
web/src/automation/automationApi.ts CHANGED
@@ -32,6 +32,11 @@ import type {
32
  VoiceEmptyPolicyOption,
33
  VoiceHarnessInput,
34
  VoiceHarnessResult,
 
 
 
 
 
35
  } from "./voiceAgentTypes";
36
 
37
  /**
@@ -1132,6 +1137,12 @@ export function parseVoiceAgent(value: unknown): VoiceAgent | null {
1132
  const maskedDisplay = voiceMaskedDisplay(binding.maskedDisplay);
1133
  const hasBinding = Object.keys(binding).length > 0 && !!maskedDisplay;
1134
  const capabilities = voiceRecord(row.capabilities);
 
 
 
 
 
 
1135
 
1136
  const safeAgent: VoiceAgent = {
1137
  automationId,
@@ -1160,10 +1171,21 @@ export function parseVoiceAgent(value: unknown): VoiceAgent | null {
1160
  audience: voiceAudience(row.audience),
1161
  capabilities: {
1162
  dryRun: capabilities.dryRun === true,
 
 
1163
  ...(capabilities.numberProvisioning === "contact_loopable"
1164
  ? { numberProvisioning: "contact_loopable" as const }
1165
  : {}),
1166
  },
 
 
 
 
 
 
 
 
 
1167
  audienceOptions: voiceAudienceOptions(row.audienceOptions),
1168
  };
1169
  return safeAgent;
@@ -1179,7 +1201,23 @@ export function parseVoiceAgentList(value: unknown): VoiceAgentList {
1179
  }
1180
 
1181
  export function listVoiceAgents(abort?: AbortSignal): Promise<VoiceAgentList> {
1182
- return send<unknown>("/voice-agents", { signal: abort }).then(parseVoiceAgentList);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1183
  }
1184
 
1185
  /** Build the complete PATCH body field-by-field. No server DTO or caller extras may hitch a ride. */
@@ -1239,6 +1277,27 @@ export function dryRunVoiceAgent(
1239
  );
1240
  }
1241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1242
  /**
1243
  * ⭐⭐ WAVE 31 · T31 — fold ONE freshly-written automation into the memo, and hand back the list.
1244
  *
@@ -1946,3 +2005,177 @@ export interface PresetPlan {
1946
  export function getPresetPlan(table: string, abort?: AbortSignal): Promise<PresetPlan> {
1947
  return send(`/automations/presets?table=${encodeURIComponent(table)}`, { signal: abort });
1948
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  VoiceEmptyPolicyOption,
33
  VoiceHarnessInput,
34
  VoiceHarnessResult,
35
+ VoiceProviderOption,
36
+ WhatsAppDryRunResult,
37
+ VoiceConsentResult,
38
+ VoiceFeedbackSchedule,
39
+ VoiceFeedbackDryRun,
40
  } from "./voiceAgentTypes";
41
 
42
  /**
 
1137
  const maskedDisplay = voiceMaskedDisplay(binding.maskedDisplay);
1138
  const hasBinding = Object.keys(binding).length > 0 && !!maskedDisplay;
1139
  const capabilities = voiceRecord(row.capabilities);
1140
+ const connection = voiceRecord(row.providerConnection);
1141
+ // Provider identity is accepted only through the redacted connection DTO. The extension bag is
1142
+ // configuration and is deliberately ignored here; a caller-injected extension cannot label UI.
1143
+ const providerKey = voiceText(connection.provider, 40);
1144
+ const directionPolicy = (Array.isArray(row.directionPolicy) ? row.directionPolicy : [])
1145
+ .map((value) => voiceText(value, 40)).filter(Boolean);
1146
 
1147
  const safeAgent: VoiceAgent = {
1148
  automationId,
 
1171
  audience: voiceAudience(row.audience),
1172
  capabilities: {
1173
  dryRun: capabilities.dryRun === true,
1174
+ activation: capabilities.activation === true,
1175
+ externalDispatch: capabilities.externalDispatch === true,
1176
  ...(capabilities.numberProvisioning === "contact_loopable"
1177
  ? { numberProvisioning: "contact_loopable" as const }
1178
  : {}),
1179
  },
1180
+ providerKey,
1181
+ providerConnection: Object.keys(connection).length ? {
1182
+ id: voiceText(connection.id, 120), provider: voiceText(connection.provider, 40),
1183
+ label: voiceText(connection.label, 80), status: voiceText(connection.status, 80),
1184
+ lastProbeAt: voiceWhole(connection.lastProbeAt, 0),
1185
+ } : null,
1186
+ providerOption: null,
1187
+ directionPolicy,
1188
+ activationState: voiceText(row.activationState, 80) || "draft",
1189
  audienceOptions: voiceAudienceOptions(row.audienceOptions),
1190
  };
1191
  return safeAgent;
 
1201
  }
1202
 
1203
  export function listVoiceAgents(abort?: AbortSignal): Promise<VoiceAgentList> {
1204
+ return send<unknown>("/voice-agents", { signal: abort }).then(parseVoiceAgentList).then((parsed) =>
1205
+ send<unknown>("/voice-agents/options", { signal: abort }).then((optionsPayload) => {
1206
+ const options = voiceRecord(optionsPayload);
1207
+ const providers: VoiceProviderOption[] = (Array.isArray(options.providers) ? options.providers : []).flatMap((value) => {
1208
+ const row = voiceRecord(value); const caps = voiceRecord(row.capabilities);
1209
+ const key = voiceText(row.key, 40); const label = voiceText(row.label, 80);
1210
+ return key && label ? [{ key, label, capabilities: {
1211
+ inboundVoice: voiceText(caps.inboundVoice, 40), outboundVoice: voiceText(caps.outboundVoice, 40),
1212
+ whatsAppMessaging: voiceText(caps.whatsAppMessaging, 40), whatsAppCalling: voiceText(caps.whatsAppCalling, 40),
1213
+ governedQuery: voiceText(caps.governedQuery, 40),
1214
+ } }] : [];
1215
+ });
1216
+ return { voiceAgents: parsed.voiceAgents.map((agent) => ({
1217
+ ...agent, providerOption: providers.find((provider) => provider.key === agent.providerKey) || null,
1218
+ })) };
1219
+ })
1220
+ );
1221
  }
1222
 
1223
  /** Build the complete PATCH body field-by-field. No server DTO or caller extras may hitch a ride. */
 
1277
  );
1278
  }
1279
 
1280
+ export function dryRunWhatsApp(voiceId: string, payload: unknown, headers: Record<string, string>): Promise<WhatsAppDryRunResult> {
1281
+ return send(`/voice-agents/${encodeURIComponent(voiceId)}/whatsapp/telnyx/dry-run`, {
1282
+ method: "POST", body: JSON.stringify({ payload, headers }),
1283
+ });
1284
+ }
1285
+ export function setVoiceFeedbackConsent(voiceId: string, contactRef: string, state: "consented" | "withdrawn", purpose: string): Promise<{ consent: VoiceConsentResult }> {
1286
+ return send(`/voice-agents/${encodeURIComponent(voiceId)}/feedback/consent`, {
1287
+ method: "POST", body: JSON.stringify({ contactRef, state, purpose }),
1288
+ });
1289
+ }
1290
+ export function createVoiceFeedbackSchedule(voiceId: string, contactRefs: string[], localTime: string, timezone: string): Promise<{ schedule: VoiceFeedbackSchedule }> {
1291
+ return send(`/voice-agents/${encodeURIComponent(voiceId)}/feedback/schedules`, {
1292
+ method: "POST", body: JSON.stringify({ contactRefs, localTime, timezone }),
1293
+ });
1294
+ }
1295
+ export function dryRunVoiceFeedback(voiceId: string, scheduleId: string, day: string): Promise<VoiceFeedbackDryRun> {
1296
+ return send(`/voice-agents/${encodeURIComponent(voiceId)}/feedback/schedules/${encodeURIComponent(scheduleId)}/dry-run`, {
1297
+ method: "POST", body: JSON.stringify({ day }),
1298
+ });
1299
+ }
1300
+
1301
  /**
1302
  * ⭐⭐ WAVE 31 · T31 — fold ONE freshly-written automation into the memo, and hand back the list.
1303
  *
 
2005
  export function getPresetPlan(table: string, abort?: AbortSignal): Promise<PresetPlan> {
2006
  return send(`/automations/presets?table=${encodeURIComponent(table)}`, { signal: abort });
2007
  }
2008
+
2009
+ // Wave 45 C2/C4 consumer contract. These are the browser allow-lists served by A/B/C. No client
2010
+ // fallback exists: an unavailable route is an unavailable feature, never permission to fabricate.
2011
+ export interface AgentWorkflowSummary {
2012
+ id: string;
2013
+ name: string;
2014
+ kind: "event_store_view";
2015
+ eventStoreId: string;
2016
+ purpose: string;
2017
+ createdAt: number;
2018
+ updatedAt: number;
2019
+ }
2020
+
2021
+ export interface AgentDatabaseGrant {
2022
+ mode: "preview" | "autonomous";
2023
+ read: boolean;
2024
+ create: string[];
2025
+ update: string[];
2026
+ overwrite: string[];
2027
+ delete: string[];
2028
+ }
2029
+
2030
+ export interface AgentSetupQuestion {
2031
+ key: string;
2032
+ text: string;
2033
+ suggestion: string;
2034
+ allowDisable: boolean;
2035
+ }
2036
+
2037
+ export interface AgentContract {
2038
+ schemaVersion: 1;
2039
+ agentId: string;
2040
+ eventStore: { id: string; kind: "agent_event_store"; visibility: "private"; hiddenFromData: true };
2041
+ workflows: AgentWorkflowSummary[];
2042
+ sharing: { visibility: "private" | "shared"; sharedWith: string[] };
2043
+ capabilities: {
2044
+ defaultMode: "preview";
2045
+ workflows: Record<string, Record<string, AgentDatabaseGrant>>;
2046
+ };
2047
+ setupInterview: {
2048
+ state: "configured" | "unconfigured";
2049
+ question: AgentSetupQuestion | null;
2050
+ progress: number;
2051
+ total: number;
2052
+ };
2053
+ eventCount: number;
2054
+ }
2055
+
2056
+ export function getAgentContract(agentId: string, abort?: AbortSignal): Promise<{ agent: AgentContract }> {
2057
+ return send(`/agents/${encodeURIComponent(agentId)}/contract`, { signal: abort });
2058
+ }
2059
+
2060
+ export function createAgentWorkflow(agentId: string, name: string, purpose = ""):
2061
+ Promise<{ workflow: AgentWorkflowSummary; agent: AgentContract }> {
2062
+ return send(`/agents/${encodeURIComponent(agentId)}/workflows`, {
2063
+ method: "POST", body: JSON.stringify({ name, purpose }),
2064
+ });
2065
+ }
2066
+
2067
+ export interface AgentGovernanceInput {
2068
+ visibility: "private" | "shared";
2069
+ sharedWith: string[];
2070
+ workflows: Record<string, Record<string, AgentDatabaseGrant>>;
2071
+ }
2072
+
2073
+ export function updateAgentGovernance(agentId: string, body: AgentGovernanceInput):
2074
+ Promise<{ agent: AgentContract }> {
2075
+ return send(`/agents/${encodeURIComponent(agentId)}/governance`, {
2076
+ method: "PATCH", body: JSON.stringify(body),
2077
+ });
2078
+ }
2079
+
2080
+ export function answerAgentSetup(agentId: string, key: string, answer: string, disable = false):
2081
+ Promise<{ setupInterview: AgentContract["setupInterview"]; agent: AgentContract }> {
2082
+ return send(`/agents/${encodeURIComponent(agentId)}/setup/answer`, {
2083
+ method: "POST", body: JSON.stringify({ key, answer, disable }),
2084
+ });
2085
+ }
2086
+
2087
+ export interface QueryToolArtifacts {
2088
+ filters: unknown[];
2089
+ sorts: unknown[];
2090
+ group: unknown;
2091
+ hiddenFields: string[];
2092
+ source: { database: string; fields: string[]; permissionScopeApplied: true };
2093
+ }
2094
+ export type QueryToolResult =
2095
+ | { status: "clarification"; alignmentQuestion: {
2096
+ id: string; question: string; choices: Array<{ field: string; label: string }>;
2097
+ maxSelections: number;
2098
+ }; resumeToken: string }
2099
+ | { status: "answered"; wording: string; speakable: string;
2100
+ citations: Array<{ database: string; rowId: string }>; rows: Record<string, unknown>[];
2101
+ artifacts: QueryToolArtifacts; semanticRouter: unknown;
2102
+ model: { provider: string | null; modelId: string | null } };
2103
+
2104
+ export interface QueryToolInput {
2105
+ database: string; prompt: string; fieldKeys?: string[]; resumeToken?: string;
2106
+ filters?: unknown[]; sorts?: unknown[]; group?: unknown; hiddenFields?: string[];
2107
+ }
2108
+ export function runQueryTool(body: QueryToolInput): Promise<QueryToolResult> {
2109
+ return send("/query/tool", { method: "POST", body: JSON.stringify(body) });
2110
+ }
2111
+ export interface QueryModelIdentity { model: string; provider: string; modelId: string; available: boolean; reason: string }
2112
+ export function getQueryModelCatalog(abort?: AbortSignal): Promise<QueryModelIdentity[]> {
2113
+ return send<{ modelStatus?: QueryModelIdentity[] }>("/query", { signal: abort })
2114
+ .then((payload) => Array.isArray(payload.modelStatus) ? payload.modelStatus : []);
2115
+ }
2116
+ export function persistQueryArtifacts(queryId: string, currentView: Record<string, unknown>, artifacts: QueryToolArtifacts): Promise<unknown> {
2117
+ const hidden = new Set(Array.isArray(artifacts.hiddenFields) ? artifacts.hiddenFields : []);
2118
+ const visible = artifacts.source.fields.filter((field) => !hidden.has(field));
2119
+ return send(`/query/${encodeURIComponent(queryId)}/events`, {
2120
+ method: "POST", body: JSON.stringify({
2121
+ workspaceBinding: { kind: "query", key: queryId },
2122
+ event: { type: "view_upsert", view: { id: queryId, config: {
2123
+ ...currentView, filters: artifacts.filters, sorts: artifacts.sorts,
2124
+ groupBy: artifacts.group, visible,
2125
+ } } },
2126
+ }),
2127
+ });
2128
+ }
2129
+
2130
+ export interface OdooStatus {
2131
+ schedule: string; health: "paused" | "error" | "unknown";
2132
+ lastRun: string | null; errors: unknown[]; frozen: boolean;
2133
+ }
2134
+ export interface OdooSchemaField {
2135
+ key: string; label: string; type: string; source: "Odoo";
2136
+ emptyDiscoverable: true; defaultEnabled: false; enabled: boolean;
2137
+ }
2138
+ export interface OdooSchema { fields: OdooSchemaField[]; default: "off"; adminOnly: true; complete: boolean; source: "Odoo" }
2139
+ export function getOdooStatus(abort?: AbortSignal): Promise<OdooStatus> {
2140
+ return send("/connectors/odoo/status", { signal: abort });
2141
+ }
2142
+ export function getOdooSchema(abort?: AbortSignal): Promise<OdooSchema> {
2143
+ return send("/connectors/odoo/schema", { signal: abort });
2144
+ }
2145
+ export function setOdooFieldEnabled(key: string, enabled: boolean): Promise<{ key: string; enabled: boolean }> {
2146
+ return send(`/connectors/odoo/schema/${encodeURIComponent(key)}`, {
2147
+ method: "PATCH", body: JSON.stringify({ enabled }),
2148
+ });
2149
+ }
2150
+
2151
+ export type OperatorCapability = "tenant.read" | "tenant.configure" | "voice.read" | "voice.configure";
2152
+ export interface OperatorGrant { id: string; actor: string; tenant: string; capabilities: OperatorCapability[]; expiresAt: number; revokedAt: number }
2153
+ export interface OperatorAudit { id?: string; actor: string; tenant: string; capability: string; action: string; outcome: string; at?: number; createdAt?: number }
2154
+ export type OperatorSetupField = "displayName" | "timezone" | "voicePurpose" | "consentPolicy" | "queryEnabled" | "providerLabel";
2155
+ export interface OperatorSetup { tenant: string; setup: Partial<Record<OperatorSetupField, string | boolean>>; secretsPresent: false; rawProviderBindings: false }
2156
+ export interface OperatorVoiceSetup {
2157
+ tenant: string;
2158
+ voice: { schemaVersion: number; maxRecipientsCeiling: number; providers: Array<{
2159
+ key: string; label: string; capabilities: Record<string, string>;
2160
+ }> };
2161
+ secretsPresent: false; rawProviderBindings: false;
2162
+ }
2163
+ export interface SystemData { databases: Array<{ key: string; label?: string; fields: unknown[]; readOnly: true }>; readOnly: true; source: "Loopable" }
2164
+ export function createOperatorGrant(tenant: string, capabilities: OperatorCapability[]): Promise<{ grant: OperatorGrant; token: string }> {
2165
+ return send("/platform-admin/operator/grants", { method: "POST", body: JSON.stringify({ tenant, capabilities }) });
2166
+ }
2167
+ function operatorHeaders(token: string, body = false): HeadersInit {
2168
+ return { "X-Loopable-Operator-Grant": token, ...(body ? { "Content-Type": "application/json" } : {}) };
2169
+ }
2170
+ export function getOperatorAudit(abort?: AbortSignal): Promise<{ audit: OperatorAudit[] }> {
2171
+ return send("/platform-admin/operator/audit", { signal: abort });
2172
+ }
2173
+ export function getOperatorSetup(tenant: string, token: string, abort?: AbortSignal): Promise<OperatorSetup> {
2174
+ return send(`/platform-admin/operator/tenants/${encodeURIComponent(tenant)}/setup`, { headers: operatorHeaders(token), signal: abort });
2175
+ }
2176
+ export function getOperatorVoiceSetup(tenant: string, token: string, abort?: AbortSignal): Promise<OperatorVoiceSetup> {
2177
+ return send(`/platform-admin/operator/tenants/${encodeURIComponent(tenant)}/voice-setup`, { headers: operatorHeaders(token), signal: abort });
2178
+ }
2179
+ export function getSystemData(abort?: AbortSignal): Promise<SystemData> {
2180
+ return send("/admin/system-data", { signal: abort });
2181
+ }
web/src/automation/voiceAgentTypes.ts CHANGED
@@ -38,6 +38,19 @@ export interface VoiceAudience {
38
  export interface VoiceCapabilities {
39
  dryRun: boolean;
40
  numberProvisioning?: "contact_loopable";
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  }
42
 
43
  export interface VoiceAudienceOption {
@@ -70,6 +83,11 @@ export interface VoiceAgent {
70
  phoneBinding: VoicePhoneBinding | null;
71
  audience: VoiceAudience;
72
  capabilities: VoiceCapabilities;
 
 
 
 
 
73
  /** Server-composed choices; the browser never invents identifiers, policies, or limits. */
74
  audienceOptions: VoiceAudienceOptions;
75
  }
@@ -99,3 +117,20 @@ export interface VoiceHarnessResult {
99
  maskedBindingCount?: number;
100
  };
101
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  export interface VoiceCapabilities {
39
  dryRun: boolean;
40
  numberProvisioning?: "contact_loopable";
41
+ activation: boolean;
42
+ externalDispatch: boolean;
43
+ }
44
+
45
+ export interface VoiceProviderCapability {
46
+ inboundVoice: string; outboundVoice: string; whatsAppMessaging: string;
47
+ whatsAppCalling: string; governedQuery: string;
48
+ }
49
+ export interface VoiceProviderOption {
50
+ key: string; label: string; capabilities: VoiceProviderCapability;
51
+ }
52
+ export interface VoiceProviderConnection {
53
+ id: string; provider: string; label: string; status: string; lastProbeAt: number;
54
  }
55
 
56
  export interface VoiceAudienceOption {
 
83
  phoneBinding: VoicePhoneBinding | null;
84
  audience: VoiceAudience;
85
  capabilities: VoiceCapabilities;
86
+ providerKey: string;
87
+ providerConnection: VoiceProviderConnection | null;
88
+ providerOption: VoiceProviderOption | null;
89
+ directionPolicy: string[];
90
+ activationState: string;
91
  /** Server-composed choices; the browser never invents identifiers, policies, or limits. */
92
  audienceOptions: VoiceAudienceOptions;
93
  }
 
117
  maskedBindingCount?: number;
118
  };
119
  }
120
+
121
+ export interface WhatsAppFreshDryRunResult {
122
+ provider: string; channel: "whatsapp"; verifiedWebhook: boolean;
123
+ query: { state: string; clarification: boolean };
124
+ simulatedReply: { text: string; status: "simulated" };
125
+ noExternalDispatch: boolean; externalDispatches: number;
126
+ eventId: string; replayed?: false;
127
+ }
128
+ export interface WhatsAppReplayDryRunResult {
129
+ verifiedWebhook: true; replayed: true; deliveryState: "pending" | "completed" | "failed";
130
+ eventId: string; query: { state?: string; clarification?: boolean };
131
+ simulatedReply?: never; noExternalDispatch: boolean; externalDispatches: number;
132
+ }
133
+ export type WhatsAppDryRunResult = WhatsAppFreshDryRunResult | WhatsAppReplayDryRunResult;
134
+ export interface VoiceConsentResult { contactRef: string; voiceAgentId: string; state: "consented" | "withdrawn"; purpose: string; updatedAt: number }
135
+ export interface VoiceFeedbackSchedule { id: string; localTime: string; timezone: string; enabled: false; activationState: "disabled"; noExternalDispatch: boolean; externalDispatches: number }
136
+ export interface VoiceFeedbackDryRun { scheduleId: string; day: string; dueCount: number; state: "dry_run_complete"; noExternalDispatch: boolean; externalDispatches: number; activationState: "disabled" }
web/src/connectors/ConnectorsPage.tsx CHANGED
@@ -31,6 +31,15 @@ import { useEffect, useState } from "react";
31
  import { API_V1, CREDENTIALS } from "../apiContract";
32
  import { brandForConnector } from "./brandMarks";
33
  import OdooConfigPanel, { type OdooConfig } from "./OdooConfig";
 
 
 
 
 
 
 
 
 
34
 
35
  /** One row of the directory. Everything optional but `key` + `label` is genuinely optional on
36
  * the wire — a builtin has no provider, a planned connector has no `connectedAs`. */
@@ -434,6 +443,7 @@ function OdooManage({
434
  {open ? (
435
  <>
436
  {err ? <p className="conn-card-meta">{err}</p> : null}
 
437
  {cfg ? (
438
  <OdooConfigPanel
439
  cfg={cfg}
@@ -466,6 +476,58 @@ function OdooManage({
466
  );
467
  }
468
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
469
  /**
470
  * ⭐⭐ W31-T44 (owner item 6b) — THE BANNER THAT SAYS THE LIST IS SHORT, EXPORTED FOR THE SAME
471
  * REASON `ConnectorCard` IS.
 
31
  import { API_V1, CREDENTIALS } from "../apiContract";
32
  import { brandForConnector } from "./brandMarks";
33
  import OdooConfigPanel, { type OdooConfig } from "./OdooConfig";
34
+ import {
35
+ AutomationError,
36
+ getOdooSchema,
37
+ getOdooStatus,
38
+ setOdooFieldEnabled,
39
+ type OdooSchema,
40
+ type OdooStatus,
41
+ } from "../automation/automationApi";
42
+ import "../styles/wave45/agent-operator.css";
43
 
44
  /** One row of the directory. Everything optional but `key` + `label` is genuinely optional on
45
  * the wire — a builtin has no provider, a planned connector has no `connectedAs`. */
 
443
  {open ? (
444
  <>
445
  {err ? <p className="conn-card-meta">{err}</p> : null}
446
+ <OdooSyncStatus />
447
  {cfg ? (
448
  <OdooConfigPanel
449
  cfg={cfg}
 
476
  );
477
  }
478
 
479
+ export function OdooSyncStatus() {
480
+ const [status, setStatus] = useState<OdooStatus | null>(null);
481
+ const [schema, setSchema] = useState<OdooSchema | null>(null);
482
+ const [problem, setProblem] = useState("");
483
+ useEffect(() => {
484
+ const controller = new AbortController();
485
+ void Promise.all([getOdooStatus(controller.signal), getOdooSchema(controller.signal)])
486
+ .then(([nextStatus, nextSchema]) => { setStatus(nextStatus); setSchema(nextSchema); })
487
+ .catch((error) => {
488
+ if (controller.signal.aborted) return;
489
+ const prefix = error instanceof AutomationError && (error.status === 403 || error.status === 404)
490
+ ? "Odoo sync is unavailable for this account. " : "";
491
+ setProblem(prefix + (error instanceof Error ? error.message : "Connector status unavailable."));
492
+ });
493
+ return () => controller.abort();
494
+ }, []);
495
+ if (problem) return <section className="w45-contract-card"><h4>Sync</h4><p className="set-error">{problem}</p></section>;
496
+ if (!status || !schema) return <section className="w45-contract-card"><h4>Sync</h4><p>Loading connector status…</p></section>;
497
+ return (
498
+ <section className="w45-contract-card" aria-labelledby="odoo-sync-heading">
499
+ <h4 id="odoo-sync-heading">Sync</h4>
500
+ <dl className="voice-agent-details">
501
+ <div><dt>Schedule</dt><dd>{status.schedule || "Not scheduled"}</dd></div>
502
+ <div><dt>Health</dt><dd>{status.health}</dd></div>
503
+ <div><dt>Last run</dt><dd>{status.lastRun || "No run reported"}</dd></div>
504
+ <div><dt>Errors</dt><dd>{status.errors.length ? status.errors.map(String).join(", ") : "None reported"}</dd></div>
505
+ </dl>
506
+ <h4>Field catalog</h4>
507
+ <p>Fields are default off unless an administrator enables them. Field permissions still apply.</p>
508
+ <div className="w45-chip-row">
509
+ {schema.fields.map((field) => (
510
+ <label className={`w45-chip ${field.enabled ? "is-on" : "is-off"}`} key={field.key}>
511
+ <input
512
+ type="checkbox"
513
+ checked={field.enabled}
514
+ onChange={async (event) => {
515
+ const enabled = event.currentTarget.checked;
516
+ try {
517
+ await setOdooFieldEnabled(field.key, enabled);
518
+ setSchema((current) => current ? { ...current, fields: current.fields.map((candidate) =>
519
+ candidate.key === field.key ? { ...candidate, enabled } : candidate) } : current);
520
+ } catch (error) { setProblem(error instanceof Error ? error.message : "Field setting unavailable."); }
521
+ }}
522
+ />
523
+ {field.label}{field.defaultEnabled === false ? " (default off)" : ""}
524
+ </label>
525
+ ))}
526
+ </div>
527
+ </section>
528
+ );
529
+ }
530
+
531
  /**
532
  * ⭐⭐ W31-T44 (owner item 6b) — THE BANNER THAT SAYS THE LIST IS SHORT, EXPORTED FOR THE SAME
533
  * REASON `ConnectorCard` IS.
web/src/customer-grid/ColumnMenu.tsx CHANGED
@@ -40,11 +40,9 @@ import { FilterBuilderPanel, WindowPicker } from "../filter-kit";
40
  // producer of a sentence, and `descriptionEditedOf` is C8's strict reader (absent is not false).
41
  import {
42
  DESCRIPTION_RESET_LABEL,
43
- deleteImpactTitle,
44
  deleteRefusalReason,
45
  descriptionResetOffered,
46
  fieldClassOf,
47
- fieldUsageOf,
48
  mayRemoveField,
49
  mayDeleteField as mayDeleteFieldRight,
50
  PRESET_DESCRIPTION_ONLY_HINT,
@@ -56,7 +54,7 @@ import { AGG_LABELS, aggOptions } from "./aggregations";
56
  import { validateFormula } from "./formulaEngine";
57
  import { BRAND_SWATCHES, defaultOptionColor, nearestSwatch, normalizeOptionColor,
58
  OPTION_PALETTE } from "./choiceColors";
59
- import { FieldProperties, fieldDeletionLocked } from "./FieldProperties";
60
 
61
  export interface ColumnMenuState {
62
  fieldKey: string;
@@ -1039,6 +1037,7 @@ function TypePicker({
1039
  only?: readonly FieldType[];
1040
  }) {
1041
  const [q, setQ] = useState("");
 
1042
  const needle = q.trim().toLowerCase();
1043
  const offerable = only
1044
  ? FIELD_TYPES.filter((r) => (only as readonly string[]).includes(r.value))
@@ -1107,29 +1106,42 @@ function TypePicker({
1107
  </div>
1108
  )}
1109
  {group.rows.map((r) => (
1110
- <button
1111
  key={r.value}
1112
- type="button"
1113
  role="option"
1114
  aria-selected={value === r.value}
1115
- className={"cg-type-row" + (value === r.value ? " is-on" : "")}
1116
- onClick={() => onPick(r.value)}
1117
  >
1118
- {/* Each row wears the mark its COLUMN will wear. A measure column's real type is
1119
- currency/int/pct and a geocode column's is `text`, so both pseudo-kinds borrow
1120
- rather than inventing a glyph no column ever shows (the iconShapes ruling). */}
1121
- <FieldTypeIcon
1122
- type={
1123
- r.value === "measure" ? "currency" : r.value === "geocode" ? "text"
1124
- : r.value === "count" || r.value === "lookup" ? "rollup" : r.value
1125
- }
1126
- size={16}
1127
- />
1128
- <span className="cg-type-label" style={{ whiteSpace: "normal" }}>
1129
- <span>{r.label}</span>
1130
- <span className="cg-field-hint">{TYPE_DESCRIPTIONS[r.value]}</span>
1131
- </span>
1132
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1133
  ))}
1134
  </Fragment>
1135
  ))}
@@ -2506,7 +2518,6 @@ export default function ColumnMenu({
2506
  const [position, setPosition] = useState<CreatePosition | null>(initialPosition ?? null);
2507
  /** Delete is DESTRUCTIVE (a custom field's stored values go with it) — first click arms,
2508
  * second click fires. Reopening the menu disarms (state is per-mount, keyed by field). */
2509
- const [confirmDelete, setConfirmDelete] = useState(false);
2510
  const [label, setLabel] = useState("");
2511
  /** Whether the user has typed their own name — an auto-suggested measure label must never
2512
  * overwrite one, but should keep tracking the measure/window until they do. */
@@ -4546,7 +4557,6 @@ export default function ColumnMenu({
4546
  const c1AllowsDelete =
4547
  !deletionLocked && !presetRefusal && !canRemoveFromMine &&
4548
  (!rightsKnown || mayDeleteFieldRight(fieldC1, viewer));
4549
- const deleteImpact = deleteImpactTitle(fieldC1, fieldUsageOf(field));
4550
 
4551
  return (
4552
  <AnchoredOverlay
@@ -4559,8 +4569,6 @@ export default function ColumnMenu({
4559
  dataKind="column-menu"
4560
  >
4561
  <PaneHead title={field.label} sub={typeLine} onClose={onClose} />
4562
- <FieldProperties field={field} />
4563
-
4564
  {/* Item 8c �� any measure-carrying column exposes its PERIOD, the property that defines
4565
  it. Item 21 (2026-08-02) moved the EDITOR into the Edit-field pane; what stays here
4566
  is one line that STATES the period and opens that pane, because the window is the
@@ -4931,9 +4939,7 @@ export default function ColumnMenu({
4931
  * audience CATEGORY plus counts, closing on "counted rather than named". A tally
4932
  * that reads as exhaustive beside a delete button is worse than no tally.
4933
  */
4934
- confirmDelete && deleteImpact
4935
- ? deleteImpact
4936
- : field.measure
4937
  ? "Removes this formula column from the workspace."
4938
  : field.automation?.preset === true
4939
  ? "Part of this database's built-in schema. It will be re-created on the " +
@@ -4945,14 +4951,11 @@ export default function ColumnMenu({
4945
  }
4946
  /* R6(c) for a reader who cannot hover: `title` is not an accessible name, so the
4947
  armed impact is given one. Unarmed, the visible label is the name it always was. */
4948
- aria-label={
4949
- confirmDelete && deleteImpact ? `Delete permanently? ${deleteImpact}` : undefined
4950
- }
4951
- onClick={() => (confirmDelete ? onDelete() : setConfirmDelete(true))}
4952
  >
4953
  <MenuLabel
4954
  icon="trash"
4955
- text={confirmDelete ? "Delete permanently?" : "Delete field"}
4956
  />
4957
  </button>
4958
  )}
 
40
  // producer of a sentence, and `descriptionEditedOf` is C8's strict reader (absent is not false).
41
  import {
42
  DESCRIPTION_RESET_LABEL,
 
43
  deleteRefusalReason,
44
  descriptionResetOffered,
45
  fieldClassOf,
 
46
  mayRemoveField,
47
  mayDeleteField as mayDeleteFieldRight,
48
  PRESET_DESCRIPTION_ONLY_HINT,
 
54
  import { validateFormula } from "./formulaEngine";
55
  import { BRAND_SWATCHES, defaultOptionColor, nearestSwatch, normalizeOptionColor,
56
  OPTION_PALETTE } from "./choiceColors";
57
+ import { fieldDeletionLocked } from "./FieldProperties";
58
 
59
  export interface ColumnMenuState {
60
  fieldKey: string;
 
1037
  only?: readonly FieldType[];
1038
  }) {
1039
  const [q, setQ] = useState("");
1040
+ const [describedKind, setDescribedKind] = useState<PickerKind | null>(null);
1041
  const needle = q.trim().toLowerCase();
1042
  const offerable = only
1043
  ? FIELD_TYPES.filter((r) => (only as readonly string[]).includes(r.value))
 
1106
  </div>
1107
  )}
1108
  {group.rows.map((r) => (
1109
+ <div
1110
  key={r.value}
 
1111
  role="option"
1112
  aria-selected={value === r.value}
1113
+ className="cg-type-option"
 
1114
  >
1115
+ <button
1116
+ type="button"
1117
+ className={"cg-type-row" + (value === r.value ? " is-on" : "")}
1118
+ onClick={() => onPick(r.value)}
1119
+ >
1120
+ <FieldTypeIcon
1121
+ type={
1122
+ r.value === "measure" ? "currency" : r.value === "geocode" ? "text"
1123
+ : r.value === "count" || r.value === "lookup" ? "rollup" : r.value
1124
+ }
1125
+ size={16}
1126
+ />
1127
+ <span className="cg-type-label">{r.label}</span>
1128
+ </button>
1129
+ <button
1130
+ type="button"
1131
+ className="cg-type-info"
1132
+ aria-label={`About ${r.label}`}
1133
+ aria-expanded={describedKind === r.value}
1134
+ title={TYPE_DESCRIPTIONS[r.value]}
1135
+ onClick={() => setDescribedKind((current) => current === r.value ? null : r.value)}
1136
+ >
1137
+ (i)
1138
+ </button>
1139
+ {describedKind === r.value && (
1140
+ <div className="cg-type-description" role="status">
1141
+ {TYPE_DESCRIPTIONS[r.value]}
1142
+ </div>
1143
+ )}
1144
+ </div>
1145
  ))}
1146
  </Fragment>
1147
  ))}
 
2518
  const [position, setPosition] = useState<CreatePosition | null>(initialPosition ?? null);
2519
  /** Delete is DESTRUCTIVE (a custom field's stored values go with it) — first click arms,
2520
  * second click fires. Reopening the menu disarms (state is per-mount, keyed by field). */
 
2521
  const [label, setLabel] = useState("");
2522
  /** Whether the user has typed their own name — an auto-suggested measure label must never
2523
  * overwrite one, but should keep tracking the measure/window until they do. */
 
4557
  const c1AllowsDelete =
4558
  !deletionLocked && !presetRefusal && !canRemoveFromMine &&
4559
  (!rightsKnown || mayDeleteFieldRight(fieldC1, viewer));
 
4560
 
4561
  return (
4562
  <AnchoredOverlay
 
4569
  dataKind="column-menu"
4570
  >
4571
  <PaneHead title={field.label} sub={typeLine} onClose={onClose} />
 
 
4572
  {/* Item 8c �� any measure-carrying column exposes its PERIOD, the property that defines
4573
  it. Item 21 (2026-08-02) moved the EDITOR into the Edit-field pane; what stays here
4574
  is one line that STATES the period and opens that pane, because the window is the
 
4939
  * audience CATEGORY plus counts, closing on "counted rather than named". A tally
4940
  * that reads as exhaustive beside a delete button is worse than no tally.
4941
  */
4942
+ field.measure
 
 
4943
  ? "Removes this formula column from the workspace."
4944
  : field.automation?.preset === true
4945
  ? "Part of this database's built-in schema. It will be re-created on the " +
 
4951
  }
4952
  /* R6(c) for a reader who cannot hover: `title` is not an accessible name, so the
4953
  armed impact is given one. Unarmed, the visible label is the name it always was. */
4954
+ onClick={onDelete}
 
 
 
4955
  >
4956
  <MenuLabel
4957
  icon="trash"
4958
+ text="Delete field"
4959
  />
4960
  </button>
4961
  )}
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -80,6 +80,7 @@ import { useGetCellContent } from "./useGetCellContent";
80
  import { useGridSelection } from "./useGridSelection";
81
  import Toolbar from "./Toolbar";
82
  import { DatePicker } from "./DatePicker";
 
83
  import JsonViewer from "./JsonViewer";
84
  import RecordDetail from "./RecordDetail";
85
  import ViewSidebar from "./ViewSidebar";
@@ -107,9 +108,10 @@ import { describe, directed, popRedo, popUndo, pushUndo, stackFor } from "./undo
107
  import type { CellChange, UndoBook, UndoEntry, UndoRow, UndoValue } from "./undoStack";
108
  import { buildXlsxWorkbook, exportFilename, groupingApplies, runExport, toExportGroups, triggerDownload } from "./export";
109
  import type { ExportFormat, ExportGrouping } from "./export";
110
- import { dataPathHash } from "./dataPath";
111
  import type { DataDatabase, DataDatabaseFolder, DataPath } from "./dataPath";
112
  import "../styles/wave44/data-workspace.css";
 
113
  // owner item 3 (2026-08-03) — a time-series view exports its SHEET, not the rows under it.
114
  import { buildTsCsv, tsSheetToTable } from "./timeSeriesData";
115
  import type { TsSheet } from "./timeSeriesData";
@@ -1553,9 +1555,63 @@ function CustomerGridSurface({
1553
  * view; taking `config` as a dependency would re-run that whole pass on every drag and
1554
  * keystroke instead of only when the host payload moved. */
1555
  const configRef = useRef(config);
1556
- configRef.current = config;
1557
  const [workspaceReady, setWorkspaceReady] = useState(false);
1558
  const [saveState, setSaveState] = useState<"saved" | "saving">("saved");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1559
  const [search, setSearch] = useState("");
1560
  const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
1561
  const [hoverRow, setHoverRow] = useState<number | undefined>(undefined);
@@ -1582,6 +1638,7 @@ function CustomerGridSurface({
1582
  >(null);
1583
  const [detailPid, setDetailPid] = useState<number | null>(null);
1584
  const [columnMenu, setColumnMenu] = useState<ColumnMenuState | null>(null);
 
1585
  const [viewActionsAnchor, setViewActionsAnchor] = useState<HTMLElement | null>(null);
1586
  /** Open choice list for a `select` / `user` cell — see onCellClicked. */
1587
  const [picker, setPicker] = useState<{
@@ -2511,6 +2568,17 @@ function CustomerGridSurface({
2511
  const displaySpec = cleanDisplay(config.display);
2512
  const displayMode: DisplayMode = serverWindowed ? "grid" : displaySpec?.mode ?? "grid";
2513
  const [routePanelOpen, setRoutePanelOpen] = useState(false);
 
 
 
 
 
 
 
 
 
 
 
2514
  useEffect(() => {
2515
  if (displayMode !== "map") setRoutePanelOpen(false);
2516
  }, [displayMode]);
@@ -3339,6 +3407,131 @@ function CustomerGridSurface({
3339
  // value that actually changed since the last render is an external selection to apply.
3340
  const embeddedSelectedKey = [...embeddedSelectedIds].sort((a, b) => a - b).join(",");
3341
  const selectedPidKey = [...selectedPids].sort((a, b) => a - b).join(",");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3342
  const embeddedPropKeyRef = useRef(embeddedSelectedKey);
3343
  useEffect(() => {
3344
  if (!embeddedSelectable) {
@@ -5112,7 +5305,11 @@ function CustomerGridSurface({
5112
  // A Data path is the shell's shareable location, not a second routing model. Keep it
5113
  // canonical when a person switches views, while ordinary grid mounts remain hash-neutral.
5114
  if (dataPath && typeof window !== "undefined") {
5115
- const nextHash = dataPathHash({ ...dataPath, view: id });
 
 
 
 
5116
  if (window.location.hash !== nextHash) window.location.hash = nextHash;
5117
  }
5118
  // Owner item 3 (2026-07-31): tell the host WHERE THE USER IS, so a fresh browser (no
@@ -5127,11 +5324,21 @@ function CustomerGridSurface({
5127
  );
5128
 
5129
  useEffect(() => {
5130
- const viewId = dataPath?.view;
5131
- if (!viewId || viewId === activeViewId) return;
 
 
 
 
 
 
 
 
 
 
5132
  if (!views.some((view) => view.id === viewId)) return;
5133
  selectView(viewId);
5134
- }, [dataPath?.view, activeViewId, views, selectView]);
5135
 
5136
  /**
5137
  * A-S4-3 (item 25) — a notification's click-through. The SHELL routes to the table and fires
@@ -5141,17 +5348,32 @@ function CustomerGridSurface({
5141
  * (deleted, or a share revoked), and a reader who can no longer see it must simply land on the
5142
  * table. `selectView` already returns early on an unknown id; the topic check stops one grid
5143
  * reacting to another's alert when both are mounted.
5144
- */
 
 
 
 
 
 
 
 
5145
  useEffect(() => {
5146
  const onOpen = (e: Event) => {
5147
  const detail = (e as CustomEvent<ViewOpenDetail>).detail;
5148
  if (!detail || detail.topic !== scope) return;
5149
- if (!views.some((v) => v.id === detail.viewId)) return;
 
5150
  selectView(detail.viewId);
5151
  };
5152
  window.addEventListener(VIEW_OPEN_EVENT, onOpen);
5153
  return () => window.removeEventListener(VIEW_OPEN_EVENT, onOpen);
5154
  }, [scope, views, selectView]);
 
 
 
 
 
 
5155
 
5156
  const addressedFieldRef = useRef<string | null>(null);
5157
  useEffect(() => {
@@ -5733,8 +5955,27 @@ function CustomerGridSurface({
5733
  * round trip landed — seconds, on a cold container, with the user clicking
5734
  * again. The gate passed because it called reconcileFolders with two DIFFERENT
5735
  * arrays; it now also calls it the way this component does.
5736
- */
5737
  const [localFolders, setLocalFolders] = useState<GridFolder[]>([]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5738
  const workspaceFolders = payload?.workspace?.folders;
5739
  const folders = useMemo(
5740
  () => reconcileFolders(workspaceFolders, localFolders, folderStamps, Date.now()),
@@ -6142,7 +6383,12 @@ function CustomerGridSurface({
6142
  return;
6143
  }
6144
  if (!Array.isArray(payload?.exports)) throw new Error("missing evaluated Views");
6145
- const received = new Map<string, { name: string; fields: Field[]; rows: Row[] }>();
 
 
 
 
 
6146
  for (const item of payload.exports) {
6147
  if (!item || typeof item !== "object") throw new Error("invalid evaluated View");
6148
  const candidate = item as {
@@ -6156,10 +6402,36 @@ function CustomerGridSurface({
6156
  !Array.isArray(candidate.columns) || !Array.isArray(candidate.rows) ||
6157
  !candidate.view || typeof candidate.view !== "object" || received.has(candidate.viewId))
6158
  throw new Error("invalid evaluated View");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6159
  received.set(candidate.viewId, {
6160
  name: candidate.name,
6161
- fields: candidate.columns as Field[],
6162
- rows: candidate.rows as Row[],
 
6163
  });
6164
  }
6165
  if (received.size !== ids.length || ids.some((id) => !received.has(id)))
@@ -6179,7 +6451,7 @@ function CustomerGridSurface({
6179
  signal(TOAST_EVENT, "Selected Views could not be exported.");
6180
  }
6181
  },
6182
- [views, scope, embedded, isQueryPreview]
6183
  );
6184
 
6185
  /**
@@ -7540,14 +7812,8 @@ function CustomerGridSurface({
7540
  : null;
7541
 
7542
  /* ══════════════════════════════════════════════════════════════════════════════════════════
7543
- ⭐⭐ W41-T42 — THE RELATIONAL PIVOT'S HOOKS, AND THEY SIT HERE FOR ONE REASON.
7544
-
7545
- ⛔ EVERYTHING BELOW THE `if (loading || !workspaceReady)` RETURN ON THE NEXT LINE IS AFTER AN
7546
- EARLY RETURN, so a hook called down there is a CONDITIONAL hook and a latent React #310
7547
- crash. `verify_hooks` caught exactly that on the first draft of this ticket, which is the
7548
- whole reason the rule is a gate [[react-hooks-order-gate]]. The pivot's rendering, its
7549
- handlers and its second control row are ORDINARY VALUES and stay beside the JSX that uses
7550
- them; only the four hooks moved up here.
7551
  ══════════════════════════════════════════════════════════════════════════════════════════ */
7552
  const secondary = config.secondaryView ?? null;
7553
  /** R9 — what this table can pivot to IS its link fields. One derivation, shared with T44. */
@@ -7642,18 +7908,9 @@ function CustomerGridSurface({
7642
  [topic.key, activeViewId]
7643
  );
7644
 
7645
- if (loading || !workspaceReady) {
7646
- /* wave17 GRID — item 3 / owner R6: one small bare rotating icon, NO WORDS. `aria-label`
7647
- is not a word on screen and stays: `.lp-spin` is an empty span, so without it the wait
7648
- is announced to a screen reader as nothing at all. (C-SPIN, SHELL defines the class.)
7649
- `--lg` because this is the case C-SPIN sizes it for — the whole surface is this mark and
7650
- nothing else, where the 14px version "reads as dust". */
7651
- return (
7652
- <div className="cg-loading">
7653
- <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" />
7654
- </div>
7655
- );
7656
- }
7657
 
7658
  const activeView = views.find((view) => view.id === activeViewId);
7659
  const routeSourceView: RouteSourceView | null = activeView
@@ -8188,34 +8445,15 @@ function CustomerGridSurface({
8188
  exportableViewIds={views.map((view) => view.id)}
8189
  folders={folders}
8190
  folderIdOf={folderIdOf}
8191
- /**
8192
- * ⭐⭐ W41-T35 — `parent` IS TAKEN AND PASSED ON, AND ITS ABSENCE HERE WAS INVISIBLE.
8193
- *
8194
- * ⛔ W41-T33 widened this callback's declaration to `(name, icon?, parent?)` and this
8195
- * lambda still read two arguments. A two-parameter function stays ASSIGNABLE to a
8196
- * three-parameter type in TypeScript, by design, so `tsc` and the production build
8197
- * were both green while "New folder inside" created a folder at the TOP LEVEL every
8198
- * time: the rail offered the door, the pane named the destination, and the third
8199
- * argument was dropped on the floor one call later. Nothing in the type system, and
8200
- * nothing in any gate, can see a parameter a lambda declines to declare
8201
- * [[two-lanes-one-contract-dead-feature]].
8202
- *
8203
- * ⚠ BOTH SIDES, and the local entry is the half that would go unnoticed: the emit is
8204
- * what persists, the local entry is what the user LOOKS at until the echo returns. A
8205
- * parent on the wire and no parent locally is the folder appearing at the root and
8206
- * then jumping under its parent a round trip later, which is the blip
8207
- * `reconcileFolders` exists to prevent, in its create costume.
8208
- */
8209
- onFolderCreate={(name, icon, parent) => {
8210
  const id = newFolderId();
8211
  // Bounded: reconcileFolders drops a local entry once the echo
8212
  // carries it or its create stamp ages out, so this only has to not
8213
  // grow without limit.
8214
- // C5 (I15): the icon rides the LOCAL entry too, or the folder the user just
8215
- // styled renders grey for one round trip and then changes colour under them.
8216
  setLocalFolders((prev) => [
8217
  ...prev.slice(-31),
8218
- { id, name, order: 9_999, icon, parent },
8219
  ]);
8220
  stampFolder((p) => ({ ...p, created: { ...p.created, [id]: Date.now() } }));
8221
  emitHostEvent({
@@ -8224,7 +8462,6 @@ function CustomerGridSurface({
8224
  surface: "views",
8225
  folderId: id,
8226
  name,
8227
- icon,
8228
  parent,
8229
  });
8230
  }}
@@ -8241,45 +8478,6 @@ function CustomerGridSurface({
8241
  name,
8242
  });
8243
  }}
8244
- /**
8245
- * ⭐⭐ WAVE 41 · T35 (owner instruction 11) — THE FOLDER'S MARK, CHANGED IN PLACE.
8246
- *
8247
- * ⛔⛔ THE NAME RIDES ALONG, AND WITHOUT IT NOTHING PERSISTS. `folder_rename` is the
8248
- * one event that carries an icon, and the host refuses one with no name at all
8249
- * (`core/grid_events.py`: `if not hit or not name: return None`). An icon-only emit
8250
- * would therefore be dropped SERVER-SIDE, silently: the rail would repaint, every
8251
- * gate would stay green, and the mark would revert on the next echo. Re-sending the
8252
- * current name is a no-op rename by construction, which is why this is safe rather
8253
- * than merely expedient.
8254
- * ⚠ AND IT BAILS RATHER THAN SENDING A BLANK. A folder the rail can no longer find
8255
- * is one another tab has deleted; emitting for it would post an event the host
8256
- * refuses on the next line down for the other reason.
8257
- *
8258
- * ⛔ `icon` IS ALWAYS PRESENT. The host reads a missing key as "leave the existing
8259
- * icon alone", so returning to the plain mark has to arrive as the DEFAULT PAIR —
8260
- * which the rail sends, because that is literally the swatch the user pressed. There
8261
- * is no clear-to-absent path here and none is needed: `FolderMark` draws
8262
- * `{folder, neutral}` and an absent icon identically.
8263
- */
8264
- onFolderIconChange={(folderId, icon) => {
8265
- const name = folders.find((f) => f.id === folderId)?.name;
8266
- if (!name) return;
8267
- // The rename stamp carries the icon too, or the folder the user just remarked
8268
- // keeps its old mark until the echo returns — the same one-round-trip lie the
8269
- // stamp already prevents for the NAME, on the other half of the same event.
8270
- stampFolder((p) => ({
8271
- ...p,
8272
- renamed: { ...p.renamed, [folderId]: { at: Date.now(), name, icon } },
8273
- }));
8274
- emitHostEvent({
8275
- id: eventId("foldicon"),
8276
- type: "folder_rename",
8277
- surface: "views",
8278
- folderId,
8279
- name,
8280
- icon,
8281
- });
8282
- }}
8283
  onFolderDelete={(folderId) => {
8284
  // The tombstone is stamped BEFORE the emit: between the click and the
8285
  // echo the payload still lists the folder, and rendering it again for
@@ -8444,6 +8642,7 @@ function CustomerGridSurface({
8444
  the rail. `.cg-shell` is a horizontal flex row, so this needs no positioning of its own.
8445
  ⚠ NOT on an embedded or Query surface: neither has a database of its own for the chat to
8446
  be about, which is the same condition the script projections already carry. */}
 
8447
  {!embedded && !queryBinding && (
8448
  chatOpen ? (
8449
  <div className="cg-chat-dock">
@@ -8466,7 +8665,14 @@ function CustomerGridSurface({
8466
  </div>
8467
  ) : null
8468
  )}
8469
- <main className="cg-main">
 
 
 
 
 
 
 
8470
  <Toolbar
8471
  manager={true}
8472
  nouns={topic.nouns}
@@ -8625,6 +8831,7 @@ function CustomerGridSurface({
8625
  not be wired yet: absent beats present-and-inert. A control row over a database whose
8626
  columns never arrived would offer Hide fields, Filter, Sort and Group on nothing. */}
8627
  {secondaryToolbar}
 
8628
  {displayMode === "map" && !pivotOn && (
8629
  <MapSettings
8630
  coordField={mapCoordField}
@@ -8635,7 +8842,10 @@ function CustomerGridSurface({
8635
  onPickSizeField={(key) => setDisplayField("sizeField", key)}
8636
  routeOpen={routePanelOpen}
8637
  selectedCount={selectedPids.size}
8638
- onToggleRoute={() => setRoutePanelOpen((open) => !open)}
 
 
 
8639
  />
8640
  )}
8641
  {/* ⭐⭐ WAVE 42 · W42-T19 (owner instruction 11) — CALENDAR'S SECOND ROW. The real
@@ -9702,6 +9912,8 @@ function CustomerGridSurface({
9702
  </button>
9703
  </div>
9704
  )}
 
 
9705
  </main>
9706
 
9707
  {menuField && columnMenu && (
@@ -9908,7 +10120,7 @@ function CustomerGridSurface({
9908
  onDelete={
9909
  menuField.custom && !menuField.shared && menuField.key !== lockedKey
9910
  ? () => {
9911
- deleteField(menuField.key);
9912
  setColumnMenu(null);
9913
  }
9914
  : /**
@@ -9932,7 +10144,7 @@ function CustomerGridSurface({
9932
  (menuField.type === "link" || menuField.type === "rollup" ||
9933
  menuField.type === "formula")
9934
  ? () => {
9935
- deleteDefinitionField(menuField.key);
9936
  setColumnMenu(null);
9937
  }
9938
  : /**
@@ -9950,7 +10162,7 @@ function CustomerGridSurface({
9950
  menuField.kind === "route_order" &&
9951
  menuField.key !== lockedKey
9952
  ? () => {
9953
- deleteRouteField(menuField.key);
9954
  setColumnMenu(null);
9955
  }
9956
  : undefined
@@ -10064,6 +10276,8 @@ function CustomerGridSurface({
10064
  locked identity column (only its position matters — the create form never shows it).
10065
  The action/pane handlers below are unreachable in this mode (create-only; Cancel
10066
  closes), supplied inert to satisfy the surface. */}
 
 
10067
  {plusMenu && fieldByKey.get(lockedKey) && (
10068
  <ColumnMenu
10069
  key="__add-at-end__"
@@ -10399,6 +10613,8 @@ function CustomerGridSurface({
10399
  <DatePicker
10400
  anchor={datePicker.anchor}
10401
  field={dateField}
 
 
10402
  value={dateValue}
10403
  today={today}
10404
  onChange={(value) => patchAndRecord(datePicker.pid, { [dateField.key]: value }, "a date")}
 
80
  import { useGridSelection } from "./useGridSelection";
81
  import Toolbar from "./Toolbar";
82
  import { DatePicker } from "./DatePicker";
83
+ import { FieldDeleteImpactDialog } from "../filter-kit/FieldsHidePanel";
84
  import JsonViewer from "./JsonViewer";
85
  import RecordDetail from "./RecordDetail";
86
  import ViewSidebar from "./ViewSidebar";
 
108
  import type { CellChange, UndoBook, UndoEntry, UndoRow, UndoValue } from "./undoStack";
109
  import { buildXlsxWorkbook, exportFilename, groupingApplies, runExport, toExportGroups, triggerDownload } from "./export";
110
  import type { ExportFormat, ExportGrouping } from "./export";
111
+ import { dataPathHash, readDataPath } from "./dataPath";
112
  import type { DataDatabase, DataDatabaseFolder, DataPath } from "./dataPath";
113
  import "../styles/wave44/data-workspace.css";
114
+ import "../styles/wave45/data-applications.css";
115
  // owner item 3 (2026-08-03) — a time-series view exports its SHEET, not the rows under it.
116
  import { buildTsCsv, tsSheetToTable } from "./timeSeriesData";
117
  import type { TsSheet } from "./timeSeriesData";
 
1555
  * view; taking `config` as a dependency would re-run that whole pass on every drag and
1556
  * keystroke instead of only when the host payload moved. */
1557
  const configRef = useRef(config);
 
1558
  const [workspaceReady, setWorkspaceReady] = useState(false);
1559
  const [saveState, setSaveState] = useState<"saved" | "saving">("saved");
1560
+ /**
1561
+ * W45-T14 / C5: the workspace component is deliberately not keyed by database because its
1562
+ * shell and View rail must survive a switch. That makes these state cells long-lived too, so
1563
+ * scope them explicitly. The render-time handoff prevents one committed frame in which the new
1564
+ * hash is paired with the previous database's View selection; returning to a warm database
1565
+ * restores its rail immediately while its guarded refresh runs in the background.
1566
+ */
1567
+ const workspaceScopeRef = useRef(scope);
1568
+ const scopedWorkspaceCache = useRef(new Map<string, {
1569
+ fields: Field[];
1570
+ views: SavedView[];
1571
+ activeViewId: string;
1572
+ config: ViewConfig;
1573
+ pendingRows: Row[];
1574
+ alerted: string[];
1575
+ }>());
1576
+ if (workspaceScopeRef.current !== scope) {
1577
+ const previousScope = workspaceScopeRef.current;
1578
+ if (workspaceReady) {
1579
+ scopedWorkspaceCache.current.set(previousScope, {
1580
+ fields,
1581
+ views,
1582
+ activeViewId,
1583
+ config,
1584
+ pendingRows,
1585
+ alerted,
1586
+ });
1587
+ }
1588
+ workspaceScopeRef.current = scope;
1589
+ const restored = scopedWorkspaceCache.current.get(scope);
1590
+ const nextFields = restored?.fields ?? [];
1591
+ const nextConfig = restored?.config ?? defaultViewConfig(nextFields);
1592
+ setFields(nextFields);
1593
+ setViews(restored?.views ?? []);
1594
+ setActiveViewId(restored?.activeViewId ?? ALL_VIEW_ID);
1595
+ setConfig(nextConfig);
1596
+ setPendingRows(restored?.pendingRows ?? []);
1597
+ setAlerted(restored?.alerted ?? []);
1598
+ setWorkspaceReady(restored !== undefined);
1599
+ setSaveState("saved");
1600
+ configRef.current = nextConfig;
1601
+ } else {
1602
+ configRef.current = config;
1603
+ }
1604
+ useEffect(() => {
1605
+ if (!workspaceReady || workspaceScopeRef.current !== scope) return;
1606
+ scopedWorkspaceCache.current.set(scope, {
1607
+ fields,
1608
+ views,
1609
+ activeViewId,
1610
+ config,
1611
+ pendingRows,
1612
+ alerted,
1613
+ });
1614
+ }, [scope, workspaceReady, fields, views, activeViewId, config, pendingRows, alerted]);
1615
  const [search, setSearch] = useState("");
1616
  const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
1617
  const [hoverRow, setHoverRow] = useState<number | undefined>(undefined);
 
1638
  >(null);
1639
  const [detailPid, setDetailPid] = useState<number | null>(null);
1640
  const [columnMenu, setColumnMenu] = useState<ColumnMenuState | null>(null);
1641
+ const [columnDelete, setColumnDelete] = useState<{ field: Field; confirm: () => void } | null>(null);
1642
  const [viewActionsAnchor, setViewActionsAnchor] = useState<HTMLElement | null>(null);
1643
  /** Open choice list for a `select` / `user` cell — see onCellClicked. */
1644
  const [picker, setPicker] = useState<{
 
2568
  const displaySpec = cleanDisplay(config.display);
2569
  const displayMode: DisplayMode = serverWindowed ? "grid" : displaySpec?.mode ?? "grid";
2570
  const [routePanelOpen, setRoutePanelOpen] = useState(false);
2571
+ useEffect(() => {
2572
+ const openRoute = (event: Event) => {
2573
+ const detail = (event as CustomEvent<{ routeId?: string; forwarded?: boolean }>).detail;
2574
+ if (!detail?.routeId || detail.forwarded) return;
2575
+ setRoutePanelOpen(true);
2576
+ setConfig((current) => ({ ...current, display: { ...(current.display ?? {}), mode: "map" } } as ViewConfig));
2577
+ window.setTimeout(() => signal("aios:route-open", { routeId: detail.routeId, forwarded: true }), 60);
2578
+ };
2579
+ window.addEventListener("aios:route-open", openRoute);
2580
+ return () => window.removeEventListener("aios:route-open", openRoute);
2581
+ }, []);
2582
  useEffect(() => {
2583
  if (displayMode !== "map") setRoutePanelOpen(false);
2584
  }, [displayMode]);
 
3407
  // value that actually changed since the last render is an external selection to apply.
3408
  const embeddedSelectedKey = [...embeddedSelectedIds].sort((a, b) => a - b).join(",");
3409
  const selectedPidKey = [...selectedPids].sort((a, b) => a - b).join(",");
3410
+ const [workspaceDrawer, setWorkspaceDrawer] = useState<"notes" | "history" | null>(null);
3411
+ type SavedApplication = { id: string; type: "chart" | "route" | "map" | "timeseries"; name: string; config?: Record<string, unknown>; starred?: boolean; semanticRoleBindings?: Record<string, string>; capabilities?: Record<string, boolean>; compatibleDatabases?: string[]; openTarget?: { database?: string } };
3412
+ const [applicationRailOpen, setApplicationRailOpen] = useState(false);
3413
+ const [applications, setApplications] = useState<SavedApplication[]>([]);
3414
+ const [applicationError, setApplicationError] = useState("");
3415
+ // Application permissions and compatibility use the canonical database key, never the grid's
3416
+ // transport scope (`customer`/`product`). Home and Starred publish this same key in their URL.
3417
+ const applicationDatabase = activeDatabaseKey ?? dataPath?.database ?? topic.key;
3418
+ const applicationKind = displayMode === "chart" ? "chart" : displayMode === "timeseries" ? "timeseries" : displayMode === "map" ? "map" : null;
3419
+ const applySavedApplication = useCallback((application: SavedApplication): boolean => {
3420
+ if (!application.id) return false;
3421
+ const stored = application.config ?? {};
3422
+ const storedDisplay = stored.display && typeof stored.display === "object"
3423
+ ? stored.display as Record<string, unknown>
3424
+ : stored;
3425
+ updateConfig({ ...config, display: {
3426
+ ...(config.display ?? { mode: displayMode }),
3427
+ ...storedDisplay,
3428
+ applicationId: application.id,
3429
+ } } as ViewConfig);
3430
+ return true;
3431
+ }, [config, displayMode, updateConfig]);
3432
+ const loadApplications = useCallback(async (signal?: AbortSignal) => {
3433
+ if (!applicationRailOpen) return;
3434
+ try {
3435
+ const response = await fetch(`${API_V1}/applications?database=${encodeURIComponent(applicationDatabase)}${applicationKind ? `&type=${applicationKind}` : ""}`, { credentials: CREDENTIALS, signal });
3436
+ const body = await response.json().catch(() => ({}));
3437
+ if (!response.ok) throw new Error(String(body?.detail?.message ?? body?.detail ?? "Could not load Applications"));
3438
+ if (!signal?.aborted) { setApplications(Array.isArray(body?.applications) ? body.applications : []); setApplicationError(""); }
3439
+ } catch (error) { if (!signal?.aborted) setApplicationError(error instanceof Error ? error.message : "Could not load Applications"); }
3440
+ }, [applicationDatabase, applicationKind, applicationRailOpen]);
3441
+ useEffect(() => {
3442
+ const controller = new AbortController();
3443
+ void loadApplications(controller.signal);
3444
+ return () => controller.abort();
3445
+ }, [loadApplications]);
3446
+
3447
+ const applicationOpenSeq = useRef(0);
3448
+ const appliedApplicationPath = useRef("");
3449
+ useEffect(() => {
3450
+ const requestedId = dataPath?.application;
3451
+ const requestedDatabase = dataPath?.database;
3452
+ const requestKey = requestedId && requestedDatabase
3453
+ ? `${requestedDatabase}::${requestedId}`
3454
+ : "";
3455
+ const mine = ++applicationOpenSeq.current;
3456
+ if (!requestKey) {
3457
+ appliedApplicationPath.current = "";
3458
+ return;
3459
+ }
3460
+ if (!workspaceReady || loading || requestedDatabase !== applicationDatabase ||
3461
+ appliedApplicationPath.current === requestKey) return;
3462
+ const controller = new AbortController();
3463
+ void fetch(`${API_V1}/applications?database=${encodeURIComponent(requestedDatabase)}`, {
3464
+ credentials: CREDENTIALS,
3465
+ signal: controller.signal,
3466
+ }).then(async (response) => response.ok ? response.json() : null).then((body) => {
3467
+ if (controller.signal.aborted || mine !== applicationOpenSeq.current) return;
3468
+ const livePath = readDataPath();
3469
+ if (livePath?.database !== requestedDatabase || livePath.application !== requestedId) return;
3470
+ const listed = Array.isArray(body?.applications) ? body.applications as SavedApplication[] : [];
3471
+ const application = listed.find((candidate) => candidate.id === requestedId);
3472
+ if (!application) return;
3473
+ const compatible = application.openTarget?.database === requestedDatabase ||
3474
+ application.compatibleDatabases?.includes(requestedDatabase) === true;
3475
+ if (!compatible || !applySavedApplication(application)) return;
3476
+ appliedApplicationPath.current = requestKey;
3477
+ signal("aios:application-open-ack", {
3478
+ applicationId: requestedId,
3479
+ database: requestedDatabase,
3480
+ });
3481
+ }).catch(() => undefined);
3482
+ return () => controller.abort();
3483
+ }, [applicationDatabase, applySavedApplication, dataPath?.application, dataPath?.database,
3484
+ loading, workspaceReady]);
3485
+
3486
+ useEffect(() => {
3487
+ // An explicit deep link is authoritative. A missing, revoked, or incompatible id must leave
3488
+ // the View untouched; it must never silently turn into that database's default Application.
3489
+ if (dataPath?.application || !applicationKind ||
3490
+ (config.display as (DisplaySpec & { applicationId?: string }) | undefined)?.applicationId) return;
3491
+ const controller = new AbortController();
3492
+ void fetch(`${API_V1}/applications/defaults/${encodeURIComponent(applicationDatabase)}/${applicationKind}`, { credentials: CREDENTIALS, signal: controller.signal })
3493
+ .then(async (response) => response.ok ? response.json() : null)
3494
+ .then((body) => {
3495
+ const application = body?.application;
3496
+ if (controller.signal.aborted || !application?.id || (body?.resolution !== "explicit" && body?.resolution !== "latest")) return;
3497
+ applySavedApplication(application as SavedApplication);
3498
+ }).catch(() => undefined);
3499
+ return () => controller.abort();
3500
+ }, [applicationDatabase, applicationKind, applySavedApplication, config.display, dataPath?.application]);
3501
+ const [drawerBusy, setDrawerBusy] = useState(false);
3502
+ const [drawerError, setDrawerError] = useState("");
3503
+ const [sharedNote, setSharedNote] = useState("");
3504
+ const [notesMode, setNotesMode] = useState<"database" | "view">("database");
3505
+ const [historyRows, setHistoryRows] = useState<Array<Record<string, unknown>>>([]);
3506
+ const [historyRetention, setHistoryRetention] = useState<30 | 90>(30);
3507
+ const historyPid = [...selectedPids][0];
3508
+ useEffect(() => {
3509
+ if (!workspaceDrawer) return;
3510
+ const controller = new AbortController();
3511
+ setDrawerBusy(true); setDrawerError("");
3512
+ const noteViewQuery = notesMode === "view" ? `&viewId=${encodeURIComponent(activeViewId)}` : "";
3513
+ const url = workspaceDrawer === "notes"
3514
+ ? `${API_V1}/grid/shared-note?scope=${encodeURIComponent(scope)}${noteViewQuery}`
3515
+ : `${API_V1}/tables/${encodeURIComponent(scope)}/history?rowId=${encodeURIComponent(String(historyPid ?? ""))}&retentionDays=${historyRetention}`;
3516
+ void fetch(url, { credentials: CREDENTIALS, signal: controller.signal }).then(async (response) => {
3517
+ const body = await response.json().catch(() => ({}));
3518
+ if (!response.ok) throw new Error(String(body?.detail?.message ?? body?.detail ?? "Could not load drawer"));
3519
+ if (workspaceDrawer === "notes") setSharedNote(String(body?.note?.body ?? body?.note ?? ""));
3520
+ else setHistoryRows(Array.isArray(body?.events) ? body.events : Array.isArray(body?.history) ? body.history : []);
3521
+ }).catch((error: unknown) => { if (!controller.signal.aborted) setDrawerError(error instanceof Error ? error.message : "Could not load drawer"); })
3522
+ .finally(() => { if (!controller.signal.aborted) setDrawerBusy(false); });
3523
+ return () => controller.abort();
3524
+ }, [activeViewId, historyPid, historyRetention, notesMode, scope, workspaceDrawer]);
3525
+ const saveSharedNote = useCallback(async () => {
3526
+ setDrawerBusy(true); setDrawerError("");
3527
+ try {
3528
+ const noteViewQuery = notesMode === "view" ? `&viewId=${encodeURIComponent(activeViewId)}` : "";
3529
+ const response = await fetch(`${API_V1}/grid/shared-note?scope=${encodeURIComponent(scope)}${noteViewQuery}`, { method: "PUT", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ body: sharedNote }) });
3530
+ const body = await response.json().catch(() => ({}));
3531
+ if (!response.ok) throw new Error(String(body?.detail?.message ?? body?.detail ?? "Could not save note"));
3532
+ } catch (error) { setDrawerError(error instanceof Error ? error.message : "Could not save note"); }
3533
+ finally { setDrawerBusy(false); }
3534
+ }, [activeViewId, notesMode, scope, sharedNote]);
3535
  const embeddedPropKeyRef = useRef(embeddedSelectedKey);
3536
  useEffect(() => {
3537
  if (!embeddedSelectable) {
 
5305
  // A Data path is the shell's shareable location, not a second routing model. Keep it
5306
  // canonical when a person switches views, while ordinary grid mounts remain hash-neutral.
5307
  if (dataPath && typeof window !== "undefined") {
5308
+ const nextPath: DataPath = { ...dataPath, view: id };
5309
+ // Default is the address with no View override. Besides keeping links compact, this makes
5310
+ // browser Back and a direct `?database=` address mean the same pinned system View.
5311
+ if (id === ALL_VIEW_ID) delete nextPath.view;
5312
+ const nextHash = dataPathHash(nextPath);
5313
  if (window.location.hash !== nextHash) window.location.hash = nextHash;
5314
  }
5315
  // Owner item 3 (2026-07-31): tell the host WHERE THE USER IS, so a fresh browser (no
 
5324
  );
5325
 
5326
  useEffect(() => {
5327
+ const viewId = dataPath ? dataPath.view ?? ALL_VIEW_ID : null;
5328
+ /**
5329
+ * W45-T14: setting `window.location.hash` is synchronous, but Shell publishes the matching
5330
+ * `dataPath` prop from its `hashchange` render. A local `setActiveViewId` renders this child in
5331
+ * between those two moments. Never replay that one-frame-old prop: acknowledge it only when
5332
+ * its database and View agree with the live location. This is the exact Default -> named ->
5333
+ * Default race: absence means Default, so the old truthy named id used to win the middle frame.
5334
+ */
5335
+ const liveDataPath = typeof window === "undefined" ? dataPath : readDataPath();
5336
+ if (dataPath && (liveDataPath?.database !== dataPath.database ||
5337
+ (liveDataPath.view ?? ALL_VIEW_ID) !== viewId)) return;
5338
+ if (viewId === null || viewId === activeViewId) return;
5339
  if (!views.some((view) => view.id === viewId)) return;
5340
  selectView(viewId);
5341
+ }, [dataPath, activeViewId, views, selectView]);
5342
 
5343
  /**
5344
  * A-S4-3 (item 25) — a notification's click-through. The SHELL routes to the table and fires
 
5348
  * (deleted, or a share revoked), and a reader who can no longer see it must simply land on the
5349
  * table. `selectView` already returns early on an unknown id; the topic check stops one grid
5350
  * reacting to another's alert when both are mounted.
5351
+ */
5352
+ const parkedViewOpenRef = useRef<ViewOpenDetail | null>(null);
5353
+ const parkedViewScopeRef = useRef(scope);
5354
+ if (parkedViewScopeRef.current !== scope) {
5355
+ // A late list for the database we just left must not replay when the user later returns.
5356
+ // A new click may park one new request below; this old request has been superseded by scope.
5357
+ parkedViewScopeRef.current = scope;
5358
+ parkedViewOpenRef.current = null;
5359
+ }
5360
  useEffect(() => {
5361
  const onOpen = (e: Event) => {
5362
  const detail = (e as CustomEvent<ViewOpenDetail>).detail;
5363
  if (!detail || detail.topic !== scope) return;
5364
+ if (!views.some((v) => v.id === detail.viewId)) { parkedViewOpenRef.current = detail; return; }
5365
+ parkedViewOpenRef.current = null;
5366
  selectView(detail.viewId);
5367
  };
5368
  window.addEventListener(VIEW_OPEN_EVENT, onOpen);
5369
  return () => window.removeEventListener(VIEW_OPEN_EVENT, onOpen);
5370
  }, [scope, views, selectView]);
5371
+ useEffect(() => {
5372
+ const parked = parkedViewOpenRef.current;
5373
+ if (!parked || parked.topic !== scope || !views.some((view) => view.id === parked.viewId)) return;
5374
+ parkedViewOpenRef.current = null;
5375
+ selectView(parked.viewId);
5376
+ }, [scope, selectView, views]);
5377
 
5378
  const addressedFieldRef = useRef<string | null>(null);
5379
  useEffect(() => {
 
5955
  * round trip landed — seconds, on a cold container, with the user clicking
5956
  * again. The gate passed because it called reconcileFolders with two DIFFERENT
5957
  * arrays; it now also calls it the way this component does.
5958
+ */
5959
  const [localFolders, setLocalFolders] = useState<GridFolder[]>([]);
5960
+ const folderScopeRef = useRef(scope);
5961
+ const scopedFolderCache = useRef(new Map<string, {
5962
+ stamps: FolderStamps;
5963
+ local: GridFolder[];
5964
+ }>());
5965
+ if (folderScopeRef.current !== scope) {
5966
+ scopedFolderCache.current.set(folderScopeRef.current, {
5967
+ stamps: folderStamps,
5968
+ local: localFolders,
5969
+ });
5970
+ folderScopeRef.current = scope;
5971
+ const restored = scopedFolderCache.current.get(scope);
5972
+ setFolderStamps(restored?.stamps ?? {});
5973
+ setLocalFolders(restored?.local ?? []);
5974
+ }
5975
+ useEffect(() => {
5976
+ if (folderScopeRef.current !== scope) return;
5977
+ scopedFolderCache.current.set(scope, { stamps: folderStamps, local: localFolders });
5978
+ }, [scope, folderStamps, localFolders]);
5979
  const workspaceFolders = payload?.workspace?.folders;
5980
  const folders = useMemo(
5981
  () => reconcileFolders(workspaceFolders, localFolders, folderStamps, Date.now()),
 
6383
  return;
6384
  }
6385
  if (!Array.isArray(payload?.exports)) throw new Error("missing evaluated Views");
6386
+ const received = new Map<string, {
6387
+ name: string;
6388
+ fields: Field[];
6389
+ rows: Row[];
6390
+ grouping?: ExportGrouping;
6391
+ }>();
6392
  for (const item of payload.exports) {
6393
  if (!item || typeof item !== "object") throw new Error("invalid evaluated View");
6394
  const candidate = item as {
 
6402
  !Array.isArray(candidate.columns) || !Array.isArray(candidate.rows) ||
6403
  !candidate.view || typeof candidate.view !== "object" || received.has(candidate.viewId))
6404
  throw new Error("invalid evaluated View");
6405
+ const exportedFields = candidate.columns as Field[];
6406
+ const exportedRows = candidate.rows as Row[];
6407
+ const localView = views.find((view) => view.id === candidate.viewId);
6408
+ const localConfig = localView ? normalizeConfig(localView.config, fields) : null;
6409
+ let grouping: ExportGrouping | undefined;
6410
+ if (localConfig?.groupBy) {
6411
+ const { visibleRows: bucketed } = runPipeline({
6412
+ rawRows: exportedRows,
6413
+ fields,
6414
+ filters: [],
6415
+ search: "",
6416
+ sorts: [],
6417
+ groupBy: localConfig.groupBy,
6418
+ collapsed: new Set<string>(),
6419
+ memberPids: [],
6420
+ filterConj: "and",
6421
+ measureSets,
6422
+ cohortSets,
6423
+ today,
6424
+ });
6425
+ grouping = {
6426
+ field: fieldByKey.get(localConfig.groupBy),
6427
+ blocks: toExportGroups(bucketed),
6428
+ };
6429
+ }
6430
  received.set(candidate.viewId, {
6431
  name: candidate.name,
6432
+ fields: exportedFields,
6433
+ rows: exportedRows,
6434
+ grouping,
6435
  });
6436
  }
6437
  if (received.size !== ids.length || ids.some((id) => !received.has(id)))
 
6451
  signal(TOAST_EVENT, "Selected Views could not be exported.");
6452
  }
6453
  },
6454
+ [views, scope, embedded, isQueryPreview, fields, fieldByKey, measureSets, cohortSets, today]
6455
  );
6456
 
6457
  /**
 
7812
  : null;
7813
 
7814
  /* ══════════════════════════════════════════════════════════════════════════════════════════
7815
+ W41 relational-pivot hooks remain unconditional. W45-T14 removed the surface-wide loading
7816
+ return so the View rail stays mounted, but hook ordering still belongs above rendering.
 
 
 
 
 
 
7817
  ══════════════════════════════════════════════════════════════════════════════════════════ */
7818
  const secondary = config.secondaryView ?? null;
7819
  /** R9 — what this table can pivot to IS its link fields. One derivation, shared with T44. */
 
7908
  [topic.key, activeViewId]
7909
  );
7910
 
7911
+ // W45-T14 keeps the outer workspace and View rail mounted. Only the keyed right pane enters
7912
+ // loading, so a database switch cannot replace either navigation DOM subtree.
7913
+ const workspaceLoading = loading || !workspaceReady;
 
 
 
 
 
 
 
 
 
7914
 
7915
  const activeView = views.find((view) => view.id === activeViewId);
7916
  const routeSourceView: RouteSourceView | null = activeView
 
8445
  exportableViewIds={views.map((view) => view.id)}
8446
  folders={folders}
8447
  folderIdOf={folderIdOf}
8448
+ /* The parent reaches both the optimistic row and the durable create event. */
8449
+ onFolderCreate={(name, parent) => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8450
  const id = newFolderId();
8451
  // Bounded: reconcileFolders drops a local entry once the echo
8452
  // carries it or its create stamp ages out, so this only has to not
8453
  // grow without limit.
 
 
8454
  setLocalFolders((prev) => [
8455
  ...prev.slice(-31),
8456
+ { id, name, order: 9_999, parent },
8457
  ]);
8458
  stampFolder((p) => ({ ...p, created: { ...p.created, [id]: Date.now() } }));
8459
  emitHostEvent({
 
8462
  surface: "views",
8463
  folderId: id,
8464
  name,
 
8465
  parent,
8466
  });
8467
  }}
 
8478
  name,
8479
  });
8480
  }}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8481
  onFolderDelete={(folderId) => {
8482
  // The tombstone is stamped BEFORE the emit: between the click and the
8483
  // echo the payload still lists the folder, and rendering it again for
 
8642
  the rail. `.cg-shell` is a horizontal flex row, so this needs no positioning of its own.
8643
  ⚠ NOT on an embedded or Query surface: neither has a database of its own for the chat to
8644
  be about, which is the same condition the script projections already carry. */}
8645
+ {applicationRailOpen && <aside className="cg-application-rail" aria-label="Applications"><header><strong>Applications</strong><button type="button" className="cg-icon-button" aria-label="Close Applications" onClick={() => setApplicationRailOpen(false)}>×</button></header><p className="cg-application-context">Reusable {applicationKind ?? "Chart, Route, Map, and Time Series"} assets for this database</p>{applicationError && <p role="alert">{applicationError}</p>}<div className="cg-application-list">{applications.map((application) => <article key={application.id} className="cg-application-card"><button type="button" className="cg-application-open" onClick={() => { const roles = Object.entries(application.semanticRoleBindings ?? {}); if (roles.length && !window.confirm(`Use ${application.name} with these semantic roles?\n${roles.map(([role, mappedField]) => `${role}: ${mappedField}`).join("\n")}`)) return; applySavedApplication(application); }}><span>{application.name}</span><small>{application.type}</small></button><div className="cg-application-actions">{application.capabilities?.star === true && <button type="button" className="cg-icon-button" aria-label={`${application.starred ? "Unstar" : "Star"} ${application.name}`} onClick={async () => { await fetch(`${API_V1}/applications/${encodeURIComponent(application.id)}`, { method: "PATCH", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ starred: !application.starred }) }); void loadApplications(); }}>{application.starred ? "★" : "☆"}</button>}<button type="button" className="cg-link-btn" onClick={async () => { await fetch(`${API_V1}/applications/defaults/${encodeURIComponent(applicationDatabase)}/${application.type}`, { method: "PUT", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ applicationId: application.id }) }); }}>Make default</button>{application.capabilities?.delete === true && <button type="button" className="cg-link-btn is-danger" onClick={async () => { if (!window.confirm(`Delete Application “${application.name}”? Views using it will keep their own saved configuration.`)) return; await fetch(`${API_V1}/applications/${encodeURIComponent(application.id)}`, { method: "DELETE", credentials: CREDENTIALS }); void loadApplications(); }}>Delete…</button>}</div></article>)}{!applicationError && applications.length === 0 && <p>No compatible saved Applications yet.</p>}</div></aside>}
8646
  {!embedded && !queryBinding && (
8647
  chatOpen ? (
8648
  <div className="cg-chat-dock">
 
8665
  </div>
8666
  ) : null
8667
  )}
8668
+ <main className="cg-main" key={scope}>
8669
+ {workspaceLoading ? (
8670
+ <div className="cg-loading">
8671
+ <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" />
8672
+ </div>
8673
+ ) : (
8674
+ <>
8675
+ <div className="cg-drawer-launchers" aria-label="Workspace details"><button type="button" className="cg-btn" aria-expanded={applicationRailOpen} onClick={() => setApplicationRailOpen((open) => { if (!open) signal(NAV_MINIMIZE_EVENT); return !open; })}>Applications</button><button type="button" className="cg-btn" aria-expanded={workspaceDrawer === "notes"} onClick={() => setWorkspaceDrawer((open) => open === "notes" ? null : "notes")}>Notes</button>{isUserTable && <button type="button" className="cg-btn" aria-expanded={workspaceDrawer === "history"} onClick={() => setWorkspaceDrawer((open) => open === "history" ? null : "history")}>History</button>}</div>
8676
  <Toolbar
8677
  manager={true}
8678
  nouns={topic.nouns}
 
8831
  not be wired yet: absent beats present-and-inert. A control row over a database whose
8832
  columns never arrived would offer Hide fields, Filter, Sort and Group on nothing. */}
8833
  {secondaryToolbar}
8834
+ {workspaceDrawer && <aside className="cg-workspace-drawer" aria-label={workspaceDrawer === "notes" ? "Notes" : "History"}><header><strong>{workspaceDrawer === "notes" ? "Notes" : "History"}</strong><button type="button" className="cg-icon-button" aria-label="Close drawer" onClick={() => setWorkspaceDrawer(null)}>×</button></header>{drawerBusy && <p role="status">Loading…</p>}{drawerError && <p role="alert">{drawerError}</p>}{workspaceDrawer === "notes" ? <><div className="cg-segmented" role="group" aria-label="Notes scope"><button type="button" aria-pressed={notesMode === "database"} onClick={() => setNotesMode("database")}>Database note</button><button type="button" aria-pressed={notesMode === "view"} onClick={() => setNotesMode("view")}>View note</button></div><textarea className="cg-input" aria-label={notesMode === "view" ? "Shared View note" : "Shared Database note"} value={sharedNote} onChange={(event) => setSharedNote(event.target.value)} /><button type="button" className="cg-btn" disabled={drawerBusy} onClick={() => void saveSharedNote()}>Save note</button></> : <><label>Retention<select className="cg-select" value={historyRetention} onChange={(event) => setHistoryRetention(Number(event.target.value) as 30 | 90)}><option value={30}>30 days</option><option value={90}>90 days · platform admin</option></select></label>{historyPid == null ? <p>Select one record to inspect its history.</p> : historyRows.length === 0 && !drawerBusy ? <p>No retained changes.</p> : <ol className="cg-history-list">{historyRows.map((event, index) => <li key={String(event.id ?? index)}><strong>{String(event.field ?? event.fieldKey ?? "Record")}</strong><span>{String(event.updatedAt ?? event.at ?? "")}</span><button type="button" className="cg-link-btn" onClick={async () => { if (!window.confirm("Restore this recorded value? This writes a new auditable change and does not erase history.")) return; const id = String(event.id ?? ""); const response = await fetch(`${API_V1}/tables/${encodeURIComponent(scope)}/history/${encodeURIComponent(id)}/restore`, { method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ rowId: historyPid, field: event.field ?? event.fieldKey, retentionDays: historyRetention }) }); if (!response.ok) setDrawerError("Restore was refused. Your current value was not changed."); else setWorkspaceDrawer(null); }}>Restore…</button></li>)}</ol>}</>}</aside>}
8835
  {displayMode === "map" && !pivotOn && (
8836
  <MapSettings
8837
  coordField={mapCoordField}
 
8842
  onPickSizeField={(key) => setDisplayField("sizeField", key)}
8843
  routeOpen={routePanelOpen}
8844
  selectedCount={selectedPids.size}
8845
+ onToggleRoute={() => setRoutePanelOpen((open) => {
8846
+ if (!open) signal(NAV_MINIMIZE_EVENT);
8847
+ return !open;
8848
+ })}
8849
  />
8850
  )}
8851
  {/* ⭐⭐ WAVE 42 · W42-T19 (owner instruction 11) — CALENDAR'S SECOND ROW. The real
 
9912
  </button>
9913
  </div>
9914
  )}
9915
+ </>
9916
+ )}
9917
  </main>
9918
 
9919
  {menuField && columnMenu && (
 
10120
  onDelete={
10121
  menuField.custom && !menuField.shared && menuField.key !== lockedKey
10122
  ? () => {
10123
+ setColumnDelete({ field: menuField, confirm: () => deleteField(menuField.key) });
10124
  setColumnMenu(null);
10125
  }
10126
  : /**
 
10144
  (menuField.type === "link" || menuField.type === "rollup" ||
10145
  menuField.type === "formula")
10146
  ? () => {
10147
+ setColumnDelete({ field: menuField, confirm: () => deleteDefinitionField(menuField.key) });
10148
  setColumnMenu(null);
10149
  }
10150
  : /**
 
10162
  menuField.kind === "route_order" &&
10163
  menuField.key !== lockedKey
10164
  ? () => {
10165
+ setColumnDelete({ field: menuField, confirm: () => deleteRouteField(menuField.key) });
10166
  setColumnMenu(null);
10167
  }
10168
  : undefined
 
10276
  locked identity column (only its position matters — the create form never shows it).
10277
  The action/pane handlers below are unreachable in this mode (create-only; Cancel
10278
  closes), supplied inert to satisfy the surface. */}
10279
+ {columnDelete && <FieldDeleteImpactDialog field={columnDelete.field} onCancel={() => setColumnDelete(null)} onConfirm={() => { columnDelete.confirm(); setColumnDelete(null); }} />}
10280
+
10281
  {plusMenu && fieldByKey.get(lockedKey) && (
10282
  <ColumnMenu
10283
  key="__add-at-end__"
 
10613
  <DatePicker
10614
  anchor={datePicker.anchor}
10615
  field={dateField}
10616
+ fields={fields}
10617
+ scopeKey={scope}
10618
  value={dateValue}
10619
  today={today}
10620
  onChange={(value) => patchAndRecord(datePicker.pid, { [dateField.key]: value }, "a date")}
web/src/customer-grid/DatePicker.tsx CHANGED
@@ -31,8 +31,19 @@ function newRule(kind: RuleKind, selected: Date): DateRecurrenceRule {
31
  }
32
  function labelForKind(kind: RuleKind): string { return ({ daily: "Every N days", weekly: "Every N weeks", monthly: "Day of every N months", monthly_ordinal: "Ordinal weekday of every N months", yearly: "Every N years", holiday: "Public holiday" } as Record<RuleKind, string>)[kind]; }
33
 
34
- export function DatePicker({ anchor, field, value, today, onChange, onRecurrence, onClose }: {
35
- anchor: AnchorRect; field: Field; value: unknown; today?: string; onChange: (value: string) => void;
 
 
 
 
 
 
 
 
 
 
 
36
  onRecurrence: (recurrence: DateRecurrence | null) => void; onClose: () => void;
37
  }) {
38
  const selected = parseIso(value) ?? parseIso(today) ?? new Date();
@@ -44,7 +55,24 @@ export function DatePicker({ anchor, field, value, today, onChange, onRecurrence
44
  const [nextDate, setNextDate] = useState<string | null | undefined>(() => field.recurrence?.nextDate);
45
  const [calendars, setCalendars] = useState<CalendarOption[]>(DEFAULT_CALENDARS);
46
  const [previewError, setPreviewError] = useState("");
47
- const recurrence = useMemo<DateRecurrence | null>(() => rules.length ? ({ startDate: selectedIso, rules, previewCount: bounded(previewCount, 1, 50, 10) }) : null, [previewCount, rules, selectedIso]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  // Server-evaluated preview: the exact payload saved below is sent here, so edited previews
50
  // cannot differ from the default next date after refresh because of timezone/holiday drift.
@@ -52,7 +80,7 @@ export function DatePicker({ anchor, field, value, today, onChange, onRecurrence
52
  if (!recurrence) { setPreview([]); setNextDate(undefined); setPreviewError(""); return; }
53
  const controller = new AbortController();
54
  void fetch(`${API_V1}/grid/recurrence-preview`, { method: "POST", credentials: CREDENTIALS, signal: controller.signal,
55
- headers: { "Content-Type": "application/json" }, body: JSON.stringify({ recurrence })
56
  }).then(async (response) => {
57
  const data = await response.json().catch(() => ({}));
58
  if (!response.ok) throw new Error(String(data?.detail?.message ?? "Could not preview recurrence"));
@@ -80,6 +108,7 @@ export function DatePicker({ anchor, field, value, today, onChange, onRecurrence
80
  const cells = Array.from({ length: Math.ceil((leading + days) / 7) * 7 }, (_, index) => index - leading + 1);
81
 
82
  return <AnchoredOverlay anchor={anchor} className="cg-date-picker" placement="bottom-start" onDismiss={onClose} role="dialog" ariaLabel={`Choose a date for ${field.label}`} dataKind="date-picker">
 
83
  <div className="cg-date-picker-head"><button type="button" className="cg-icon-button" aria-label="Previous month" onClick={() => setCursor(addMonths(cursor, -1))}>‹</button><strong>{MONTHS[cursor.getUTCMonth()]} {cursor.getUTCFullYear()}</strong><button type="button" className="cg-icon-button" aria-label="Next month" onClick={() => setCursor(addMonths(cursor, 1))}>›</button></div>
84
  <div className="cg-date-weekdays">{WEEKDAYS.map((day) => <span key={day}>{day}</span>)}</div>
85
  <div className="cg-date-grid">{cells.map((day, index) => {
@@ -88,6 +117,18 @@ export function DatePicker({ anchor, field, value, today, onChange, onRecurrence
88
  return <button key={dateIso} type="button" className={"cg-date-day" + (dateIso === selectedIso ? " is-selected" : "")} aria-pressed={dateIso === selectedIso} onClick={() => onChange(dateIso)}>{day}</button>;
89
  })}</div>
90
  <div className="cg-date-recurrence"><div className="cg-pop-title">Repeat rules</div>
 
 
 
 
 
 
 
 
 
 
 
 
91
  {rules.map((rule, index) => <div className="cg-date-rule" key={`${rule.kind}-${index}`}>
92
  <select className="cg-select" value={ruleKind(rule)} aria-label={`Repeat rule ${index + 1}`} onChange={(event) => replaceKind(index, event.target.value as RuleKind)}>{(["daily", "weekly", "monthly", "monthly_ordinal", "yearly", "holiday"] as RuleKind[]).map((kind) => <option key={kind} value={kind}>{labelForKind(kind)}</option>)}</select>
93
  <label>Every <input className="cg-input cg-date-interval" min="1" max="366" type="number" value={rule.interval ?? 1} onChange={(event) => updateRule(index, { interval: bounded(event.target.value, 1, 366, 1) })} /></label>
 
31
  }
32
  function labelForKind(kind: RuleKind): string { return ({ daily: "Every N days", weekly: "Every N weeks", monthly: "Day of every N months", monthly_ordinal: "Ordinal weekday of every N months", yearly: "Every N years", holiday: "Public holiday" } as Record<RuleKind, string>)[kind]; }
33
 
34
+ type RecurrenceCondition = {
35
+ colId: string;
36
+ op: "eq" | "neq" | "not_empty" | "between";
37
+ value: string;
38
+ value2?: string;
39
+ };
40
+ type LinkedRecurrence = DateRecurrence & {
41
+ anchorField?: { table: "same" | string; field: string; linkedVia?: string };
42
+ conditions?: RecurrenceCondition[];
43
+ };
44
+
45
+ export function DatePicker({ anchor, field, fields, scopeKey, value, today, onChange, onRecurrence, onClose }: {
46
+ anchor: AnchorRect; field: Field; fields: Field[]; scopeKey: string; value: unknown; today?: string; onChange: (value: string) => void;
47
  onRecurrence: (recurrence: DateRecurrence | null) => void; onClose: () => void;
48
  }) {
49
  const selected = parseIso(value) ?? parseIso(today) ?? new Date();
 
55
  const [nextDate, setNextDate] = useState<string | null | undefined>(() => field.recurrence?.nextDate);
56
  const [calendars, setCalendars] = useState<CalendarOption[]>(DEFAULT_CALENDARS);
57
  const [previewError, setPreviewError] = useState("");
58
+ const storedRecurrence = field.recurrence as LinkedRecurrence | undefined;
59
+ const [anchorTable, setAnchorTable] = useState(() => storedRecurrence?.anchorField?.table ?? "same");
60
+ const [anchorField, setAnchorField] = useState(() => storedRecurrence?.anchorField?.field ?? "");
61
+ const [linkedVia, setLinkedVia] = useState(() => storedRecurrence?.anchorField?.linkedVia ?? "");
62
+ const [conditions, setConditions] = useState<RecurrenceCondition[]>(() => storedRecurrence?.conditions ?? []);
63
+ const dateFields = useMemo(() => fields.filter((candidate) => candidate.type === "date"), [fields]);
64
+ const linkedFields = useMemo(() => fields.filter((candidate) => candidate.type === "link" && candidate.link?.table), [fields]);
65
+ const recurrence = useMemo<LinkedRecurrence | null>(() => rules.length ? ({
66
+ startDate: selectedIso,
67
+ rules,
68
+ previewCount: bounded(previewCount, 1, 50, 10),
69
+ ...(anchorField ? { anchorField: {
70
+ table: anchorTable,
71
+ field: anchorField,
72
+ ...(anchorTable !== "same" && linkedVia ? { linkedVia } : {}),
73
+ } } : {}),
74
+ ...(conditions.length ? { conditions } : {}),
75
+ }) : null, [anchorField, anchorTable, conditions, linkedVia, previewCount, rules, selectedIso]);
76
 
77
  // Server-evaluated preview: the exact payload saved below is sent here, so edited previews
78
  // cannot differ from the default next date after refresh because of timezone/holiday drift.
 
80
  if (!recurrence) { setPreview([]); setNextDate(undefined); setPreviewError(""); return; }
81
  const controller = new AbortController();
82
  void fetch(`${API_V1}/grid/recurrence-preview`, { method: "POST", credentials: CREDENTIALS, signal: controller.signal,
83
+ headers: { "Content-Type": "application/json" }, body: JSON.stringify({ recurrence, scopeKey })
84
  }).then(async (response) => {
85
  const data = await response.json().catch(() => ({}));
86
  if (!response.ok) throw new Error(String(data?.detail?.message ?? "Could not preview recurrence"));
 
108
  const cells = Array.from({ length: Math.ceil((leading + days) / 7) * 7 }, (_, index) => index - leading + 1);
109
 
110
  return <AnchoredOverlay anchor={anchor} className="cg-date-picker" placement="bottom-start" onDismiss={onClose} role="dialog" ariaLabel={`Choose a date for ${field.label}`} dataKind="date-picker">
111
+ <label className="cg-date-boundary">Date<input className="cg-input" type="date" value={selectedIso} aria-label={`Date value for ${field.label}`} onChange={(event) => onChange(event.target.value)} /></label>
112
  <div className="cg-date-picker-head"><button type="button" className="cg-icon-button" aria-label="Previous month" onClick={() => setCursor(addMonths(cursor, -1))}>‹</button><strong>{MONTHS[cursor.getUTCMonth()]} {cursor.getUTCFullYear()}</strong><button type="button" className="cg-icon-button" aria-label="Next month" onClick={() => setCursor(addMonths(cursor, 1))}>›</button></div>
113
  <div className="cg-date-weekdays">{WEEKDAYS.map((day) => <span key={day}>{day}</span>)}</div>
114
  <div className="cg-date-grid">{cells.map((day, index) => {
 
117
  return <button key={dateIso} type="button" className={"cg-date-day" + (dateIso === selectedIso ? " is-selected" : "")} aria-pressed={dateIso === selectedIso} onClick={() => onChange(dateIso)}>{day}</button>;
118
  })}</div>
119
  <div className="cg-date-recurrence"><div className="cg-pop-title">Repeat rules</div>
120
+ <div className="cg-date-boundary" aria-label="Recurrence anchor">
121
+ <label>Anchor database<select className="cg-select" value={anchorTable} onChange={(event) => {
122
+ const table = event.target.value;
123
+ setAnchorTable(table);
124
+ if (table === "same") setLinkedVia("");
125
+ else setLinkedVia(linkedFields.find((candidate) => candidate.link?.table === table)?.key ?? "");
126
+ setAnchorField("");
127
+ }}><option value="same">This database</option>{linkedFields.map((candidate) => <option value={candidate.link!.table} key={candidate.key}>{candidate.label} · {candidate.link!.table}</option>)}</select></label>
128
+ {anchorTable === "same" ? <label>Date field<select className="cg-select" value={anchorField} onChange={(event) => setAnchorField(event.target.value)}><option value="">This date</option>{dateFields.map((candidate) => <option value={candidate.key} key={candidate.key}>{candidate.label}</option>)}</select></label>
129
+ : <><label>Linked through<select className="cg-select" value={linkedVia} onChange={(event) => setLinkedVia(event.target.value)}>{linkedFields.filter((candidate) => candidate.link?.table === anchorTable).map((candidate) => <option value={candidate.key} key={candidate.key}>{candidate.label}</option>)}</select></label><label>Linked date field key<input className="cg-input" value={anchorField} onChange={(event) => setAnchorField(event.target.value)} placeholder="due_date" /></label></>}
130
+ </div>
131
+ <div className="cg-date-boundary" aria-label="Recurrence conditions"><div className="cg-pop-title">Only when</div>{conditions.map((condition, index) => <div className="cg-date-holidays" key={`${condition.colId}-${index}`}><select className="cg-select" aria-label={`Condition field ${index + 1}`} value={condition.colId} onChange={(event) => setConditions((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, colId: event.target.value } : item))}>{fields.map((candidate) => <option key={candidate.key} value={candidate.key}>{candidate.label}</option>)}</select><select className="cg-select" aria-label={`Condition operator ${index + 1}`} value={condition.op} onChange={(event) => setConditions((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, op: event.target.value as RecurrenceCondition["op"], ...(event.target.value === "between" ? {} : { value2: undefined }) } : item))}><option value="eq">is</option><option value="neq">is not</option><option value="not_empty">is not empty</option><option value="between">is between</option></select>{condition.op !== "not_empty" && <input className="cg-input" aria-label={`Condition value ${index + 1}`} value={condition.value} onChange={(event) => setConditions((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, value: event.target.value } : item))} />}{condition.op === "between" && <input className="cg-input" aria-label={`Condition second value ${index + 1}`} value={condition.value2 ?? ""} onChange={(event) => setConditions((current) => current.map((item, itemIndex) => itemIndex === index ? { ...item, value2: event.target.value } : item))} />}<button type="button" className="cg-link-btn" onClick={() => setConditions((current) => current.filter((_, itemIndex) => itemIndex !== index))}>Remove</button></div>)}<button type="button" className="cg-link-btn" disabled={!fields.length} onClick={() => setConditions((current) => [...current, { colId: fields[0]?.key ?? "", op: "eq", value: "" }])}>+ Add condition</button></div>
132
  {rules.map((rule, index) => <div className="cg-date-rule" key={`${rule.kind}-${index}`}>
133
  <select className="cg-select" value={ruleKind(rule)} aria-label={`Repeat rule ${index + 1}`} onChange={(event) => replaceKind(index, event.target.value as RuleKind)}>{(["daily", "weekly", "monthly", "monthly_ordinal", "yearly", "holiday"] as RuleKind[]).map((kind) => <option key={kind} value={kind}>{labelForKind(kind)}</option>)}</select>
134
  <label>Every <input className="cg-input cg-date-interval" min="1" max="366" type="number" value={rule.interval ?? 1} onChange={(event) => updateRule(index, { interval: bounded(event.target.value, 1, 366, 1) })} /></label>
web/src/customer-grid/MapView.tsx CHANGED
@@ -96,16 +96,20 @@ import { LP_INK, LP_MAP_SELECTED, LP_PURPLE, LP_PURPLE_DEEP } from "./theme";
96
  import { RouteNav } from "./RouteNav";
97
  import { normalizedRouteMapLinks } from "./routeLinks";
98
  import {
 
99
  requestRouteDelivery,
 
100
  usesNormalizedCustomerZones,
101
  zoneCollectionPath,
102
  zoneItemPath,
103
  zoneMutationPayload,
104
  } from "./routeZoneApi";
105
- import { mapNavigatorMode, normalizedZoneZipCodes, routeSourceStopIds, toggleRouteSelection, zoneMembershipPids } from "./routeZoneTypes";
106
  import type {
107
  MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate, MapZoneDto,
108
- RouteDeliveryDto, RouteDeliveryRequest, RouteSelectionRequest, RouteSelectionResponse,
 
 
109
  } from "./routeZoneTypes";
110
  import "./map.css";
111
 
@@ -336,15 +340,15 @@ const ZONE_COLOR_CHOICES = [
336
  { value: "#C7B7E8", label: "Purple" },
337
  ];
338
 
339
- type ZoneGeometry = {
340
- type: "Polygon" | "MultiPolygon";
341
- coordinates: number[][][] | number[][][][];
342
- };
343
-
344
  /** Move a durable GeoJSON boundary without changing its topology or membership snapshot. */
345
  export function translateZoneGeometry(
346
  geometry: ZoneGeometry, delta: { lon: number; lat: number }
347
  ): ZoneGeometry {
 
 
 
 
 
348
  const point = (pair: number[]) => [
349
  Math.max(-180, Math.min(180, pair[0] + delta.lon)),
350
  Math.max(-90, Math.min(90, pair[1] + delta.lat)),
@@ -532,10 +536,23 @@ export function MapView({
532
  /** C2 named-route read model. Legacy route-order columns remain compatibility only. */
533
  const [namedRoutes, setNamedRoutes] = useState<MapRouteDto[]>([]);
534
  const [routeFolders, setRouteFolders] = useState<MapRouteFolderDto[]>([]);
 
 
535
  const [createdRoute, setCreatedRoute] = useState<MapRouteDto | null>(null);
536
  const [selectedRouteIds, setSelectedRouteIds] = useState<ReadonlySet<string>>(new Set());
537
  /** The Route detail is the only pin-edit target. Route selection never chooses it implicitly. */
538
  const [activeRouteId, setActiveRouteId] = useState<string | null>(null);
 
 
 
 
 
 
 
 
 
 
 
539
  const [routePinPrompt, setRoutePinPrompt] = useState<{
540
  routeId: string; customerPid: number; title: string; present: boolean;
541
  } | null>(null);
@@ -549,20 +566,43 @@ export function MapView({
549
  const [zoneEditorId, setZoneEditorId] = useState("");
550
  const [zoneName, setZoneName] = useState("");
551
  const [zoneColor, setZoneColor] = useState(ZONE_COLOR_CHOICES[0].value);
552
- const [zoneGeographicField, setZoneGeographicField] = useState("");
553
- const [zoneGeographicValue, setZoneGeographicValue] = useState("");
554
- const [zoneZipCodes, setZoneZipCodes] = useState("");
555
  const [drawnZoneGeometry, setDrawnZoneGeometry] = useState<ZoneGeometry | null>(null);
 
 
 
 
 
 
 
556
  const [zoneMove, setZoneMove] = useState<ZoneMove | null>(null);
557
  const [zoneGeometryDraft, setZoneGeometryDraft] = useState<{ id: string; geometry: ZoneGeometry } | null>(null);
558
  const [zoneBusy, setZoneBusy] = useState(false);
559
  const [zoneErr, setZoneErr] = useState<string | null>(null);
 
 
 
 
 
 
 
 
 
 
 
 
560
  const normalizedCustomerZones = usesNormalizedCustomerZones(tableKey);
561
  const mapNavigator = mapNavigatorMode(routePanelOpen, zoneNavigatorOpen);
562
  const activeNamedRoute = useMemo(
563
  () => activeRouteId ? namedRoutes.find((route) => route.id === activeRouteId) || null : null,
564
  [activeRouteId, namedRoutes]
565
  );
 
 
 
 
 
 
566
  useEffect(() => {
567
  setRoutePinPrompt(null);
568
  setRoutePinNotice(null);
@@ -572,10 +612,10 @@ export function MapView({
572
  }, [activeNamedRoute, activeRouteId]);
573
  useEffect(() => {
574
  if (routePanelOpen) {
575
- setZoneNavigatorOpen(false);
576
- setZoneEditorOpen(false);
577
  return;
578
  }
 
 
579
  setActiveRouteId(null);
580
  setRoutePinPrompt(null);
581
  setRoutePinNotice(null);
@@ -830,60 +870,68 @@ export function MapView({
830
  }, [mapRows, field.key, coordField, colorField, sizeField]);
831
  const noCoords = mapRows.length - points.length;
832
 
833
- /** Geography is selected from existing row data rather than introduced as a parallel value
834
- * store. The choice is also recorded on a Zone as C3 provenance. */
835
- const geographicFields = useMemo(() => {
836
- const candidates = new Set<string>();
837
- for (const row of mapRows.slice(0, 250)) {
838
- for (const key of Object.keys(row)) {
839
- if (/(address|city|state|province|region|country|zip|postal|territory|area)/i.test(key))
840
- candidates.add(key);
841
- }
842
- }
843
- return [...candidates].sort((a, b) => a.localeCompare(b));
844
- }, [mapRows]);
845
- useEffect(() => {
846
- if (zoneGeographicField && geographicFields.includes(zoneGeographicField)) return;
847
- setZoneGeographicField(geographicFields[0] || "");
848
- setZoneGeographicValue("");
849
- }, [geographicFields, zoneGeographicField]);
850
- const geographicValues = useMemo(() => {
851
- if (!zoneGeographicField) return [];
852
- const values = new Set<string>();
853
- for (const row of mapRows) {
854
- const value = String(row[zoneGeographicField] ?? "").trim();
855
- if (value) values.add(value);
856
- }
857
- return [...values].sort((a, b) => a.localeCompare(b));
858
- }, [mapRows, zoneGeographicField]);
859
-
860
  const loadZones = useCallback(async () => {
 
 
 
 
861
  try {
862
  const res = await fetch(zoneCollectionPath(tableKey), {
863
  credentials: "same-origin",
 
864
  });
865
  const body = res.ok ? await res.json().catch(() => null) : null;
 
866
  setZones(Array.isArray(body?.zones) ? body.zones : []);
867
  } catch {
 
 
868
  setZones([]);
869
  }
870
  }, [tableKey]);
871
  useEffect(() => { void loadZones(); }, [loadZones]);
872
- const visibleRoutePids = useMemo(
873
- () => [...new Set(rows.map((row) => row.pid))].sort((a, b) => a - b).join(","),
874
- [rows]
875
- );
876
  const loadNamedRoutes = useCallback(async () => {
 
 
 
 
877
  try {
878
- const res = await fetch(`/api/v1/customers/routes?visiblePids=${encodeURIComponent(visibleRoutePids)}`, {
879
  credentials: "same-origin",
 
880
  });
881
  const body = res.ok ? await res.json().catch(() => null) : null;
 
882
  if (Array.isArray(body?.routes)) setNamedRoutes(body.routes);
883
  if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
884
- } catch { /* Keep the last honest Route navigation when a refresh is temporarily unavailable. */ }
885
- }, [visibleRoutePids]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
886
  useEffect(() => { void loadNamedRoutes(); }, [loadNamedRoutes, routePanelOpen]);
 
 
 
887
  useEffect(() => {
888
  // A managed clause belongs to one saved View. Never carry it into another View's authored state.
889
  setManagedRouteViewState(null);
@@ -971,7 +1019,11 @@ export function MapView({
971
  const updateNamedRoute = useCallback(async (
972
  route: MapRouteDto, patch: MapRouteUpdate
973
  ): Promise<string | null> => {
974
- if (!route.permission.canEdit || route.compatibility === "legacy-route-order")
 
 
 
 
975
  return "This Route is read-only.";
976
  try {
977
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, {
@@ -990,7 +1042,7 @@ export function MapView({
990
  }, []);
991
 
992
  const deleteNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
993
- if (!route.permission.canEdit || route.compatibility === "legacy-route-order")
994
  return "This Route is read-only.";
995
  try {
996
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, {
@@ -1119,6 +1171,8 @@ export function MapView({
1119
  } catch { return "The Route could not be created."; }
1120
  }, [activeView, loadNamedRoutes]);
1121
  const duplicateNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
 
 
1122
  try {
1123
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/duplicate`, {
1124
  method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
@@ -1134,7 +1188,7 @@ export function MapView({
1134
  } catch { return "The Route could not be duplicated."; }
1135
  }, [loadNamedRoutes]);
1136
  const shareNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
1137
- if (!route.permission.canEdit || route.compatibility === "legacy-route-order")
1138
  return "Only the Route owner can share this Route.";
1139
  try {
1140
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/share-ready`, {
@@ -1231,8 +1285,9 @@ export function MapView({
1231
  setZoneEditorId("");
1232
  setZoneName("");
1233
  setZoneColor(ZONE_COLOR_CHOICES[0].value);
1234
- setZoneZipCodes("");
1235
  setDrawnZoneGeometry(null);
 
1236
  setZoneErr(null);
1237
  setZoneEditorOpen(true);
1238
  }, []);
@@ -1240,10 +1295,9 @@ export function MapView({
1240
  setZoneEditorId(zone.id);
1241
  setZoneName(zone.name);
1242
  setZoneColor(zone.color);
1243
- setZoneGeographicField(zone.geographicField || "");
1244
- setZoneGeographicValue("");
1245
- setZoneZipCodes((zone.zipCodes || []).join(", "));
1246
  setDrawnZoneGeometry(null);
 
1247
  setZoneErr(null);
1248
  setZoneEditorOpen(true);
1249
  }, []);
@@ -1286,39 +1340,27 @@ export function MapView({
1286
  .map((pair) => project(pair[0], pair[1])),
1287
  })).filter((ring) => ring.points.length >= 4));
1288
  }), [activeZones, zoneGeometryDraft]);
1289
-
1290
- const selectionZoneGeometry = useCallback((): ZoneGeometry | null => {
1291
- if (drawnZoneGeometry) return drawnZoneGeometry;
1292
- const selected = points.filter((point) => selectedPids.has(point.pid));
1293
- if (selected.length < 2) return null;
1294
- const xs = selected.map((point) => point.p.x);
1295
- const ys = selected.map((point) => point.p.y);
1296
- const pad = Math.max(WORLD * 0.004, (Math.max(...xs) - Math.min(...xs)) * 0.12,
1297
- (Math.max(...ys) - Math.min(...ys)) * 0.12);
1298
- const corners = [
1299
- { x: Math.min(...xs) - pad, y: Math.min(...ys) - pad },
1300
- { x: Math.max(...xs) + pad, y: Math.min(...ys) - pad },
1301
- { x: Math.max(...xs) + pad, y: Math.max(...ys) + pad },
1302
- { x: Math.min(...xs) - pad, y: Math.max(...ys) + pad },
1303
- ].map(unproject).map(({ lon, lat }) => [lon, lat]);
1304
- return { type: "Polygon", coordinates: [[...corners, corners[0]]] };
1305
- }, [drawnZoneGeometry, points, selectedPids]);
1306
 
1307
  const saveZone = useCallback(async (existing?: MapZone) => {
1308
- const geometryGeoJson = drawnZoneGeometry || existing?.geometryGeoJson || selectionZoneGeometry();
1309
  const name = zoneName.trim() || existing?.name || "";
1310
- const zipCodes = normalizedZoneZipCodes(zoneZipCodes);
1311
- if (!name || (!geometryGeoJson && zipCodes.length === 0)) {
1312
- setZoneErr("Name a Zone and add a boundary or at least one ZIP code.");
1313
  return;
1314
  }
1315
  if (normalizedCustomerZones && !existing && !activeView?.id) {
1316
  setZoneErr("Open a saved View before creating a Customer Zone.");
1317
  return;
1318
  }
1319
- const memberships = zoneMembershipPids(
1320
- selectedPids, allRows || mapRows, zipCodes, zoneGeographicField
1321
- );
1322
  setZoneBusy(true);
1323
  setZoneErr(null);
1324
  try {
@@ -1331,9 +1373,6 @@ export function MapView({
1331
  color: zoneColor || existing?.color || ZONE_COLOR_CHOICES[0].value,
1332
  geometryGeoJson,
1333
  visible: existing?.visible ?? true,
1334
- geographicField: zoneGeographicField,
1335
- zipCodes,
1336
- memberships,
1337
  })),
1338
  });
1339
  const body = await res.json().catch(() => null);
@@ -1364,8 +1403,7 @@ export function MapView({
1364
  } finally {
1365
  setZoneBusy(false);
1366
  }
1367
- }, [drawnZoneGeometry, selectionZoneGeometry, zoneName, zoneColor, zoneGeographicField,
1368
- zoneZipCodes, selectedPids, allRows, mapRows, tableKey, normalizedCustomerZones,
1369
  activeView?.id, onZoneChanged]);
1370
 
1371
  const setZoneVisible = useCallback(async (zone: MapZone, visible: boolean) => {
@@ -2497,6 +2535,63 @@ export function MapView({
2497
  * page from the keyboard. */
2498
  const onFrameKeyDown = useCallback(
2499
  (e: ReactKeyboardEvent<HTMLDivElement>) => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2500
  const step = e.shiftKey ? 160 : 60;
2501
  switch (e.key) {
2502
  case "ArrowLeft": panBy(step, 0); break;
@@ -2517,9 +2612,19 @@ export function MapView({
2517
  }
2518
  e.preventDefault();
2519
  },
2520
- [panBy, zoomBy, rotateBy, doFit, drag]
2521
  );
2522
 
 
 
 
 
 
 
 
 
 
 
2523
  const onPointerDown = useCallback(
2524
  (e: ReactPointerEvent<SVGSVGElement>) => {
2525
  if (e.button !== 0 || !view) return;
@@ -2718,17 +2823,31 @@ export function MapView({
2718
  // A selection gesture is also a deliberate geographic outline. Keep its exact
2719
  // lon/lat geometry ready for C3's Save Zone action; the membership snapshot above
2720
  // remains the answer to "which current records were in it".
2721
- const outline = drag.kind === "rect"
2722
- ? [
2723
- { x: b.x0, y: b.y0 }, { x: b.x1, y: b.y0 },
2724
- { x: b.x1, y: b.y1 }, { x: b.x0, y: b.y1 },
2725
- ]
2726
- : drag.pts;
2727
- const coordinates = outline
2728
- .map((screen) => unproject(fromScreen(screen, view)))
2729
- .map(({ lon, lat }) => [lon, lat]);
2730
- if (coordinates.length >= 3)
2731
- setDrawnZoneGeometry({ type: "Polygon", coordinates: [[...coordinates, coordinates[0]]] });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2732
  }
2733
  setDrag(null);
2734
  }
@@ -2736,7 +2855,8 @@ export function MapView({
2736
  if (e.currentTarget.hasPointerCapture(e.pointerId))
2737
  e.currentTarget.releasePointerCapture(e.pointerId);
2738
  },
2739
- [drag, view, points, onSelectPids, zoneMove, zoneGeometryDraft, persistZoneGeometry]
 
2740
  );
2741
 
2742
  /**
@@ -2840,6 +2960,18 @@ export function MapView({
2840
  const sizeLegend = sizeRange && !sizeRange.none && sizeRange.max > sizeRange.min
2841
  ? [sizeRange.min, (sizeRange.min + sizeRange.max) / 2, sizeRange.max]
2842
  : null;
 
 
 
 
 
 
 
 
 
 
 
 
2843
 
2844
  return (
2845
  <div className="cg-mapview">
@@ -2884,28 +3016,6 @@ export function MapView({
2884
  </a>
2885
  </span>
2886
  )}
2887
- {zones !== null && (
2888
- <button
2889
- type="button"
2890
- className="cg-btn cg-map-zone-trigger"
2891
- disabled={mapNavigator === "routes"}
2892
- aria-expanded={mapNavigator === "zones"}
2893
- aria-controls="cg-zone-popover"
2894
- aria-haspopup="dialog"
2895
- aria-label="Choose Zones"
2896
- onClick={() => {
2897
- setZoneNavigatorOpen((open) => {
2898
- const next = !open;
2899
- if (next) setZoneEditorOpen(false);
2900
- return next;
2901
- });
2902
- }}
2903
- title={mapNavigator === "routes" ? "Close Routes before choosing Zones" : "Choose Zones"}
2904
- >
2905
- Zone{activeZoneIds.size ? ` (${activeZoneIds.size.toLocaleString()})` : ""}
2906
- <svg viewBox="0 0 12 8" aria-hidden="true"><path d="m2 2 4 4 4-4" /></svg>
2907
- </button>
2908
- )}
2909
  {/* ═══════════════════════════════════════════════════════════════════════════════════
2910
  THE ROUTE PANEL — rebuilt for owner items 2, 4, 6, 8 and 9.
2911
 
@@ -2924,6 +3034,7 @@ export function MapView({
2924
  ═══════════════════════════════════════════════════════════════════════════════════ */}
2925
  {mapNavigator === "routes" && (
2926
  <aside id="cg-route-popover" className="cg-route-popover cg-route-nav-panel cg-route-index" aria-label="Routes">
 
2927
  <RouteNav
2928
  routes={namedRoutes}
2929
  folders={routeFolders}
@@ -2954,6 +3065,9 @@ export function MapView({
2954
  mapLinks={activeRouteMaps.links}
2955
  mapLinkRefusal={activeRouteMapsRefusal}
2956
  deliveries={routeDeliveries}
 
 
 
2957
  onSchedule={scheduleNamedRouteDelivery}
2958
  onDeleteDelivery={deleteNamedRouteDelivery}
2959
  />
@@ -2996,6 +3110,7 @@ export function MapView({
2996
  {geoControl}
2997
  {zones !== null && mapNavigator === "zones" && !zoneEditorOpen && (
2998
  <aside id="cg-zone-popover" className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label="Zone chooser">
 
2999
  <div className="cg-route-popover-head">
3000
  <button type="button" className="cg-route-index-back" onClick={() => setZoneNavigatorOpen(false)}>Back</button>
3001
  <span className="cg-views-title">Zones</span>
@@ -3030,11 +3145,40 @@ export function MapView({
3030
  )}
3031
  {zones !== null && mapNavigator === "zones" && zoneEditorOpen && (
3032
  <aside id="cg-zone-popover" className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label={zoneEditor ? `Edit ${zoneEditor.name}` : "Create Zone"}>
 
3033
  <div className="cg-route-popover-head">
3034
  <button type="button" className="cg-route-index-back" onClick={() => { setZoneErr(null); setZoneEditorOpen(false); }}>Back to Zones</button>
3035
  <span className="cg-views-title">{zoneEditor ? "Edit Zone" : "New Zone"}</span>
3036
  </div>
3037
  <div className="cg-map-zones cg-map-zone-editor">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3038
  {zoneEditor && (
3039
  <button
3040
  type="button"
@@ -3045,54 +3189,6 @@ export function MapView({
3045
  {zoneEditor.visible ? "Hide Zone" : "Show Zone"}
3046
  </button>
3047
  )}
3048
- <label className="cg-map-zone-control">
3049
- Geography
3050
- <select
3051
- className="cg-route-select"
3052
- value={zoneGeographicField}
3053
- aria-label="Geographic field"
3054
- onChange={(event) => {
3055
- setZoneGeographicField(event.target.value);
3056
- setZoneGeographicValue("");
3057
- }}
3058
- >
3059
- <option value="">Choose a geographic field</option>
3060
- {geographicFields.map((key) => <option key={key} value={key}>{key}</option>)}
3061
- </select>
3062
- </label>
3063
- {zoneGeographicField && (
3064
- <label className="cg-map-zone-control">
3065
- Group
3066
- <select
3067
- className="cg-route-select"
3068
- value={zoneGeographicValue}
3069
- aria-label="Geographic group"
3070
- onChange={(event) => {
3071
- const value = event.target.value;
3072
- setZoneGeographicValue(value);
3073
- if (value) {
3074
- onSelectPids(
3075
- mapRows.filter((row) => String(row[zoneGeographicField] ?? "").trim() === value).map((row) => row.pid),
3076
- "replace"
3077
- );
3078
- }
3079
- }}
3080
- >
3081
- <option value="">Choose a group</option>
3082
- {geographicValues.map((value) => <option key={value} value={value}>{value}</option>)}
3083
- </select>
3084
- </label>
3085
- )}
3086
- <label className="cg-map-zone-control">
3087
- ZIP codes
3088
- <input
3089
- className="cg-input"
3090
- value={zoneZipCodes}
3091
- aria-label="Zone ZIP codes"
3092
- placeholder="75201, 75202"
3093
- onChange={(event) => setZoneZipCodes(event.target.value)}
3094
- />
3095
- </label>
3096
  <label className="cg-map-zone-control">
3097
  Zone name
3098
  <input
@@ -3113,11 +3209,12 @@ export function MapView({
3113
  <button
3114
  type="button"
3115
  className="cg-btn cg-btn--primary"
3116
- disabled={zoneBusy || (normalizedCustomerZones && !!zoneEditor && !zoneEditor.permission?.canEdit)}
 
3117
  onClick={() => void saveZone(zoneEditor || undefined)}
3118
  title={drawnZoneGeometry
3119
  ? (zoneEditor ? "Replace this Zone boundary with the drawn shape" : "Save the drawn Zone")
3120
- : zoneEditor ? "Save Zone details" : "Save a Zone around the selected records"}
3121
  >
3122
  {zoneBusy ? "Saving Zone" : zoneEditor ? "Update Zone" : "Save Zone"}
3123
  </button>
@@ -3150,10 +3247,13 @@ export function MapView({
3150
  </span>
3151
  </div>
3152
  <div
 
3153
  className="cg-map-frame"
3154
  tabIndex={0}
3155
  role="group"
3156
- aria-label="Map canvas. Arrow keys pan, plus and minus zoom, square brackets rotate, zero fits to data and faces north."
 
 
3157
  onKeyDown={onFrameKeyDown}
3158
  onPointerDown={() => { if (!routePanelOpen) signal(NAV_MINIMIZE_EVENT); }}
3159
  >
@@ -3170,6 +3270,32 @@ export function MapView({
3170
  onPointerCancel={onPointerUp}
3171
  >
3172
  <rect className="cg-map-water" x={0} y={0} width={VIEW_W} height={VIEW_H} />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3173
  <g transform={tf}>
3174
  {/* --- W37-T35: the raster basemap, UNDER everything, inside the same transform.
3175
  ⛔ AND THE VENDORED GEOMETRY BELOW IS HIDDEN WHILE IT PAINTS. Drawing a
@@ -3243,6 +3369,20 @@ export function MapView({
3243
  fill={ring.zone.color}
3244
  stroke={ring.zone.color}
3245
  strokeWidth={hair(1.4)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3246
  onPointerDown={(event) => {
3247
  if (event.button !== 0 || !view) return;
3248
  event.stopPropagation();
@@ -3268,6 +3408,16 @@ export function MapView({
3268
  <title>{`${ring.zone.name}: click to select records, drag to move boundary`}</title>
3269
  </polygon>
3270
  ))}
 
 
 
 
 
 
 
 
 
 
3271
  {/* The planned path, UNDER the pins so it never hides a stop. Inside
3272
  the zoomed group, so it pans and scales with the geography; the
3273
  stroke is pre-divided by k like every other line here. */}
 
96
  import { RouteNav } from "./RouteNav";
97
  import { normalizedRouteMapLinks } from "./routeLinks";
98
  import {
99
+ fetchRouteAssignees,
100
  requestRouteDelivery,
101
+ routeInventoryPath,
102
  usesNormalizedCustomerZones,
103
  zoneCollectionPath,
104
  zoneItemPath,
105
  zoneMutationPayload,
106
  } from "./routeZoneApi";
107
+ import { mapNavigatorMode, routeSourceStopIds, toggleRouteSelection } from "./routeZoneTypes";
108
  import type {
109
  MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate, MapZoneDto,
110
+ RouteAssigneeDirectory, RouteDeliveryDto, RouteDeliveryRequest,
111
+ RouteSelectionRequest, RouteSelectionResponse,
112
+ ZoneGeometry,
113
  } from "./routeZoneTypes";
114
  import "./map.css";
115
 
 
340
  { value: "#C7B7E8", label: "Purple" },
341
  ];
342
 
 
 
 
 
 
343
  /** Move a durable GeoJSON boundary without changing its topology or membership snapshot. */
344
  export function translateZoneGeometry(
345
  geometry: ZoneGeometry, delta: { lon: number; lat: number }
346
  ): ZoneGeometry {
347
+ if (geometry.type === "Circle") return {
348
+ type: "Circle",
349
+ center: [Math.max(-180, Math.min(180, geometry.center[0] + delta.lon)), Math.max(-90, Math.min(90, geometry.center[1] + delta.lat))],
350
+ radiusMeters: geometry.radiusMeters,
351
+ };
352
  const point = (pair: number[]) => [
353
  Math.max(-180, Math.min(180, pair[0] + delta.lon)),
354
  Math.max(-90, Math.min(90, pair[1] + delta.lat)),
 
536
  /** C2 named-route read model. Legacy route-order columns remain compatibility only. */
537
  const [namedRoutes, setNamedRoutes] = useState<MapRouteDto[]>([]);
538
  const [routeFolders, setRouteFolders] = useState<MapRouteFolderDto[]>([]);
539
+ const [routeAssignees, setRouteAssignees] = useState<RouteAssigneeDirectory | null>(null);
540
+ const [routeAssigneeError, setRouteAssigneeError] = useState<string | null>(null);
541
  const [createdRoute, setCreatedRoute] = useState<MapRouteDto | null>(null);
542
  const [selectedRouteIds, setSelectedRouteIds] = useState<ReadonlySet<string>>(new Set());
543
  /** The Route detail is the only pin-edit target. Route selection never chooses it implicitly. */
544
  const [activeRouteId, setActiveRouteId] = useState<string | null>(null);
545
+ const pendingInboxRoute = useRef<string | null>(null);
546
+ useEffect(() => {
547
+ const openRoute = (event: Event) => {
548
+ const routeId = String((event as CustomEvent<{ routeId?: string }>).detail?.routeId ?? "");
549
+ if (!routeId) return;
550
+ pendingInboxRoute.current = routeId;
551
+ setActiveRouteId(routeId);
552
+ };
553
+ window.addEventListener("aios:route-open", openRoute);
554
+ return () => window.removeEventListener("aios:route-open", openRoute);
555
+ }, []);
556
  const [routePinPrompt, setRoutePinPrompt] = useState<{
557
  routeId: string; customerPid: number; title: string; present: boolean;
558
  } | null>(null);
 
566
  const [zoneEditorId, setZoneEditorId] = useState("");
567
  const [zoneName, setZoneName] = useState("");
568
  const [zoneColor, setZoneColor] = useState(ZONE_COLOR_CHOICES[0].value);
569
+ const [zoneDrawShape, setZoneDrawShape] = useState<"polygon" | "circle">("polygon");
 
 
570
  const [drawnZoneGeometry, setDrawnZoneGeometry] = useState<ZoneGeometry | null>(null);
571
+ const [zoneKeyboardDraft, setZoneKeyboardDraft] = useState<{
572
+ shape: "polygon" | "circle";
573
+ cursor: Pt;
574
+ points: Pt[];
575
+ center?: Pt;
576
+ } | null>(null);
577
+ const mapFrameRef = useRef<HTMLDivElement | null>(null);
578
  const [zoneMove, setZoneMove] = useState<ZoneMove | null>(null);
579
  const [zoneGeometryDraft, setZoneGeometryDraft] = useState<{ id: string; geometry: ZoneGeometry } | null>(null);
580
  const [zoneBusy, setZoneBusy] = useState(false);
581
  const [zoneErr, setZoneErr] = useState<string | null>(null);
582
+ const zoneRequestRef = useRef<{ generation: number; controller: AbortController | null }>({
583
+ generation: 0,
584
+ controller: null,
585
+ });
586
+ const routeRequestRef = useRef<{ generation: number; controller: AbortController | null }>({
587
+ generation: 0,
588
+ controller: null,
589
+ });
590
+ const routeAssigneeRequestRef = useRef<{ generation: number; controller: AbortController | null }>({
591
+ generation: 0,
592
+ controller: null,
593
+ });
594
  const normalizedCustomerZones = usesNormalizedCustomerZones(tableKey);
595
  const mapNavigator = mapNavigatorMode(routePanelOpen, zoneNavigatorOpen);
596
  const activeNamedRoute = useMemo(
597
  () => activeRouteId ? namedRoutes.find((route) => route.id === activeRouteId) || null : null,
598
  [activeRouteId, namedRoutes]
599
  );
600
+ useEffect(() => {
601
+ const routeId = pendingInboxRoute.current;
602
+ if (!routeId || !namedRoutes.some((route) => route.id === routeId)) return;
603
+ pendingInboxRoute.current = null;
604
+ setActiveRouteId(routeId);
605
+ }, [namedRoutes]);
606
  useEffect(() => {
607
  setRoutePinPrompt(null);
608
  setRoutePinNotice(null);
 
612
  }, [activeNamedRoute, activeRouteId]);
613
  useEffect(() => {
614
  if (routePanelOpen) {
 
 
615
  return;
616
  }
617
+ setZoneNavigatorOpen(false);
618
+ setZoneEditorOpen(false);
619
  setActiveRouteId(null);
620
  setRoutePinPrompt(null);
621
  setRoutePinNotice(null);
 
870
  }, [mapRows, field.key, coordField, colorField, sizeField]);
871
  const noCoords = mapRows.length - points.length;
872
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
873
  const loadZones = useCallback(async () => {
874
+ zoneRequestRef.current.controller?.abort();
875
+ const controller = new AbortController();
876
+ const generation = zoneRequestRef.current.generation + 1;
877
+ zoneRequestRef.current = { generation, controller };
878
  try {
879
  const res = await fetch(zoneCollectionPath(tableKey), {
880
  credentials: "same-origin",
881
+ signal: controller.signal,
882
  });
883
  const body = res.ok ? await res.json().catch(() => null) : null;
884
+ if (zoneRequestRef.current.generation !== generation) return;
885
  setZones(Array.isArray(body?.zones) ? body.zones : []);
886
  } catch {
887
+ if (controller.signal.aborted) return;
888
+ if (zoneRequestRef.current.generation !== generation) return;
889
  setZones([]);
890
  }
891
  }, [tableKey]);
892
  useEffect(() => { void loadZones(); }, [loadZones]);
 
 
 
 
893
  const loadNamedRoutes = useCallback(async () => {
894
+ routeRequestRef.current.controller?.abort();
895
+ const controller = new AbortController();
896
+ const generation = routeRequestRef.current.generation + 1;
897
+ routeRequestRef.current = { generation, controller };
898
  try {
899
+ const res = await fetch(routeInventoryPath(), {
900
  credentials: "same-origin",
901
+ signal: controller.signal,
902
  });
903
  const body = res.ok ? await res.json().catch(() => null) : null;
904
+ if (routeRequestRef.current.generation !== generation) return;
905
  if (Array.isArray(body?.routes)) setNamedRoutes(body.routes);
906
  if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
907
+ } catch {
908
+ if (controller.signal.aborted) return;
909
+ /* Keep the last honest Route navigation when a refresh is temporarily unavailable. */
910
+ }
911
+ }, []);
912
+ const loadRouteAssignees = useCallback(async () => {
913
+ routeAssigneeRequestRef.current.controller?.abort();
914
+ const controller = new AbortController();
915
+ const generation = routeAssigneeRequestRef.current.generation + 1;
916
+ routeAssigneeRequestRef.current = { generation, controller };
917
+ const result = await fetchRouteAssignees(controller.signal);
918
+ if (controller.signal.aborted || routeAssigneeRequestRef.current.generation !== generation) return;
919
+ if (result.directory) {
920
+ setRouteAssignees(result.directory);
921
+ setRouteAssigneeError(null);
922
+ } else {
923
+ setRouteAssigneeError(result.error || "Route assignees are unavailable.");
924
+ }
925
+ }, []);
926
+ useEffect(() => () => {
927
+ zoneRequestRef.current.controller?.abort();
928
+ routeRequestRef.current.controller?.abort();
929
+ routeAssigneeRequestRef.current.controller?.abort();
930
+ }, []);
931
  useEffect(() => { void loadNamedRoutes(); }, [loadNamedRoutes, routePanelOpen]);
932
+ useEffect(() => {
933
+ if (routePanelOpen) void loadRouteAssignees();
934
+ }, [loadRouteAssignees, routePanelOpen]);
935
  useEffect(() => {
936
  // A managed clause belongs to one saved View. Never carry it into another View's authored state.
937
  setManagedRouteViewState(null);
 
1019
  const updateNamedRoute = useCallback(async (
1020
  route: MapRouteDto, patch: MapRouteUpdate
1021
  ): Promise<string | null> => {
1022
+ const scheduleChange = "assignee" in patch || "date" in patch;
1023
+ const actionAllowed = "starred" in patch
1024
+ ? route.capabilities?.star === true
1025
+ : scheduleChange ? route.permission.canEdit === true : route.capabilities?.rename === true;
1026
+ if (!actionAllowed || route.compatibility === "legacy-route-order")
1027
  return "This Route is read-only.";
1028
  try {
1029
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, {
 
1042
  }, []);
1043
 
1044
  const deleteNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
1045
+ if (route.capabilities?.delete !== true || route.compatibility === "legacy-route-order")
1046
  return "This Route is read-only.";
1047
  try {
1048
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, {
 
1171
  } catch { return "The Route could not be created."; }
1172
  }, [activeView, loadNamedRoutes]);
1173
  const duplicateNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
1174
+ if (route.capabilities?.duplicate !== true || route.compatibility === "legacy-route-order")
1175
+ return "This Route cannot be duplicated.";
1176
  try {
1177
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/duplicate`, {
1178
  method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
 
1188
  } catch { return "The Route could not be duplicated."; }
1189
  }, [loadNamedRoutes]);
1190
  const shareNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
1191
+ if (route.capabilities?.share !== true || route.compatibility === "legacy-route-order")
1192
  return "Only the Route owner can share this Route.";
1193
  try {
1194
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/share-ready`, {
 
1285
  setZoneEditorId("");
1286
  setZoneName("");
1287
  setZoneColor(ZONE_COLOR_CHOICES[0].value);
1288
+ setZoneDrawShape("polygon");
1289
  setDrawnZoneGeometry(null);
1290
+ setZoneKeyboardDraft(null);
1291
  setZoneErr(null);
1292
  setZoneEditorOpen(true);
1293
  }, []);
 
1295
  setZoneEditorId(zone.id);
1296
  setZoneName(zone.name);
1297
  setZoneColor(zone.color);
1298
+ setZoneDrawShape(zone.geometryGeoJson?.type === "Circle" ? "circle" : "polygon");
 
 
1299
  setDrawnZoneGeometry(null);
1300
+ setZoneKeyboardDraft(null);
1301
  setZoneErr(null);
1302
  setZoneEditorOpen(true);
1303
  }, []);
 
1340
  .map((pair) => project(pair[0], pair[1])),
1341
  })).filter((ring) => ring.points.length >= 4));
1342
  }), [activeZones, zoneGeometryDraft]);
1343
+ const zoneCircles = useMemo(() => activeZones.flatMap((zone) => {
1344
+ const geometry = zoneGeometryDraft?.id === zone.id ? zoneGeometryDraft.geometry : zone.geometryGeoJson;
1345
+ if (!geometry || geometry.type !== "Circle") return [];
1346
+ const center = project(geometry.center[0], geometry.center[1]);
1347
+ const latitudeRadians = geometry.center[1] * Math.PI / 180;
1348
+ const lonDelta = geometry.radiusMeters / Math.max(1, 111_320 * Math.cos(latitudeRadians));
1349
+ const edge = project(geometry.center[0] + lonDelta, geometry.center[1]);
1350
+ return [{ zone, geometry, center, radius: Math.abs(edge.x - center.x) }];
1351
+ }), [activeZones, zoneGeometryDraft]);
 
 
 
 
 
 
 
 
1352
 
1353
  const saveZone = useCallback(async (existing?: MapZone) => {
1354
+ const geometryGeoJson = drawnZoneGeometry || existing?.geometryGeoJson;
1355
  const name = zoneName.trim() || existing?.name || "";
1356
+ if (!name || !geometryGeoJson) {
1357
+ setZoneErr("Name a Zone and draw its boundary on the map.");
 
1358
  return;
1359
  }
1360
  if (normalizedCustomerZones && !existing && !activeView?.id) {
1361
  setZoneErr("Open a saved View before creating a Customer Zone.");
1362
  return;
1363
  }
 
 
 
1364
  setZoneBusy(true);
1365
  setZoneErr(null);
1366
  try {
 
1373
  color: zoneColor || existing?.color || ZONE_COLOR_CHOICES[0].value,
1374
  geometryGeoJson,
1375
  visible: existing?.visible ?? true,
 
 
 
1376
  })),
1377
  });
1378
  const body = await res.json().catch(() => null);
 
1403
  } finally {
1404
  setZoneBusy(false);
1405
  }
1406
+ }, [drawnZoneGeometry, zoneName, zoneColor, tableKey, normalizedCustomerZones,
 
1407
  activeView?.id, onZoneChanged]);
1408
 
1409
  const setZoneVisible = useCallback(async (zone: MapZone, visible: boolean) => {
 
2535
  * page from the keyboard. */
2536
  const onFrameKeyDown = useCallback(
2537
  (e: ReactKeyboardEvent<HTMLDivElement>) => {
2538
+ if (zoneKeyboardDraft) {
2539
+ const keyboardStep = e.shiftKey ? 24 : 8;
2540
+ const moved = { ...zoneKeyboardDraft.cursor };
2541
+ if (e.key === "ArrowLeft") moved.x = Math.max(8, moved.x - keyboardStep);
2542
+ else if (e.key === "ArrowRight") moved.x = Math.min(VIEW_W - 8, moved.x + keyboardStep);
2543
+ else if (e.key === "ArrowUp") moved.y = Math.max(8, moved.y - keyboardStep);
2544
+ else if (e.key === "ArrowDown") moved.y = Math.min(VIEW_H - 8, moved.y + keyboardStep);
2545
+ else if (e.key === " ") {
2546
+ if (zoneKeyboardDraft.shape === "polygon")
2547
+ setZoneKeyboardDraft({ ...zoneKeyboardDraft, points: [...zoneKeyboardDraft.points, zoneKeyboardDraft.cursor] });
2548
+ else if (!zoneKeyboardDraft.center)
2549
+ setZoneKeyboardDraft({ ...zoneKeyboardDraft, center: zoneKeyboardDraft.cursor });
2550
+ setZoneErr(null);
2551
+ e.preventDefault();
2552
+ return;
2553
+ } else if (e.key === "Enter") {
2554
+ if (!view) return;
2555
+ if (zoneKeyboardDraft.shape === "polygon") {
2556
+ if (zoneKeyboardDraft.points.length < 3) {
2557
+ setZoneErr("Add at least three polygon vertices with Space, then press Enter.");
2558
+ e.preventDefault();
2559
+ return;
2560
+ }
2561
+ const coordinates = zoneKeyboardDraft.points
2562
+ .map((screen) => unproject(fromScreen(screen, view)))
2563
+ .map(({ lon, lat }) => [lon, lat]);
2564
+ setDrawnZoneGeometry({ type: "Polygon", coordinates: [[...coordinates, coordinates[0]]] });
2565
+ } else {
2566
+ if (!zoneKeyboardDraft.center) {
2567
+ setZoneErr("Press Space to place the circle center, move to its edge, then press Enter.");
2568
+ e.preventDefault();
2569
+ return;
2570
+ }
2571
+ const center = unproject(fromScreen(zoneKeyboardDraft.center, view));
2572
+ const edge = unproject(fromScreen(zoneKeyboardDraft.cursor, view));
2573
+ setDrawnZoneGeometry({
2574
+ type: "Circle",
2575
+ center: [center.lon, center.lat],
2576
+ radiusMeters: Math.max(1, Math.round(haversineKm(
2577
+ { lat: center.lat, lon: center.lon }, { lat: edge.lat, lon: edge.lon }
2578
+ ) * 1000)),
2579
+ });
2580
+ }
2581
+ setZoneKeyboardDraft(null);
2582
+ setZoneErr(null);
2583
+ e.preventDefault();
2584
+ return;
2585
+ } else if (e.key === "Escape") {
2586
+ setZoneKeyboardDraft(null);
2587
+ setZoneErr(null);
2588
+ e.preventDefault();
2589
+ return;
2590
+ } else return;
2591
+ setZoneKeyboardDraft({ ...zoneKeyboardDraft, cursor: moved });
2592
+ e.preventDefault();
2593
+ return;
2594
+ }
2595
  const step = e.shiftKey ? 160 : 60;
2596
  switch (e.key) {
2597
  case "ArrowLeft": panBy(step, 0); break;
 
2612
  }
2613
  e.preventDefault();
2614
  },
2615
+ [panBy, zoomBy, rotateBy, doFit, drag, view, zoneKeyboardDraft]
2616
  );
2617
 
2618
+ const startKeyboardZoneDrawing = useCallback(() => {
2619
+ setZoneKeyboardDraft({
2620
+ shape: zoneDrawShape,
2621
+ cursor: { x: VIEW_W / 2, y: VIEW_H / 2 },
2622
+ points: [],
2623
+ });
2624
+ setZoneErr(null);
2625
+ requestAnimationFrame(() => mapFrameRef.current?.focus());
2626
+ }, [zoneDrawShape]);
2627
+
2628
  const onPointerDown = useCallback(
2629
  (e: ReactPointerEvent<SVGSVGElement>) => {
2630
  if (e.button !== 0 || !view) return;
 
2823
  // A selection gesture is also a deliberate geographic outline. Keep its exact
2824
  // lon/lat geometry ready for C3's Save Zone action; the membership snapshot above
2825
  // remains the answer to "which current records were in it".
2826
+ if (zoneEditorOpen && zoneDrawShape === "circle") {
2827
+ const centerScreen = { x: (b.x0 + b.x1) / 2, y: (b.y0 + b.y1) / 2 };
2828
+ const edgeScreen = { x: b.x1, y: centerScreen.y };
2829
+ const center = unproject(fromScreen(centerScreen, view));
2830
+ const edge = unproject(fromScreen(edgeScreen, view));
2831
+ setDrawnZoneGeometry({
2832
+ type: "Circle",
2833
+ center: [center.lon, center.lat],
2834
+ radiusMeters: Math.max(1, Math.round(haversineKm(
2835
+ { lat: center.lat, lon: center.lon }, { lat: edge.lat, lon: edge.lon }
2836
+ ) * 1000)),
2837
+ });
2838
+ } else {
2839
+ const outline = drag.kind === "rect"
2840
+ ? [
2841
+ { x: b.x0, y: b.y0 }, { x: b.x1, y: b.y0 },
2842
+ { x: b.x1, y: b.y1 }, { x: b.x0, y: b.y1 },
2843
+ ]
2844
+ : drag.pts;
2845
+ const coordinates = outline
2846
+ .map((screen) => unproject(fromScreen(screen, view)))
2847
+ .map(({ lon, lat }) => [lon, lat]);
2848
+ if (coordinates.length >= 3)
2849
+ setDrawnZoneGeometry({ type: "Polygon", coordinates: [[...coordinates, coordinates[0]]] });
2850
+ }
2851
  }
2852
  setDrag(null);
2853
  }
 
2855
  if (e.currentTarget.hasPointerCapture(e.pointerId))
2856
  e.currentTarget.releasePointerCapture(e.pointerId);
2857
  },
2858
+ [drag, view, points, onSelectPids, zoneMove, zoneGeometryDraft, persistZoneGeometry,
2859
+ zoneDrawShape, zoneEditorOpen]
2860
  );
2861
 
2862
  /**
 
2960
  const sizeLegend = sizeRange && !sizeRange.none && sizeRange.max > sizeRange.min
2961
  ? [sizeRange.min, (sizeRange.min + sizeRange.max) / 2, sizeRange.max]
2962
  : null;
2963
+ const navigatorTabs = (
2964
+ <div className="cg-map-navigator-tabs" role="tablist" aria-label="Map assets">
2965
+ <button type="button" role="tab" aria-selected={mapNavigator === "routes"}
2966
+ onClick={() => { setZoneNavigatorOpen(false); setZoneEditorOpen(false); }}>
2967
+ Routes
2968
+ </button>
2969
+ <button type="button" role="tab" aria-selected={mapNavigator === "zones"}
2970
+ onClick={() => { setZoneNavigatorOpen(true); setActiveRouteId(null); }}>
2971
+ Zones
2972
+ </button>
2973
+ </div>
2974
+ );
2975
 
2976
  return (
2977
  <div className="cg-mapview">
 
3016
  </a>
3017
  </span>
3018
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3019
  {/* ═══════════════════════════════════════════════════════════════════════════════════
3020
  THE ROUTE PANEL — rebuilt for owner items 2, 4, 6, 8 and 9.
3021
 
 
3034
  ═══════════════════════════════════════════════════════════════════════════════════ */}
3035
  {mapNavigator === "routes" && (
3036
  <aside id="cg-route-popover" className="cg-route-popover cg-route-nav-panel cg-route-index" aria-label="Routes">
3037
+ {navigatorTabs}
3038
  <RouteNav
3039
  routes={namedRoutes}
3040
  folders={routeFolders}
 
3065
  mapLinks={activeRouteMaps.links}
3066
  mapLinkRefusal={activeRouteMapsRefusal}
3067
  deliveries={routeDeliveries}
3068
+ assignees={routeAssignees?.people ?? null}
3069
+ routeToday={routeAssignees?.today ?? null}
3070
+ assigneeError={routeAssigneeError}
3071
  onSchedule={scheduleNamedRouteDelivery}
3072
  onDeleteDelivery={deleteNamedRouteDelivery}
3073
  />
 
3110
  {geoControl}
3111
  {zones !== null && mapNavigator === "zones" && !zoneEditorOpen && (
3112
  <aside id="cg-zone-popover" className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label="Zone chooser">
3113
+ {navigatorTabs}
3114
  <div className="cg-route-popover-head">
3115
  <button type="button" className="cg-route-index-back" onClick={() => setZoneNavigatorOpen(false)}>Back</button>
3116
  <span className="cg-views-title">Zones</span>
 
3145
  )}
3146
  {zones !== null && mapNavigator === "zones" && zoneEditorOpen && (
3147
  <aside id="cg-zone-popover" className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label={zoneEditor ? `Edit ${zoneEditor.name}` : "Create Zone"}>
3148
+ {navigatorTabs}
3149
  <div className="cg-route-popover-head">
3150
  <button type="button" className="cg-route-index-back" onClick={() => { setZoneErr(null); setZoneEditorOpen(false); }}>Back to Zones</button>
3151
  <span className="cg-views-title">{zoneEditor ? "Edit Zone" : "New Zone"}</span>
3152
  </div>
3153
  <div className="cg-map-zones cg-map-zone-editor">
3154
+ <fieldset className="cg-zone-shape-picker">
3155
+ <legend>Boundary</legend>
3156
+ <div role="group" aria-label="Zone boundary shape">
3157
+ <button type="button" aria-pressed={zoneDrawShape === "polygon"}
3158
+ onClick={() => setZoneDrawShape("polygon")}>Polygon</button>
3159
+ <button type="button" aria-pressed={zoneDrawShape === "circle"}
3160
+ onClick={() => setZoneDrawShape("circle")}>Circle</button>
3161
+ </div>
3162
+ <span>Choose a shape, then drag on the map or use the keyboard drawing controls.</span>
3163
+ {!zoneKeyboardDraft ? (
3164
+ <button type="button" className="cg-link-btn" onClick={startKeyboardZoneDrawing}>
3165
+ Start keyboard drawing
3166
+ </button>
3167
+ ) : (
3168
+ <>
3169
+ <button type="button" className="cg-link-btn" onClick={() => { setZoneKeyboardDraft(null); setZoneErr(null); }}>
3170
+ Cancel keyboard drawing
3171
+ </button>
3172
+ <span role="status" aria-live="polite">
3173
+ {zoneKeyboardDraft.shape === "polygon"
3174
+ ? `${zoneKeyboardDraft.points.length} vertices. Arrow keys move the cursor, Space adds a vertex, Enter finalizes, and Escape cancels.`
3175
+ : zoneKeyboardDraft.center
3176
+ ? "Circle center placed. Arrow keys move the edge, Enter finalizes, and Escape cancels."
3177
+ : "Arrow keys move the circle center. Space places it, then move to the edge and press Enter. Escape cancels."}
3178
+ </span>
3179
+ </>
3180
+ )}
3181
+ </fieldset>
3182
  {zoneEditor && (
3183
  <button
3184
  type="button"
 
3189
  {zoneEditor.visible ? "Hide Zone" : "Show Zone"}
3190
  </button>
3191
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3192
  <label className="cg-map-zone-control">
3193
  Zone name
3194
  <input
 
3209
  <button
3210
  type="button"
3211
  className="cg-btn cg-btn--primary"
3212
+ disabled={zoneBusy || !zoneName.trim() || (!drawnZoneGeometry && !zoneEditor?.geometryGeoJson)
3213
+ || (normalizedCustomerZones && !!zoneEditor && !zoneEditor.permission?.canEdit)}
3214
  onClick={() => void saveZone(zoneEditor || undefined)}
3215
  title={drawnZoneGeometry
3216
  ? (zoneEditor ? "Replace this Zone boundary with the drawn shape" : "Save the drawn Zone")
3217
+ : zoneEditor ? "Save Zone details" : "Draw a boundary before saving"}
3218
  >
3219
  {zoneBusy ? "Saving Zone" : zoneEditor ? "Update Zone" : "Save Zone"}
3220
  </button>
 
3247
  </span>
3248
  </div>
3249
  <div
3250
+ ref={mapFrameRef}
3251
  className="cg-map-frame"
3252
  tabIndex={0}
3253
  role="group"
3254
+ aria-label={zoneKeyboardDraft
3255
+ ? `Keyboard ${zoneKeyboardDraft.shape} drawing canvas. Follow the announced drawing instructions.`
3256
+ : "Map canvas. Arrow keys pan, plus and minus zoom, square brackets rotate, zero fits to data and faces north."}
3257
  onKeyDown={onFrameKeyDown}
3258
  onPointerDown={() => { if (!routePanelOpen) signal(NAV_MINIMIZE_EVENT); }}
3259
  >
 
3270
  onPointerCancel={onPointerUp}
3271
  >
3272
  <rect className="cg-map-water" x={0} y={0} width={VIEW_W} height={VIEW_H} />
3273
+ {zoneKeyboardDraft && (
3274
+ <g className="cg-zone-keyboard-draft" aria-hidden="true">
3275
+ {zoneKeyboardDraft.shape === "polygon" && zoneKeyboardDraft.points.length > 0 && (
3276
+ <polyline
3277
+ points={[...zoneKeyboardDraft.points, zoneKeyboardDraft.cursor]
3278
+ .map((point) => `${point.x},${point.y}`).join(" ")}
3279
+ fill="none" stroke={zoneColor} strokeWidth="3" strokeDasharray="6 4"
3280
+ />
3281
+ )}
3282
+ {zoneKeyboardDraft.shape === "circle" && zoneKeyboardDraft.center && (
3283
+ <circle
3284
+ cx={zoneKeyboardDraft.center.x} cy={zoneKeyboardDraft.center.y}
3285
+ r={Math.hypot(
3286
+ zoneKeyboardDraft.cursor.x - zoneKeyboardDraft.center.x,
3287
+ zoneKeyboardDraft.cursor.y - zoneKeyboardDraft.center.y
3288
+ )}
3289
+ fill={zoneColor} fillOpacity="0.12" stroke={zoneColor}
3290
+ strokeWidth="3" strokeDasharray="6 4"
3291
+ />
3292
+ )}
3293
+ {zoneKeyboardDraft.points.map((point, index) => (
3294
+ <circle key={`${point.x}:${point.y}:${index}`} cx={point.x} cy={point.y} r="4" fill={zoneColor} />
3295
+ ))}
3296
+ <circle cx={zoneKeyboardDraft.cursor.x} cy={zoneKeyboardDraft.cursor.y} r="6" fill={zoneColor} stroke="white" strokeWidth="2" />
3297
+ </g>
3298
+ )}
3299
  <g transform={tf}>
3300
  {/* --- W37-T35: the raster basemap, UNDER everything, inside the same transform.
3301
  ⛔ AND THE VENDORED GEOMETRY BELOW IS HIDDEN WHILE IT PAINTS. Drawing a
 
3369
  fill={ring.zone.color}
3370
  stroke={ring.zone.color}
3371
  strokeWidth={hair(1.4)}
3372
+ tabIndex={0}
3373
+ role="button"
3374
+ aria-label={`${ring.zone.name} Zone. Enter selects records; arrow keys move the boundary.`}
3375
+ onKeyDown={(event) => {
3376
+ if (event.key === "Enter" || event.key === " ") {
3377
+ event.preventDefault(); onSelectPids(ring.zone.memberships, "replace"); return;
3378
+ }
3379
+ const delta = event.key === "ArrowLeft" ? { lon: -0.0005, lat: 0 }
3380
+ : event.key === "ArrowRight" ? { lon: 0.0005, lat: 0 }
3381
+ : event.key === "ArrowUp" ? { lon: 0, lat: 0.0005 }
3382
+ : event.key === "ArrowDown" ? { lon: 0, lat: -0.0005 } : null;
3383
+ if (!delta) return;
3384
+ event.preventDefault(); void persistZoneGeometry(ring.zone, translateZoneGeometry(ring.geometry, delta));
3385
+ }}
3386
  onPointerDown={(event) => {
3387
  if (event.button !== 0 || !view) return;
3388
  event.stopPropagation();
 
3408
  <title>{`${ring.zone.name}: click to select records, drag to move boundary`}</title>
3409
  </polygon>
3410
  ))}
3411
+ {zoneCircles.map(({ zone, geometry, center, radius }) => (
3412
+ <circle key={zone.id} className="cg-map-zone" cx={center.x} cy={center.y} r={radius}
3413
+ fill={zone.color} stroke={zone.color} strokeWidth={hair(1.4)} tabIndex={0} role="button"
3414
+ aria-label={`${zone.name} Circle Zone. Enter selects records; arrow keys move the boundary.`}
3415
+ onPointerDown={(event) => { if (event.button !== 0 || !view) return; event.stopPropagation(); movedRef.current = false; event.currentTarget.ownerSVGElement?.setPointerCapture(event.pointerId); setZoneMove({ zone, geometry, start: localPoint(event.clientX, event.clientY) }); }}
3416
+ onClick={(event) => { event.stopPropagation(); if (movedRef.current) { movedRef.current = false; return; } onSelectPids(zone.memberships, "replace"); }}
3417
+ onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); onSelectPids(zone.memberships, "replace"); return; } const delta = event.key === "ArrowLeft" ? { lon: -0.0005, lat: 0 } : event.key === "ArrowRight" ? { lon: 0.0005, lat: 0 } : event.key === "ArrowUp" ? { lon: 0, lat: 0.0005 } : event.key === "ArrowDown" ? { lon: 0, lat: -0.0005 } : null; if (delta) { event.preventDefault(); void persistZoneGeometry(zone, translateZoneGeometry(geometry, delta)); } }}>
3418
+ <title>{`${zone.name}: circle radius ${Math.round(geometry.radiusMeters)} metres`}</title>
3419
+ </circle>
3420
+ ))}
3421
  {/* The planned path, UNDER the pins so it never hides a stop. Inside
3422
  the zoomed group, so it pans and scales with the geography; the
3423
  stroke is pre-divided by k like every other line here. */}
web/src/customer-grid/RouteNav.tsx CHANGED
@@ -5,18 +5,24 @@ import { submitRouteStopMove } from "./routeStopMove";
5
  import { boundedGoogleMapsUrl } from "./routeZoneTypes";
6
  import type {
7
  MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate,
8
- RouteDeliveryDto, RouteDeliveryRequest,
9
  } from "./routeZoneTypes";
10
  import "../styles/wave42/route-nav.css";
11
 
12
  type Result = Promise<string | null>;
13
 
 
 
 
 
 
 
14
  export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources, storageKey,
15
  createdRoute, onCreatedDismiss, onToggle, onActiveRouteChange, onOpenRecord, onCreate,
16
  onMoveToOrder, onUpdate, onDuplicate, onDelete, onShare, onRouteMove, onRouteReorder,
17
  onFolderCreate, onFolderUpdate, onFolderDelete, onFolderReorder, filteredRecordCount,
18
  onSelectFiltered, onCreateStart, mapLinks, mapLinkRefusal, deliveries, onSchedule,
19
- onDeleteDelivery }: {
20
  routes: MapRouteDto[];
21
  folders: MapRouteFolderDto[];
22
  selectedIds: ReadonlySet<string>;
@@ -46,6 +52,9 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
46
  mapLinks: NormalizedRouteMapLink[];
47
  mapLinkRefusal: string | null;
48
  deliveries: RouteDeliveryDto[] | null;
 
 
 
49
  onSchedule: (route: MapRouteDto, request: RouteDeliveryRequest) => Result;
50
  onDeleteDelivery: (route: MapRouteDto, delivery: RouteDeliveryDto) => Result;
51
  }) {
@@ -64,6 +73,11 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
64
  const [orderErrors, setOrderErrors] = useState<Record<number, string>>({});
65
  const [editName, setEditName] = useState("");
66
  const [editMapsUrl, setEditMapsUrl] = useState("");
 
 
 
 
 
67
  const [deleteConfirm, setDeleteConfirm] = useState(false);
68
  const [menuId, setMenuId] = useState<string | null>(null);
69
  const [renameId, setRenameId] = useState<string | null>(null);
@@ -79,6 +93,13 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
79
  const route = activeRouteId ? routes.find((item) => item.id === activeRouteId) : null;
80
  const source = sources.find((item) => item.id === sourceId) || sources[0];
81
  const mapsUrl = boundedGoogleMapsUrl(route?.mapsUrl);
 
 
 
 
 
 
 
82
  const knownFolders = useMemo(() => new Set(folders.map((folder) => folder.id)), [folders]);
83
  const validAt = resolveStoredPath(at, knownFolders);
84
  const level = useMemo(
@@ -118,6 +139,14 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
118
  setMapCopyNotice(null);
119
  setMapCopyError(null);
120
  }, [route?.id, route?.mapsUrl, route?.name]);
 
 
 
 
 
 
 
 
121
 
122
  const copyMapLinks = () => {
123
  setMapCopyNotice(null);
@@ -153,6 +182,35 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
153
  }).finally(() => setDeliveryBusy(false));
154
  };
155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  const removeDelivery = (target: MapRouteDto, delivery: RouteDeliveryDto) => {
157
  setDeliveryBusy(true);
158
  setDeliveryError(null);
@@ -344,6 +402,60 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
344
  </div>
345
  ) : <p className="cg-w44-route-empty">{route.compatibility === "legacy-route-order"
346
  ? "This legacy Route is read-only." : "Only the owner and an editor of the source View can change this Route."}</p>}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
347
  {canEdit && (
348
  <section className="cg-w44-route-delivery" aria-labelledby="cg-route-delivery-title">
349
  <div>
@@ -517,10 +629,15 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
517
  <button type="button" className="cg-w44-route-more" aria-label={`Actions for ${item.name}`}
518
  aria-expanded={menuId === item.id} onClick={() => setMenuId(menuId === item.id ? null : item.id)}>...</button>
519
  {menuId === item.id && <div className="cg-w44-route-menu" role="menu">
520
- <button type="button" role="menuitem" disabled={!item.permission.canEdit}
521
  onClick={() => { setRenameId(item.id); setRenameDraft(item.name); setMenuId(null); }}>Rename</button>
522
- <button type="button" role="menuitem" onClick={() => { setMenuId(null); finish(onDuplicate(item)); }}>Duplicate</button>
523
- <button type="button" role="menuitem" disabled={!item.permission.canEdit}
 
 
 
 
 
524
  onClick={() => { setMenuId(null); finish(onShare(item)); }}>Share</button>
525
  {folders.map((folder) => <button type="button" role="menuitem" key={folder.id}
526
  onClick={() => { setMenuId(null); finish(onRouteMove(item, folder.id)); }}>Move to {folder.name}</button>)}
@@ -530,7 +647,7 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
530
  onClick={() => { const next = swap(routeIds, item.id, -1); if (next) finish(onRouteReorder(next)); }}>Move up</button>
531
  <button type="button" role="menuitem" disabled={index === routeIds.length - 1 || busy}
532
  onClick={() => { const next = swap(routeIds, item.id, 1); if (next) finish(onRouteReorder(next)); }}>Move down</button>
533
- <button type="button" role="menuitem" disabled={!item.permission.canEdit}
534
  onClick={() => { setMenuId(null); if (window.confirm(`Delete ${item.name}?`)) finish(onDelete(item)); }}>Delete</button>
535
  </div>}
536
  </div>
 
5
  import { boundedGoogleMapsUrl } from "./routeZoneTypes";
6
  import type {
7
  MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate,
8
+ RouteAssignee, RouteDeliveryDto, RouteDeliveryRequest,
9
  } from "./routeZoneTypes";
10
  import "../styles/wave42/route-nav.css";
11
 
12
  type Result = Promise<string | null>;
13
 
14
+ type RouteAction = "rename" | "duplicate" | "star" | "share" | "delete";
15
+
16
+ function mayRouteAction(route: MapRouteDto, action: RouteAction): boolean {
17
+ return route.compatibility !== "legacy-route-order" && route.capabilities?.[action] === true;
18
+ }
19
+
20
  export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources, storageKey,
21
  createdRoute, onCreatedDismiss, onToggle, onActiveRouteChange, onOpenRecord, onCreate,
22
  onMoveToOrder, onUpdate, onDuplicate, onDelete, onShare, onRouteMove, onRouteReorder,
23
  onFolderCreate, onFolderUpdate, onFolderDelete, onFolderReorder, filteredRecordCount,
24
  onSelectFiltered, onCreateStart, mapLinks, mapLinkRefusal, deliveries, onSchedule,
25
+ onDeleteDelivery, assignees, routeToday, assigneeError }: {
26
  routes: MapRouteDto[];
27
  folders: MapRouteFolderDto[];
28
  selectedIds: ReadonlySet<string>;
 
52
  mapLinks: NormalizedRouteMapLink[];
53
  mapLinkRefusal: string | null;
54
  deliveries: RouteDeliveryDto[] | null;
55
+ assignees: RouteAssignee[] | null;
56
+ routeToday: string | null;
57
+ assigneeError: string | null;
58
  onSchedule: (route: MapRouteDto, request: RouteDeliveryRequest) => Result;
59
  onDeleteDelivery: (route: MapRouteDto, delivery: RouteDeliveryDto) => Result;
60
  }) {
 
73
  const [orderErrors, setOrderErrors] = useState<Record<number, string>>({});
74
  const [editName, setEditName] = useState("");
75
  const [editMapsUrl, setEditMapsUrl] = useState("");
76
+ const [assignmentAssignee, setAssignmentAssignee] = useState("");
77
+ const [assignmentDate, setAssignmentDate] = useState("");
78
+ const [assignmentNotice, setAssignmentNotice] = useState<string | null>(null);
79
+ const [assignmentError, setAssignmentError] = useState<string | null>(null);
80
+ const [assignmentBusy, setAssignmentBusy] = useState(false);
81
  const [deleteConfirm, setDeleteConfirm] = useState(false);
82
  const [menuId, setMenuId] = useState<string | null>(null);
83
  const [renameId, setRenameId] = useState<string | null>(null);
 
93
  const route = activeRouteId ? routes.find((item) => item.id === activeRouteId) : null;
94
  const source = sources.find((item) => item.id === sourceId) || sources[0];
95
  const mapsUrl = boundedGoogleMapsUrl(route?.mapsUrl);
96
+ const assigneeNames = useMemo(
97
+ () => new Set((assignees || []).map((person) => person.username)),
98
+ [assignees]
99
+ );
100
+ const savedAssigneeUnavailable = Boolean(
101
+ route?.assignee && !assigneeNames.has(route.assignee)
102
+ );
103
  const knownFolders = useMemo(() => new Set(folders.map((folder) => folder.id)), [folders]);
104
  const validAt = resolveStoredPath(at, knownFolders);
105
  const level = useMemo(
 
139
  setMapCopyNotice(null);
140
  setMapCopyError(null);
141
  }, [route?.id, route?.mapsUrl, route?.name]);
142
+ useEffect(() => {
143
+ setAssignmentAssignee(route?.assignee || "");
144
+ setAssignmentDate(route?.date || "");
145
+ }, [route?.assignee, route?.date, route?.id]);
146
+ useEffect(() => {
147
+ setAssignmentNotice(null);
148
+ setAssignmentError(null);
149
+ }, [route?.id]);
150
 
151
  const copyMapLinks = () => {
152
  setMapCopyNotice(null);
 
182
  }).finally(() => setDeliveryBusy(false));
183
  };
184
 
185
+ const saveAssignment = (target: MapRouteDto, clear = false) => {
186
+ const assignee = clear ? "" : assignmentAssignee.trim().toLowerCase();
187
+ const date = clear ? "" : assignmentDate.trim();
188
+ if (Boolean(assignee) !== Boolean(date)) {
189
+ setAssignmentError("Choose both a person and a date, or clear both.");
190
+ return;
191
+ }
192
+ if (assignee && (!assignees || !assigneeNames.has(assignee))) {
193
+ setAssignmentError("Choose a currently permitted person.");
194
+ return;
195
+ }
196
+ setAssignmentBusy(true);
197
+ setAssignmentError(null);
198
+ setAssignmentNotice(null);
199
+ void onUpdate(target, {
200
+ assignee: assignee || null,
201
+ date: date || null,
202
+ }).then((message) => {
203
+ if (message) setAssignmentError(message);
204
+ else {
205
+ setAssignmentAssignee(assignee);
206
+ setAssignmentDate(date);
207
+ setAssignmentNotice(assignee
208
+ ? `${target.name} is assigned for ${date}.`
209
+ : `${target.name} is unassigned.`);
210
+ }
211
+ }).finally(() => setAssignmentBusy(false));
212
+ };
213
+
214
  const removeDelivery = (target: MapRouteDto, delivery: RouteDeliveryDto) => {
215
  setDeliveryBusy(true);
216
  setDeliveryError(null);
 
402
  </div>
403
  ) : <p className="cg-w44-route-empty">{route.compatibility === "legacy-route-order"
404
  ? "This legacy Route is read-only." : "Only the owner and an editor of the source View can change this Route."}</p>}
405
+ {canEdit && (
406
+ <section className="cg-w44-route-delivery cg-w45-route-assignment"
407
+ aria-labelledby="cg-route-assignment-title">
408
+ <div>
409
+ <h3 id="cg-route-assignment-title">Route assignment</h3>
410
+ <p>Creates an internal Inbox task on the selected date. No message is sent.</p>
411
+ </div>
412
+ <label className="cg-w44-route-label">Assignee
413
+ <select className="cg-input" value={assignmentAssignee}
414
+ disabled={assignmentBusy || assignees === null}
415
+ onChange={(event) => {
416
+ setAssignmentAssignee(event.target.value);
417
+ setAssignmentError(null);
418
+ setAssignmentNotice(null);
419
+ }}>
420
+ <option value="">Unassigned</option>
421
+ {savedAssigneeUnavailable && route.assignee && (
422
+ <option value={route.assignee} disabled>{route.assignee} (unavailable)</option>
423
+ )}
424
+ {(assignees || []).map((person) => (
425
+ <option key={person.username} value={person.username}>
426
+ {person.name} ({person.username})
427
+ </option>
428
+ ))}
429
+ </select>
430
+ </label>
431
+ <label className="cg-w44-route-label">Date
432
+ <input className="cg-input" type="date" min={routeToday || undefined}
433
+ value={assignmentDate} disabled={assignmentBusy}
434
+ onChange={(event) => {
435
+ setAssignmentDate(event.target.value);
436
+ setAssignmentError(null);
437
+ setAssignmentNotice(null);
438
+ }} />
439
+ </label>
440
+ <div className="cg-form-actions">
441
+ <button type="button" className="cg-btn cg-btn--primary"
442
+ disabled={assignmentBusy
443
+ || Boolean(assignmentAssignee) !== Boolean(assignmentDate)
444
+ || (Boolean(assignmentAssignee) && (assignees === null || !assigneeNames.has(assignmentAssignee)))
445
+ || (assignmentAssignee === (route.assignee || "") && assignmentDate === (route.date || ""))}
446
+ onClick={() => saveAssignment(route)}>
447
+ {assignmentBusy ? "Saving" : "Save assignment"}
448
+ </button>
449
+ {(route.assignee || route.date) && (
450
+ <button type="button" className="cg-btn" disabled={assignmentBusy}
451
+ onClick={() => saveAssignment(route, true)}>Clear assignment</button>
452
+ )}
453
+ </div>
454
+ {assigneeError && <span className="cg-w44-route-warning" role="alert">{assigneeError}</span>}
455
+ {assignmentNotice && <span className="cg-w44-route-empty" role="status">{assignmentNotice}</span>}
456
+ {assignmentError && <span className="cg-w44-route-warning" role="alert">{assignmentError}</span>}
457
+ </section>
458
+ )}
459
  {canEdit && (
460
  <section className="cg-w44-route-delivery" aria-labelledby="cg-route-delivery-title">
461
  <div>
 
629
  <button type="button" className="cg-w44-route-more" aria-label={`Actions for ${item.name}`}
630
  aria-expanded={menuId === item.id} onClick={() => setMenuId(menuId === item.id ? null : item.id)}>...</button>
631
  {menuId === item.id && <div className="cg-w44-route-menu" role="menu">
632
+ <button type="button" role="menuitem" disabled={!mayRouteAction(item, "rename")}
633
  onClick={() => { setRenameId(item.id); setRenameDraft(item.name); setMenuId(null); }}>Rename</button>
634
+ <button type="button" role="menuitem" disabled={!mayRouteAction(item, "duplicate")}
635
+ onClick={() => { setMenuId(null); finish(onDuplicate(item)); }}>Duplicate</button>
636
+ <button type="button" role="menuitem" disabled={!mayRouteAction(item, "star")}
637
+ onClick={() => { setMenuId(null); finish(onUpdate(item, { starred: !item.starred })); }}>
638
+ {item.starred ? "Unstar" : "Star"}
639
+ </button>
640
+ <button type="button" role="menuitem" disabled={!mayRouteAction(item, "share")}
641
  onClick={() => { setMenuId(null); finish(onShare(item)); }}>Share</button>
642
  {folders.map((folder) => <button type="button" role="menuitem" key={folder.id}
643
  onClick={() => { setMenuId(null); finish(onRouteMove(item, folder.id)); }}>Move to {folder.name}</button>)}
 
647
  onClick={() => { const next = swap(routeIds, item.id, -1); if (next) finish(onRouteReorder(next)); }}>Move up</button>
648
  <button type="button" role="menuitem" disabled={index === routeIds.length - 1 || busy}
649
  onClick={() => { const next = swap(routeIds, item.id, 1); if (next) finish(onRouteReorder(next)); }}>Move down</button>
650
+ <button type="button" role="menuitem" disabled={!mayRouteAction(item, "delete")}
651
  onClick={() => { setMenuId(null); if (window.confirm(`Delete ${item.name}?`)) finish(onDelete(item)); }}>Delete</button>
652
  </div>}
653
  </div>