fsanyoto commited on
Commit
2680976
Β·
verified Β·
1 Parent(s): ea2c336

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,6 +1,12 @@
1
  {
2
- "current": "v3 (6b9fa62)",
3
  "releases": [
 
 
 
 
 
 
4
  {
5
  "version": "v3",
6
  "sha": "6b9fa62",
 
1
  {
2
+ "current": "v4 (de5037f)",
3
  "releases": [
4
+ {
5
+ "version": "v4",
6
+ "sha": "de5037f",
7
+ "date": "2026-08-05",
8
+ "subject": "release v4"
9
+ },
10
  {
11
  "version": "v3",
12
  "sha": "6b9fa62",
VERSION CHANGED
@@ -1 +1 @@
1
- v3 (6b9fa62)
 
1
+ v4 (de5037f)
api/routes_alerts.py CHANGED
@@ -1,233 +1,254 @@
1
- """routes_alerts.py β€” the Alerts module (wave 20, owner item 25, contract C-ALERT).
2
-
3
- GET /api/v1/alerts -> {alerts:[...]}
4
- POST /api/v1/alerts <- {viewId, topic, label?}
5
- DELETE /api/v1/alerts/{alert_id}
6
- POST /api/v1/alerts/{alert_id}/run -> evaluate now (the pane's manual refresh)
7
- GET /api/v1/notifications -> {unread, items:[...]}
8
- POST /api/v1/notifications/read <- {ids:[...]|null, read?:bool}
9
-
10
- The semantics β€” an alert is a view plus a remembered matched set, a notification is a NEW
11
- ENTRANT, and the first evaluation seeds silently β€” live in `core.alerts` with the reasoning.
12
- This file owns the two things a route must: WHO may do it, and HOW the view gets evaluated.
13
-
14
- ⭐ **THE EVALUATION RUNS AS THE ALERT'S OWNER, NOT AS THE CALLER.** `_run_alert` builds the pool
15
- for `rec['owner']`, never for whoever tripped the write hook. Any other choice leaks: a
16
- full-access admin editing a cell would otherwise evaluate a BU-scoped user's alert over the whole
17
- book, and the notification would name customers that user may not see β€” a permission leak wearing
18
- a notification's clothes. The owner's own scope is the only correct basis for their alert.
19
-
20
- ⚠ **AN ALERT IS NOT A SECOND READ PATH.** It resolves rows through the same
21
- `routes_customers.grid_assembly` / `routes_tables.ut_assembly` the grid uses, so a row that an
22
- alert can see is by construction a row its owner could open. Re-implementing the filter here
23
- would be a second definition of "matches", and those two would drift.
24
- """
25
- from fastapi import APIRouter, Body, Depends
26
-
27
- import core.alerts as alerts
28
- from deps import Session, err, require_session
29
-
30
- router = APIRouter(prefix="/api/v1")
31
-
32
- #: The alert-bearing surfaces. `ut_` tables are admitted by prefix, like everywhere else.
33
- _TOPICS = ("customer", "product")
34
-
35
-
36
- def _topic_or_400(raw):
37
- topic = str(raw or "").strip().lower()
38
- if topic.startswith("ut_") or topic in _TOPICS:
39
- return topic
40
- raise err(400, "bad_topic", f"topic must be one of {', '.join(_TOPICS)} or a ut_ table")
41
-
42
-
43
- def _owner_session(session: Session, owner: str):
44
- """A `Session` for the alert's OWNER (see the module note on why the owner, not the caller).
45
-
46
- ⚠ `Session` exposes `uname`/`admin` as PROPERTIES derived from `user`, not as fields β€” so an
47
- owner session is built by swapping the `user` RECORD and letting both derive themselves. An
48
- earlier version passed `uname=`/`admin=` to the constructor, which would have raised on the
49
- first write hook of the wave; the properties are the single definition of who a session is,
50
- and going around them is how a session with an admin flag and a non-admin record exists.
51
-
52
- Returns None when the owner is gone or deactivated β€” their alerts then stop evaluating rather
53
- than evaluating as somebody else, which is the fail-closed direction.
54
- """
55
- import core.users as users
56
-
57
- if str(owner) == str(session.uname):
58
- return session
59
- rec = (users.registry() or {}).get(str(owner))
60
- if not isinstance(rec, dict) or not rec.get("active", True):
61
- return None
62
- # `_public` is THE definition of what a session may know about its own account (never a hash
63
- # or a salt) β€” the same one `routes_auth` uses. Building the dict by hand here would be a
64
- # second definition, and the one that leaks is always the copy.
65
- return Session(tenant=session.tenant, user=users._public(str(owner), rec),
66
- claims=session.claims, runtime=session.runtime)
67
-
68
-
69
- def _evaluate(session: Session, rec: dict):
70
- """Resolve `rec`'s view over its topic AS THE ALERT'S OWNER, then fold the result in."""
71
- import aios_grid
72
- from harness import filter_eval
73
-
74
- owner_sess = _owner_session(session, rec.get("owner"))
75
- if owner_sess is None:
76
- return {"skipped": "owner_unavailable"}
77
- topic = str(rec.get("topic") or "")
78
- try:
79
- if topic.startswith("ut_"):
80
- from routes_tables import ut_assembly
81
- g = ut_assembly(owner_sess, topic,
82
- storage_key=f"{owner_sess.tenant}:{topic}:{owner_sess.uname}")
83
- else:
84
- from routes_customers import grid_assembly
85
- g = grid_assembly(owner_sess, scope=topic, consume_corrections=False)
86
- except Exception as e: # noqa: BLE001
87
- return {"skipped": "unavailable", "detail": type(e).__name__}
88
-
89
- view = (g.get("views") or {}).get(str(rec.get("viewId")))
90
- if not isinstance(view, dict):
91
- # Deleted, or un-shared out from under the alert. Say so on the RECORD rather than
92
- # deleting the alert: an alert that silently vanishes is indistinguishable from one that
93
- # never fires, and the user cannot debug what is not there.
94
- return {"skipped": "view_missing"}
95
-
96
- # The SAME row build the grid and `/customers` use β€” `rows_from_pool` is what puts derived
97
- # and overlay values on a row. Evaluating a filter against raw pool dicts would silently
98
- # never match any condition on a user-created or measure column.
99
- rows = aios_grid.rows_from_pool(g["rows_src"], g["fields"], g["ws"].get("overlays"),
100
- derived=g.get("derived"))
101
- config = view.get("config") or view
102
- ctx = filter_eval.EvalCtx(
103
- cohort_sets={str(k): {str(p) for p in (v.get("memberPids") or ())}
104
- for k, v in (g.get("lists") or {}).items() if isinstance(v, dict)},
105
- measure_sets=g.get("measure_sets") or {},
106
- today=g.get("today"))
107
- pids = filter_eval.visible_pids(config.get("filters") or [], rows, g["fields"], ctx,
108
- member_pids=config.get("memberPids"))
109
- labels = {str(r.get("pid")): str(r.get("name") or r.get("pid")) for r in rows}
110
- return alerts.evaluate(rec.get("id"), [str(p) for p in pids],
111
- labels=labels, partial=False, st=session.runtime)
112
-
113
-
114
- @router.get("/alerts")
115
- def list_alerts(session: Session = Depends(require_session)):
116
- return {"alerts": alerts.list_alerts(user=session.uname, is_admin=session.admin,
117
- st=session.runtime)}
118
-
119
-
120
- @router.post("/alerts")
121
- def create_alert(body: dict = Body(default=None), session: Session = Depends(require_session)):
122
- body = body or {}
123
- view_id = str(body.get("viewId") or "").strip()
124
- if not view_id:
125
- raise err(400, "bad_view", "an alert needs the id of the view it watches")
126
- topic = _topic_or_400(body.get("topic"))
127
- _require_filtered_view(session, topic, view_id)
128
- import uuid
129
- aid = f"al_{uuid.uuid4().hex[:12]}"
130
- rec = alerts.create(aid, view_id=view_id, topic=topic, owner=session.uname,
131
- label=body.get("label") or "", st=session.runtime)
132
- # SEED IMMEDIATELY, so the alert starts from "everything currently matching is old news".
133
- # Deferring this to the first write hook would mean the next edit announces the whole view.
134
- outcome = _evaluate(session, rec)
135
- return {"alert": {**rec, "seeded": True}, "first": outcome}
136
-
137
-
138
- def _require_filtered_view(session: Session, topic: str, view_id: str):
139
- """400 unless `view_id` exists on `topic` AND actually narrows something.
140
-
141
- β›” AN ALERT ON AN UNFILTERED VIEW IS SILENTLY INCAPABLE OF ALERTING, which is worse than one
142
- that is refused. `filter_eval` treats an inactive tree as "no narrowing, every row shows"
143
- (`visible_pids`'s own rule), so such an alert seeds with the entire table and can never see an
144
- entrant again β€” there is nothing left to enter. The owner's words are *"when a Record gets
145
- into that Filter's criteria"*: no criteria, no alert, and said at creation rather than
146
- discovered by never being notified.
147
-
148
- `is_rule_active` is the SAME activeness predicate the engine and the column tints use β€” a
149
- half-typed rule is not a filter, and this must agree with what actually narrows or it would
150
- accept a view whose one rule the engine then ignores.
151
- """
152
- from harness import filter_eval
153
-
154
- try:
155
- if topic.startswith("ut_"):
156
- from routes_tables import ut_assembly
157
- g = ut_assembly(session, topic,
158
- storage_key=f"{session.tenant}:{topic}:{session.uname}")
159
- else:
160
- from routes_customers import grid_assembly
161
- g = grid_assembly(session, scope=topic, consume_corrections=False)
162
- except Exception: # noqa: BLE001
163
- raise err(503, "unavailable", "the table is unavailable β€” try again in a moment")
164
- view = (g.get("views") or {}).get(str(view_id))
165
- if not isinstance(view, dict):
166
- raise err(404, "no_view", "that view does not exist on this table")
167
- nodes, _conj = filter_eval.tree_parts((view.get("config") or view).get("filters") or [])
168
-
169
- def _any_active(ns):
170
- for n in ns or ():
171
- if isinstance(n, dict) and isinstance(n.get("children"), list):
172
- if _any_active(n["children"]):
173
- return True
174
- elif filter_eval.is_rule_active(n):
175
- return True
176
- return False
177
-
178
- if not _any_active(nodes):
179
- raise err(400, "no_filter",
180
- "this view has no active filter, so no record can ever ENTER it β€” add a "
181
- "condition to the view first, then create the alert")
182
-
183
-
184
- @router.delete("/alerts/{alert_id}")
185
- def delete_alert(alert_id: str, session: Session = Depends(require_session)):
186
- rec = next((r for r in alerts.list_alerts(st=session.runtime)
187
- if str(r.get("id")) == str(alert_id)), None)
188
- if rec is None:
189
- raise err(404, "no_alert", "that alert does not exist")
190
- if str(rec.get("owner")) != str(session.uname) and not session.admin:
191
- raise err(403, "not_yours", "only the alert's owner (or an administrator) can delete it")
192
- alerts.delete(alert_id, st=session.runtime)
193
- return {"ok": True}
194
-
195
-
196
- @router.post("/alerts/{alert_id}/run")
197
- def run_alert(alert_id: str, session: Session = Depends(require_session)):
198
- rec = next((r for r in alerts.list_alerts(user=session.uname, is_admin=session.admin,
199
- st=session.runtime)
200
- if str(r.get("id")) == str(alert_id)), None)
201
- if rec is None:
202
- raise err(404, "no_alert", "that alert does not exist")
203
- return _evaluate(session, rec)
204
-
205
-
206
- @router.get("/notifications")
207
- def notifications(session: Session = Depends(require_session)):
208
- return alerts.inbox(session.uname, st=session.runtime)
209
-
210
-
211
- @router.post("/notifications/read")
212
- def read_notifications(body: dict = Body(default=None),
213
- session: Session = Depends(require_session)):
214
- body = body or {}
215
- ids = body.get("ids")
216
- if ids is not None and not isinstance(ids, list):
217
- raise err(400, "bad_ids", "ids must be a list, or null to mark every notification")
218
- return alerts.mark_read(session.uname, ids, read=bool(body.get("read", True)),
219
- st=session.runtime)
220
-
221
-
222
- def after_write(session: Session, topic_key: str):
223
- """THE WRITE HOOK β€” call after a write that could change what a view matches.
224
-
225
- Exported as a plain function (not a route) so `core.grid_events`' callers and S2's automation
226
- upserts reach it the same way. It never raises: an alert evaluation failing must not fail the
227
- edit that triggered it.
228
- """
229
- try:
230
- return alerts.after_write(topic_key, st=session.runtime,
231
- runner=lambda rec: _evaluate(session, rec))
232
- except Exception: # noqa: BLE001
233
- return {"evaluated": 0}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """routes_alerts.py β€” the Alerts module (wave 20, owner item 25, contract C-ALERT).
2
+
3
+ GET /api/v1/alerts -> {alerts:[...]}
4
+ POST /api/v1/alerts <- {viewId, topic, label?}
5
+ DELETE /api/v1/alerts/{alert_id}
6
+ POST /api/v1/alerts/{alert_id}/run -> evaluate now (the pane's manual refresh)
7
+ GET /api/v1/notifications -> {unread, items:[...]}
8
+ POST /api/v1/notifications/read <- {ids:[...]|null, read?:bool}
9
+
10
+ The semantics β€” an alert is a view plus a remembered matched set, a notification is a NEW
11
+ ENTRANT, and the first evaluation seeds silently β€” live in `core.alerts` with the reasoning.
12
+ This file owns the two things a route must: WHO may do it, and HOW the view gets evaluated.
13
+
14
+ ⭐ **THE EVALUATION RUNS AS THE ALERT'S OWNER, NOT AS THE CALLER.** `_run_alert` builds the pool
15
+ for `rec['owner']`, never for whoever tripped the write hook. Any other choice leaks: a
16
+ full-access admin editing a cell would otherwise evaluate a BU-scoped user's alert over the whole
17
+ book, and the notification would name customers that user may not see β€” a permission leak wearing
18
+ a notification's clothes. The owner's own scope is the only correct basis for their alert.
19
+
20
+ ⚠ **AN ALERT IS NOT A SECOND READ PATH.** It resolves rows through the same
21
+ `routes_customers.grid_assembly` / `routes_tables.ut_assembly` the grid uses, so a row that an
22
+ alert can see is by construction a row its owner could open. Re-implementing the filter here
23
+ would be a second definition of "matches", and those two would drift.
24
+ """
25
+ from fastapi import APIRouter, Body, Depends
26
+
27
+ import core.alerts as alerts
28
+ from deps import Session, err, require_session
29
+
30
+ router = APIRouter(prefix="/api/v1")
31
+
32
+ #: The alert-bearing surfaces. `ut_` tables are admitted by prefix, like everywhere else.
33
+ _TOPICS = ("customer", "product")
34
+
35
+
36
+ def _topic_or_400(raw):
37
+ topic = str(raw or "").strip().lower()
38
+ if topic.startswith("ut_") or topic in _TOPICS:
39
+ return topic
40
+ raise err(400, "bad_topic", f"topic must be one of {', '.join(_TOPICS)} or a ut_ table")
41
+
42
+
43
+ def _owner_session(session: Session, owner: str):
44
+ """A `Session` for the alert's OWNER (see the module note on why the owner, not the caller).
45
+
46
+ ⚠ `Session` exposes `uname`/`admin` as PROPERTIES derived from `user`, not as fields β€” so an
47
+ owner session is built by swapping the `user` RECORD and letting both derive themselves. An
48
+ earlier version passed `uname=`/`admin=` to the constructor, which would have raised on the
49
+ first write hook of the wave; the properties are the single definition of who a session is,
50
+ and going around them is how a session with an admin flag and a non-admin record exists.
51
+
52
+ Returns None when the owner is gone or deactivated β€” their alerts then stop evaluating rather
53
+ than evaluating as somebody else, which is the fail-closed direction.
54
+ """
55
+ import core.users as users
56
+
57
+ if str(owner) == str(session.uname):
58
+ return session
59
+ rec = (users.registry() or {}).get(str(owner))
60
+ if not isinstance(rec, dict) or not rec.get("active", True):
61
+ return None
62
+ # `_public` is THE definition of what a session may know about its own account (never a hash
63
+ # or a salt) β€” the same one `routes_auth` uses. Building the dict by hand here would be a
64
+ # second definition, and the one that leaks is always the copy.
65
+ return Session(tenant=session.tenant, user=users._public(str(owner), rec),
66
+ claims=session.claims, runtime=session.runtime)
67
+
68
+
69
+ def _evaluate(session: Session, rec: dict):
70
+ """Resolve `rec`'s view over its topic AS THE ALERT'S OWNER, then fold the result in."""
71
+ import aios_grid
72
+ from harness import filter_eval
73
+
74
+ owner_sess = _owner_session(session, rec.get("owner"))
75
+ if owner_sess is None:
76
+ return {"skipped": "owner_unavailable"}
77
+ topic = str(rec.get("topic") or "")
78
+ try:
79
+ if topic.startswith("ut_"):
80
+ from routes_tables import ut_assembly
81
+ g = ut_assembly(owner_sess, topic,
82
+ storage_key=f"{owner_sess.tenant}:{topic}:{owner_sess.uname}")
83
+ else:
84
+ from routes_customers import grid_assembly
85
+ g = grid_assembly(owner_sess, scope=topic, consume_corrections=False)
86
+ except Exception as e: # noqa: BLE001
87
+ return {"skipped": "unavailable", "detail": type(e).__name__}
88
+
89
+ view = (g.get("views") or {}).get(str(rec.get("viewId")))
90
+ if not isinstance(view, dict):
91
+ # Deleted, or un-shared out from under the alert. Say so on the RECORD rather than
92
+ # deleting the alert: an alert that silently vanishes is indistinguishable from one that
93
+ # never fires, and the user cannot debug what is not there.
94
+ return {"skipped": "view_missing"}
95
+
96
+ # The SAME row build the grid and `/customers` use β€” `rows_from_pool` is what puts derived
97
+ # and overlay values on a row. Evaluating a filter against raw pool dicts would silently
98
+ # never match any condition on a user-created or measure column.
99
+ rows = aios_grid.rows_from_pool(g["rows_src"], g["fields"], g["ws"].get("overlays"),
100
+ derived=g.get("derived"))
101
+ config = view.get("config") or view
102
+ ctx = filter_eval.EvalCtx(
103
+ cohort_sets={str(k): {str(p) for p in (v.get("memberPids") or ())}
104
+ for k, v in (g.get("lists") or {}).items() if isinstance(v, dict)},
105
+ measure_sets=g.get("measure_sets") or {},
106
+ today=g.get("today"))
107
+ pids = filter_eval.visible_pids(config.get("filters") or [], rows, g["fields"], ctx,
108
+ member_pids=config.get("memberPids"))
109
+ labels = {str(r.get("pid")): str(r.get("name") or r.get("pid")) for r in rows}
110
+ return alerts.evaluate(rec.get("id"), [str(p) for p in pids],
111
+ labels=labels, partial=False, st=session.runtime)
112
+
113
+
114
+ @router.get("/alerts")
115
+ def list_alerts(session: Session = Depends(require_session)):
116
+ return {"alerts": alerts.list_alerts(user=session.uname, is_admin=session.admin,
117
+ st=session.runtime)}
118
+
119
+
120
+ @router.post("/alerts")
121
+ def create_alert(body: dict = Body(default=None), session: Session = Depends(require_session)):
122
+ body = body or {}
123
+ view_id = str(body.get("viewId") or "").strip()
124
+ if not view_id:
125
+ raise err(400, "bad_view", "an alert needs the id of the view it watches")
126
+ topic = _topic_or_400(body.get("topic"))
127
+ _require_filtered_view(session, topic, view_id)
128
+ import uuid
129
+ aid = f"al_{uuid.uuid4().hex[:12]}"
130
+ rec = alerts.create(aid, view_id=view_id, topic=topic, owner=session.uname,
131
+ label=body.get("label") or "", st=session.runtime)
132
+ # SEED IMMEDIATELY, so the alert starts from "everything currently matching is old news".
133
+ # Deferring this to the first write hook would mean the next edit announces the whole view.
134
+ outcome = _evaluate(session, rec)
135
+ return {"alert": {**rec, "seeded": True}, "first": outcome}
136
+
137
+
138
+ def _require_filtered_view(session: Session, topic: str, view_id: str):
139
+ """400 unless `view_id` exists on `topic` AND actually narrows something.
140
+
141
+ β›” AN ALERT ON AN UNFILTERED VIEW IS SILENTLY INCAPABLE OF ALERTING, which is worse than one
142
+ that is refused. `filter_eval` treats an inactive tree as "no narrowing, every row shows"
143
+ (`visible_pids`'s own rule), so such an alert seeds with the entire table and can never see an
144
+ entrant again β€” there is nothing left to enter. The owner's words are *"when a Record gets
145
+ into that Filter's criteria"*: no criteria, no alert, and said at creation rather than
146
+ discovered by never being notified.
147
+
148
+ `is_rule_active` is the SAME activeness predicate the engine and the column tints use β€” a
149
+ half-typed rule is not a filter, and this must agree with what actually narrows or it would
150
+ accept a view whose one rule the engine then ignores.
151
+ """
152
+ from harness import filter_eval
153
+
154
+ try:
155
+ if topic.startswith("ut_"):
156
+ from routes_tables import ut_assembly
157
+ g = ut_assembly(session, topic,
158
+ storage_key=f"{session.tenant}:{topic}:{session.uname}")
159
+ else:
160
+ from routes_customers import grid_assembly
161
+ g = grid_assembly(session, scope=topic, consume_corrections=False)
162
+ except Exception: # noqa: BLE001
163
+ raise err(503, "unavailable", "the table is unavailable β€” try again in a moment")
164
+ view = (g.get("views") or {}).get(str(view_id))
165
+ if not isinstance(view, dict):
166
+ raise err(404, "no_view", "that view does not exist on this table")
167
+ nodes, _conj = filter_eval.tree_parts((view.get("config") or view).get("filters") or [])
168
+
169
+ def _any_active(ns):
170
+ for n in ns or ():
171
+ if isinstance(n, dict) and isinstance(n.get("children"), list):
172
+ if _any_active(n["children"]):
173
+ return True
174
+ elif filter_eval.is_rule_active(n):
175
+ return True
176
+ return False
177
+
178
+ if not _any_active(nodes):
179
+ raise err(400, "no_filter",
180
+ "this view has no active filter, so no record can ever ENTER it β€” add a "
181
+ "condition to the view first, then create the alert")
182
+
183
+
184
+ @router.delete("/alerts/{alert_id}")
185
+ def delete_alert(alert_id: str, session: Session = Depends(require_session)):
186
+ rec = next((r for r in alerts.list_alerts(st=session.runtime)
187
+ if str(r.get("id")) == str(alert_id)), None)
188
+ if rec is None:
189
+ raise err(404, "no_alert", "that alert does not exist")
190
+ if str(rec.get("owner")) != str(session.uname) and not session.admin:
191
+ raise err(403, "not_yours", "only the alert's owner (or an administrator) can delete it")
192
+ alerts.delete(alert_id, st=session.runtime)
193
+ return {"ok": True}
194
+
195
+
196
+ @router.post("/alerts/{alert_id}/run")
197
+ def run_alert(alert_id: str, session: Session = Depends(require_session)):
198
+ rec = next((r for r in alerts.list_alerts(user=session.uname, is_admin=session.admin,
199
+ st=session.runtime)
200
+ if str(r.get("id")) == str(alert_id)), None)
201
+ if rec is None:
202
+ raise err(404, "no_alert", "that alert does not exist")
203
+ return _evaluate(session, rec)
204
+
205
+
206
+ @router.get("/notifications")
207
+ def notifications(session: Session = Depends(require_session)):
208
+ """The inbox β€” RE-EVALUATED on read, which is a deliberate design choice.
209
+
210
+ ⭐ A-S1-2 RESOLVED THE OTHER WAY, and the reason is structural rather than a shortcut. The
211
+ plan was a push hook: the automation engine calls `after_write` when it lands rows. But
212
+ `run_async` runs on a BACKGROUND THREAD with no `Session` in scope, and an alert must be
213
+ evaluated as its OWNER (see `_evaluate`) β€” so a push hook would have to mint a session inside
214
+ a worker thread from a tenant runtime, which is exactly the kind of ad-hoc identity
215
+ construction that leaks scope.
216
+
217
+ Pulling on read has none of that: the caller IS a session, the assemblies are already
218
+ scope-cached, and the user cannot observe the difference β€” an inbox is only ever read by
219
+ someone opening it. The cost is that a notification is minted when you LOOK rather than when
220
+ the row landed, so the `at` stamp is detection time, not arrival time.
221
+
222
+ `after_write` stays exported for the day the engine can hand over a real identity.
223
+ """
224
+ for rec in alerts.list_alerts(user=session.uname, is_admin=False, st=session.runtime):
225
+ try:
226
+ _evaluate(session, rec)
227
+ except Exception: # noqa: BLE001
228
+ continue # one bad alert must not empty the pane
229
+ return alerts.inbox(session.uname, st=session.runtime)
230
+
231
+
232
+ @router.post("/notifications/read")
233
+ def read_notifications(body: dict = Body(default=None),
234
+ session: Session = Depends(require_session)):
235
+ body = body or {}
236
+ ids = body.get("ids")
237
+ if ids is not None and not isinstance(ids, list):
238
+ raise err(400, "bad_ids", "ids must be a list, or null to mark every notification")
239
+ return alerts.mark_read(session.uname, ids, read=bool(body.get("read", True)),
240
+ st=session.runtime)
241
+
242
+
243
+ def after_write(session: Session, topic_key: str):
244
+ """THE WRITE HOOK β€” call after a write that could change what a view matches.
245
+
246
+ Exported as a plain function (not a route) so `core.grid_events`' callers and S2's automation
247
+ upserts reach it the same way. It never raises: an alert evaluation failing must not fail the
248
+ edit that triggered it.
249
+ """
250
+ try:
251
+ return alerts.after_write(topic_key, st=session.runtime,
252
+ runner=lambda rec: _evaluate(session, rec))
253
+ except Exception: # noqa: BLE001
254
+ return {"evaluated": 0}
platform/core/user_tables.py CHANGED
@@ -1,517 +1,532 @@
1
- """USER-CREATED TABLES (wave-9 I8 / contract C6) β€” databases that are not a connector.
2
-
3
- The owner's "+ New" flow has two branches: connect a SOURCE (Odoo today) or *"create a completely
4
- new database blank, where this time the user can actually insert row that they want."* The first
5
- branch is the connector seam and lives in `harness/datastore.py`; THIS module is the second.
6
-
7
- WHY A SEPARATE STORE AND NOT A REGISTRY ROW. `core/registry.py` is a static Python list read at
8
- import time β€” it is the catalogue of modules the PRODUCT ships, and a tenant cannot append to it
9
- at runtime without editing code. A user-created table is tenant data, so it lives in the tenant
10
- store and is MERGED into the nav beside the registry rows. That also keeps the archived/allowed
11
- machinery honest: a user table is never "archived", it is deleted, and it is never in
12
- `allowed_modules` because it is not a module.
13
-
14
- SHAPE (one store key, `user_tables`):
15
-
16
- {table_key: {'key', 'label', 'source', 'createdBy', 'created', 'fields': [...], 'rows': {...}}}
17
-
18
- `source` is deliberately NOT 'Odoo' β€” the nav badge is generated from it, so a blank table reads
19
- "Blank" and can never be mistaken for connected data. `rows` is `{row_id: {field_key: value}}`,
20
- which is the same overlay shape `TableStore` already uses, so the grid's write path needs no new
21
- storage concept.
22
-
23
- ⚠ ROW WRITES ARE ONLY EVER LEGAL HERE. An Odoo-sourced table is READ-ONLY at the source and the
24
- row endpoints refuse unless `is_user_table(key)` β€” a user must not be able to invent a customer
25
- in Odoo by typing into a grid. (Wave 18 note: the events seam has NO row event types; row
26
- add/delete are REST endpoints on `aios-web/api/routes_tables.py`, and this predicate is their
27
- wall.)
28
-
29
- WAVE 18 (C3-UT): every function takes an optional `st` STORE HANDLE β€” anything exposing
30
- `get(name)` / `update(name, fn, flush=)` / `exists(name)`. Default = `core.store` (tenant #0,
31
- the Streamlit host, unchanged). The API passes the session's `TenantRuntime`, whose accessors
32
- apply the tenant prefix / repo binding, so a Nurilab table lands in Nurilab's store.
33
- """
34
- import datetime as _dt
35
- import re
36
-
37
- import core.store as store
38
-
39
- STORE_KEY = 'user_tables'
40
- MAX_TABLES = 40
41
- MAX_LABEL = 60
42
- MAX_ROWS = 5000
43
- MAX_FIELDS = 60
44
- #: the badge the nav paints for a table with no connector behind it
45
- BLANK_SOURCE = 'Blank'
46
- #: automation-created tables carry their maker instead (wave 18 C4-AUTO)
47
- AUTOMATION_SOURCE = 'Automation'
48
- #: every user table's key is prefixed, so it can never collide with a registry module key
49
- KEY_PREFIX = 'ut_'
50
-
51
- #: The field types a user table may declare. ⚠ Kept a SUBSET of
52
- #: `aios_grid.CUSTOM_FIELD_TYPES` (gated in verify_api's W18-UT section) β€” minus the two
53
- #: machine-written kinds (`formula` computes client-side over a workspace stratum; a base
54
- #: column of that type would have no author). Local literal rather than an aios_grid import so
55
- #: this module stays dependency-light for the API's boot path.
56
- UT_FIELD_TYPES = {'text', 'select', 'multiselect', 'user', 'int', 'currency', 'pct', 'date',
57
- 'checkbox', 'phone', 'email', 'url', 'rating'}
58
-
59
-
60
- def _st(st):
61
- return st if st is not None else store
62
-
63
-
64
- def _slug(label):
65
- s = re.sub(r'[^a-z0-9]+', '_', str(label or '').strip().lower()).strip('_')
66
- return (s or 'table')[:40]
67
-
68
-
69
- def clean_fields(raw):
70
- """Validate a caller-supplied field list into the stored shape β€” refuse junk, never store
71
- it. Returns a list of `{key,label,type,source}` dicts (source is always 'overlay': every
72
- base column of a user table is user-editable by construction), or None when nothing
73
- survives. Unknown types are DROPPED, not coerced β€” a column silently retyped is a lie."""
74
- out, seen = [], set()
75
- for f in (raw or [])[:MAX_FIELDS]:
76
- if not isinstance(f, dict):
77
- continue
78
- label = ' '.join(str(f.get('label') or f.get('key') or '').split())[:80]
79
- key = re.sub(r'[^a-z0-9_]+', '_', str(f.get('key') or _slug(label)).strip().lower())
80
- key = key.strip('_')[:60]
81
- ftype = str(f.get('type') or 'text').strip().lower()
82
- if not key or key in seen or ftype not in UT_FIELD_TYPES or not label:
83
- continue
84
- seen.add(key)
85
- entry = {'key': key, 'label': label, 'type': ftype, 'source': 'overlay'}
86
- if ftype in ('select', 'multiselect'):
87
- opts = [' '.join(str(o).split())[:60] for o in (f.get('options') or [])
88
- if str(o).strip()][:50]
89
- if opts:
90
- entry['options'] = opts
91
- if f.get('default') is True:
92
- entry['default'] = True
93
- out.append(entry)
94
- return out or None
95
-
96
-
97
- def all_tables(st=None):
98
- """{key: definition} β€” every user-created table in this tenant."""
99
- try:
100
- return dict(_st(st).get(STORE_KEY) or {})
101
- except Exception:
102
- return {}
103
-
104
-
105
- def get(table_key, st=None):
106
- return all_tables(st).get(str(table_key))
107
-
108
-
109
- def is_user_table(table_key, st=None):
110
- """THE permission predicate for row writes. Cheap and total: a key that is not in this store
111
- is not a user table, so it cannot accept invented rows."""
112
- return str(table_key or '').startswith(KEY_PREFIX) and get(table_key, st) is not None
113
-
114
-
115
- def create(label, username, fields=None, source=None, st=None):
116
- """Create a blank table. Returns its key, or None if refused.
117
-
118
- Refuses rather than raises on the ordinary conditions (no name, duplicate, cap reached) β€”
119
- the caller is a UI form and a refusal is a message, not an exception.
120
- """
121
- label = str(label or '').strip()[:MAX_LABEL]
122
- if not label:
123
- return None
124
- existing = all_tables(st)
125
- if len(existing) >= MAX_TABLES:
126
- return None
127
- key = KEY_PREFIX + _slug(label)
128
- if key in existing: # a second table of the same name gets a suffix
129
- for n in range(2, 50):
130
- if f'{key}_{n}' not in existing:
131
- key = f'{key}_{n}'
132
- break
133
- else:
134
- return None
135
- # A blank table still needs ONE column to be a table at all: a row with no fields cannot be
136
- # displayed, edited or identified. 'name' is the identity column, the same role `customer`
137
- # plays in the Customer table.
138
- defn = {
139
- 'key': key,
140
- 'label': label,
141
- 'source': (source if source in (BLANK_SOURCE, AUTOMATION_SOURCE) else BLANK_SOURCE),
142
- 'createdBy': username,
143
- 'created': _dt.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
144
- 'fields': clean_fields(fields) or [{'key': 'name', 'label': 'Name', 'type': 'text',
145
- 'source': 'overlay', 'default': True}],
146
- 'rows': {},
147
- }
148
-
149
- def _add(cur):
150
- cur[key] = defn
151
- return cur
152
-
153
- _st(st).update(STORE_KEY, _add, flush='sync') # a creation is not a hot path; commit it
154
- return key
155
-
156
-
157
- def delete(table_key, st=None):
158
- def _drop(cur):
159
- cur.pop(str(table_key), None)
160
- return cur
161
- _st(st).update(STORE_KEY, _drop, flush='sync')
162
-
163
-
164
- def set_fields(table_key, fields, st=None):
165
- """Replace a table's base-field contract (wave 18 β€” the automation engine grows tables it
166
- creates). Cleaned with the same validator as `create`; refuses to leave a table fieldless."""
167
- clean = clean_fields(fields)
168
- if not clean or not is_user_table(table_key, st):
169
- return False
170
-
171
- def _set(cur):
172
- t = cur.get(str(table_key))
173
- if t is not None:
174
- t['fields'] = clean
175
- return cur
176
-
177
- _st(st).update(STORE_KEY, _set, flush='sync')
178
- return True
179
-
180
-
181
- def add_row(table_key, values=None, username=None, st=None, rid=None):
182
- """Append one row. Returns the new row id, or None if refused.
183
-
184
- `rid` RESTORES A ROW UNDER ITS OLD ID (contract C-ADDROW / C-UNDO). Undo has to put a deleted
185
- row back where it was: a restore under a fresh id would break every cohort, comment and view
186
- filter that named the original, so the id is part of what is being undone. It is honoured
187
- only when that id is FREE β€” an undo can never overwrite a row somebody has since created in
188
- the gap, and it never invents a non-numeric id, because `scoped_pool` reads row ids as ints.
189
- """
190
- if not is_user_table(table_key, st):
191
- return None # ⚠ never on a connector-backed table
192
- defn = get(table_key, st) or {}
193
- rows = defn.get('rows') or {}
194
- if len(rows) >= MAX_ROWS:
195
- return None
196
- want = str(rid or '').strip()
197
- if want and want.isdigit() and want not in rows:
198
- rid = want
199
- else:
200
- rid = str(max((int(r) for r in rows if str(r).isdigit()), default=0) + 1)
201
- valid = {f['key'] for f in (defn.get('fields') or [])}
202
- clean = {k: str(v) for k, v in (values or {}).items() if k in valid}
203
-
204
- def _add(cur):
205
- t = cur.get(str(table_key))
206
- if t is not None:
207
- t.setdefault('rows', {})[rid] = clean
208
- return cur
209
-
210
- _st(st).update(STORE_KEY, _add, flush='async')
211
- return rid
212
-
213
-
214
- # β›” `upsert_rows` USED TO LIVE HERE, AND DELETING IT IS THE FIX (DEBT D-6, wave 20).
215
- #
216
- # There were TWO bulk-upsert implementations β€” this one and `automation_engine.upsert_rows` β€”
217
- # with different counts (`{updated, inserted, orphans}` vs the engine's seven, including the
218
- # `capped` count that makes a full table LOUD), a different signature (a dict keyed by value vs
219
- # a list of rows) and a different cap story. D-6 called it a "silent drift risk"; the honest
220
- # measurement is worse and simpler: **this one had zero callers, anywhere in the repo.** It was
221
- # not drifting from the engine, it was a second answer nobody had ever asked.
222
- #
223
- # So there is now one implementation because there is one implementation β€” no parity gate to
224
- # maintain, no second definition to keep in step. If a host-side bulk upsert is ever wanted, the
225
- # engine's is the one that has been exercised (verify_automation section B) and it is PURE:
226
- # `(existing, incoming, key_field, cap) -> (rows, counts)`, so it can be lifted here without its
227
- # store half coming along. Do not re-derive a new one.
228
-
229
-
230
- def set_label(table_key, label, st=None):
231
- """Rename a table IN ITS DEFINITION. Returns the stored label, or None if refused.
232
-
233
- ⚠ WAVE 20, item 6a β€” THE RENAME USED TO WRITE ONLY `nav_meta`. That bucket is the nav's
234
- display layer, so the rail showed the new name while everything reading the DEFINITION β€”
235
- the automation editor's database picker above all β€” went on showing the old one. A rename
236
- that only some surfaces can see is worse than no rename: the picker was not stale-looking,
237
- it was confidently wrong, and a user choosing "Influencers" there could be choosing the
238
- table they had renamed to something else months earlier.
239
- """
240
- label = ' '.join(str(label or '').split())[:MAX_LABEL]
241
- if not label or not is_user_table(table_key, st):
242
- return None
243
-
244
- def _set(cur):
245
- t = cur.get(str(table_key))
246
- if t is not None:
247
- t['label'] = label
248
- return cur
249
-
250
- _st(st).update(STORE_KEY, _set, flush='sync')
251
- return label
252
-
253
-
254
- # ---------------------------------------------------------------------------------------------
255
- # THE SHARED FIELD SCHEMA (contract C-FIELD, owner ruling R2)
256
- # ---------------------------------------------------------------------------------------------
257
- # R2 reverses wave 17's "fields are per-user" law FOR THIS PATH: a `ut_*` table's fields are the
258
- # TABLE'S SCHEMA, the way they are in Airtable β€” everyone with access to the database sees the
259
- # same columns, and the creator or an admin edits them. Per-field `editRole` narrows or widens
260
- # who may edit ONE column's definition without handing over the whole table.
261
- #
262
- # ⚠ `editRole` GOVERNS THE SCHEMA, NEVER THE VALUES. 'everyone' means anybody with access may
263
- # rename this column or change its options; it does not decide who may type in its cells. Those
264
- # are different questions and conflating them would let a column's own settings quietly become a
265
- # data-permission system nobody wrote.
266
-
267
- #: Who may edit ONE field's definition. Fail-closed default: admins (= creator or admin).
268
- FIELD_EDIT_ROLES = ('admins', 'everyone')
269
-
270
-
271
- def _clean_field(raw, previous=None):
272
- """One field dict β†’ the stored shape, or None. The single validator for create AND patch, so
273
- a column cannot be typed one way on the way in and another on the way back."""
274
- prev = previous or {}
275
- raw = raw if isinstance(raw, dict) else {}
276
- label = ' '.join(str(raw.get('label') or prev.get('label') or '').split())[:80]
277
- key = re.sub(r'[^a-z0-9_]+', '_',
278
- str(raw.get('key') or prev.get('key') or _slug(label)).strip().lower())
279
- key = key.strip('_')[:60]
280
- ftype = str(raw.get('type') or prev.get('type') or 'text').strip().lower()
281
- if not key or not label or ftype not in UT_FIELD_TYPES:
282
- return None
283
- out = {'key': key, 'label': label, 'type': ftype, 'source': 'overlay'}
284
- opts_raw = raw.get('options') if 'options' in raw else prev.get('options')
285
- if ftype in ('select', 'multiselect'):
286
- opts = [' '.join(str(o).split())[:60] for o in (opts_raw or []) if str(o).strip()][:50]
287
- if opts:
288
- out['options'] = opts
289
- role = str(raw.get('editRole') or prev.get('editRole') or 'admins').strip().lower()
290
- out['editRole'] = role if role in FIELD_EDIT_ROLES else 'admins'
291
- if prev.get('default') is True or raw.get('default') is True:
292
- out['default'] = True
293
- # An automation column carries the binding the engine reads; it is preserved across a patch
294
- # rather than re-declared, because the automation editor owns it and this route does not.
295
- auto = raw.get('automation') if 'automation' in raw else prev.get('automation')
296
- if isinstance(auto, dict):
297
- out['automation'] = auto
298
- return out
299
-
300
-
301
- def may_edit_field(table_key, fkey, viewer, is_admin=False, st=None):
302
- """May `viewer` change THIS column's definition? Creator/admin always; others only when the
303
- field itself says `editRole: 'everyone'`. Fail-closed on an unknown field."""
304
- if may_open(table_key, viewer, is_admin, st) and (
305
- bool(is_admin) or (get(table_key, st) or {}).get('createdBy') == viewer):
306
- return True
307
- for f in ((get(table_key, st) or {}).get('fields') or []):
308
- if f.get('key') == str(fkey):
309
- return f.get('editRole') == 'everyone'
310
- return False
311
-
312
-
313
- def add_field(table_key, raw, st=None):
314
- """Append one column to the shared schema. Returns the stored field, or None if refused."""
315
- if not is_user_table(table_key, st):
316
- return None
317
- defn = get(table_key, st) or {}
318
- have = [f for f in (defn.get('fields') or [])]
319
- if len(have) >= MAX_FIELDS:
320
- return None
321
- field = _clean_field(raw)
322
- if not field or any(f.get('key') == field['key'] for f in have):
323
- return None
324
-
325
- def _add(cur):
326
- t = cur.get(str(table_key))
327
- if t is not None:
328
- t.setdefault('fields', []).append(field)
329
- return cur
330
-
331
- _st(st).update(STORE_KEY, _add, flush='sync')
332
- return field
333
-
334
-
335
- def patch_field(table_key, fkey, raw, st=None):
336
- """Edit one column's definition IN PLACE. Returns the stored field, or None if refused.
337
-
338
- ⚠ THE KEY NEVER MOVES. A field's key is what every stored cell is filed under, so accepting
339
- a new one here would orphan every value in the column while looking like a rename. The
340
- LABEL is the renameable thing; the key is identity.
341
- """
342
- if not is_user_table(table_key, st):
343
- return None
344
- fields = [dict(f) for f in ((get(table_key, st) or {}).get('fields') or [])]
345
- idx = next((i for i, f in enumerate(fields) if f.get('key') == str(fkey)), -1)
346
- if idx < 0:
347
- return None
348
- merged = dict(raw or {})
349
- merged['key'] = str(fkey)
350
- field = _clean_field(merged, fields[idx])
351
- if not field:
352
- return None
353
-
354
- def _set(cur):
355
- t = cur.get(str(table_key))
356
- if t is not None:
357
- for i, f in enumerate(t.get('fields') or []):
358
- if f.get('key') == str(fkey):
359
- t['fields'][i] = field
360
- break
361
- return cur
362
-
363
- _st(st).update(STORE_KEY, _set, flush='sync')
364
- return field
365
-
366
-
367
- def delete_field(table_key, fkey, st=None):
368
- """Drop one column from the shared schema. Refuses to leave a table fieldless.
369
-
370
- ⚠ THE CELLS ARE LEFT IN THE ROWS ON PURPOSE. A deleted column whose values were also
371
- scrubbed makes an accidental delete unrecoverable; the values are invisible without a field
372
- declaring them, and re-adding the column with the same key brings them back. Same reasoning
373
- as `routes_tables.delete_table` leaving the workspace bucket in place. Booked, not hidden.
374
- """
375
- if not is_user_table(table_key, st):
376
- return False
377
- fields = (get(table_key, st) or {}).get('fields') or []
378
- if len(fields) <= 1 or not any(f.get('key') == str(fkey) for f in fields):
379
- return False
380
-
381
- def _drop(cur):
382
- t = cur.get(str(table_key))
383
- if t is not None:
384
- t['fields'] = [f for f in (t.get('fields') or []) if f.get('key') != str(fkey)]
385
- return cur
386
-
387
- _st(st).update(STORE_KEY, _drop, flush='sync')
388
- return True
389
-
390
-
391
- def rename_choice_values(table_key, fkey, renames, st=None):
392
- """Rename select/multiselect OPTIONS **and migrate every stored cell** (contract C-RENAME).
393
-
394
- `renames` = `[{'from': old, 'to': new}, …]` β€” an EXPLICIT MAPPING, never a diff. A diff
395
- cannot tell "renamed Blue to Navy" from "deleted Blue and added Navy", and guessing wrong
396
- empties a column silently.
397
-
398
- Returns `{'options': n, 'cells': n}`. This is the DEFINITION half β€” the base options list and
399
- the base row values. A user's per-user overlay stratum and any view filter naming the old
400
- value are `core.table_store`'s half of the same contract; the caller runs both.
401
- """
402
- pairs = []
403
- for r in (renames or [])[:50]:
404
- if not isinstance(r, dict):
405
- continue
406
- a = ' '.join(str(r.get('from') or '').split())[:60]
407
- b = ' '.join(str(r.get('to') or '').split())[:60]
408
- if a and b and a != b:
409
- pairs.append((a, b))
410
- if not pairs or not is_user_table(table_key, st):
411
- return {'options': 0, 'cells': 0}
412
- mapping = dict(pairs)
413
- counts = {'options': 0, 'cells': 0}
414
-
415
- def _apply(cur):
416
- t = cur.get(str(table_key))
417
- if t is None:
418
- return cur
419
- multi = False
420
- for f in (t.get('fields') or []):
421
- if f.get('key') != str(fkey):
422
- continue
423
- multi = f.get('type') == 'multiselect'
424
- opts = f.get('options') or []
425
- new_opts, seen = [], set()
426
- for o in opts:
427
- v = mapping.get(o, o)
428
- if v not in seen: # a rename ONTO an existing option merges them
429
- seen.add(v)
430
- new_opts.append(v)
431
- if o in mapping:
432
- counts['options'] += 1
433
- if opts:
434
- f['options'] = new_opts
435
- for row in (t.get('rows') or {}).values():
436
- if not isinstance(row, dict) or str(fkey) not in row:
437
- continue
438
- cell = str(row.get(str(fkey)) or '')
439
- if not cell:
440
- continue
441
- if multi:
442
- # ⚠ MULTISELECT CELLS ARE COMMA-JOINED LABEL STRINGS, so a rename has to walk the
443
- # parts. Rewriting the whole string would only ever hit a single-value cell.
444
- parts = [p.strip() for p in cell.split(',')]
445
- nxt = [mapping.get(p, p) for p in parts]
446
- if nxt != parts:
447
- row[str(fkey)] = ', '.join(dict.fromkeys(nxt))
448
- counts['cells'] += 1
449
- elif cell in mapping:
450
- row[str(fkey)] = mapping[cell]
451
- counts['cells'] += 1
452
- return cur
453
-
454
- _st(st).update(STORE_KEY, _apply, flush='sync')
455
- return counts
456
-
457
-
458
- def delete_row(table_key, row_id, st=None):
459
- if not is_user_table(table_key, st):
460
- return False
461
-
462
- def _drop(cur):
463
- t = cur.get(str(table_key))
464
- if t is not None:
465
- (t.get('rows') or {}).pop(str(row_id), None)
466
- return cur
467
-
468
- _st(st).update(STORE_KEY, _drop, flush='async')
469
- return True
470
-
471
-
472
- #: Names the ENGINE uses for itself when no human is on the other end of a run. β›” A table
473
- #: stamped with one of these has NO HUMAN OWNER, so `may_open` can only admit an admin β€” which
474
- #: is why the automation engine must never mint one (see `ut_ensure`'s owner rule, wave 20).
475
- #: Named here rather than inline so the two modules that care about it read the SAME list.
476
- MACHINE_OWNERS = ('automation', 'scheduler')
477
-
478
-
479
- def may_open(table_key, viewer, is_admin=False, st=None):
480
- """FAIL-CLOSED visibility: the creator, or an admin. Nothing else. **THE one resolver.**
481
-
482
- A user table cannot be gated by `allowed_modules` β€” a module grant written last month cannot
483
- describe a table created this morning β€” so it needs its own rule, and the safe rule is the
484
- narrow one. Tables are stored tenant-wide under one key, so without this ANY user (including
485
- a BU-scoped sales agent) could open a table somebody else created just by knowing its key.
486
- Sharing a user table with named colleagues is a follow-on, and it should reuse the shared-
487
- VIEW vocabulary rather than inventing a second one.
488
-
489
- β›” WAVE 20 β€” THERE WAS A SECOND, WIDER RULE, AND THE TWO DISAGREED. `routes_automation`'s
490
- table picker admitted `createdBy in (uname, 'automation', 'scheduler')`, so a non-admin could
491
- SEE an automation-created database in the picker and then be refused when they opened it,
492
- edited it, or tried to delete it. Two ideas of who owns a table is the same defect class as
493
- the two ideas of an agent's book (D-30): both surfaces look right in isolation and only
494
- disagree in front of a user. The picker now calls THIS function, and the engine stamps a
495
- real owner (see `MACHINE_OWNERS`) so nothing legitimate is narrowed by the merge.
496
- """
497
- t = get(table_key, st)
498
- if not t:
499
- return False
500
- return bool(is_admin) or t.get('createdBy') == viewer
501
-
502
-
503
- def nav_entries(viewer=None, is_admin=False, st=None):
504
- """Registry-SHAPED dicts so the nav can render user tables beside real modules with no
505
- special-casing: the same keys the flat nav reads (`key`, `label`, `source`).
506
-
507
- Filtered by `may_open`, so the nav cannot offer a row the dispatcher would refuse.
508
- """
509
- out = []
510
- for key, t in sorted(all_tables(st).items(),
511
- key=lambda kv: (kv[1].get('label') or '').lower()):
512
- if viewer is not None and not may_open(key, viewer, is_admin, st=st):
513
- continue
514
- out.append({'key': key, 'label': t.get('label') or key,
515
- 'source': t.get('source') or BLANK_SOURCE,
516
- 'user_table': True, 'nav': True, 'validate': False})
517
- return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """USER-CREATED TABLES (wave-9 I8 / contract C6) β€” databases that are not a connector.
2
+
3
+ The owner's "+ New" flow has two branches: connect a SOURCE (Odoo today) or *"create a completely
4
+ new database blank, where this time the user can actually insert row that they want."* The first
5
+ branch is the connector seam and lives in `harness/datastore.py`; THIS module is the second.
6
+
7
+ WHY A SEPARATE STORE AND NOT A REGISTRY ROW. `core/registry.py` is a static Python list read at
8
+ import time β€” it is the catalogue of modules the PRODUCT ships, and a tenant cannot append to it
9
+ at runtime without editing code. A user-created table is tenant data, so it lives in the tenant
10
+ store and is MERGED into the nav beside the registry rows. That also keeps the archived/allowed
11
+ machinery honest: a user table is never "archived", it is deleted, and it is never in
12
+ `allowed_modules` because it is not a module.
13
+
14
+ SHAPE (one store key, `user_tables`):
15
+
16
+ {table_key: {'key', 'label', 'source', 'createdBy', 'created', 'fields': [...], 'rows': {...}}}
17
+
18
+ `source` is deliberately NOT 'Odoo' β€” the nav badge is generated from it, so a blank table reads
19
+ "Blank" and can never be mistaken for connected data. `rows` is `{row_id: {field_key: value}}`,
20
+ which is the same overlay shape `TableStore` already uses, so the grid's write path needs no new
21
+ storage concept.
22
+
23
+ ⚠ ROW WRITES ARE ONLY EVER LEGAL HERE. An Odoo-sourced table is READ-ONLY at the source and the
24
+ row endpoints refuse unless `is_user_table(key)` β€” a user must not be able to invent a customer
25
+ in Odoo by typing into a grid. (Wave 18 note: the events seam has NO row event types; row
26
+ add/delete are REST endpoints on `aios-web/api/routes_tables.py`, and this predicate is their
27
+ wall.)
28
+
29
+ WAVE 18 (C3-UT): every function takes an optional `st` STORE HANDLE β€” anything exposing
30
+ `get(name)` / `update(name, fn, flush=)` / `exists(name)`. Default = `core.store` (tenant #0,
31
+ the Streamlit host, unchanged). The API passes the session's `TenantRuntime`, whose accessors
32
+ apply the tenant prefix / repo binding, so a Nurilab table lands in Nurilab's store.
33
+ """
34
+ import datetime as _dt
35
+ import re
36
+
37
+ import core.store as store
38
+
39
+ STORE_KEY = 'user_tables'
40
+ MAX_TABLES = 40
41
+ MAX_LABEL = 60
42
+ MAX_ROWS = 5000
43
+ MAX_FIELDS = 60
44
+ #: the badge the nav paints for a table with no connector behind it
45
+ BLANK_SOURCE = 'Blank'
46
+ #: automation-created tables carry their maker instead (wave 18 C4-AUTO)
47
+ AUTOMATION_SOURCE = 'Automation'
48
+ #: every user table's key is prefixed, so it can never collide with a registry module key
49
+ KEY_PREFIX = 'ut_'
50
+
51
+ #: The field types a user table may declare. ⚠ Kept a SUBSET of
52
+ #: `aios_grid.CUSTOM_FIELD_TYPES` (gated in verify_api's W18-UT section) β€” minus the two
53
+ #: machine-written kinds (`formula` computes client-side over a workspace stratum; a base
54
+ #: column of that type would have no author). Local literal rather than an aios_grid import so
55
+ #: this module stays dependency-light for the API's boot path.
56
+ UT_FIELD_TYPES = {'text', 'select', 'multiselect', 'user', 'int', 'currency', 'pct', 'date',
57
+ 'checkbox', 'phone', 'email', 'url', 'rating'}
58
+
59
+
60
+ def _st(st):
61
+ return st if st is not None else store
62
+
63
+
64
+ def _slug(label):
65
+ s = re.sub(r'[^a-z0-9]+', '_', str(label or '').strip().lower()).strip('_')
66
+ return (s or 'table')[:40]
67
+
68
+
69
+ def clean_fields(raw):
70
+ """Validate a caller-supplied field list into the stored shape β€” refuse junk, never store
71
+ it. Returns a list of `{key,label,type,source}` dicts (source is always 'overlay': every
72
+ base column of a user table is user-editable by construction), or None when nothing
73
+ survives. Unknown types are DROPPED, not coerced β€” a column silently retyped is a lie."""
74
+ out, seen = [], set()
75
+ for f in (raw or [])[:MAX_FIELDS]:
76
+ if not isinstance(f, dict):
77
+ continue
78
+ label = ' '.join(str(f.get('label') or f.get('key') or '').split())[:80]
79
+ key = re.sub(r'[^a-z0-9_]+', '_', str(f.get('key') or _slug(label)).strip().lower())
80
+ key = key.strip('_')[:60]
81
+ ftype = str(f.get('type') or 'text').strip().lower()
82
+ if not key or key in seen or ftype not in UT_FIELD_TYPES or not label:
83
+ continue
84
+ seen.add(key)
85
+ entry = {'key': key, 'label': label, 'type': ftype, 'source': 'overlay'}
86
+ if ftype in ('select', 'multiselect'):
87
+ opts = [' '.join(str(o).split())[:60] for o in (f.get('options') or [])
88
+ if str(o).strip()][:50]
89
+ if opts:
90
+ entry['options'] = opts
91
+ if f.get('default') is True:
92
+ entry['default'] = True
93
+ out.append(entry)
94
+ return out or None
95
+
96
+
97
+ def all_tables(st=None):
98
+ """{key: definition} β€” every user-created table in this tenant."""
99
+ try:
100
+ return dict(_st(st).get(STORE_KEY) or {})
101
+ except Exception:
102
+ return {}
103
+
104
+
105
+ def get(table_key, st=None):
106
+ return all_tables(st).get(str(table_key))
107
+
108
+
109
+ def is_user_table(table_key, st=None):
110
+ """THE permission predicate for row writes. Cheap and total: a key that is not in this store
111
+ is not a user table, so it cannot accept invented rows."""
112
+ return str(table_key or '').startswith(KEY_PREFIX) and get(table_key, st) is not None
113
+
114
+
115
+ def create(label, username, fields=None, source=None, st=None):
116
+ """Create a blank table. Returns its key, or None if refused.
117
+
118
+ Refuses rather than raises on the ordinary conditions (no name, duplicate, cap reached) β€”
119
+ the caller is a UI form and a refusal is a message, not an exception.
120
+ """
121
+ label = str(label or '').strip()[:MAX_LABEL]
122
+ if not label:
123
+ return None
124
+ existing = all_tables(st)
125
+ if len(existing) >= MAX_TABLES:
126
+ return None
127
+ key = KEY_PREFIX + _slug(label)
128
+ if key in existing: # a second table of the same name gets a suffix
129
+ for n in range(2, 50):
130
+ if f'{key}_{n}' not in existing:
131
+ key = f'{key}_{n}'
132
+ break
133
+ else:
134
+ return None
135
+ # A blank table still needs ONE column to be a table at all: a row with no fields cannot be
136
+ # displayed, edited or identified. 'name' is the identity column, the same role `customer`
137
+ # plays in the Customer table.
138
+ defn = {
139
+ 'key': key,
140
+ 'label': label,
141
+ 'source': (source if source in (BLANK_SOURCE, AUTOMATION_SOURCE) else BLANK_SOURCE),
142
+ 'createdBy': username,
143
+ 'created': _dt.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
144
+ 'fields': clean_fields(fields) or [{'key': 'name', 'label': 'Name', 'type': 'text',
145
+ 'source': 'overlay', 'default': True}],
146
+ 'rows': {},
147
+ }
148
+
149
+ def _add(cur):
150
+ cur[key] = defn
151
+ return cur
152
+
153
+ _st(st).update(STORE_KEY, _add, flush='sync') # a creation is not a hot path; commit it
154
+ return key
155
+
156
+
157
+ def delete(table_key, st=None):
158
+ def _drop(cur):
159
+ cur.pop(str(table_key), None)
160
+ return cur
161
+ _st(st).update(STORE_KEY, _drop, flush='sync')
162
+
163
+
164
+ def set_fields(table_key, fields, st=None):
165
+ """Replace a table's base-field contract (wave 18 β€” the automation engine grows tables it
166
+ creates). Cleaned with the same validator as `create`; refuses to leave a table fieldless."""
167
+ clean = clean_fields(fields)
168
+ if not clean or not is_user_table(table_key, st):
169
+ return False
170
+
171
+ def _set(cur):
172
+ t = cur.get(str(table_key))
173
+ if t is not None:
174
+ t['fields'] = clean
175
+ return cur
176
+
177
+ _st(st).update(STORE_KEY, _set, flush='sync')
178
+ return True
179
+
180
+
181
+ def add_row(table_key, values=None, username=None, st=None, rid=None):
182
+ """Append one row. Returns the new row id, or None if refused.
183
+
184
+ `rid` RESTORES A ROW UNDER ITS OLD ID (contract C-ADDROW / C-UNDO). Undo has to put a deleted
185
+ row back where it was: a restore under a fresh id would break every cohort, comment and view
186
+ filter that named the original, so the id is part of what is being undone. It is honoured
187
+ only when that id is FREE β€” an undo can never overwrite a row somebody has since created in
188
+ the gap, and it never invents a non-numeric id, because `scoped_pool` reads row ids as ints.
189
+ """
190
+ if not is_user_table(table_key, st):
191
+ return None # ⚠ never on a connector-backed table
192
+ defn = get(table_key, st) or {}
193
+ rows = defn.get('rows') or {}
194
+ if len(rows) >= MAX_ROWS:
195
+ return None
196
+ want = str(rid or '').strip()
197
+ if want and want.isdigit() and want not in rows:
198
+ rid = want
199
+ else:
200
+ rid = str(max((int(r) for r in rows if str(r).isdigit()), default=0) + 1)
201
+ valid = {f['key'] for f in (defn.get('fields') or [])}
202
+ clean = {k: str(v) for k, v in (values or {}).items() if k in valid}
203
+
204
+ def _add(cur):
205
+ t = cur.get(str(table_key))
206
+ if t is not None:
207
+ t.setdefault('rows', {})[rid] = clean
208
+ return cur
209
+
210
+ _st(st).update(STORE_KEY, _add, flush='async')
211
+ return rid
212
+
213
+
214
+ # β›” `upsert_rows` USED TO LIVE HERE, AND DELETING IT IS THE FIX (DEBT D-6, wave 20).
215
+ #
216
+ # There were TWO bulk-upsert implementations β€” this one and `automation_engine.upsert_rows` β€”
217
+ # with different counts (`{updated, inserted, orphans}` vs the engine's seven, including the
218
+ # `capped` count that makes a full table LOUD), a different signature (a dict keyed by value vs
219
+ # a list of rows) and a different cap story. D-6 called it a "silent drift risk"; the honest
220
+ # measurement is worse and simpler: **this one had zero callers, anywhere in the repo.** It was
221
+ # not drifting from the engine, it was a second answer nobody had ever asked.
222
+ #
223
+ # So there is now one implementation because there is one implementation β€” no parity gate to
224
+ # maintain, no second definition to keep in step. If a host-side bulk upsert is ever wanted, the
225
+ # engine's is the one that has been exercised (verify_automation section B) and it is PURE:
226
+ # `(existing, incoming, key_field, cap) -> (rows, counts)`, so it can be lifted here without its
227
+ # store half coming along. Do not re-derive a new one.
228
+
229
+
230
+ def set_label(table_key, label, st=None):
231
+ """Rename a table IN ITS DEFINITION. Returns the stored label, or None if refused.
232
+
233
+ ⚠ WAVE 20, item 6a β€” THE RENAME USED TO WRITE ONLY `nav_meta`. That bucket is the nav's
234
+ display layer, so the rail showed the new name while everything reading the DEFINITION β€”
235
+ the automation editor's database picker above all β€” went on showing the old one. A rename
236
+ that only some surfaces can see is worse than no rename: the picker was not stale-looking,
237
+ it was confidently wrong, and a user choosing "Influencers" there could be choosing the
238
+ table they had renamed to something else months earlier.
239
+ """
240
+ label = ' '.join(str(label or '').split())[:MAX_LABEL]
241
+ if not label or not is_user_table(table_key, st):
242
+ return None
243
+
244
+ def _set(cur):
245
+ t = cur.get(str(table_key))
246
+ if t is not None:
247
+ t['label'] = label
248
+ return cur
249
+
250
+ _st(st).update(STORE_KEY, _set, flush='sync')
251
+ return label
252
+
253
+
254
+ # ---------------------------------------------------------------------------------------------
255
+ # THE SHARED FIELD SCHEMA (contract C-FIELD, owner ruling R2)
256
+ # ---------------------------------------------------------------------------------------------
257
+ # R2 reverses wave 17's "fields are per-user" law FOR THIS PATH: a `ut_*` table's fields are the
258
+ # TABLE'S SCHEMA, the way they are in Airtable β€” everyone with access to the database sees the
259
+ # same columns, and the creator or an admin edits them. Per-field `editRole` narrows or widens
260
+ # who may edit ONE column's definition without handing over the whole table.
261
+ #
262
+ # ⚠ `editRole` GOVERNS THE SCHEMA, NEVER THE VALUES. 'everyone' means anybody with access may
263
+ # rename this column or change its options; it does not decide who may type in its cells. Those
264
+ # are different questions and conflating them would let a column's own settings quietly become a
265
+ # data-permission system nobody wrote.
266
+
267
+ #: Who may edit ONE field's definition. Fail-closed default: admins (= creator or admin).
268
+ FIELD_EDIT_ROLES = ('admins', 'everyone')
269
+
270
+
271
+ def _clean_field(raw, previous=None):
272
+ """One field dict β†’ the stored shape, or None. The single validator for create AND patch, so
273
+ a column cannot be typed one way on the way in and another on the way back."""
274
+ prev = previous or {}
275
+ raw = raw if isinstance(raw, dict) else {}
276
+ label = ' '.join(str(raw.get('label') or prev.get('label') or '').split())[:80]
277
+ key = re.sub(r'[^a-z0-9_]+', '_',
278
+ str(raw.get('key') or prev.get('key') or _slug(label)).strip().lower())
279
+ key = key.strip('_')[:60]
280
+ ftype = str(raw.get('type') or prev.get('type') or 'text').strip().lower()
281
+ if not key or not label or ftype not in UT_FIELD_TYPES:
282
+ return None
283
+ out = {'key': key, 'label': label, 'type': ftype, 'source': 'overlay'}
284
+ opts_raw = raw.get('options') if 'options' in raw else prev.get('options')
285
+ if ftype in ('select', 'multiselect'):
286
+ opts = [' '.join(str(o).split())[:60] for o in (opts_raw or []) if str(o).strip()][:50]
287
+ if opts:
288
+ out['options'] = opts
289
+ role = str(raw.get('editRole') or prev.get('editRole') or 'admins').strip().lower()
290
+ out['editRole'] = role if role in FIELD_EDIT_ROLES else 'admins'
291
+ if prev.get('default') is True or raw.get('default') is True:
292
+ out['default'] = True
293
+ # An automation column carries the binding the engine reads; it is preserved across a patch
294
+ # rather than re-declared, because the automation editor owns it and this route does not.
295
+ auto = raw.get('automation') if 'automation' in raw else prev.get('automation')
296
+ if isinstance(auto, dict):
297
+ out['automation'] = auto
298
+ return out
299
+
300
+
301
+ def may_edit_field(table_key, fkey, viewer, is_admin=False, st=None):
302
+ """May `viewer` change THIS column's definition? Creator/admin always; others only when the
303
+ field itself says `editRole: 'everyone'`. Fail-closed on an unknown field."""
304
+ if may_open(table_key, viewer, is_admin, st) and (
305
+ bool(is_admin) or (get(table_key, st) or {}).get('createdBy') == viewer):
306
+ return True
307
+ for f in ((get(table_key, st) or {}).get('fields') or []):
308
+ if f.get('key') == str(fkey):
309
+ return f.get('editRole') == 'everyone'
310
+ return False
311
+
312
+
313
+ def add_field(table_key, raw, st=None):
314
+ """Append one column to the shared schema. Returns the stored field, or None if refused."""
315
+ if not is_user_table(table_key, st):
316
+ return None
317
+ defn = get(table_key, st) or {}
318
+ have = [f for f in (defn.get('fields') or [])]
319
+ if len(have) >= MAX_FIELDS:
320
+ return None
321
+ field = _clean_field(raw)
322
+ if not field or any(f.get('key') == field['key'] for f in have):
323
+ return None
324
+
325
+ def _add(cur):
326
+ t = cur.get(str(table_key))
327
+ if t is not None:
328
+ t.setdefault('fields', []).append(field)
329
+ return cur
330
+
331
+ _st(st).update(STORE_KEY, _add, flush='sync')
332
+ return field
333
+
334
+
335
+ def patch_field(table_key, fkey, raw, st=None):
336
+ """Edit one column's definition IN PLACE. Returns the stored field, or None if refused.
337
+
338
+ ⚠ THE KEY NEVER MOVES. A field's key is what every stored cell is filed under, so accepting
339
+ a new one here would orphan every value in the column while looking like a rename. The
340
+ LABEL is the renameable thing; the key is identity.
341
+ """
342
+ if not is_user_table(table_key, st):
343
+ return None
344
+ fields = [dict(f) for f in ((get(table_key, st) or {}).get('fields') or [])]
345
+ idx = next((i for i, f in enumerate(fields) if f.get('key') == str(fkey)), -1)
346
+ if idx < 0:
347
+ return None
348
+ merged = dict(raw or {})
349
+ merged['key'] = str(fkey)
350
+ field = _clean_field(merged, fields[idx])
351
+ if not field:
352
+ return None
353
+
354
+ def _set(cur):
355
+ t = cur.get(str(table_key))
356
+ if t is not None:
357
+ for i, f in enumerate(t.get('fields') or []):
358
+ if f.get('key') == str(fkey):
359
+ t['fields'][i] = field
360
+ break
361
+ return cur
362
+
363
+ _st(st).update(STORE_KEY, _set, flush='sync')
364
+ return field
365
+
366
+
367
+ def delete_field(table_key, fkey, st=None):
368
+ """Drop one column from the shared schema. Refuses to leave a table fieldless.
369
+
370
+ ⚠ THE CELLS ARE LEFT IN THE ROWS ON PURPOSE. A deleted column whose values were also
371
+ scrubbed makes an accidental delete unrecoverable; the values are invisible without a field
372
+ declaring them, and re-adding the column with the same key brings them back. Same reasoning
373
+ as `routes_tables.delete_table` leaving the workspace bucket in place. Booked, not hidden.
374
+ """
375
+ if not is_user_table(table_key, st):
376
+ return False
377
+ fields = (get(table_key, st) or {}).get('fields') or []
378
+ if len(fields) <= 1 or not any(f.get('key') == str(fkey) for f in fields):
379
+ return False
380
+
381
+ def _drop(cur):
382
+ t = cur.get(str(table_key))
383
+ if t is not None:
384
+ t['fields'] = [f for f in (t.get('fields') or []) if f.get('key') != str(fkey)]
385
+ return cur
386
+
387
+ _st(st).update(STORE_KEY, _drop, flush='sync')
388
+ return True
389
+
390
+
391
+ def rename_choice_values(table_key, fkey, renames, st=None):
392
+ """Rename select/multiselect OPTIONS **and migrate every stored cell** (contract C-RENAME).
393
+
394
+ `renames` = `[{'from': old, 'to': new}, …]` β€” an EXPLICIT MAPPING, never a diff. A diff
395
+ cannot tell "renamed Blue to Navy" from "deleted Blue and added Navy", and guessing wrong
396
+ empties a column silently.
397
+
398
+ Returns `{'options': n, 'cells': n}`. This is the DEFINITION half β€” the base options list and
399
+ the base row values. A user's per-user overlay stratum and any view filter naming the old
400
+ value are `core.table_store`'s half of the same contract; the caller runs both.
401
+ """
402
+ pairs = []
403
+ for r in (renames or [])[:50]:
404
+ if not isinstance(r, dict):
405
+ continue
406
+ a = ' '.join(str(r.get('from') or '').split())[:60]
407
+ b = ' '.join(str(r.get('to') or '').split())[:60]
408
+ if a and b and a != b:
409
+ pairs.append((a, b))
410
+ if not pairs or not is_user_table(table_key, st):
411
+ return {'options': 0, 'cells': 0}
412
+ mapping = dict(pairs)
413
+ counts = {'options': 0, 'cells': 0}
414
+
415
+ def _apply(cur):
416
+ t = cur.get(str(table_key))
417
+ if t is None:
418
+ return cur
419
+ multi = False
420
+ for f in (t.get('fields') or []):
421
+ if f.get('key') != str(fkey):
422
+ continue
423
+ multi = f.get('type') == 'multiselect'
424
+ opts = f.get('options') or []
425
+ new_opts, seen = [], set()
426
+ for o in opts:
427
+ v = mapping.get(o, o)
428
+ if v not in seen: # a rename ONTO an existing option merges them
429
+ seen.add(v)
430
+ new_opts.append(v)
431
+ if o in mapping:
432
+ counts['options'] += 1
433
+ if opts:
434
+ f['options'] = new_opts
435
+ for row in (t.get('rows') or {}).values():
436
+ if not isinstance(row, dict) or str(fkey) not in row:
437
+ continue
438
+ cell = str(row.get(str(fkey)) or '')
439
+ if not cell:
440
+ continue
441
+ if multi:
442
+ # ⚠ MULTISELECT CELLS ARE COMMA-JOINED LABEL STRINGS, so a rename has to walk the
443
+ # parts. Rewriting the whole string would only ever hit a single-value cell.
444
+ parts = [p.strip() for p in cell.split(',')]
445
+ nxt = [mapping.get(p, p) for p in parts]
446
+ if nxt != parts:
447
+ row[str(fkey)] = ', '.join(dict.fromkeys(nxt))
448
+ counts['cells'] += 1
449
+ elif cell in mapping:
450
+ row[str(fkey)] = mapping[cell]
451
+ counts['cells'] += 1
452
+ return cur
453
+
454
+ _st(st).update(STORE_KEY, _apply, flush='sync')
455
+ return counts
456
+
457
+
458
+ def delete_row(table_key, row_id, st=None):
459
+ if not is_user_table(table_key, st):
460
+ return False
461
+
462
+ def _drop(cur):
463
+ t = cur.get(str(table_key))
464
+ if t is not None:
465
+ (t.get('rows') or {}).pop(str(row_id), None)
466
+ return cur
467
+
468
+ _st(st).update(STORE_KEY, _drop, flush='async')
469
+ return True
470
+
471
+
472
+ #: Names the ENGINE uses for itself when no human is on the other end of a run. β›” A table
473
+ #: stamped with one of these has NO HUMAN OWNER, so `may_open` can only admit an admin β€” which
474
+ #: is why the automation engine must never mint one (see `ut_ensure`'s owner rule, wave 20).
475
+ #: Named here rather than inline so the two modules that care about it read the SAME list.
476
+ MACHINE_OWNERS = ('automation', 'scheduler')
477
+
478
+
479
+ def may_open(table_key, viewer, is_admin=False, st=None):
480
+ """FAIL-CLOSED visibility: the creator, or an admin. Nothing else. **THE one resolver.**
481
+
482
+ A user table cannot be gated by `allowed_modules` β€” a module grant written last month cannot
483
+ describe a table created this morning β€” so it needs its own rule, and the safe rule is the
484
+ narrow one. Tables are stored tenant-wide under one key, so without this ANY user (including
485
+ a BU-scoped sales agent) could open a table somebody else created just by knowing its key.
486
+ Sharing a user table with named colleagues is a follow-on, and it should reuse the shared-
487
+ VIEW vocabulary rather than inventing a second one.
488
+
489
+ β›” WAVE 20 β€” THERE WAS A SECOND, WIDER RULE, AND THE TWO DISAGREED. `routes_automation`'s
490
+ table picker admitted `createdBy in (uname, 'automation', 'scheduler')`, so a non-admin could
491
+ SEE an automation-created database in the picker and then be refused when they opened it,
492
+ edited it, or tried to delete it. Two ideas of who owns a table is the same defect class as
493
+ the two ideas of an agent's book (D-30): both surfaces look right in isolation and only
494
+ disagree in front of a user. The picker now calls THIS function, and the engine stamps a
495
+ real owner (see `MACHINE_OWNERS`) so nothing legitimate is narrowed by the merge.
496
+ """
497
+ t = get(table_key, st)
498
+ if not t:
499
+ return False
500
+ if bool(is_admin) or t.get('createdBy') == viewer:
501
+ return True
502
+ # ⭐ WAVE 20 (R10, closes DEBT D-32) β€” A GRANT ADMITS TOO. `core/shares.py` is the ONE registry
503
+ # for view/folder/database grants, and this is the line that makes a shared DATABASE actually
504
+ # open: without it the share was RECORDED and the receiver's nav never changed, which reads as
505
+ # "sharing is broken" rather than as a missing wall.
506
+ #
507
+ # ⚠ PURELY ADDITIVE, and deliberately last: it can only ever admit somebody a grant NAMES, and
508
+ # can never deny anyone the creator-or-admin rule already admits. `role_for` is fail-closed on
509
+ # a junk bucket or an unreadable store, so an unreachable registry degrades to today's rule
510
+ # rather than to an open door.
511
+ try:
512
+ import core.shares as shares
513
+ return shares.may_see('database', table_key, viewer, is_admin=is_admin, st=st)
514
+ except Exception:
515
+ return False
516
+
517
+
518
+ def nav_entries(viewer=None, is_admin=False, st=None):
519
+ """Registry-SHAPED dicts so the nav can render user tables beside real modules with no
520
+ special-casing: the same keys the flat nav reads (`key`, `label`, `source`).
521
+
522
+ Filtered by `may_open`, so the nav cannot offer a row the dispatcher would refuse.
523
+ """
524
+ out = []
525
+ for key, t in sorted(all_tables(st).items(),
526
+ key=lambda kv: (kv[1].get('label') or '').lower()):
527
+ if viewer is not None and not may_open(key, viewer, is_admin, st=st):
528
+ continue
529
+ out.append({'key': key, 'label': t.get('label') or key,
530
+ 'source': t.get('source') or BLANK_SOURCE,
531
+ 'user_table': True, 'nav': True, 'validate': False})
532
+ return out
web/src/apiContract.ts CHANGED
@@ -86,3 +86,18 @@ export function signal(name: string, detail?: unknown): void {
86
  if (typeof window === "undefined") return;
87
  window.dispatchEvent(new CustomEvent(name, { detail }));
88
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  if (typeof window === "undefined") return;
87
  window.dispatchEvent(new CustomEvent(name, { detail }));
88
  }
89
+
90
+ /**
91
+ * Wave 20 (item 25) — the shell→grid channel for an alert's click-through.
92
+ *
93
+ * A notification names `{topic, viewId}`; the SHELL routes to the table and the GRID owns view
94
+ * selection, so neither has to learn the other's state. An alert for a view the reader can no
95
+ * longer see must do NOTHING rather than throw β€” the listener checks its own view list first.
96
+ */
97
+ export const VIEW_OPEN_EVENT = "aios:view-open";
98
+
99
+ /** `detail` of {@link VIEW_OPEN_EVENT}. */
100
+ export interface ViewOpenDetail {
101
+ topic: string;
102
+ viewId: string;
103
+ }
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -39,7 +39,9 @@ import ColumnMenu from "./ColumnMenu";
39
  import type { ColumnMenuState } from "./ColumnMenu";
40
  import { HEADER_ICONS } from "./iconShapes";
41
  import { emitHostEvent, eventId } from "./hostBridge";
42
- import { NAV_MINIMIZE_EVENT, ROWS_STALE_EVENT, TOAST_EVENT, signal } from "../apiContract";
 
 
43
  import { addTableRow, deleteTableRow } from "./apiBridge";
44
  // Owner item 16 / R4 / C-UNDO β€” the stack and every inverse. Pure, so a node gate can run it.
45
  import { describe, directed, popRedo, popUndo, pushUndo, stackFor } from "./undoStack";
@@ -1375,6 +1377,7 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
1375
  return () => window.removeEventListener("keydown", onKey, true);
1376
  }, [scope, applyEntry]);
1377
 
 
1378
  /**
1379
  * R4 β€” **BULK BACKSPACE/DELETE IS ONE ACTION.** glide's own delete walks the selection and
1380
  * calls `onCellEdited` per cell, which would put forty entries on the stack for one keypress;
@@ -2193,6 +2196,26 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2193
  },
2194
  [views, activeViewId, config, persistView, fields]
2195
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2196
  const createView = useCallback(
2197
  (name: string, mode: DisplayMode, permissions: ViewPermissions) => {
2198
  const acceptedName = uniqueDisplayName(name, views.map((view) => view.name));
@@ -3668,6 +3691,19 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3668
  newId,
3669
  });
3670
  }}
 
 
 
 
 
 
 
 
 
 
 
 
 
3671
  onItemMove={(viewId, folderId) => {
3672
  stampFolder((p) => ({
3673
  ...p,
 
39
  import type { ColumnMenuState } from "./ColumnMenu";
40
  import { HEADER_ICONS } from "./iconShapes";
41
  import { emitHostEvent, eventId } from "./hostBridge";
42
+ import { NAV_MINIMIZE_EVENT, ROWS_STALE_EVENT, TOAST_EVENT, VIEW_OPEN_EVENT, signal }
43
+ from "../apiContract";
44
+ import type { ViewOpenDetail } from "../apiContract";
45
  import { addTableRow, deleteTableRow } from "./apiBridge";
46
  // Owner item 16 / R4 / C-UNDO β€” the stack and every inverse. Pure, so a node gate can run it.
47
  import { describe, directed, popRedo, popUndo, pushUndo, stackFor } from "./undoStack";
 
1377
  return () => window.removeEventListener("keydown", onKey, true);
1378
  }, [scope, applyEntry]);
1379
 
1380
+
1381
  /**
1382
  * R4 β€” **BULK BACKSPACE/DELETE IS ONE ACTION.** glide's own delete walks the selection and
1383
  * calls `onCellEdited` per cell, which would put forty entries on the stack for one keypress;
 
2196
  },
2197
  [views, activeViewId, config, persistView, fields]
2198
  );
2199
+
2200
+ /**
2201
+ * A-S4-3 (item 25) β€” a notification's click-through. The SHELL routes to the table and fires
2202
+ * this; the GRID owns view selection, so neither learns the other's state.
2203
+ *
2204
+ * β›” IGNORE, NEVER THROW, when the view is not ours: an alert can outlive the view it watches
2205
+ * (deleted, or a share revoked), and a reader who can no longer see it must simply land on the
2206
+ * table. `selectView` already returns early on an unknown id; the topic check stops one grid
2207
+ * reacting to another's alert when both are mounted.
2208
+ */
2209
+ useEffect(() => {
2210
+ const onOpen = (e: Event) => {
2211
+ const detail = (e as CustomEvent<ViewOpenDetail>).detail;
2212
+ if (!detail || detail.topic !== scope) return;
2213
+ if (!views.some((v) => v.id === detail.viewId)) return;
2214
+ selectView(detail.viewId);
2215
+ };
2216
+ window.addEventListener(VIEW_OPEN_EVENT, onOpen);
2217
+ return () => window.removeEventListener(VIEW_OPEN_EVENT, onOpen);
2218
+ }, [scope, views, selectView]);
2219
  const createView = useCallback(
2220
  (name: string, mode: DisplayMode, permissions: ViewPermissions) => {
2221
  const acceptedName = uniqueDisplayName(name, views.map((view) => view.name));
 
3691
  newId,
3692
  });
3693
  }}
3694
+ onFolderReorder={(order) => {
3695
+ // A-S4-1 (item 19). S4 built the drag and the reconcile behind an OPTIONAL prop, so
3696
+ // its absence silently disabled the whole feature rather than breaking anything β€”
3697
+ // which is why every gate stayed green while folders would not drag at all. The
3698
+ // stamp is what stops the rail snapping back for one round trip (the echo window).
3699
+ stampFolder((p) => ({ ...p, ordered: { at: Date.now(), order } }));
3700
+ emitHostEvent({
3701
+ id: eventId("foldord"),
3702
+ type: "folder_reorder",
3703
+ surface: "views",
3704
+ order,
3705
+ });
3706
+ }}
3707
  onItemMove={(viewId, folderId) => {
3708
  stampFolder((p) => ({
3709
  ...p,
web/src/customer-grid/types.ts CHANGED
@@ -1869,6 +1869,9 @@ export interface ViewConfig {
1869
  export type ViewKind = "system" | "list" | "custom" | "locked";
1870
 
1871
  export interface SavedView {
 
 
 
1872
  /** C4 β€” the folder this view sits in; null/absent = root. */
1873
  folderId?: string | null;
1874
  id: string;
@@ -2652,6 +2655,15 @@ export type HostEvent =
2652
  folderId: string;
2653
  newId: string;
2654
  }
 
 
 
 
 
 
 
 
 
2655
  /** Drag-drop persistence. `folderId: null` means "back to root". */
2656
  | {
2657
  id: string;
 
1869
  export type ViewKind = "system" | "list" | "custom" | "locked";
1870
 
1871
  export interface SavedView {
1872
+ /** C-SHARE (wave 20, item 23) β€” this view reached me through a GRANT rather than by
1873
+ * being mine. Drives the second mark beside the padlock in the rail. */
1874
+ shared?: boolean;
1875
  /** C4 β€” the folder this view sits in; null/absent = root. */
1876
  folderId?: string | null;
1877
  id: string;
 
2655
  folderId: string;
2656
  newId: string;
2657
  }
2658
+ /**
2659
+ * C-FOLDER-REORDER (wave 20, item 19) β€” this user's folder ORDER in the rail.
2660
+ *
2661
+ * The FULL order, never a delta: a partial list cannot say where an unnamed folder went, so
2662
+ * "moved B after C" would leave every other position to be re-derived by two sides that can
2663
+ * disagree. The client sends the list it is looking at; the host ignores ids it no longer
2664
+ * owns and keeps anything omitted after the named ones.
2665
+ */
2666
+ | { id: string; type: "folder_reorder"; surface: FolderSurface; order: string[] }
2667
  /** Drag-drop persistence. `folderId: null` means "back to root". */
2668
  | {
2669
  id: string;